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