1 /*
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 */
16
17 #define LOG_TAG "NetlinkEvent"
18
19 #include <arpa/inet.h>
20 #include <limits.h>
21 #include <linux/genetlink.h>
22 #include <linux/if.h>
23 #include <linux/if_addr.h>
24 #include <linux/if_link.h>
25 #include <linux/netfilter/nfnetlink.h>
26 #include <linux/netfilter/nfnetlink_log.h>
27 #include <linux/netlink.h>
28 #include <linux/rtnetlink.h>
29 #include <net/if.h>
30 #include <netinet/icmp6.h>
31 #include <netinet/in.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <sys/socket.h>
35 #include <sys/types.h>
36
37 /* From kernel's net/netfilter/xt_quota2.c */
38 const int LOCAL_QLOG_NL_EVENT = 112;
39 const int LOCAL_NFLOG_PACKET = NFNL_SUBSYS_ULOG << 8 | NFULNL_MSG_PACKET;
40
41 /* From deprecated ipt_ULOG.h to parse QLOG_NL_EVENT. */
42 #define ULOG_MAC_LEN 80
43 #define ULOG_PREFIX_LEN 32
44 typedef struct ulog_packet_msg {
45 unsigned long mark;
46 long timestamp_sec;
47 long timestamp_usec;
48 unsigned int hook;
49 char indev_name[IFNAMSIZ];
50 char outdev_name[IFNAMSIZ];
51 size_t data_len;
52 char prefix[ULOG_PREFIX_LEN];
53 unsigned char mac_len;
54 unsigned char mac[ULOG_MAC_LEN];
55 unsigned char payload[0];
56 } ulog_packet_msg_t;
57
58 #include <android-base/parseint.h>
59 #include <log/log.h>
60 #include <sysutils/NetlinkEvent.h>
61
62 using android::base::ParseInt;
63
NetlinkEvent()64 NetlinkEvent::NetlinkEvent() {
65 mAction = Action::kUnknown;
66 memset(mParams, 0, sizeof(mParams));
67 mPath = nullptr;
68 mSubsystem = nullptr;
69 }
70
~NetlinkEvent()71 NetlinkEvent::~NetlinkEvent() {
72 int i;
73 if (mPath)
74 free(mPath);
75 if (mSubsystem)
76 free(mSubsystem);
77 for (i = 0; i < NL_PARAMS_MAX; i++) {
78 if (!mParams[i])
79 break;
80 free(mParams[i]);
81 }
82 }
83
dump()84 void NetlinkEvent::dump() {
85 int i;
86
87 for (i = 0; i < NL_PARAMS_MAX; i++) {
88 if (!mParams[i])
89 break;
90 SLOGD("NL param '%s'\n", mParams[i]);
91 }
92 }
93
94 /*
95 * Returns the message name for a message in the NETLINK_ROUTE family, or NULL
96 * if parsing that message is not supported.
97 */
rtMessageName(int type)98 static const char *rtMessageName(int type) {
99 #define NL_EVENT_RTM_NAME(rtm) case rtm: return #rtm;
100 switch (type) {
101 NL_EVENT_RTM_NAME(RTM_NEWLINK);
102 NL_EVENT_RTM_NAME(RTM_DELLINK);
103 NL_EVENT_RTM_NAME(RTM_NEWADDR);
104 NL_EVENT_RTM_NAME(RTM_DELADDR);
105 NL_EVENT_RTM_NAME(RTM_NEWROUTE);
106 NL_EVENT_RTM_NAME(RTM_DELROUTE);
107 NL_EVENT_RTM_NAME(RTM_NEWNDUSEROPT);
108 NL_EVENT_RTM_NAME(LOCAL_QLOG_NL_EVENT);
109 NL_EVENT_RTM_NAME(LOCAL_NFLOG_PACKET);
110 default:
111 return nullptr;
112 }
113 #undef NL_EVENT_RTM_NAME
114 }
115
116 /*
117 * Checks that a binary NETLINK_ROUTE message is long enough for a payload of
118 * size bytes.
119 */
checkRtNetlinkLength(const struct nlmsghdr * nh,size_t size)120 static bool checkRtNetlinkLength(const struct nlmsghdr *nh, size_t size) {
121 if (nh->nlmsg_len < NLMSG_LENGTH(size)) {
122 SLOGE("Got a short %s message\n", rtMessageName(nh->nlmsg_type));
123 return false;
124 }
125 return true;
126 }
127
128 /*
129 * Utility function to log errors.
130 */
maybeLogDuplicateAttribute(bool isDup,const char * attributeName,const char * messageName)131 static bool maybeLogDuplicateAttribute(bool isDup,
132 const char *attributeName,
133 const char *messageName) {
134 if (isDup) {
135 SLOGE("Multiple %s attributes in %s, ignoring\n", attributeName, messageName);
136 return true;
137 }
138 return false;
139 }
140
141 /*
142 * Parse a RTM_NEWLINK message.
143 */
parseIfInfoMessage(const struct nlmsghdr * nh)144 bool NetlinkEvent::parseIfInfoMessage(const struct nlmsghdr *nh) {
145 struct ifinfomsg *ifi = (struct ifinfomsg *) NLMSG_DATA(nh);
146 if (!checkRtNetlinkLength(nh, sizeof(*ifi)))
147 return false;
148
149 if ((ifi->ifi_flags & IFF_LOOPBACK) != 0) {
150 return false;
151 }
152
153 int len = IFLA_PAYLOAD(nh);
154 struct rtattr *rta;
155 for (rta = IFLA_RTA(ifi); RTA_OK(rta, len); rta = RTA_NEXT(rta, len)) {
156 switch(rta->rta_type) {
157 case IFLA_IFNAME:
158 asprintf(&mParams[0], "INTERFACE=%s", (char *) RTA_DATA(rta));
159 // We can get the interface change information from sysfs update
160 // already. But in case we missed those message when devices start.
161 // We do a update again when received a kLinkUp event. To make
162 // the message consistent, use IFINDEX here as well since sysfs
163 // uses IFINDEX.
164 asprintf(&mParams[1], "IFINDEX=%d", ifi->ifi_index);
165 mAction = (ifi->ifi_flags & IFF_LOWER_UP) ? Action::kLinkUp :
166 Action::kLinkDown;
167 mSubsystem = strdup("net");
168 return true;
169 }
170 }
171
172 return false;
173 }
174
175 /*
176 * Parse a RTM_NEWADDR or RTM_DELADDR message.
177 */
parseIfAddrMessage(const struct nlmsghdr * nh)178 bool NetlinkEvent::parseIfAddrMessage(const struct nlmsghdr *nh) {
179 struct ifaddrmsg *ifaddr = (struct ifaddrmsg *) NLMSG_DATA(nh);
180 struct ifa_cacheinfo *cacheinfo = nullptr;
181 char addrstr[INET6_ADDRSTRLEN] = "";
182 char ifname[IFNAMSIZ] = "";
183 uint32_t flags;
184
185 if (!checkRtNetlinkLength(nh, sizeof(*ifaddr)))
186 return false;
187
188 // Sanity check.
189 int type = nh->nlmsg_type;
190 if (type != RTM_NEWADDR && type != RTM_DELADDR) {
191 SLOGE("parseIfAddrMessage on incorrect message type 0x%x\n", type);
192 return false;
193 }
194
195 // For log messages.
196 const char *msgtype = rtMessageName(type);
197
198 // First 8 bits of flags. In practice will always be overridden when parsing IFA_FLAGS below.
199 flags = ifaddr->ifa_flags;
200
201 struct rtattr *rta;
202 int len = IFA_PAYLOAD(nh);
203 for (rta = IFA_RTA(ifaddr); RTA_OK(rta, len); rta = RTA_NEXT(rta, len)) {
204 if (rta->rta_type == IFA_ADDRESS) {
205 // Only look at the first address, because we only support notifying
206 // one change at a time.
207 if (maybeLogDuplicateAttribute(*addrstr != '\0', "IFA_ADDRESS", msgtype))
208 continue;
209
210 // Convert the IP address to a string.
211 if (ifaddr->ifa_family == AF_INET) {
212 struct in_addr *addr4 = (struct in_addr *) RTA_DATA(rta);
213 if (RTA_PAYLOAD(rta) < sizeof(*addr4)) {
214 SLOGE("Short IPv4 address (%zu bytes) in %s",
215 RTA_PAYLOAD(rta), msgtype);
216 continue;
217 }
218 inet_ntop(AF_INET, addr4, addrstr, sizeof(addrstr));
219 } else if (ifaddr->ifa_family == AF_INET6) {
220 struct in6_addr *addr6 = (struct in6_addr *) RTA_DATA(rta);
221 if (RTA_PAYLOAD(rta) < sizeof(*addr6)) {
222 SLOGE("Short IPv6 address (%zu bytes) in %s",
223 RTA_PAYLOAD(rta), msgtype);
224 continue;
225 }
226 inet_ntop(AF_INET6, addr6, addrstr, sizeof(addrstr));
227 } else {
228 SLOGE("Unknown address family %d\n", ifaddr->ifa_family);
229 continue;
230 }
231
232 // Find the interface name.
233 if (!if_indextoname(ifaddr->ifa_index, ifname)) {
234 SLOGD("Unknown ifindex %d in %s", ifaddr->ifa_index, msgtype);
235 }
236
237 } else if (rta->rta_type == IFA_CACHEINFO) {
238 // Address lifetime information.
239 if (maybeLogDuplicateAttribute(cacheinfo, "IFA_CACHEINFO", msgtype))
240 continue;
241
242 if (RTA_PAYLOAD(rta) < sizeof(*cacheinfo)) {
243 SLOGE("Short IFA_CACHEINFO (%zu vs. %zu bytes) in %s",
244 RTA_PAYLOAD(rta), sizeof(cacheinfo), msgtype);
245 continue;
246 }
247
248 cacheinfo = (struct ifa_cacheinfo *) RTA_DATA(rta);
249
250 } else if (rta->rta_type == IFA_FLAGS) {
251 flags = *(uint32_t*)RTA_DATA(rta);
252 }
253 }
254
255 if (addrstr[0] == '\0') {
256 SLOGE("No IFA_ADDRESS in %s\n", msgtype);
257 return false;
258 }
259
260 // Fill in netlink event information.
261 mAction = (type == RTM_NEWADDR) ? Action::kAddressUpdated :
262 Action::kAddressRemoved;
263 mSubsystem = strdup("net");
264 asprintf(&mParams[0], "ADDRESS=%s/%d", addrstr, ifaddr->ifa_prefixlen);
265 asprintf(&mParams[1], "INTERFACE=%s", ifname);
266 asprintf(&mParams[2], "FLAGS=%u", flags);
267 asprintf(&mParams[3], "SCOPE=%u", ifaddr->ifa_scope);
268 asprintf(&mParams[4], "IFINDEX=%u", ifaddr->ifa_index);
269
270 if (cacheinfo) {
271 asprintf(&mParams[5], "PREFERRED=%u", cacheinfo->ifa_prefered);
272 asprintf(&mParams[6], "VALID=%u", cacheinfo->ifa_valid);
273 asprintf(&mParams[7], "CSTAMP=%u", cacheinfo->cstamp);
274 asprintf(&mParams[8], "TSTAMP=%u", cacheinfo->tstamp);
275 }
276
277 return true;
278 }
279
280 /*
281 * Parse a QLOG_NL_EVENT message.
282 */
parseUlogPacketMessage(const struct nlmsghdr * nh)283 bool NetlinkEvent::parseUlogPacketMessage(const struct nlmsghdr *nh) {
284 const char *devname;
285 ulog_packet_msg_t *pm = (ulog_packet_msg_t *) NLMSG_DATA(nh);
286 if (!checkRtNetlinkLength(nh, sizeof(*pm)))
287 return false;
288
289 devname = pm->indev_name[0] ? pm->indev_name : pm->outdev_name;
290 asprintf(&mParams[0], "ALERT_NAME=%s", pm->prefix);
291 asprintf(&mParams[1], "INTERFACE=%s", devname);
292 mSubsystem = strdup("qlog");
293 mAction = Action::kChange;
294 return true;
295 }
296
nlAttrLen(const nlattr * nla)297 static size_t nlAttrLen(const nlattr* nla) {
298 return nla->nla_len - NLA_HDRLEN;
299 }
300
nlAttrData(const nlattr * nla)301 static const uint8_t* nlAttrData(const nlattr* nla) {
302 return reinterpret_cast<const uint8_t*>(nla) + NLA_HDRLEN;
303 }
304
nlAttrU32(const nlattr * nla)305 static uint32_t nlAttrU32(const nlattr* nla) {
306 return *reinterpret_cast<const uint32_t*>(nlAttrData(nla));
307 }
308
309 /*
310 * Parse a LOCAL_NFLOG_PACKET message.
311 */
parseNfPacketMessage(struct nlmsghdr * nh)312 bool NetlinkEvent::parseNfPacketMessage(struct nlmsghdr *nh) {
313 int uid = -1;
314 int len = 0;
315 char* raw = nullptr;
316
317 struct nlattr* uid_attr = findNlAttr(nh, sizeof(struct genlmsghdr), NFULA_UID);
318 if (uid_attr) {
319 uid = ntohl(nlAttrU32(uid_attr));
320 }
321
322 struct nlattr* payload = findNlAttr(nh, sizeof(struct genlmsghdr), NFULA_PAYLOAD);
323 if (payload) {
324 /* First 256 bytes is plenty */
325 len = nlAttrLen(payload);
326 if (len > 256) len = 256;
327 raw = (char*)nlAttrData(payload);
328 }
329
330 size_t hexSize = 5 + (len * 2);
331 char* hex = (char*)calloc(1, hexSize);
332 strlcpy(hex, "HEX=", hexSize);
333 for (int i = 0; i < len; i++) {
334 hex[4 + (i * 2)] = "0123456789abcdef"[(raw[i] >> 4) & 0xf];
335 hex[5 + (i * 2)] = "0123456789abcdef"[raw[i] & 0xf];
336 }
337
338 asprintf(&mParams[0], "UID=%d", uid);
339 mParams[1] = hex;
340 mSubsystem = strdup("strict");
341 mAction = Action::kChange;
342 return true;
343 }
344
345 /*
346 * Parse a RTM_NEWROUTE or RTM_DELROUTE message.
347 */
parseRtMessage(const struct nlmsghdr * nh)348 bool NetlinkEvent::parseRtMessage(const struct nlmsghdr *nh) {
349 uint8_t type = nh->nlmsg_type;
350 const char *msgname = rtMessageName(type);
351
352 // Sanity check.
353 if (type != RTM_NEWROUTE && type != RTM_DELROUTE) {
354 SLOGE("%s: incorrect message type %d (%s)\n", __func__, type, msgname);
355 return false;
356 }
357
358 struct rtmsg *rtm = (struct rtmsg *) NLMSG_DATA(nh);
359 if (!checkRtNetlinkLength(nh, sizeof(*rtm)))
360 return false;
361
362 if (// Ignore static routes we've set up ourselves.
363 (rtm->rtm_protocol != RTPROT_KERNEL &&
364 rtm->rtm_protocol != RTPROT_RA) ||
365 // We're only interested in global unicast routes.
366 (rtm->rtm_scope != RT_SCOPE_UNIVERSE) ||
367 (rtm->rtm_type != RTN_UNICAST) ||
368 // We don't support source routing.
369 (rtm->rtm_src_len != 0) ||
370 // Cloned routes aren't real routes.
371 (rtm->rtm_flags & RTM_F_CLONED)) {
372 return false;
373 }
374
375 int family = rtm->rtm_family;
376 int prefixLength = rtm->rtm_dst_len;
377
378 // Currently we only support: destination, (one) next hop, ifindex.
379 char dst[INET6_ADDRSTRLEN] = "";
380 char gw[INET6_ADDRSTRLEN] = "";
381 char dev[IFNAMSIZ] = "";
382
383 size_t len = RTM_PAYLOAD(nh);
384 struct rtattr *rta;
385 for (rta = RTM_RTA(rtm); RTA_OK(rta, len); rta = RTA_NEXT(rta, len)) {
386 switch (rta->rta_type) {
387 case RTA_DST:
388 if (maybeLogDuplicateAttribute(*dst, "RTA_DST", msgname))
389 continue;
390 if (!inet_ntop(family, RTA_DATA(rta), dst, sizeof(dst)))
391 return false;
392 continue;
393 case RTA_GATEWAY:
394 if (maybeLogDuplicateAttribute(*gw, "RTA_GATEWAY", msgname))
395 continue;
396 if (!inet_ntop(family, RTA_DATA(rta), gw, sizeof(gw)))
397 return false;
398 continue;
399 case RTA_OIF:
400 if (maybeLogDuplicateAttribute(*dev, "RTA_OIF", msgname))
401 continue;
402 if (!if_indextoname(* (int *) RTA_DATA(rta), dev))
403 return false;
404 continue;
405 default:
406 continue;
407 }
408 }
409
410 // If there's no RTA_DST attribute, then:
411 // - If the prefix length is zero, it's the default route.
412 // - If the prefix length is nonzero, there's something we don't understand.
413 // Ignore the event.
414 if (!*dst && !prefixLength) {
415 if (family == AF_INET) {
416 strncpy(dst, "0.0.0.0", sizeof(dst));
417 } else if (family == AF_INET6) {
418 strncpy(dst, "::", sizeof(dst));
419 }
420 }
421
422 // A useful route must have a destination and at least either a gateway or
423 // an interface.
424 if (!*dst || (!*gw && !*dev))
425 return false;
426
427 // Fill in netlink event information.
428 mAction = (type == RTM_NEWROUTE) ? Action::kRouteUpdated :
429 Action::kRouteRemoved;
430 mSubsystem = strdup("net");
431 asprintf(&mParams[0], "ROUTE=%s/%d", dst, prefixLength);
432 asprintf(&mParams[1], "GATEWAY=%s", (*gw) ? gw : "");
433 asprintf(&mParams[2], "INTERFACE=%s", (*dev) ? dev : "");
434
435 return true;
436 }
437
438 /*
439 * Parse a RTM_NEWNDUSEROPT message.
440 */
parseNdUserOptMessage(const struct nlmsghdr * nh)441 bool NetlinkEvent::parseNdUserOptMessage(const struct nlmsghdr *nh) {
442 struct nduseroptmsg *msg = (struct nduseroptmsg *) NLMSG_DATA(nh);
443 if (!checkRtNetlinkLength(nh, sizeof(*msg)))
444 return false;
445
446 // Check the length is valid.
447 int len = NLMSG_PAYLOAD(nh, sizeof(*msg));
448 if (msg->nduseropt_opts_len > len) {
449 SLOGE("RTM_NEWNDUSEROPT invalid length %d > %d\n",
450 msg->nduseropt_opts_len, len);
451 return false;
452 }
453 len = msg->nduseropt_opts_len;
454
455 // Check address family and packet type.
456 if (msg->nduseropt_family != AF_INET6) {
457 SLOGE("RTM_NEWNDUSEROPT message for unknown family %d\n",
458 msg->nduseropt_family);
459 return false;
460 }
461
462 if (msg->nduseropt_icmp_type != ND_ROUTER_ADVERT ||
463 msg->nduseropt_icmp_code != 0) {
464 SLOGE("RTM_NEWNDUSEROPT message for unknown ICMPv6 type/code %d/%d\n",
465 msg->nduseropt_icmp_type, msg->nduseropt_icmp_code);
466 return false;
467 }
468
469 // Find the interface name.
470 char ifname[IFNAMSIZ];
471 if (!if_indextoname(msg->nduseropt_ifindex, ifname)) {
472 SLOGE("RTM_NEWNDUSEROPT on unknown ifindex %d\n",
473 msg->nduseropt_ifindex);
474 return false;
475 }
476
477 // The kernel sends a separate netlink message for each ND option in the RA.
478 // So only parse the first ND option in the message.
479 struct nd_opt_hdr *opthdr = (struct nd_opt_hdr *) (msg + 1);
480
481 // The length is in multiples of 8 octets.
482 uint16_t optlen = opthdr->nd_opt_len;
483 if (optlen * 8 > len) {
484 SLOGE("Invalid option length %d > %d for ND option %d\n",
485 optlen * 8, len, opthdr->nd_opt_type);
486 return false;
487 }
488
489 if (opthdr->nd_opt_type == ND_OPT_RDNSS) {
490 // DNS Servers (RFC 6106).
491 // Each address takes up 2*8 octets, and the header takes up 8 octets.
492 // So for a valid option with one or more addresses, optlen must be
493 // odd and greater than 1.
494 if ((optlen < 3) || !(optlen & 0x1)) {
495 SLOGE("Invalid optlen %d for RDNSS option\n", optlen);
496 return false;
497 }
498 const int numaddrs = (optlen - 1) / 2;
499
500 // Find the lifetime.
501 struct nd_opt_rdnss *rndss_opt = (struct nd_opt_rdnss *) opthdr;
502 const uint32_t lifetime = ntohl(rndss_opt->nd_opt_rdnss_lifetime);
503
504 // Construct a comma-separated string of DNS addresses.
505 // Reserve sufficient space for an IPv6 link-local address: all but the
506 // last address are followed by ','; the last is followed by '\0'.
507 static const size_t kMaxSingleAddressLength =
508 INET6_ADDRSTRLEN + strlen("%") + IFNAMSIZ + strlen(",");
509 const size_t bufsize = numaddrs * kMaxSingleAddressLength;
510 char *buf = (char *) malloc(bufsize);
511 if (!buf) {
512 SLOGE("RDNSS option: out of memory\n");
513 return false;
514 }
515
516 struct in6_addr *addrs = (struct in6_addr *) (rndss_opt + 1);
517 size_t pos = 0;
518 for (int i = 0; i < numaddrs; i++) {
519 if (i > 0) {
520 buf[pos++] = ',';
521 }
522 inet_ntop(AF_INET6, addrs + i, buf + pos, bufsize - pos);
523 pos += strlen(buf + pos);
524 if (IN6_IS_ADDR_LINKLOCAL(addrs + i)) {
525 buf[pos++] = '%';
526 pos += strlcpy(buf + pos, ifname, bufsize - pos);
527 }
528 }
529 buf[pos] = '\0';
530
531 mAction = Action::kRdnss;
532 mSubsystem = strdup("net");
533 asprintf(&mParams[0], "INTERFACE=%s", ifname);
534 asprintf(&mParams[1], "LIFETIME=%u", lifetime);
535 asprintf(&mParams[2], "SERVERS=%s", buf);
536 free(buf);
537 } else if (opthdr->nd_opt_type == ND_OPT_DNSSL) {
538 // TODO: support DNSSL.
539 } else if (opthdr->nd_opt_type == ND_OPT_CAPTIVE_PORTAL) {
540 // TODO: support CAPTIVE PORTAL.
541 } else if (opthdr->nd_opt_type == ND_OPT_PREF64) {
542 // TODO: support PREF64.
543 } else {
544 SLOGD("Unknown ND option type %d\n", opthdr->nd_opt_type);
545 return false;
546 }
547
548 return true;
549 }
550
551 /*
552 * Parse a binary message from a NETLINK_ROUTE netlink socket.
553 *
554 * Note that this function can only parse one message, because the message's
555 * content has to be stored in the class's member variables (mAction,
556 * mSubsystem, etc.). Invalid or unrecognized messages are skipped, but if
557 * there are multiple valid messages in the buffer, only the first one will be
558 * returned.
559 *
560 * TODO: consider only ever looking at the first message.
561 */
parseBinaryNetlinkMessage(char * buffer,int size)562 bool NetlinkEvent::parseBinaryNetlinkMessage(char *buffer, int size) {
563 struct nlmsghdr *nh;
564
565 for (nh = (struct nlmsghdr *) buffer;
566 NLMSG_OK(nh, (unsigned) size) && (nh->nlmsg_type != NLMSG_DONE);
567 nh = NLMSG_NEXT(nh, size)) {
568
569 if (!rtMessageName(nh->nlmsg_type)) {
570 SLOGD("Unexpected netlink message type %d\n", nh->nlmsg_type);
571 continue;
572 }
573
574 if (nh->nlmsg_type == RTM_NEWLINK) {
575 if (parseIfInfoMessage(nh))
576 return true;
577
578 } else if (nh->nlmsg_type == LOCAL_QLOG_NL_EVENT) {
579 if (parseUlogPacketMessage(nh))
580 return true;
581
582 } else if (nh->nlmsg_type == RTM_NEWADDR ||
583 nh->nlmsg_type == RTM_DELADDR) {
584 if (parseIfAddrMessage(nh))
585 return true;
586
587 } else if (nh->nlmsg_type == RTM_NEWROUTE ||
588 nh->nlmsg_type == RTM_DELROUTE) {
589 if (parseRtMessage(nh))
590 return true;
591
592 } else if (nh->nlmsg_type == RTM_NEWNDUSEROPT) {
593 if (parseNdUserOptMessage(nh))
594 return true;
595
596 } else if (nh->nlmsg_type == LOCAL_NFLOG_PACKET) {
597 if (parseNfPacketMessage(nh))
598 return true;
599
600 }
601 }
602
603 return false;
604 }
605
606 /* If the string between 'str' and 'end' begins with 'prefixlen' characters
607 * from the 'prefix' array, then return 'str + prefixlen', otherwise return
608 * NULL.
609 */
610 static const char*
has_prefix(const char * str,const char * end,const char * prefix,size_t prefixlen)611 has_prefix(const char* str, const char* end, const char* prefix, size_t prefixlen)
612 {
613 if ((end - str) >= (ptrdiff_t)prefixlen &&
614 (prefixlen == 0 || !memcmp(str, prefix, prefixlen))) {
615 return str + prefixlen;
616 } else {
617 return nullptr;
618 }
619 }
620
621 /* Same as strlen(x) for constant string literals ONLY */
622 #define CONST_STRLEN(x) (sizeof(x)-1)
623
624 /* Convenience macro to call has_prefix with a constant string literal */
625 #define HAS_CONST_PREFIX(str,end,prefix) has_prefix((str),(end),prefix,CONST_STRLEN(prefix))
626
627
628 /*
629 * Parse an ASCII-formatted message from a NETLINK_KOBJECT_UEVENT
630 * netlink socket.
631 */
parseAsciiNetlinkMessage(char * buffer,int size)632 bool NetlinkEvent::parseAsciiNetlinkMessage(char *buffer, int size) {
633 const char *s = buffer;
634 const char *end;
635 int param_idx = 0;
636 int first = 1;
637
638 if (size == 0)
639 return false;
640
641 /* Ensure the buffer is zero-terminated, the code below depends on this */
642 buffer[size-1] = '\0';
643
644 end = s + size;
645 while (s < end) {
646 if (first) {
647 const char *p;
648 /* buffer is 0-terminated, no need to check p < end */
649 for (p = s; *p != '@'; p++) {
650 if (!*p) { /* no '@', should not happen */
651 return false;
652 }
653 }
654 mPath = strdup(p+1);
655 first = 0;
656 } else {
657 const char* a;
658 if ((a = HAS_CONST_PREFIX(s, end, "ACTION=")) != nullptr) {
659 if (!strcmp(a, "add"))
660 mAction = Action::kAdd;
661 else if (!strcmp(a, "remove"))
662 mAction = Action::kRemove;
663 else if (!strcmp(a, "change"))
664 mAction = Action::kChange;
665 } else if ((a = HAS_CONST_PREFIX(s, end, "SEQNUM=")) != nullptr) {
666 if (!ParseInt(a, &mSeq)) {
667 SLOGE("NetlinkEvent::parseAsciiNetlinkMessage: failed to parse SEQNUM=%s", a);
668 }
669 } else if ((a = HAS_CONST_PREFIX(s, end, "SUBSYSTEM=")) != nullptr) {
670 mSubsystem = strdup(a);
671 } else if (param_idx < NL_PARAMS_MAX) {
672 mParams[param_idx++] = strdup(s);
673 }
674 }
675 s += strlen(s) + 1;
676 }
677 return true;
678 }
679
decode(char * buffer,int size,int format)680 bool NetlinkEvent::decode(char *buffer, int size, int format) {
681 if (format == NetlinkListener::NETLINK_FORMAT_BINARY
682 || format == NetlinkListener::NETLINK_FORMAT_BINARY_UNICAST) {
683 return parseBinaryNetlinkMessage(buffer, size);
684 } else {
685 return parseAsciiNetlinkMessage(buffer, size);
686 }
687 }
688
findParam(const char * paramName)689 const char *NetlinkEvent::findParam(const char *paramName) {
690 size_t len = strlen(paramName);
691 for (int i = 0; i < NL_PARAMS_MAX && mParams[i] != nullptr; ++i) {
692 const char *ptr = mParams[i] + len;
693 if (!strncmp(mParams[i], paramName, len) && *ptr == '=')
694 return ++ptr;
695 }
696
697 SLOGE("NetlinkEvent::FindParam(): Parameter '%s' not found", paramName);
698 return nullptr;
699 }
700
findNlAttr(const nlmsghdr * nh,size_t hdrlen,uint16_t attr)701 nlattr* NetlinkEvent::findNlAttr(const nlmsghdr* nh, size_t hdrlen, uint16_t attr) {
702 if (nh == nullptr || NLMSG_HDRLEN + NLMSG_ALIGN(hdrlen) > SSIZE_MAX) {
703 return nullptr;
704 }
705
706 // Skip header, padding, and family header.
707 const ssize_t NLA_START = NLMSG_HDRLEN + NLMSG_ALIGN(hdrlen);
708 ssize_t left = nh->nlmsg_len - NLA_START;
709 uint8_t* hdr = ((uint8_t*)nh) + NLA_START;
710
711 while (left >= NLA_HDRLEN) {
712 nlattr* nla = (nlattr*)hdr;
713 if (nla->nla_type == attr) {
714 return nla;
715 }
716
717 hdr += NLA_ALIGN(nla->nla_len);
718 left -= NLA_ALIGN(nla->nla_len);
719 }
720
721 return nullptr;
722 }
723