blob: 515cc1047cbfee6f9c9ccae9cd04d2d2570f5e18 [file] [log] [blame]
San Mehat168415b2009-05-06 11:14:21 -07001/*
2 * Copyright (C) 2008 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 */
San Mehat168415b2009-05-06 11:14:21 -070016
17#define LOG_TAG "NetlinkEvent"
San Mehat168415b2009-05-06 11:14:21 -070018
Lorenzo Colitti381f70f2013-08-02 05:58:37 +090019#include <arpa/inet.h>
Lorenzo Colittie439ffc2017-10-03 18:44:11 +090020#include <limits.h>
21#include <linux/genetlink.h>
Mike J. Chenec16b9d2011-06-23 14:55:28 -070022#include <linux/if.h>
Lorenzo Colitti9b342932014-06-19 13:16:04 +090023#include <linux/if_addr.h>
24#include <linux/if_link.h>
JP Abgralle6f80142011-07-14 16:46:32 -070025#include <linux/netfilter/nfnetlink.h>
Jeff Sharkey9a20e672014-10-30 14:51:59 -070026#include <linux/netfilter/nfnetlink_log.h>
Mark Salyzyn66ce3e02016-09-28 10:07:20 -070027#include <linux/netlink.h>
28#include <linux/rtnetlink.h>
29#include <net/if.h>
Mark Salyzyn66ce3e02016-09-28 10:07:20 -070030#include <netinet/icmp6.h>
Lorenzo Colittie439ffc2017-10-03 18:44:11 +090031#include <netinet/in.h>
Mark Salyzyn66ce3e02016-09-28 10:07:20 -070032#include <stdlib.h>
33#include <string.h>
Maciej Żenczykowski28b94af2021-10-25 15:24:18 -070034#include <sys/personality.h>
Mark Salyzyn66ce3e02016-09-28 10:07:20 -070035#include <sys/socket.h>
36#include <sys/types.h>
Maciej Żenczykowski28b94af2021-10-25 15:24:18 -070037#include <sys/utsname.h>
38
39#include <android-base/parseint.h>
40#include <log/log.h>
41#include <sysutils/NetlinkEvent.h>
42
43using android::base::ParseInt;
Jeff Sharkey9a20e672014-10-30 14:51:59 -070044
JP Abgralle6f80142011-07-14 16:46:32 -070045/* From kernel's net/netfilter/xt_quota2.c */
Jeff Sharkey9a20e672014-10-30 14:51:59 -070046const int LOCAL_QLOG_NL_EVENT = 112;
47const int LOCAL_NFLOG_PACKET = NFNL_SUBSYS_ULOG << 8 | NFULNL_MSG_PACKET;
JP Abgralle6f80142011-07-14 16:46:32 -070048
Maciej Żenczykowski28b94af2021-10-25 15:24:18 -070049/******************************************************************************
50 * WARNING: HERE BE DRAGONS! *
51 * *
52 * This is here to provide for compatibility with both 32 and 64-bit kernels *
53 * from 32-bit userspace. *
54 * *
55 * The kernel definition of this struct uses types (like long) that are not *
56 * the same across 32-bit and 64-bit builds, and there is no compatibility *
57 * layer to fix it up before it reaches userspace. *
58 * As such we need to detect the bit-ness of the kernel and deal with it. *
59 * *
60 ******************************************************************************/
61
62/*
63 * This is the verbatim kernel declaration from net/netfilter/xt_quota2.c,
64 * it is *NOT* of a well defined layout and is included here for compile
65 * time assertions only.
66 *
67 * It got there from deprecated ipt_ULOG.h to parse QLOG_NL_EVENT.
68 */
Christopher Ferris71ac5c82019-12-09 15:10:06 -080069#define ULOG_MAC_LEN 80
70#define ULOG_PREFIX_LEN 32
71typedef struct ulog_packet_msg {
72 unsigned long mark;
73 long timestamp_sec;
74 long timestamp_usec;
75 unsigned int hook;
76 char indev_name[IFNAMSIZ];
77 char outdev_name[IFNAMSIZ];
78 size_t data_len;
79 char prefix[ULOG_PREFIX_LEN];
80 unsigned char mac_len;
81 unsigned char mac[ULOG_MAC_LEN];
82 unsigned char payload[0];
83} ulog_packet_msg_t;
84
Maciej Żenczykowski28b94af2021-10-25 15:24:18 -070085// On Linux int is always 32 bits, while sizeof(long) == sizeof(void*),
86// thus long on a 32-bit Linux kernel is 32-bits, like int always is
87typedef int long32;
88typedef unsigned int ulong32;
89static_assert(sizeof(long32) == 4);
90static_assert(sizeof(ulong32) == 4);
Jeff Sharkey9a20e672014-10-30 14:51:59 -070091
Maciej Żenczykowski28b94af2021-10-25 15:24:18 -070092// Here's the same structure definition with the assumption the kernel
93// is compiled for 32-bits.
94typedef struct {
95 ulong32 mark;
96 long32 timestamp_sec;
97 long32 timestamp_usec;
98 unsigned int hook;
99 char indev_name[IFNAMSIZ];
100 char outdev_name[IFNAMSIZ];
101 ulong32 data_len;
102 char prefix[ULOG_PREFIX_LEN];
103 unsigned char mac_len;
104 unsigned char mac[ULOG_MAC_LEN];
105 unsigned char payload[0];
106} ulog_packet_msg32_t;
107
108// long on a 64-bit kernel is 64-bits with 64-bit alignment,
109// while long long is 64-bit but may have 32-bit aligment.
110typedef long long __attribute__((__aligned__(8))) long64;
111typedef unsigned long long __attribute__((__aligned__(8))) ulong64;
112static_assert(sizeof(long64) == 8);
113static_assert(sizeof(ulong64) == 8);
114
115// Here's the same structure definition with the assumption the kernel
116// is compiled for 64-bits.
117typedef struct {
118 ulong64 mark;
119 long64 timestamp_sec;
120 long64 timestamp_usec;
121 unsigned int hook;
122 char indev_name[IFNAMSIZ];
123 char outdev_name[IFNAMSIZ];
124 ulong64 data_len;
125 char prefix[ULOG_PREFIX_LEN];
126 unsigned char mac_len;
127 unsigned char mac[ULOG_MAC_LEN];
128 unsigned char payload[0];
129} ulog_packet_msg64_t;
130
131// One expects the 32-bit version to be smaller than the 64-bit version.
132static_assert(sizeof(ulog_packet_msg32_t) < sizeof(ulog_packet_msg64_t));
133// And either way the 'native' version should match either the 32 or 64 bit one.
134static_assert(sizeof(ulog_packet_msg_t) == sizeof(ulog_packet_msg32_t) ||
135 sizeof(ulog_packet_msg_t) == sizeof(ulog_packet_msg64_t));
136
137// In practice these sizes are always simply (for both x86 and arm):
138static_assert(sizeof(ulog_packet_msg32_t) == 168);
139static_assert(sizeof(ulog_packet_msg64_t) == 192);
140
141// Figure out the bitness of userspace.
142// Trivial and known at compile time.
143static bool isUserspace64bit(void) {
144 return sizeof(long) == 8;
145}
146
147// Figure out the bitness of the kernel.
148static bool isKernel64Bit(void) {
149 // a 64-bit userspace requires a 64-bit kernel
150 if (isUserspace64bit()) return true;
151
152 static bool init = false;
153 static bool cache = false;
154 if (init) return cache;
155
156 // Retrieve current personality - on Linux this system call *cannot* fail.
157 int p = personality(0xffffffff);
158 // But if it does just assume kernel and userspace (which is 32-bit) match...
159 if (p == -1) return false;
160
161 // This will effectively mask out the bottom 8 bits, and switch to 'native'
162 // personality, and then return the previous personality of this thread
163 // (likely PER_LINUX or PER_LINUX32) with any extra options unmodified.
164 int q = personality((p & ~PER_MASK) | PER_LINUX);
165 // Per man page this theoretically could error out with EINVAL,
166 // but kernel code analysis suggests setting PER_LINUX cannot fail.
167 // Either way, assume kernel and userspace (which is 32-bit) match...
168 if (q != p) return false;
169
170 struct utsname u;
171 (void)uname(&u); // only possible failure is EFAULT, but u is on stack.
172
173 // Switch back to previous personality.
174 // Theoretically could fail with EINVAL on arm64 with no 32-bit support,
175 // but then we wouldn't have fetched 'p' from the kernel in the first place.
176 // Either way there's nothing meaningul we can do in case of error.
177 // Since PER_LINUX32 vs PER_LINUX only affects uname.machine it doesn't
178 // really hurt us either. We're really just switching back to be 'clean'.
179 (void)personality(p);
180
181 // Possible values of utsname.machine observed on x86_64 desktop (arm via qemu):
182 // x86_64 i686 aarch64 armv7l
183 // additionally observed on arm device:
184 // armv8l
185 // presumably also might just be possible:
186 // i386 i486 i586
187 // and there might be other weird arm32 cases.
188 // We note that the 64 is present in both 64-bit archs,
189 // and in general is likely to be present in only 64-bit archs.
190 cache = !!strstr(u.machine, "64");
191 init = true;
192 return cache;
193}
194
195/******************************************************************************/
Lorenzo Colittid0e49382019-04-10 23:04:41 +0900196
San Mehat168415b2009-05-06 11:14:21 -0700197NetlinkEvent::NetlinkEvent() {
Jeff Sharkeye4f39402015-03-13 13:27:33 -0700198 mAction = Action::kUnknown;
San Mehatebfe3db2009-10-10 17:35:13 -0700199 memset(mParams, 0, sizeof(mParams));
Yi Kong48885252018-07-24 16:34:27 -0700200 mPath = nullptr;
201 mSubsystem = nullptr;
San Mehat168415b2009-05-06 11:14:21 -0700202}
203
204NetlinkEvent::~NetlinkEvent() {
205 int i;
206 if (mPath)
207 free(mPath);
208 if (mSubsystem)
209 free(mSubsystem);
210 for (i = 0; i < NL_PARAMS_MAX; i++) {
211 if (!mParams[i])
212 break;
213 free(mParams[i]);
214 }
215}
216
San Mehatd6744132009-12-24 07:17:09 -0800217void NetlinkEvent::dump() {
218 int i;
219
220 for (i = 0; i < NL_PARAMS_MAX; i++) {
221 if (!mParams[i])
222 break;
San Mehat7e8529a2010-03-25 09:31:42 -0700223 SLOGD("NL param '%s'\n", mParams[i]);
San Mehatd6744132009-12-24 07:17:09 -0800224 }
225}
226
Mike J. Chenec16b9d2011-06-23 14:55:28 -0700227/*
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900228 * Returns the message name for a message in the NETLINK_ROUTE family, or NULL
229 * if parsing that message is not supported.
230 */
231static const char *rtMessageName(int type) {
232#define NL_EVENT_RTM_NAME(rtm) case rtm: return #rtm;
233 switch (type) {
234 NL_EVENT_RTM_NAME(RTM_NEWLINK);
235 NL_EVENT_RTM_NAME(RTM_DELLINK);
236 NL_EVENT_RTM_NAME(RTM_NEWADDR);
237 NL_EVENT_RTM_NAME(RTM_DELADDR);
238 NL_EVENT_RTM_NAME(RTM_NEWROUTE);
239 NL_EVENT_RTM_NAME(RTM_DELROUTE);
240 NL_EVENT_RTM_NAME(RTM_NEWNDUSEROPT);
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700241 NL_EVENT_RTM_NAME(LOCAL_QLOG_NL_EVENT);
242 NL_EVENT_RTM_NAME(LOCAL_NFLOG_PACKET);
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900243 default:
Yi Kong48885252018-07-24 16:34:27 -0700244 return nullptr;
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900245 }
246#undef NL_EVENT_RTM_NAME
247}
248
249/*
250 * Checks that a binary NETLINK_ROUTE message is long enough for a payload of
251 * size bytes.
252 */
253static bool checkRtNetlinkLength(const struct nlmsghdr *nh, size_t size) {
254 if (nh->nlmsg_len < NLMSG_LENGTH(size)) {
255 SLOGE("Got a short %s message\n", rtMessageName(nh->nlmsg_type));
256 return false;
257 }
258 return true;
259}
260
261/*
262 * Utility function to log errors.
263 */
264static bool maybeLogDuplicateAttribute(bool isDup,
265 const char *attributeName,
266 const char *messageName) {
267 if (isDup) {
268 SLOGE("Multiple %s attributes in %s, ignoring\n", attributeName, messageName);
269 return true;
270 }
271 return false;
272}
273
274/*
275 * Parse a RTM_NEWLINK message.
276 */
277bool NetlinkEvent::parseIfInfoMessage(const struct nlmsghdr *nh) {
278 struct ifinfomsg *ifi = (struct ifinfomsg *) NLMSG_DATA(nh);
279 if (!checkRtNetlinkLength(nh, sizeof(*ifi)))
280 return false;
281
282 if ((ifi->ifi_flags & IFF_LOOPBACK) != 0) {
283 return false;
284 }
285
286 int len = IFLA_PAYLOAD(nh);
287 struct rtattr *rta;
288 for (rta = IFLA_RTA(ifi); RTA_OK(rta, len); rta = RTA_NEXT(rta, len)) {
289 switch(rta->rta_type) {
290 case IFLA_IFNAME:
291 asprintf(&mParams[0], "INTERFACE=%s", (char *) RTA_DATA(rta));
Chenbo Feng5e5e5e92018-03-02 01:32:53 -0800292 // We can get the interface change information from sysfs update
293 // already. But in case we missed those message when devices start.
294 // We do a update again when received a kLinkUp event. To make
295 // the message consistent, use IFINDEX here as well since sysfs
296 // uses IFINDEX.
297 asprintf(&mParams[1], "IFINDEX=%d", ifi->ifi_index);
Jeff Sharkeye4f39402015-03-13 13:27:33 -0700298 mAction = (ifi->ifi_flags & IFF_LOWER_UP) ? Action::kLinkUp :
299 Action::kLinkDown;
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900300 mSubsystem = strdup("net");
301 return true;
302 }
303 }
304
305 return false;
306}
307
308/*
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900309 * Parse a RTM_NEWADDR or RTM_DELADDR message.
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900310 */
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900311bool NetlinkEvent::parseIfAddrMessage(const struct nlmsghdr *nh) {
312 struct ifaddrmsg *ifaddr = (struct ifaddrmsg *) NLMSG_DATA(nh);
Yi Kong48885252018-07-24 16:34:27 -0700313 struct ifa_cacheinfo *cacheinfo = nullptr;
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900314 char addrstr[INET6_ADDRSTRLEN] = "";
Lorenzo Colittief6454d2016-02-16 21:42:16 +0900315 char ifname[IFNAMSIZ] = "";
Lorenzo Colitti077d1ea2020-05-11 11:37:17 +0900316 uint32_t flags;
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900317
318 if (!checkRtNetlinkLength(nh, sizeof(*ifaddr)))
319 return false;
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900320
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900321 int type = nh->nlmsg_type;
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900322 if (type != RTM_NEWADDR && type != RTM_DELADDR) {
323 SLOGE("parseIfAddrMessage on incorrect message type 0x%x\n", type);
324 return false;
325 }
326
327 // For log messages.
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900328 const char *msgtype = rtMessageName(type);
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900329
Lorenzo Colitti077d1ea2020-05-11 11:37:17 +0900330 // First 8 bits of flags. In practice will always be overridden when parsing IFA_FLAGS below.
331 flags = ifaddr->ifa_flags;
332
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900333 struct rtattr *rta;
334 int len = IFA_PAYLOAD(nh);
335 for (rta = IFA_RTA(ifaddr); RTA_OK(rta, len); rta = RTA_NEXT(rta, len)) {
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900336 if (rta->rta_type == IFA_ADDRESS) {
337 // Only look at the first address, because we only support notifying
338 // one change at a time.
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900339 if (maybeLogDuplicateAttribute(*addrstr != '\0', "IFA_ADDRESS", msgtype))
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900340 continue;
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900341
342 // Convert the IP address to a string.
343 if (ifaddr->ifa_family == AF_INET) {
344 struct in_addr *addr4 = (struct in_addr *) RTA_DATA(rta);
345 if (RTA_PAYLOAD(rta) < sizeof(*addr4)) {
Mark Salyzyn80f63d42014-05-01 07:47:04 -0700346 SLOGE("Short IPv4 address (%zu bytes) in %s",
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900347 RTA_PAYLOAD(rta), msgtype);
348 continue;
349 }
350 inet_ntop(AF_INET, addr4, addrstr, sizeof(addrstr));
351 } else if (ifaddr->ifa_family == AF_INET6) {
352 struct in6_addr *addr6 = (struct in6_addr *) RTA_DATA(rta);
353 if (RTA_PAYLOAD(rta) < sizeof(*addr6)) {
Mark Salyzyn80f63d42014-05-01 07:47:04 -0700354 SLOGE("Short IPv6 address (%zu bytes) in %s",
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900355 RTA_PAYLOAD(rta), msgtype);
356 continue;
357 }
358 inet_ntop(AF_INET6, addr6, addrstr, sizeof(addrstr));
359 } else {
360 SLOGE("Unknown address family %d\n", ifaddr->ifa_family);
361 continue;
362 }
363
364 // Find the interface name.
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900365 if (!if_indextoname(ifaddr->ifa_index, ifname)) {
Lorenzo Colittief6454d2016-02-16 21:42:16 +0900366 SLOGD("Unknown ifindex %d in %s", ifaddr->ifa_index, msgtype);
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900367 }
368
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900369 } else if (rta->rta_type == IFA_CACHEINFO) {
370 // Address lifetime information.
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900371 if (maybeLogDuplicateAttribute(cacheinfo, "IFA_CACHEINFO", msgtype))
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900372 continue;
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900373
374 if (RTA_PAYLOAD(rta) < sizeof(*cacheinfo)) {
Mark Salyzyn80f63d42014-05-01 07:47:04 -0700375 SLOGE("Short IFA_CACHEINFO (%zu vs. %zu bytes) in %s",
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900376 RTA_PAYLOAD(rta), sizeof(cacheinfo), msgtype);
377 continue;
378 }
379
380 cacheinfo = (struct ifa_cacheinfo *) RTA_DATA(rta);
Lorenzo Colitti096fc532020-04-26 19:21:12 +0900381
382 } else if (rta->rta_type == IFA_FLAGS) {
Lorenzo Colitti096fc532020-04-26 19:21:12 +0900383 flags = *(uint32_t*)RTA_DATA(rta);
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900384 }
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900385 }
386
387 if (addrstr[0] == '\0') {
388 SLOGE("No IFA_ADDRESS in %s\n", msgtype);
389 return false;
390 }
391
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900392 // Fill in netlink event information.
Jeff Sharkeye4f39402015-03-13 13:27:33 -0700393 mAction = (type == RTM_NEWADDR) ? Action::kAddressUpdated :
394 Action::kAddressRemoved;
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900395 mSubsystem = strdup("net");
Lorenzo Colittief6454d2016-02-16 21:42:16 +0900396 asprintf(&mParams[0], "ADDRESS=%s/%d", addrstr, ifaddr->ifa_prefixlen);
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900397 asprintf(&mParams[1], "INTERFACE=%s", ifname);
Lorenzo Colitti096fc532020-04-26 19:21:12 +0900398 asprintf(&mParams[2], "FLAGS=%u", flags);
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900399 asprintf(&mParams[3], "SCOPE=%u", ifaddr->ifa_scope);
Rubin Xu5f406242018-05-16 23:35:41 +0100400 asprintf(&mParams[4], "IFINDEX=%u", ifaddr->ifa_index);
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900401
402 if (cacheinfo) {
Rubin Xu5f406242018-05-16 23:35:41 +0100403 asprintf(&mParams[5], "PREFERRED=%u", cacheinfo->ifa_prefered);
404 asprintf(&mParams[6], "VALID=%u", cacheinfo->ifa_valid);
405 asprintf(&mParams[7], "CSTAMP=%u", cacheinfo->cstamp);
406 asprintf(&mParams[8], "TSTAMP=%u", cacheinfo->tstamp);
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900407 }
408
409 return true;
410}
411
412/*
413 * Parse a QLOG_NL_EVENT message.
414 */
415bool NetlinkEvent::parseUlogPacketMessage(const struct nlmsghdr *nh) {
Maciej Żenczykowski28b94af2021-10-25 15:24:18 -0700416 const char* alert;
417 const char* devname;
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900418
Maciej Żenczykowski28b94af2021-10-25 15:24:18 -0700419 if (isKernel64Bit()) {
420 ulog_packet_msg64_t* pm64 = (ulog_packet_msg64_t*)NLMSG_DATA(nh);
421 if (!checkRtNetlinkLength(nh, sizeof(*pm64))) return false;
422 alert = pm64->prefix;
423 devname = pm64->indev_name[0] ? pm64->indev_name : pm64->outdev_name;
424 } else {
425 ulog_packet_msg32_t* pm32 = (ulog_packet_msg32_t*)NLMSG_DATA(nh);
426 if (!checkRtNetlinkLength(nh, sizeof(*pm32))) return false;
427 alert = pm32->prefix;
428 devname = pm32->indev_name[0] ? pm32->indev_name : pm32->outdev_name;
429 }
430
431 asprintf(&mParams[0], "ALERT_NAME=%s", alert);
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900432 asprintf(&mParams[1], "INTERFACE=%s", devname);
433 mSubsystem = strdup("qlog");
Jeff Sharkeye4f39402015-03-13 13:27:33 -0700434 mAction = Action::kChange;
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900435 return true;
436}
437
Lorenzo Colittie439ffc2017-10-03 18:44:11 +0900438static size_t nlAttrLen(const nlattr* nla) {
439 return nla->nla_len - NLA_HDRLEN;
440}
441
442static const uint8_t* nlAttrData(const nlattr* nla) {
443 return reinterpret_cast<const uint8_t*>(nla) + NLA_HDRLEN;
444}
445
446static uint32_t nlAttrU32(const nlattr* nla) {
447 return *reinterpret_cast<const uint32_t*>(nlAttrData(nla));
448}
449
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900450/*
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700451 * Parse a LOCAL_NFLOG_PACKET message.
452 */
453bool NetlinkEvent::parseNfPacketMessage(struct nlmsghdr *nh) {
454 int uid = -1;
455 int len = 0;
Yi Kong48885252018-07-24 16:34:27 -0700456 char* raw = nullptr;
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700457
Lorenzo Colittie439ffc2017-10-03 18:44:11 +0900458 struct nlattr* uid_attr = findNlAttr(nh, sizeof(struct genlmsghdr), NFULA_UID);
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700459 if (uid_attr) {
Lorenzo Colittie439ffc2017-10-03 18:44:11 +0900460 uid = ntohl(nlAttrU32(uid_attr));
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700461 }
462
Lorenzo Colittie439ffc2017-10-03 18:44:11 +0900463 struct nlattr* payload = findNlAttr(nh, sizeof(struct genlmsghdr), NFULA_PAYLOAD);
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700464 if (payload) {
465 /* First 256 bytes is plenty */
Lorenzo Colittie439ffc2017-10-03 18:44:11 +0900466 len = nlAttrLen(payload);
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700467 if (len > 256) len = 256;
Lorenzo Colittie439ffc2017-10-03 18:44:11 +0900468 raw = (char*)nlAttrData(payload);
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700469 }
470
Lorenzo Colittid0e49382019-04-10 23:04:41 +0900471 size_t hexSize = 5 + (len * 2);
472 char* hex = (char*)calloc(1, hexSize);
473 strlcpy(hex, "HEX=", hexSize);
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700474 for (int i = 0; i < len; i++) {
475 hex[4 + (i * 2)] = "0123456789abcdef"[(raw[i] >> 4) & 0xf];
476 hex[5 + (i * 2)] = "0123456789abcdef"[raw[i] & 0xf];
477 }
478
479 asprintf(&mParams[0], "UID=%d", uid);
480 mParams[1] = hex;
481 mSubsystem = strdup("strict");
Jeff Sharkeye4f39402015-03-13 13:27:33 -0700482 mAction = Action::kChange;
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700483 return true;
484}
485
486/*
Lorenzo Colittid7ff7ea2014-06-11 17:37:12 +0900487 * Parse a RTM_NEWROUTE or RTM_DELROUTE message.
488 */
489bool NetlinkEvent::parseRtMessage(const struct nlmsghdr *nh) {
490 uint8_t type = nh->nlmsg_type;
491 const char *msgname = rtMessageName(type);
492
Lorenzo Colittid7ff7ea2014-06-11 17:37:12 +0900493 if (type != RTM_NEWROUTE && type != RTM_DELROUTE) {
494 SLOGE("%s: incorrect message type %d (%s)\n", __func__, type, msgname);
495 return false;
496 }
497
498 struct rtmsg *rtm = (struct rtmsg *) NLMSG_DATA(nh);
499 if (!checkRtNetlinkLength(nh, sizeof(*rtm)))
500 return false;
501
502 if (// Ignore static routes we've set up ourselves.
503 (rtm->rtm_protocol != RTPROT_KERNEL &&
504 rtm->rtm_protocol != RTPROT_RA) ||
505 // We're only interested in global unicast routes.
506 (rtm->rtm_scope != RT_SCOPE_UNIVERSE) ||
507 (rtm->rtm_type != RTN_UNICAST) ||
508 // We don't support source routing.
509 (rtm->rtm_src_len != 0) ||
510 // Cloned routes aren't real routes.
511 (rtm->rtm_flags & RTM_F_CLONED)) {
512 return false;
513 }
514
515 int family = rtm->rtm_family;
516 int prefixLength = rtm->rtm_dst_len;
517
518 // Currently we only support: destination, (one) next hop, ifindex.
519 char dst[INET6_ADDRSTRLEN] = "";
520 char gw[INET6_ADDRSTRLEN] = "";
521 char dev[IFNAMSIZ] = "";
522
523 size_t len = RTM_PAYLOAD(nh);
524 struct rtattr *rta;
525 for (rta = RTM_RTA(rtm); RTA_OK(rta, len); rta = RTA_NEXT(rta, len)) {
526 switch (rta->rta_type) {
527 case RTA_DST:
528 if (maybeLogDuplicateAttribute(*dst, "RTA_DST", msgname))
529 continue;
530 if (!inet_ntop(family, RTA_DATA(rta), dst, sizeof(dst)))
531 return false;
532 continue;
533 case RTA_GATEWAY:
534 if (maybeLogDuplicateAttribute(*gw, "RTA_GATEWAY", msgname))
535 continue;
536 if (!inet_ntop(family, RTA_DATA(rta), gw, sizeof(gw)))
537 return false;
538 continue;
539 case RTA_OIF:
540 if (maybeLogDuplicateAttribute(*dev, "RTA_OIF", msgname))
541 continue;
542 if (!if_indextoname(* (int *) RTA_DATA(rta), dev))
543 return false;
Chih-Hung Hsiehe6e2b3c2018-10-10 14:39:02 -0700544 continue;
Lorenzo Colittid7ff7ea2014-06-11 17:37:12 +0900545 default:
546 continue;
547 }
548 }
549
550 // If there's no RTA_DST attribute, then:
551 // - If the prefix length is zero, it's the default route.
552 // - If the prefix length is nonzero, there's something we don't understand.
553 // Ignore the event.
554 if (!*dst && !prefixLength) {
555 if (family == AF_INET) {
556 strncpy(dst, "0.0.0.0", sizeof(dst));
557 } else if (family == AF_INET6) {
558 strncpy(dst, "::", sizeof(dst));
559 }
560 }
561
562 // A useful route must have a destination and at least either a gateway or
563 // an interface.
564 if (!*dst || (!*gw && !*dev))
565 return false;
566
567 // Fill in netlink event information.
Jeff Sharkeye4f39402015-03-13 13:27:33 -0700568 mAction = (type == RTM_NEWROUTE) ? Action::kRouteUpdated :
569 Action::kRouteRemoved;
Lorenzo Colittid7ff7ea2014-06-11 17:37:12 +0900570 mSubsystem = strdup("net");
571 asprintf(&mParams[0], "ROUTE=%s/%d", dst, prefixLength);
572 asprintf(&mParams[1], "GATEWAY=%s", (*gw) ? gw : "");
573 asprintf(&mParams[2], "INTERFACE=%s", (*dev) ? dev : "");
574
575 return true;
576}
577
578/*
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900579 * Parse a RTM_NEWNDUSEROPT message.
580 */
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900581bool NetlinkEvent::parseNdUserOptMessage(const struct nlmsghdr *nh) {
582 struct nduseroptmsg *msg = (struct nduseroptmsg *) NLMSG_DATA(nh);
583 if (!checkRtNetlinkLength(nh, sizeof(*msg)))
584 return false;
585
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900586 // Check the length is valid.
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900587 int len = NLMSG_PAYLOAD(nh, sizeof(*msg));
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900588 if (msg->nduseropt_opts_len > len) {
589 SLOGE("RTM_NEWNDUSEROPT invalid length %d > %d\n",
590 msg->nduseropt_opts_len, len);
591 return false;
592 }
593 len = msg->nduseropt_opts_len;
594
595 // Check address family and packet type.
596 if (msg->nduseropt_family != AF_INET6) {
597 SLOGE("RTM_NEWNDUSEROPT message for unknown family %d\n",
598 msg->nduseropt_family);
599 return false;
600 }
601
602 if (msg->nduseropt_icmp_type != ND_ROUTER_ADVERT ||
603 msg->nduseropt_icmp_code != 0) {
604 SLOGE("RTM_NEWNDUSEROPT message for unknown ICMPv6 type/code %d/%d\n",
605 msg->nduseropt_icmp_type, msg->nduseropt_icmp_code);
606 return false;
607 }
608
609 // Find the interface name.
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900610 char ifname[IFNAMSIZ];
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900611 if (!if_indextoname(msg->nduseropt_ifindex, ifname)) {
612 SLOGE("RTM_NEWNDUSEROPT on unknown ifindex %d\n",
613 msg->nduseropt_ifindex);
614 return false;
615 }
616
617 // The kernel sends a separate netlink message for each ND option in the RA.
618 // So only parse the first ND option in the message.
619 struct nd_opt_hdr *opthdr = (struct nd_opt_hdr *) (msg + 1);
620
621 // The length is in multiples of 8 octets.
622 uint16_t optlen = opthdr->nd_opt_len;
623 if (optlen * 8 > len) {
624 SLOGE("Invalid option length %d > %d for ND option %d\n",
625 optlen * 8, len, opthdr->nd_opt_type);
626 return false;
627 }
628
629 if (opthdr->nd_opt_type == ND_OPT_RDNSS) {
630 // DNS Servers (RFC 6106).
631 // Each address takes up 2*8 octets, and the header takes up 8 octets.
632 // So for a valid option with one or more addresses, optlen must be
633 // odd and greater than 1.
634 if ((optlen < 3) || !(optlen & 0x1)) {
635 SLOGE("Invalid optlen %d for RDNSS option\n", optlen);
636 return false;
637 }
Erik Klineba48ff72015-06-17 15:53:29 +0900638 const int numaddrs = (optlen - 1) / 2;
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900639
640 // Find the lifetime.
641 struct nd_opt_rdnss *rndss_opt = (struct nd_opt_rdnss *) opthdr;
Erik Klineba48ff72015-06-17 15:53:29 +0900642 const uint32_t lifetime = ntohl(rndss_opt->nd_opt_rdnss_lifetime);
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900643
Lorenzo Colittid0e49382019-04-10 23:04:41 +0900644 // Construct a comma-separated string of DNS addresses.
Erik Klineba48ff72015-06-17 15:53:29 +0900645 // Reserve sufficient space for an IPv6 link-local address: all but the
646 // last address are followed by ','; the last is followed by '\0'.
Erik Klinecc451782015-07-28 17:31:19 +0900647 static const size_t kMaxSingleAddressLength =
Erik Klineba48ff72015-06-17 15:53:29 +0900648 INET6_ADDRSTRLEN + strlen("%") + IFNAMSIZ + strlen(",");
Lorenzo Colittid0e49382019-04-10 23:04:41 +0900649 const size_t bufsize = numaddrs * kMaxSingleAddressLength;
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900650 char *buf = (char *) malloc(bufsize);
651 if (!buf) {
652 SLOGE("RDNSS option: out of memory\n");
653 return false;
654 }
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900655
656 struct in6_addr *addrs = (struct in6_addr *) (rndss_opt + 1);
Lorenzo Colittid0e49382019-04-10 23:04:41 +0900657 size_t pos = 0;
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900658 for (int i = 0; i < numaddrs; i++) {
659 if (i > 0) {
660 buf[pos++] = ',';
661 }
662 inet_ntop(AF_INET6, addrs + i, buf + pos, bufsize - pos);
663 pos += strlen(buf + pos);
Erik Klineba48ff72015-06-17 15:53:29 +0900664 if (IN6_IS_ADDR_LINKLOCAL(addrs + i)) {
665 buf[pos++] = '%';
666 pos += strlcpy(buf + pos, ifname, bufsize - pos);
667 }
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900668 }
669 buf[pos] = '\0';
670
Jeff Sharkeye4f39402015-03-13 13:27:33 -0700671 mAction = Action::kRdnss;
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900672 mSubsystem = strdup("net");
673 asprintf(&mParams[0], "INTERFACE=%s", ifname);
674 asprintf(&mParams[1], "LIFETIME=%u", lifetime);
Lorenzo Colittid0e49382019-04-10 23:04:41 +0900675 asprintf(&mParams[2], "SERVERS=%s", buf);
676 free(buf);
Lorenzo Colitticbfd65d2017-11-28 15:32:40 +0900677 } else if (opthdr->nd_opt_type == ND_OPT_DNSSL) {
678 // TODO: support DNSSL.
Maciej Żenczykowskia806a712020-03-31 19:55:06 -0700679 } else if (opthdr->nd_opt_type == ND_OPT_CAPTIVE_PORTAL) {
680 // TODO: support CAPTIVE PORTAL.
681 } else if (opthdr->nd_opt_type == ND_OPT_PREF64) {
682 // TODO: support PREF64.
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900683 } else {
684 SLOGD("Unknown ND option type %d\n", opthdr->nd_opt_type);
685 return false;
686 }
687
688 return true;
689}
690
691/*
692 * Parse a binary message from a NETLINK_ROUTE netlink socket.
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900693 *
694 * Note that this function can only parse one message, because the message's
695 * content has to be stored in the class's member variables (mAction,
696 * mSubsystem, etc.). Invalid or unrecognized messages are skipped, but if
697 * there are multiple valid messages in the buffer, only the first one will be
698 * returned.
699 *
700 * TODO: consider only ever looking at the first message.
Mike J. Chenec16b9d2011-06-23 14:55:28 -0700701 */
702bool NetlinkEvent::parseBinaryNetlinkMessage(char *buffer, int size) {
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700703 struct nlmsghdr *nh;
Mike J. Chenec16b9d2011-06-23 14:55:28 -0700704
Lorenzo Colitti96834562013-08-17 03:40:31 +0900705 for (nh = (struct nlmsghdr *) buffer;
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900706 NLMSG_OK(nh, (unsigned) size) && (nh->nlmsg_type != NLMSG_DONE);
Lorenzo Colitti96834562013-08-17 03:40:31 +0900707 nh = NLMSG_NEXT(nh, size)) {
JP Abgralle6f80142011-07-14 16:46:32 -0700708
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900709 if (!rtMessageName(nh->nlmsg_type)) {
710 SLOGD("Unexpected netlink message type %d\n", nh->nlmsg_type);
711 continue;
712 }
713
Mike J. Chenec16b9d2011-06-23 14:55:28 -0700714 if (nh->nlmsg_type == RTM_NEWLINK) {
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900715 if (parseIfInfoMessage(nh))
716 return true;
JP Abgralle6f80142011-07-14 16:46:32 -0700717
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700718 } else if (nh->nlmsg_type == LOCAL_QLOG_NL_EVENT) {
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900719 if (parseUlogPacketMessage(nh))
720 return true;
JP Abgralle6f80142011-07-14 16:46:32 -0700721
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900722 } else if (nh->nlmsg_type == RTM_NEWADDR ||
723 nh->nlmsg_type == RTM_DELADDR) {
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900724 if (parseIfAddrMessage(nh))
725 return true;
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900726
Lorenzo Colittid7ff7ea2014-06-11 17:37:12 +0900727 } else if (nh->nlmsg_type == RTM_NEWROUTE ||
728 nh->nlmsg_type == RTM_DELROUTE) {
729 if (parseRtMessage(nh))
730 return true;
731
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900732 } else if (nh->nlmsg_type == RTM_NEWNDUSEROPT) {
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900733 if (parseNdUserOptMessage(nh))
734 return true;
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900735
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700736 } else if (nh->nlmsg_type == LOCAL_NFLOG_PACKET) {
737 if (parseNfPacketMessage(nh))
738 return true;
739
JP Abgralle6f80142011-07-14 16:46:32 -0700740 }
Mike J. Chenec16b9d2011-06-23 14:55:28 -0700741 }
742
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900743 return false;
Mike J. Chenec16b9d2011-06-23 14:55:28 -0700744}
745
David 'Digit' Turner3311eea2011-01-17 01:59:22 +0100746/* If the string between 'str' and 'end' begins with 'prefixlen' characters
747 * from the 'prefix' array, then return 'str + prefixlen', otherwise return
748 * NULL.
749 */
750static const char*
751has_prefix(const char* str, const char* end, const char* prefix, size_t prefixlen)
752{
Yunlian Jiang33f67172017-02-07 15:39:25 -0800753 if ((end - str) >= (ptrdiff_t)prefixlen &&
754 (prefixlen == 0 || !memcmp(str, prefix, prefixlen))) {
David 'Digit' Turner3311eea2011-01-17 01:59:22 +0100755 return str + prefixlen;
Yunlian Jiang33f67172017-02-07 15:39:25 -0800756 } else {
Yi Kong48885252018-07-24 16:34:27 -0700757 return nullptr;
Yunlian Jiang33f67172017-02-07 15:39:25 -0800758 }
David 'Digit' Turner3311eea2011-01-17 01:59:22 +0100759}
760
761/* Same as strlen(x) for constant string literals ONLY */
762#define CONST_STRLEN(x) (sizeof(x)-1)
763
764/* Convenience macro to call has_prefix with a constant string literal */
765#define HAS_CONST_PREFIX(str,end,prefix) has_prefix((str),(end),prefix,CONST_STRLEN(prefix))
766
767
Mike J. Chenec16b9d2011-06-23 14:55:28 -0700768/*
769 * Parse an ASCII-formatted message from a NETLINK_KOBJECT_UEVENT
770 * netlink socket.
771 */
772bool NetlinkEvent::parseAsciiNetlinkMessage(char *buffer, int size) {
Mike J. Chen17260b12011-06-23 15:00:30 -0700773 const char *s = buffer;
774 const char *end;
San Mehat168415b2009-05-06 11:14:21 -0700775 int param_idx = 0;
San Mehat168415b2009-05-06 11:14:21 -0700776 int first = 1;
777
David 'Digit' Turner3311eea2011-01-17 01:59:22 +0100778 if (size == 0)
779 return false;
780
781 /* Ensure the buffer is zero-terminated, the code below depends on this */
782 buffer[size-1] = '\0';
783
San Mehat168415b2009-05-06 11:14:21 -0700784 end = s + size;
785 while (s < end) {
786 if (first) {
David 'Digit' Turner3311eea2011-01-17 01:59:22 +0100787 const char *p;
788 /* buffer is 0-terminated, no need to check p < end */
789 for (p = s; *p != '@'; p++) {
790 if (!*p) { /* no '@', should not happen */
791 return false;
792 }
793 }
794 mPath = strdup(p+1);
San Mehat168415b2009-05-06 11:14:21 -0700795 first = 0;
796 } else {
David 'Digit' Turner3311eea2011-01-17 01:59:22 +0100797 const char* a;
Yi Kong48885252018-07-24 16:34:27 -0700798 if ((a = HAS_CONST_PREFIX(s, end, "ACTION=")) != nullptr) {
San Mehat168415b2009-05-06 11:14:21 -0700799 if (!strcmp(a, "add"))
Jeff Sharkeye4f39402015-03-13 13:27:33 -0700800 mAction = Action::kAdd;
San Mehat168415b2009-05-06 11:14:21 -0700801 else if (!strcmp(a, "remove"))
Jeff Sharkeye4f39402015-03-13 13:27:33 -0700802 mAction = Action::kRemove;
San Mehat168415b2009-05-06 11:14:21 -0700803 else if (!strcmp(a, "change"))
Jeff Sharkeye4f39402015-03-13 13:27:33 -0700804 mAction = Action::kChange;
Yi Kong48885252018-07-24 16:34:27 -0700805 } else if ((a = HAS_CONST_PREFIX(s, end, "SEQNUM=")) != nullptr) {
Lorenzo Colittid0e49382019-04-10 23:04:41 +0900806 if (!ParseInt(a, &mSeq)) {
807 SLOGE("NetlinkEvent::parseAsciiNetlinkMessage: failed to parse SEQNUM=%s", a);
808 }
Yi Kong48885252018-07-24 16:34:27 -0700809 } else if ((a = HAS_CONST_PREFIX(s, end, "SUBSYSTEM=")) != nullptr) {
David 'Digit' Turner3311eea2011-01-17 01:59:22 +0100810 mSubsystem = strdup(a);
811 } else if (param_idx < NL_PARAMS_MAX) {
San Mehat168415b2009-05-06 11:14:21 -0700812 mParams[param_idx++] = strdup(s);
David 'Digit' Turner3311eea2011-01-17 01:59:22 +0100813 }
San Mehat168415b2009-05-06 11:14:21 -0700814 }
David 'Digit' Turner3311eea2011-01-17 01:59:22 +0100815 s += strlen(s) + 1;
San Mehat168415b2009-05-06 11:14:21 -0700816 }
817 return true;
818}
819
Mike J. Chenec16b9d2011-06-23 14:55:28 -0700820bool NetlinkEvent::decode(char *buffer, int size, int format) {
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700821 if (format == NetlinkListener::NETLINK_FORMAT_BINARY
822 || format == NetlinkListener::NETLINK_FORMAT_BINARY_UNICAST) {
Mike J. Chen17260b12011-06-23 15:00:30 -0700823 return parseBinaryNetlinkMessage(buffer, size);
824 } else {
825 return parseAsciiNetlinkMessage(buffer, size);
826 }
Mike J. Chenec16b9d2011-06-23 14:55:28 -0700827}
828
San Mehat168415b2009-05-06 11:14:21 -0700829const char *NetlinkEvent::findParam(const char *paramName) {
Chih-Wei Huang80ec37a2010-07-14 14:00:41 +0800830 size_t len = strlen(paramName);
Yi Kong48885252018-07-24 16:34:27 -0700831 for (int i = 0; i < NL_PARAMS_MAX && mParams[i] != nullptr; ++i) {
Chih-Wei Huang80ec37a2010-07-14 14:00:41 +0800832 const char *ptr = mParams[i] + len;
833 if (!strncmp(mParams[i], paramName, len) && *ptr == '=')
834 return ++ptr;
San Mehat168415b2009-05-06 11:14:21 -0700835 }
836
San Mehat7e8529a2010-03-25 09:31:42 -0700837 SLOGE("NetlinkEvent::FindParam(): Parameter '%s' not found", paramName);
Yi Kong48885252018-07-24 16:34:27 -0700838 return nullptr;
San Mehat168415b2009-05-06 11:14:21 -0700839}
Lorenzo Colittie439ffc2017-10-03 18:44:11 +0900840
841nlattr* NetlinkEvent::findNlAttr(const nlmsghdr* nh, size_t hdrlen, uint16_t attr) {
842 if (nh == nullptr || NLMSG_HDRLEN + NLMSG_ALIGN(hdrlen) > SSIZE_MAX) {
843 return nullptr;
844 }
845
846 // Skip header, padding, and family header.
847 const ssize_t NLA_START = NLMSG_HDRLEN + NLMSG_ALIGN(hdrlen);
848 ssize_t left = nh->nlmsg_len - NLA_START;
849 uint8_t* hdr = ((uint8_t*)nh) + NLA_START;
850
851 while (left >= NLA_HDRLEN) {
852 nlattr* nla = (nlattr*)hdr;
853 if (nla->nla_type == attr) {
854 return nla;
855 }
856
857 hdr += NLA_ALIGN(nla->nla_len);
858 left -= NLA_ALIGN(nla->nla_len);
859 }
860
861 return nullptr;
862}