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     int type = nh->nlmsg_type;
189     if (type != RTM_NEWADDR && type != RTM_DELADDR) {
190         SLOGE("parseIfAddrMessage on incorrect message type 0x%x\n", type);
191         return false;
192     }
193 
194     // For log messages.
195     const char *msgtype = rtMessageName(type);
196 
197     // First 8 bits of flags. In practice will always be overridden when parsing IFA_FLAGS below.
198     flags = ifaddr->ifa_flags;
199 
200     struct rtattr *rta;
201     int len = IFA_PAYLOAD(nh);
202     for (rta = IFA_RTA(ifaddr); RTA_OK(rta, len); rta = RTA_NEXT(rta, len)) {
203         if (rta->rta_type == IFA_ADDRESS) {
204             // Only look at the first address, because we only support notifying
205             // one change at a time.
206             if (maybeLogDuplicateAttribute(*addrstr != '\0', "IFA_ADDRESS", msgtype))
207                 continue;
208 
209             // Convert the IP address to a string.
210             if (ifaddr->ifa_family == AF_INET) {
211                 struct in_addr *addr4 = (struct in_addr *) RTA_DATA(rta);
212                 if (RTA_PAYLOAD(rta) < sizeof(*addr4)) {
213                     SLOGE("Short IPv4 address (%zu bytes) in %s",
214                           RTA_PAYLOAD(rta), msgtype);
215                     continue;
216                 }
217                 inet_ntop(AF_INET, addr4, addrstr, sizeof(addrstr));
218             } else if (ifaddr->ifa_family == AF_INET6) {
219                 struct in6_addr *addr6 = (struct in6_addr *) RTA_DATA(rta);
220                 if (RTA_PAYLOAD(rta) < sizeof(*addr6)) {
221                     SLOGE("Short IPv6 address (%zu bytes) in %s",
222                           RTA_PAYLOAD(rta), msgtype);
223                     continue;
224                 }
225                 inet_ntop(AF_INET6, addr6, addrstr, sizeof(addrstr));
226             } else {
227                 SLOGE("Unknown address family %d\n", ifaddr->ifa_family);
228                 continue;
229             }
230 
231             // Find the interface name.
232             if (!if_indextoname(ifaddr->ifa_index, ifname)) {
233                 SLOGD("Unknown ifindex %d in %s", ifaddr->ifa_index, msgtype);
234             }
235 
236         } else if (rta->rta_type == IFA_CACHEINFO) {
237             // Address lifetime information.
238             if (maybeLogDuplicateAttribute(cacheinfo, "IFA_CACHEINFO", msgtype))
239                 continue;
240 
241             if (RTA_PAYLOAD(rta) < sizeof(*cacheinfo)) {
242                 SLOGE("Short IFA_CACHEINFO (%zu vs. %zu bytes) in %s",
243                       RTA_PAYLOAD(rta), sizeof(cacheinfo), msgtype);
244                 continue;
245             }
246 
247             cacheinfo = (struct ifa_cacheinfo *) RTA_DATA(rta);
248 
249         } else if (rta->rta_type == IFA_FLAGS) {
250             flags = *(uint32_t*)RTA_DATA(rta);
251         }
252     }
253 
254     if (addrstr[0] == '\0') {
255         SLOGE("No IFA_ADDRESS in %s\n", msgtype);
256         return false;
257     }
258 
259     // Fill in netlink event information.
260     mAction = (type == RTM_NEWADDR) ? Action::kAddressUpdated :
261                                       Action::kAddressRemoved;
262     mSubsystem = strdup("net");
263     asprintf(&mParams[0], "ADDRESS=%s/%d", addrstr, ifaddr->ifa_prefixlen);
264     asprintf(&mParams[1], "INTERFACE=%s", ifname);
265     asprintf(&mParams[2], "FLAGS=%u", flags);
266     asprintf(&mParams[3], "SCOPE=%u", ifaddr->ifa_scope);
267     asprintf(&mParams[4], "IFINDEX=%u", ifaddr->ifa_index);
268 
269     if (cacheinfo) {
270         asprintf(&mParams[5], "PREFERRED=%u", cacheinfo->ifa_prefered);
271         asprintf(&mParams[6], "VALID=%u", cacheinfo->ifa_valid);
272         asprintf(&mParams[7], "CSTAMP=%u", cacheinfo->cstamp);
273         asprintf(&mParams[8], "TSTAMP=%u", cacheinfo->tstamp);
274     }
275 
276     return true;
277 }
278 
279 /*
280  * Parse a QLOG_NL_EVENT message.
281  */
parseUlogPacketMessage(const struct nlmsghdr * nh)282 bool NetlinkEvent::parseUlogPacketMessage(const struct nlmsghdr *nh) {
283     const char *devname;
284     ulog_packet_msg_t *pm = (ulog_packet_msg_t *) NLMSG_DATA(nh);
285     if (!checkRtNetlinkLength(nh, sizeof(*pm)))
286         return false;
287 
288     devname = pm->indev_name[0] ? pm->indev_name : pm->outdev_name;
289     asprintf(&mParams[0], "ALERT_NAME=%s", pm->prefix);
290     asprintf(&mParams[1], "INTERFACE=%s", devname);
291     mSubsystem = strdup("qlog");
292     mAction = Action::kChange;
293     return true;
294 }
295 
nlAttrLen(const nlattr * nla)296 static size_t nlAttrLen(const nlattr* nla) {
297     return nla->nla_len - NLA_HDRLEN;
298 }
299 
nlAttrData(const nlattr * nla)300 static const uint8_t* nlAttrData(const nlattr* nla) {
301     return reinterpret_cast<const uint8_t*>(nla) + NLA_HDRLEN;
302 }
303 
nlAttrU32(const nlattr * nla)304 static uint32_t nlAttrU32(const nlattr* nla) {
305     return *reinterpret_cast<const uint32_t*>(nlAttrData(nla));
306 }
307 
308 /*
309  * Parse a LOCAL_NFLOG_PACKET message.
310  */
parseNfPacketMessage(struct nlmsghdr * nh)311 bool NetlinkEvent::parseNfPacketMessage(struct nlmsghdr *nh) {
312     int uid = -1;
313     int len = 0;
314     char* raw = nullptr;
315 
316     struct nlattr* uid_attr = findNlAttr(nh, sizeof(struct genlmsghdr), NFULA_UID);
317     if (uid_attr) {
318         uid = ntohl(nlAttrU32(uid_attr));
319     }
320 
321     struct nlattr* payload = findNlAttr(nh, sizeof(struct genlmsghdr), NFULA_PAYLOAD);
322     if (payload) {
323         /* First 256 bytes is plenty */
324         len = nlAttrLen(payload);
325         if (len > 256) len = 256;
326         raw = (char*)nlAttrData(payload);
327     }
328 
329     size_t hexSize = 5 + (len * 2);
330     char* hex = (char*)calloc(1, hexSize);
331     strlcpy(hex, "HEX=", hexSize);
332     for (int i = 0; i < len; i++) {
333         hex[4 + (i * 2)] = "0123456789abcdef"[(raw[i] >> 4) & 0xf];
334         hex[5 + (i * 2)] = "0123456789abcdef"[raw[i] & 0xf];
335     }
336 
337     asprintf(&mParams[0], "UID=%d", uid);
338     mParams[1] = hex;
339     mSubsystem = strdup("strict");
340     mAction = Action::kChange;
341     return true;
342 }
343 
344 /*
345  * Parse a RTM_NEWROUTE or RTM_DELROUTE message.
346  */
parseRtMessage(const struct nlmsghdr * nh)347 bool NetlinkEvent::parseRtMessage(const struct nlmsghdr *nh) {
348     uint8_t type = nh->nlmsg_type;
349     const char *msgname = rtMessageName(type);
350 
351     if (type != RTM_NEWROUTE && type != RTM_DELROUTE) {
352         SLOGE("%s: incorrect message type %d (%s)\n", __func__, type, msgname);
353         return false;
354     }
355 
356     struct rtmsg *rtm = (struct rtmsg *) NLMSG_DATA(nh);
357     if (!checkRtNetlinkLength(nh, sizeof(*rtm)))
358         return false;
359 
360     if (// Ignore static routes we've set up ourselves.
361         (rtm->rtm_protocol != RTPROT_KERNEL &&
362          rtm->rtm_protocol != RTPROT_RA) ||
363         // We're only interested in global unicast routes.
364         (rtm->rtm_scope != RT_SCOPE_UNIVERSE) ||
365         (rtm->rtm_type != RTN_UNICAST) ||
366         // We don't support source routing.
367         (rtm->rtm_src_len != 0) ||
368         // Cloned routes aren't real routes.
369         (rtm->rtm_flags & RTM_F_CLONED)) {
370         return false;
371     }
372 
373     int family = rtm->rtm_family;
374     int prefixLength = rtm->rtm_dst_len;
375 
376     // Currently we only support: destination, (one) next hop, ifindex.
377     char dst[INET6_ADDRSTRLEN] = "";
378     char gw[INET6_ADDRSTRLEN] = "";
379     char dev[IFNAMSIZ] = "";
380 
381     size_t len = RTM_PAYLOAD(nh);
382     struct rtattr *rta;
383     for (rta = RTM_RTA(rtm); RTA_OK(rta, len); rta = RTA_NEXT(rta, len)) {
384         switch (rta->rta_type) {
385             case RTA_DST:
386                 if (maybeLogDuplicateAttribute(*dst, "RTA_DST", msgname))
387                     continue;
388                 if (!inet_ntop(family, RTA_DATA(rta), dst, sizeof(dst)))
389                     return false;
390                 continue;
391             case RTA_GATEWAY:
392                 if (maybeLogDuplicateAttribute(*gw, "RTA_GATEWAY", msgname))
393                     continue;
394                 if (!inet_ntop(family, RTA_DATA(rta), gw, sizeof(gw)))
395                     return false;
396                 continue;
397             case RTA_OIF:
398                 if (maybeLogDuplicateAttribute(*dev, "RTA_OIF", msgname))
399                     continue;
400                 if (!if_indextoname(* (int *) RTA_DATA(rta), dev))
401                     return false;
402                 continue;
403             default:
404                 continue;
405         }
406     }
407 
408    // If there's no RTA_DST attribute, then:
409    // - If the prefix length is zero, it's the default route.
410    // - If the prefix length is nonzero, there's something we don't understand.
411    //   Ignore the event.
412    if (!*dst && !prefixLength) {
413         if (family == AF_INET) {
414             strncpy(dst, "0.0.0.0", sizeof(dst));
415         } else if (family == AF_INET6) {
416             strncpy(dst, "::", sizeof(dst));
417         }
418     }
419 
420     // A useful route must have a destination and at least either a gateway or
421     // an interface.
422     if (!*dst || (!*gw && !*dev))
423         return false;
424 
425     // Fill in netlink event information.
426     mAction = (type == RTM_NEWROUTE) ? Action::kRouteUpdated :
427                                        Action::kRouteRemoved;
428     mSubsystem = strdup("net");
429     asprintf(&mParams[0], "ROUTE=%s/%d", dst, prefixLength);
430     asprintf(&mParams[1], "GATEWAY=%s", (*gw) ? gw : "");
431     asprintf(&mParams[2], "INTERFACE=%s", (*dev) ? dev : "");
432 
433     return true;
434 }
435 
436 /*
437  * Parse a RTM_NEWNDUSEROPT message.
438  */
parseNdUserOptMessage(const struct nlmsghdr * nh)439 bool NetlinkEvent::parseNdUserOptMessage(const struct nlmsghdr *nh) {
440     struct nduseroptmsg *msg = (struct nduseroptmsg *) NLMSG_DATA(nh);
441     if (!checkRtNetlinkLength(nh, sizeof(*msg)))
442         return false;
443 
444     // Check the length is valid.
445     int len = NLMSG_PAYLOAD(nh, sizeof(*msg));
446     if (msg->nduseropt_opts_len > len) {
447         SLOGE("RTM_NEWNDUSEROPT invalid length %d > %d\n",
448               msg->nduseropt_opts_len, len);
449         return false;
450     }
451     len = msg->nduseropt_opts_len;
452 
453     // Check address family and packet type.
454     if (msg->nduseropt_family != AF_INET6) {
455         SLOGE("RTM_NEWNDUSEROPT message for unknown family %d\n",
456               msg->nduseropt_family);
457         return false;
458     }
459 
460     if (msg->nduseropt_icmp_type != ND_ROUTER_ADVERT ||
461         msg->nduseropt_icmp_code != 0) {
462         SLOGE("RTM_NEWNDUSEROPT message for unknown ICMPv6 type/code %d/%d\n",
463               msg->nduseropt_icmp_type, msg->nduseropt_icmp_code);
464         return false;
465     }
466 
467     // Find the interface name.
468     char ifname[IFNAMSIZ];
469     if (!if_indextoname(msg->nduseropt_ifindex, ifname)) {
470         SLOGE("RTM_NEWNDUSEROPT on unknown ifindex %d\n",
471               msg->nduseropt_ifindex);
472         return false;
473     }
474 
475     // The kernel sends a separate netlink message for each ND option in the RA.
476     // So only parse the first ND option in the message.
477     struct nd_opt_hdr *opthdr = (struct nd_opt_hdr *) (msg + 1);
478 
479     // The length is in multiples of 8 octets.
480     uint16_t optlen = opthdr->nd_opt_len;
481     if (optlen * 8 > len) {
482         SLOGE("Invalid option length %d > %d for ND option %d\n",
483               optlen * 8, len, opthdr->nd_opt_type);
484         return false;
485     }
486 
487     if (opthdr->nd_opt_type == ND_OPT_RDNSS) {
488         // DNS Servers (RFC 6106).
489         // Each address takes up 2*8 octets, and the header takes up 8 octets.
490         // So for a valid option with one or more addresses, optlen must be
491         // odd and greater than 1.
492         if ((optlen < 3) || !(optlen & 0x1)) {
493             SLOGE("Invalid optlen %d for RDNSS option\n", optlen);
494             return false;
495         }
496         const int numaddrs = (optlen - 1) / 2;
497 
498         // Find the lifetime.
499         struct nd_opt_rdnss *rndss_opt = (struct nd_opt_rdnss *) opthdr;
500         const uint32_t lifetime = ntohl(rndss_opt->nd_opt_rdnss_lifetime);
501 
502         // Construct a comma-separated string of DNS addresses.
503         // Reserve sufficient space for an IPv6 link-local address: all but the
504         // last address are followed by ','; the last is followed by '\0'.
505         static const size_t kMaxSingleAddressLength =
506                 INET6_ADDRSTRLEN + strlen("%") + IFNAMSIZ + strlen(",");
507         const size_t bufsize = numaddrs * kMaxSingleAddressLength;
508         char *buf = (char *) malloc(bufsize);
509         if (!buf) {
510             SLOGE("RDNSS option: out of memory\n");
511             return false;
512         }
513 
514         struct in6_addr *addrs = (struct in6_addr *) (rndss_opt + 1);
515         size_t pos = 0;
516         for (int i = 0; i < numaddrs; i++) {
517             if (i > 0) {
518                 buf[pos++] = ',';
519             }
520             inet_ntop(AF_INET6, addrs + i, buf + pos, bufsize - pos);
521             pos += strlen(buf + pos);
522             if (IN6_IS_ADDR_LINKLOCAL(addrs + i)) {
523                 buf[pos++] = '%';
524                 pos += strlcpy(buf + pos, ifname, bufsize - pos);
525             }
526         }
527         buf[pos] = '\0';
528 
529         mAction = Action::kRdnss;
530         mSubsystem = strdup("net");
531         asprintf(&mParams[0], "INTERFACE=%s", ifname);
532         asprintf(&mParams[1], "LIFETIME=%u", lifetime);
533         asprintf(&mParams[2], "SERVERS=%s", buf);
534         free(buf);
535     } else if (opthdr->nd_opt_type == ND_OPT_DNSSL) {
536         // TODO: support DNSSL.
537     } else if (opthdr->nd_opt_type == ND_OPT_CAPTIVE_PORTAL) {
538         // TODO: support CAPTIVE PORTAL.
539     } else if (opthdr->nd_opt_type == ND_OPT_PREF64) {
540         // TODO: support PREF64.
541     } else {
542         SLOGD("Unknown ND option type %d\n", opthdr->nd_opt_type);
543         return false;
544     }
545 
546     return true;
547 }
548 
549 /*
550  * Parse a binary message from a NETLINK_ROUTE netlink socket.
551  *
552  * Note that this function can only parse one message, because the message's
553  * content has to be stored in the class's member variables (mAction,
554  * mSubsystem, etc.). Invalid or unrecognized messages are skipped, but if
555  * there are multiple valid messages in the buffer, only the first one will be
556  * returned.
557  *
558  * TODO: consider only ever looking at the first message.
559  */
parseBinaryNetlinkMessage(char * buffer,int size)560 bool NetlinkEvent::parseBinaryNetlinkMessage(char *buffer, int size) {
561     struct nlmsghdr *nh;
562 
563     for (nh = (struct nlmsghdr *) buffer;
564          NLMSG_OK(nh, (unsigned) size) && (nh->nlmsg_type != NLMSG_DONE);
565          nh = NLMSG_NEXT(nh, size)) {
566 
567         if (!rtMessageName(nh->nlmsg_type)) {
568             SLOGD("Unexpected netlink message type %d\n", nh->nlmsg_type);
569             continue;
570         }
571 
572         if (nh->nlmsg_type == RTM_NEWLINK) {
573             if (parseIfInfoMessage(nh))
574                 return true;
575 
576         } else if (nh->nlmsg_type == LOCAL_QLOG_NL_EVENT) {
577             if (parseUlogPacketMessage(nh))
578                 return true;
579 
580         } else if (nh->nlmsg_type == RTM_NEWADDR ||
581                    nh->nlmsg_type == RTM_DELADDR) {
582             if (parseIfAddrMessage(nh))
583                 return true;
584 
585         } else if (nh->nlmsg_type == RTM_NEWROUTE ||
586                    nh->nlmsg_type == RTM_DELROUTE) {
587             if (parseRtMessage(nh))
588                 return true;
589 
590         } else if (nh->nlmsg_type == RTM_NEWNDUSEROPT) {
591             if (parseNdUserOptMessage(nh))
592                 return true;
593 
594         } else if (nh->nlmsg_type == LOCAL_NFLOG_PACKET) {
595             if (parseNfPacketMessage(nh))
596                 return true;
597 
598         }
599     }
600 
601     return false;
602 }
603 
604 /* If the string between 'str' and 'end' begins with 'prefixlen' characters
605  * from the 'prefix' array, then return 'str + prefixlen', otherwise return
606  * NULL.
607  */
608 static const char*
has_prefix(const char * str,const char * end,const char * prefix,size_t prefixlen)609 has_prefix(const char* str, const char* end, const char* prefix, size_t prefixlen)
610 {
611     if ((end - str) >= (ptrdiff_t)prefixlen &&
612         (prefixlen == 0 || !memcmp(str, prefix, prefixlen))) {
613         return str + prefixlen;
614     } else {
615         return nullptr;
616     }
617 }
618 
619 /* Same as strlen(x) for constant string literals ONLY */
620 #define CONST_STRLEN(x)  (sizeof(x)-1)
621 
622 /* Convenience macro to call has_prefix with a constant string literal  */
623 #define HAS_CONST_PREFIX(str,end,prefix)  has_prefix((str),(end),prefix,CONST_STRLEN(prefix))
624 
625 
626 /*
627  * Parse an ASCII-formatted message from a NETLINK_KOBJECT_UEVENT
628  * netlink socket.
629  */
parseAsciiNetlinkMessage(char * buffer,int size)630 bool NetlinkEvent::parseAsciiNetlinkMessage(char *buffer, int size) {
631     const char *s = buffer;
632     const char *end;
633     int param_idx = 0;
634     int first = 1;
635 
636     if (size == 0)
637         return false;
638 
639     /* Ensure the buffer is zero-terminated, the code below depends on this */
640     buffer[size-1] = '\0';
641 
642     end = s + size;
643     while (s < end) {
644         if (first) {
645             const char *p;
646             /* buffer is 0-terminated, no need to check p < end */
647             for (p = s; *p != '@'; p++) {
648                 if (!*p) { /* no '@', should not happen */
649                     return false;
650                 }
651             }
652             mPath = strdup(p+1);
653             first = 0;
654         } else {
655             const char* a;
656             if ((a = HAS_CONST_PREFIX(s, end, "ACTION=")) != nullptr) {
657                 if (!strcmp(a, "add"))
658                     mAction = Action::kAdd;
659                 else if (!strcmp(a, "remove"))
660                     mAction = Action::kRemove;
661                 else if (!strcmp(a, "change"))
662                     mAction = Action::kChange;
663             } else if ((a = HAS_CONST_PREFIX(s, end, "SEQNUM=")) != nullptr) {
664                 if (!ParseInt(a, &mSeq)) {
665                     SLOGE("NetlinkEvent::parseAsciiNetlinkMessage: failed to parse SEQNUM=%s", a);
666                 }
667             } else if ((a = HAS_CONST_PREFIX(s, end, "SUBSYSTEM=")) != nullptr) {
668                 mSubsystem = strdup(a);
669             } else if (param_idx < NL_PARAMS_MAX) {
670                 mParams[param_idx++] = strdup(s);
671             }
672         }
673         s += strlen(s) + 1;
674     }
675     return true;
676 }
677 
decode(char * buffer,int size,int format)678 bool NetlinkEvent::decode(char *buffer, int size, int format) {
679     if (format == NetlinkListener::NETLINK_FORMAT_BINARY
680             || format == NetlinkListener::NETLINK_FORMAT_BINARY_UNICAST) {
681         return parseBinaryNetlinkMessage(buffer, size);
682     } else {
683         return parseAsciiNetlinkMessage(buffer, size);
684     }
685 }
686 
findParam(const char * paramName)687 const char *NetlinkEvent::findParam(const char *paramName) {
688     size_t len = strlen(paramName);
689     for (int i = 0; i < NL_PARAMS_MAX && mParams[i] != nullptr; ++i) {
690         const char *ptr = mParams[i] + len;
691         if (!strncmp(mParams[i], paramName, len) && *ptr == '=')
692             return ++ptr;
693     }
694 
695     SLOGE("NetlinkEvent::FindParam(): Parameter '%s' not found", paramName);
696     return nullptr;
697 }
698 
findNlAttr(const nlmsghdr * nh,size_t hdrlen,uint16_t attr)699 nlattr* NetlinkEvent::findNlAttr(const nlmsghdr* nh, size_t hdrlen, uint16_t attr) {
700     if (nh == nullptr || NLMSG_HDRLEN + NLMSG_ALIGN(hdrlen) > SSIZE_MAX) {
701         return nullptr;
702     }
703 
704     // Skip header, padding, and family header.
705     const ssize_t NLA_START = NLMSG_HDRLEN + NLMSG_ALIGN(hdrlen);
706     ssize_t left = nh->nlmsg_len - NLA_START;
707     uint8_t* hdr = ((uint8_t*)nh) + NLA_START;
708 
709     while (left >= NLA_HDRLEN) {
710         nlattr* nla = (nlattr*)hdr;
711         if (nla->nla_type == attr) {
712             return nla;
713         }
714 
715         hdr += NLA_ALIGN(nla->nla_len);
716         left -= NLA_ALIGN(nla->nla_len);
717     }
718 
719     return nullptr;
720 }
721