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 <android-base/macros.h>
20 #include <android-base/unique_fd.h>
21 #include <libnl++/Buffer.h>
22 #include <libnl++/Message.h>
23 #include <libnl++/MessageFactory.h>
24 
25 #include <linux/netlink.h>
26 #include <poll.h>
27 
28 #include <optional>
29 #include <set>
30 #include <vector>
31 
32 namespace android::nl {
33 
34 /**
35  * A wrapper around AF_NETLINK sockets.
36  *
37  * This class is not thread safe to use a single instance between multiple threads, but it's fine to
38  * use multiple instances over multiple threads.
39  */
40 class Socket {
41   public:
42     static constexpr size_t defaultReceiveSize = 8192;
43 
44     /**
45      * Socket constructor.
46      *
47      * \param protocol the Netlink protocol to use.
48      * \param pid port id. Default value of 0 allows the kernel to assign us a unique pid.
49      *        (NOTE: this is NOT the same as process id).
50      * \param groups Netlink multicast groups to listen to. This is a 32-bit bitfield, where each
51      *        bit is a different group. Default value of 0 means no groups are selected.
52      *        See man netlink.7.
53      * for more details.
54      */
55     Socket(int protocol, unsigned pid = 0, uint32_t groups = 0);
56 
57     /**
58      * Send Netlink message with incremented sequence number to the Kernel.
59      *
60      * \param msg Message to send. Its sequence number will be updated.
61      * \return true, if succeeded.
62      */
63     template <typename T, unsigned BUFSIZE>
send(MessageFactory<T,BUFSIZE> & req)64     bool send(MessageFactory<T, BUFSIZE>& req) {
65         sockaddr_nl sa = {};
66         sa.nl_family = AF_NETLINK;
67         sa.nl_pid = 0;  // Kernel
68         return send(req, sa);
69     }
70 
71     /**
72      * Send Netlink message with incremented sequence number.
73      *
74      * \param msg Message to send. Its sequence number will be updated.
75      * \param sa Destination address.
76      * \return true, if succeeded.
77      */
78     template <typename T, unsigned BUFSIZE>
send(MessageFactory<T,BUFSIZE> & req,const sockaddr_nl & sa)79     bool send(MessageFactory<T, BUFSIZE>& req, const sockaddr_nl& sa) {
80         req.header.nlmsg_seq = mSeq + 1;
81 
82         const auto msg = req.build();
83         if (!msg.has_value()) return false;
84 
85         return send(*msg, sa);
86     }
87 
88     /**
89      * Send Netlink message.
90      *
91      * \param msg Message to send.
92      * \param sa Destination address.
93      * \return true, if succeeded.
94      */
95     bool send(const Buffer<nlmsghdr>& msg, const sockaddr_nl& sa);
96 
97     /**
98      * Receive one or multiple Netlink messages.
99      *
100      * WARNING: the underlying buffer is owned by Socket class and the data is valid until the next
101      * call to the read function or until deallocation of Socket instance.
102      *
103      * \param maxSize Maximum total size of received messages
104      * \return Buffer view with message data, std::nullopt on error.
105      */
106     std::optional<Buffer<nlmsghdr>> receive(size_t maxSize = defaultReceiveSize);
107 
108     /**
109      * Receive one or multiple Netlink messages and the sender process address.
110      *
111      * WARNING: the underlying buffer is owned by Socket class and the data is valid until the next
112      * call to the read function or until deallocation of Socket instance.
113      *
114      * \param maxSize Maximum total size of received messages.
115      * \return A pair (for use with structured binding) containing:
116      *         - buffer view with message data, std::nullopt on error;
117      *         - sender process address.
118      */
119     std::pair<std::optional<Buffer<nlmsghdr>>, sockaddr_nl> receiveFrom(
120             size_t maxSize = defaultReceiveSize);
121 
122     /**
123      * Receive matching Netlink message of a given payload type.
124      *
125      * This method should be used if the caller expects exactly one incoming message of exactly
126      * given type (such as ACK). If there is a use case to handle multiple types of messages,
127      * please use receive(size_t) directly and iterate through potential multipart messages.
128      *
129      * If this method is used in such an environment, it will only return the first matching message
130      * from multipart packet and will issue warnings on messages that do not match.
131      *
132      * \param msgtypes Expected message types (such as NLMSG_ERROR).
133      * \param maxSize Maximum total size of received messages.
134      * \return Parsed message or std::nullopt in case of error.
135      */
136     template <typename T>
137     std::optional<Message<T>> receive(const std::set<nlmsgtype_t>& msgtypes,
138                                       size_t maxSize = defaultReceiveSize) {
139         const auto msg = receive(msgtypes, maxSize);
140         if (!msg.has_value()) return std::nullopt;
141 
142         const auto parsed = Message<T>::parse(*msg);
143         if (!parsed.has_value()) {
144             LOG(WARNING) << "Received matching Netlink message, but couldn't parse it";
145             return std::nullopt;
146         }
147 
148         return parsed;
149     }
150 
151     /**
152      * Receive Netlink ACK message.
153      *
154      * \param req Message to match sequence number against.
155      * \return true if received ACK message, false in case of error.
156      */
157     template <typename T, unsigned BUFSIZE>
receiveAck(MessageFactory<T,BUFSIZE> & req)158     bool receiveAck(MessageFactory<T, BUFSIZE>& req) {
159         return receiveAck(req.header.nlmsg_seq);
160     }
161 
162     /**
163      * Receive Netlink ACK message.
164      *
165      * \param seq Sequence number of message to ACK.
166      * \return true if received ACK message, false in case of error.
167      */
168     bool receiveAck(uint32_t seq);
169 
170     /**
171      * Fetches the socket PID.
172      *
173      * \return PID that socket is bound to or std::nullopt.
174      */
175     std::optional<unsigned> getPid();
176 
177     /**
178      * Creates a pollfd object for the socket.
179      *
180      * \param events Value for pollfd.events.
181      * \return A populated pollfd object.
182      */
183     pollfd preparePoll(short events = 0);
184 
185     /**
186      * Live iterator continuously receiving messages from Netlink socket.
187      *
188      * Iteration ends when socket fails to receive a buffer.
189      *
190      * Example:
191      * ```
192      *     nl::Socket sock(NETLINK_ROUTE, 0, RTMGRP_LINK);
193      *     for (const auto rawMsg : sock) {
194      *         const auto msg = nl::Message<ifinfomsg>::parse(rawMsg, {RTM_NEWLINK, RTM_DELLINK});
195      *         if (!msg.has_value()) continue;
196      *
197      *         LOG(INFO) << msg->attributes.get<std::string>(IFLA_IFNAME)
198      *                   << " is " << ((msg->data.ifi_flags & IFF_UP) ? "up" : "down");
199      *     }
200      *     LOG(FATAL) << "Failed to read from Netlink socket";
201      * ```
202      */
203     class receive_iterator {
204       public:
205         receive_iterator(Socket& socket, bool end);
206 
207         receive_iterator operator++();
208         bool operator==(const receive_iterator& other) const;
209         const Buffer<nlmsghdr>& operator*() const;
210 
211       private:
212         Socket& mSocket;
213         bool mIsEnd;
214         Buffer<nlmsghdr>::iterator mCurrent;
215 
216         void receive();
217     };
218     receive_iterator begin();
219     receive_iterator end();
220 
221   private:
222     const int mProtocol;
223     base::unique_fd mFd;
224     std::vector<uint8_t> mReceiveBuffer;
225 
226     bool mFailed = false;
227     uint32_t mSeq = 0;
228 
229     bool increaseReceiveBuffer(size_t maxSize);
230     std::optional<Buffer<nlmsghdr>> receive(const std::set<nlmsgtype_t>& msgtypes, size_t maxSize);
231 
232     DISALLOW_COPY_AND_ASSIGN(Socket);
233 };
234 
235 }  // namespace android::nl
236