Tomasz Wasilczyk | 8732967 | 2019-07-12 11:43:00 -0700 | [diff] [blame] | 1 | /* |
| 2 | * Copyright (C) 2019 The Android Open Source Project |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | #pragma once |
| 18 | |
| 19 | #include "NetlinkRequest.h" |
| 20 | |
| 21 | #include <android-base/macros.h> |
| 22 | #include <android-base/unique_fd.h> |
| 23 | |
| 24 | #include <linux/netlink.h> |
| 25 | |
Tomasz Wasilczyk | 55f2193 | 2019-12-20 09:20:24 -0800 | [diff] [blame] | 26 | namespace android::netdevice { |
Tomasz Wasilczyk | 8732967 | 2019-07-12 11:43:00 -0700 | [diff] [blame] | 27 | |
| 28 | /** |
| 29 | * A wrapper around AF_NETLINK sockets. |
| 30 | * |
| 31 | * This class is not thread safe to use a single instance between multiple threads, but it's fine to |
| 32 | * use multiple instances over multiple threads. |
| 33 | */ |
| 34 | struct NetlinkSocket { |
| 35 | NetlinkSocket(int protocol); |
| 36 | |
| 37 | /** |
| 38 | * Send Netlink message to Kernel. |
| 39 | * |
chrisweir | cf36cea | 2019-11-08 16:41:02 -0800 | [diff] [blame] | 40 | * \param msg Message to send, nlmsg_seq will be set to next sequence number |
| 41 | * \return true, if succeeded |
Tomasz Wasilczyk | 8732967 | 2019-07-12 11:43:00 -0700 | [diff] [blame] | 42 | */ |
| 43 | template <class T, unsigned int BUFSIZE> |
| 44 | bool send(NetlinkRequest<T, BUFSIZE>& req) { |
| 45 | if (!req.isGood()) return false; |
| 46 | return send(req.header()); |
| 47 | } |
| 48 | |
| 49 | /** |
| 50 | * Receive Netlink ACK message from Kernel. |
| 51 | * |
chrisweir | cf36cea | 2019-11-08 16:41:02 -0800 | [diff] [blame] | 52 | * \return true if received ACK message, false in case of error |
Tomasz Wasilczyk | 8732967 | 2019-07-12 11:43:00 -0700 | [diff] [blame] | 53 | */ |
| 54 | bool receiveAck(); |
| 55 | |
| 56 | private: |
| 57 | uint32_t mSeq = 0; |
| 58 | base::unique_fd mFd; |
| 59 | bool mFailed = false; |
| 60 | |
| 61 | bool send(struct nlmsghdr* msg); |
| 62 | |
| 63 | DISALLOW_COPY_AND_ASSIGN(NetlinkSocket); |
| 64 | }; |
| 65 | |
Tomasz Wasilczyk | 55f2193 | 2019-12-20 09:20:24 -0800 | [diff] [blame] | 66 | } // namespace android::netdevice |