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 #include <libnl++/Socket.h>
18 
19 #include <libnl++/printer.h>
20 
21 #include <android-base/logging.h>
22 
23 namespace android::nl {
24 
25 /**
26  * Print all outbound/inbound Netlink messages.
27  */
28 static constexpr bool kSuperVerbose = false;
29 
Socket(int protocol,unsigned pid,uint32_t groups)30 Socket::Socket(int protocol, unsigned pid, uint32_t groups) : mProtocol(protocol) {
31     mFd.reset(socket(AF_NETLINK, SOCK_RAW, protocol));
32     if (!mFd.ok()) {
33         PLOG(ERROR) << "Can't open Netlink socket";
34         mFailed = true;
35         return;
36     }
37 
38     sockaddr_nl sa = {};
39     sa.nl_family = AF_NETLINK;
40     sa.nl_pid = pid;
41     sa.nl_groups = groups;
42 
43     if (bind(mFd.get(), reinterpret_cast<sockaddr*>(&sa), sizeof(sa)) < 0) {
44         PLOG(ERROR) << "Can't bind Netlink socket";
45         mFd.reset();
46         mFailed = true;
47     }
48 }
49 
send(const Buffer<nlmsghdr> & msg,const sockaddr_nl & sa)50 bool Socket::send(const Buffer<nlmsghdr>& msg, const sockaddr_nl& sa) {
51     if constexpr (kSuperVerbose) {
52         LOG(VERBOSE) << (mFailed ? "(not) " : "") << "sending to " << sa.nl_pid << ": "
53                      << toString(msg, mProtocol);
54     }
55     if (mFailed) return false;
56 
57     mSeq = msg->nlmsg_seq;
58     const auto rawMsg = msg.getRaw();
59     const auto bytesSent = sendto(mFd.get(), rawMsg.ptr(), rawMsg.len(), 0,
60                                   reinterpret_cast<const sockaddr*>(&sa), sizeof(sa));
61     if (bytesSent < 0) {
62         PLOG(ERROR) << "Can't send Netlink message";
63         return false;
64     } else if (size_t(bytesSent) != rawMsg.len()) {
65         LOG(ERROR) << "Can't send Netlink message: truncated message";
66         return false;
67     }
68     return true;
69 }
70 
increaseReceiveBuffer(size_t maxSize)71 bool Socket::increaseReceiveBuffer(size_t maxSize) {
72     if (maxSize == 0) {
73         LOG(ERROR) << "Maximum receive size should not be zero";
74         return false;
75     }
76 
77     if (mReceiveBuffer.size() < maxSize) mReceiveBuffer.resize(maxSize);
78     return true;
79 }
80 
receive(size_t maxSize)81 std::optional<Buffer<nlmsghdr>> Socket::receive(size_t maxSize) {
82     return receiveFrom(maxSize).first;
83 }
84 
receiveFrom(size_t maxSize)85 std::pair<std::optional<Buffer<nlmsghdr>>, sockaddr_nl> Socket::receiveFrom(size_t maxSize) {
86     if (mFailed) return {std::nullopt, {}};
87 
88     if (!increaseReceiveBuffer(maxSize)) return {std::nullopt, {}};
89 
90     sockaddr_nl sa = {};
91     socklen_t saLen = sizeof(sa);
92     const auto bytesReceived = recvfrom(mFd.get(), mReceiveBuffer.data(), maxSize, MSG_TRUNC,
93                                         reinterpret_cast<sockaddr*>(&sa), &saLen);
94 
95     if (bytesReceived <= 0) {
96         PLOG(ERROR) << "Failed to receive Netlink message";
97         return {std::nullopt, {}};
98     } else if (size_t(bytesReceived) > maxSize) {
99         PLOG(ERROR) << "Received data larger than maximum receive size: "  //
100                     << bytesReceived << " > " << maxSize;
101         return {std::nullopt, {}};
102     }
103 
104     Buffer<nlmsghdr> msg(reinterpret_cast<nlmsghdr*>(mReceiveBuffer.data()), bytesReceived);
105     if constexpr (kSuperVerbose) {
106         LOG(VERBOSE) << "received from " << sa.nl_pid << ": " << toString(msg, mProtocol);
107     }
108     return {msg, sa};
109 }
110 
receiveAck(uint32_t seq)111 bool Socket::receiveAck(uint32_t seq) {
112     const auto nlerr = receive<nlmsgerr>({NLMSG_ERROR});
113     if (!nlerr.has_value()) return false;
114 
115     if (nlerr->data.msg.nlmsg_seq != seq) {
116         LOG(ERROR) << "Received ACK for a different message (" << nlerr->data.msg.nlmsg_seq
117                    << ", expected " << seq << "). Multi-message tracking is not implemented.";
118         return false;
119     }
120 
121     if (nlerr->data.error == 0) return true;
122 
123     LOG(WARNING) << "Received Netlink error message: " << strerror(-nlerr->data.error);
124     return false;
125 }
126 
receive(const std::set<nlmsgtype_t> & msgtypes,size_t maxSize)127 std::optional<Buffer<nlmsghdr>> Socket::receive(const std::set<nlmsgtype_t>& msgtypes,
128                                                 size_t maxSize) {
129     if (mFailed || !increaseReceiveBuffer(maxSize)) return std::nullopt;
130 
131     for (const auto rawMsg : *this) {
132         if (msgtypes.count(rawMsg->nlmsg_type) == 0) {
133             LOG(WARNING) << "Received (and ignored) unexpected Netlink message of type "
134                          << rawMsg->nlmsg_type;
135             continue;
136         }
137 
138         return rawMsg;
139     }
140 
141     return std::nullopt;
142 }
143 
getPid()144 std::optional<unsigned> Socket::getPid() {
145     if (mFailed) return std::nullopt;
146 
147     sockaddr_nl sa = {};
148     socklen_t sasize = sizeof(sa);
149     if (getsockname(mFd.get(), reinterpret_cast<sockaddr*>(&sa), &sasize) < 0) {
150         PLOG(ERROR) << "Failed to get PID of Netlink socket";
151         return std::nullopt;
152     }
153     return sa.nl_pid;
154 }
155 
preparePoll(short events)156 pollfd Socket::preparePoll(short events) {
157     return {mFd.get(), events, 0};
158 }
159 
receive_iterator(Socket & socket,bool end)160 Socket::receive_iterator::receive_iterator(Socket& socket, bool end)
161     : mSocket(socket), mIsEnd(end) {
162     if (!end) receive();
163 }
164 
operator ++()165 Socket::receive_iterator Socket::receive_iterator::operator++() {
166     CHECK(!mIsEnd) << "Trying to increment end iterator";
167     ++mCurrent;
168     if (mCurrent.isEnd()) receive();
169     return *this;
170 }
171 
operator ==(const receive_iterator & other) const172 bool Socket::receive_iterator::operator==(const receive_iterator& other) const {
173     if (mIsEnd != other.mIsEnd) return false;
174     if (mIsEnd && other.mIsEnd) return true;
175     return mCurrent == other.mCurrent;
176 }
177 
operator *() const178 const Buffer<nlmsghdr>& Socket::receive_iterator::operator*() const {
179     CHECK(!mIsEnd) << "Trying to dereference end iterator";
180     return *mCurrent;
181 }
182 
receive()183 void Socket::receive_iterator::receive() {
184     CHECK(!mIsEnd) << "Trying to receive on end iterator";
185     CHECK(mCurrent.isEnd()) << "Trying to receive without draining previous read";
186 
187     const auto buf = mSocket.receive();
188     if (buf.has_value()) {
189         mCurrent = buf->begin();
190     } else {
191         mIsEnd = true;
192     }
193 }
194 
begin()195 Socket::receive_iterator Socket::begin() {
196     return {*this, false};
197 }
198 
end()199 Socket::receive_iterator Socket::end() {
200     return {*this, true};
201 }
202 
203 }  // namespace android::nl
204