blob: 2351afa8ea6b030a7e992f46018a3b793795be3e [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>
34#include <sys/socket.h>
35#include <sys/types.h>
Jeff Sharkey9a20e672014-10-30 14:51:59 -070036
JP Abgralle6f80142011-07-14 16:46:32 -070037/* From kernel's net/netfilter/xt_quota2.c */
Jeff Sharkey9a20e672014-10-30 14:51:59 -070038const int LOCAL_QLOG_NL_EVENT = 112;
39const int LOCAL_NFLOG_PACKET = NFNL_SUBSYS_ULOG << 8 | NFULNL_MSG_PACKET;
JP Abgralle6f80142011-07-14 16:46:32 -070040
Christopher Ferris71ac5c82019-12-09 15:10:06 -080041/* From deprecated ipt_ULOG.h to parse QLOG_NL_EVENT. */
42#define ULOG_MAC_LEN 80
43#define ULOG_PREFIX_LEN 32
44typedef 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
Lorenzo Colittid0e49382019-04-10 23:04:41 +090058#include <android-base/parseint.h>
Mark Salyzyncfd5b082016-10-17 14:28:00 -070059#include <log/log.h>
Mark Salyzyn66ce3e02016-09-28 10:07:20 -070060#include <sysutils/NetlinkEvent.h>
Jeff Sharkey9a20e672014-10-30 14:51:59 -070061
Lorenzo Colittid0e49382019-04-10 23:04:41 +090062using android::base::ParseInt;
63
San Mehat168415b2009-05-06 11:14:21 -070064NetlinkEvent::NetlinkEvent() {
Jeff Sharkeye4f39402015-03-13 13:27:33 -070065 mAction = Action::kUnknown;
San Mehatebfe3db2009-10-10 17:35:13 -070066 memset(mParams, 0, sizeof(mParams));
Yi Kong48885252018-07-24 16:34:27 -070067 mPath = nullptr;
68 mSubsystem = nullptr;
San Mehat168415b2009-05-06 11:14:21 -070069}
70
71NetlinkEvent::~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
San Mehatd6744132009-12-24 07:17:09 -080084void NetlinkEvent::dump() {
85 int i;
86
87 for (i = 0; i < NL_PARAMS_MAX; i++) {
88 if (!mParams[i])
89 break;
San Mehat7e8529a2010-03-25 09:31:42 -070090 SLOGD("NL param '%s'\n", mParams[i]);
San Mehatd6744132009-12-24 07:17:09 -080091 }
92}
93
Mike J. Chenec16b9d2011-06-23 14:55:28 -070094/*
Lorenzo Colitti9b342932014-06-19 13:16:04 +090095 * Returns the message name for a message in the NETLINK_ROUTE family, or NULL
96 * if parsing that message is not supported.
97 */
98static 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);
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700108 NL_EVENT_RTM_NAME(LOCAL_QLOG_NL_EVENT);
109 NL_EVENT_RTM_NAME(LOCAL_NFLOG_PACKET);
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900110 default:
Yi Kong48885252018-07-24 16:34:27 -0700111 return nullptr;
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900112 }
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 */
120static 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 */
131static 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 */
144bool 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));
Chenbo Feng5e5e5e92018-03-02 01:32:53 -0800159 // 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);
Jeff Sharkeye4f39402015-03-13 13:27:33 -0700165 mAction = (ifi->ifi_flags & IFF_LOWER_UP) ? Action::kLinkUp :
166 Action::kLinkDown;
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900167 mSubsystem = strdup("net");
168 return true;
169 }
170 }
171
172 return false;
173}
174
175/*
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900176 * Parse a RTM_NEWADDR or RTM_DELADDR message.
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900177 */
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900178bool NetlinkEvent::parseIfAddrMessage(const struct nlmsghdr *nh) {
179 struct ifaddrmsg *ifaddr = (struct ifaddrmsg *) NLMSG_DATA(nh);
Yi Kong48885252018-07-24 16:34:27 -0700180 struct ifa_cacheinfo *cacheinfo = nullptr;
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900181 char addrstr[INET6_ADDRSTRLEN] = "";
Lorenzo Colittief6454d2016-02-16 21:42:16 +0900182 char ifname[IFNAMSIZ] = "";
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900183
184 if (!checkRtNetlinkLength(nh, sizeof(*ifaddr)))
185 return false;
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900186
187 // Sanity check.
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900188 int type = nh->nlmsg_type;
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900189 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.
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900195 const char *msgtype = rtMessageName(type);
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900196
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900197 struct rtattr *rta;
198 int len = IFA_PAYLOAD(nh);
199 for (rta = IFA_RTA(ifaddr); RTA_OK(rta, len); rta = RTA_NEXT(rta, len)) {
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900200 if (rta->rta_type == IFA_ADDRESS) {
201 // Only look at the first address, because we only support notifying
202 // one change at a time.
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900203 if (maybeLogDuplicateAttribute(*addrstr != '\0', "IFA_ADDRESS", msgtype))
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900204 continue;
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900205
206 // Convert the IP address to a string.
207 if (ifaddr->ifa_family == AF_INET) {
208 struct in_addr *addr4 = (struct in_addr *) RTA_DATA(rta);
209 if (RTA_PAYLOAD(rta) < sizeof(*addr4)) {
Mark Salyzyn80f63d42014-05-01 07:47:04 -0700210 SLOGE("Short IPv4 address (%zu bytes) in %s",
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900211 RTA_PAYLOAD(rta), msgtype);
212 continue;
213 }
214 inet_ntop(AF_INET, addr4, addrstr, sizeof(addrstr));
215 } else if (ifaddr->ifa_family == AF_INET6) {
216 struct in6_addr *addr6 = (struct in6_addr *) RTA_DATA(rta);
217 if (RTA_PAYLOAD(rta) < sizeof(*addr6)) {
Mark Salyzyn80f63d42014-05-01 07:47:04 -0700218 SLOGE("Short IPv6 address (%zu bytes) in %s",
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900219 RTA_PAYLOAD(rta), msgtype);
220 continue;
221 }
222 inet_ntop(AF_INET6, addr6, addrstr, sizeof(addrstr));
223 } else {
224 SLOGE("Unknown address family %d\n", ifaddr->ifa_family);
225 continue;
226 }
227
228 // Find the interface name.
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900229 if (!if_indextoname(ifaddr->ifa_index, ifname)) {
Lorenzo Colittief6454d2016-02-16 21:42:16 +0900230 SLOGD("Unknown ifindex %d in %s", ifaddr->ifa_index, msgtype);
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900231 }
232
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900233 } else if (rta->rta_type == IFA_CACHEINFO) {
234 // Address lifetime information.
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900235 if (maybeLogDuplicateAttribute(cacheinfo, "IFA_CACHEINFO", msgtype))
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900236 continue;
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900237
238 if (RTA_PAYLOAD(rta) < sizeof(*cacheinfo)) {
Mark Salyzyn80f63d42014-05-01 07:47:04 -0700239 SLOGE("Short IFA_CACHEINFO (%zu vs. %zu bytes) in %s",
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900240 RTA_PAYLOAD(rta), sizeof(cacheinfo), msgtype);
241 continue;
242 }
243
244 cacheinfo = (struct ifa_cacheinfo *) RTA_DATA(rta);
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900245 }
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900246 }
247
248 if (addrstr[0] == '\0') {
249 SLOGE("No IFA_ADDRESS in %s\n", msgtype);
250 return false;
251 }
252
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900253 // Fill in netlink event information.
Jeff Sharkeye4f39402015-03-13 13:27:33 -0700254 mAction = (type == RTM_NEWADDR) ? Action::kAddressUpdated :
255 Action::kAddressRemoved;
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900256 mSubsystem = strdup("net");
Lorenzo Colittief6454d2016-02-16 21:42:16 +0900257 asprintf(&mParams[0], "ADDRESS=%s/%d", addrstr, ifaddr->ifa_prefixlen);
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900258 asprintf(&mParams[1], "INTERFACE=%s", ifname);
259 asprintf(&mParams[2], "FLAGS=%u", ifaddr->ifa_flags);
260 asprintf(&mParams[3], "SCOPE=%u", ifaddr->ifa_scope);
Rubin Xu5f406242018-05-16 23:35:41 +0100261 asprintf(&mParams[4], "IFINDEX=%u", ifaddr->ifa_index);
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900262
263 if (cacheinfo) {
Rubin Xu5f406242018-05-16 23:35:41 +0100264 asprintf(&mParams[5], "PREFERRED=%u", cacheinfo->ifa_prefered);
265 asprintf(&mParams[6], "VALID=%u", cacheinfo->ifa_valid);
266 asprintf(&mParams[7], "CSTAMP=%u", cacheinfo->cstamp);
267 asprintf(&mParams[8], "TSTAMP=%u", cacheinfo->tstamp);
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900268 }
269
270 return true;
271}
272
273/*
274 * Parse a QLOG_NL_EVENT message.
275 */
276bool NetlinkEvent::parseUlogPacketMessage(const struct nlmsghdr *nh) {
277 const char *devname;
278 ulog_packet_msg_t *pm = (ulog_packet_msg_t *) NLMSG_DATA(nh);
279 if (!checkRtNetlinkLength(nh, sizeof(*pm)))
280 return false;
281
282 devname = pm->indev_name[0] ? pm->indev_name : pm->outdev_name;
283 asprintf(&mParams[0], "ALERT_NAME=%s", pm->prefix);
284 asprintf(&mParams[1], "INTERFACE=%s", devname);
285 mSubsystem = strdup("qlog");
Jeff Sharkeye4f39402015-03-13 13:27:33 -0700286 mAction = Action::kChange;
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900287 return true;
288}
289
Lorenzo Colittie439ffc2017-10-03 18:44:11 +0900290static size_t nlAttrLen(const nlattr* nla) {
291 return nla->nla_len - NLA_HDRLEN;
292}
293
294static const uint8_t* nlAttrData(const nlattr* nla) {
295 return reinterpret_cast<const uint8_t*>(nla) + NLA_HDRLEN;
296}
297
298static uint32_t nlAttrU32(const nlattr* nla) {
299 return *reinterpret_cast<const uint32_t*>(nlAttrData(nla));
300}
301
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900302/*
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700303 * Parse a LOCAL_NFLOG_PACKET message.
304 */
305bool NetlinkEvent::parseNfPacketMessage(struct nlmsghdr *nh) {
306 int uid = -1;
307 int len = 0;
Yi Kong48885252018-07-24 16:34:27 -0700308 char* raw = nullptr;
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700309
Lorenzo Colittie439ffc2017-10-03 18:44:11 +0900310 struct nlattr* uid_attr = findNlAttr(nh, sizeof(struct genlmsghdr), NFULA_UID);
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700311 if (uid_attr) {
Lorenzo Colittie439ffc2017-10-03 18:44:11 +0900312 uid = ntohl(nlAttrU32(uid_attr));
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700313 }
314
Lorenzo Colittie439ffc2017-10-03 18:44:11 +0900315 struct nlattr* payload = findNlAttr(nh, sizeof(struct genlmsghdr), NFULA_PAYLOAD);
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700316 if (payload) {
317 /* First 256 bytes is plenty */
Lorenzo Colittie439ffc2017-10-03 18:44:11 +0900318 len = nlAttrLen(payload);
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700319 if (len > 256) len = 256;
Lorenzo Colittie439ffc2017-10-03 18:44:11 +0900320 raw = (char*)nlAttrData(payload);
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700321 }
322
Lorenzo Colittid0e49382019-04-10 23:04:41 +0900323 size_t hexSize = 5 + (len * 2);
324 char* hex = (char*)calloc(1, hexSize);
325 strlcpy(hex, "HEX=", hexSize);
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700326 for (int i = 0; i < len; i++) {
327 hex[4 + (i * 2)] = "0123456789abcdef"[(raw[i] >> 4) & 0xf];
328 hex[5 + (i * 2)] = "0123456789abcdef"[raw[i] & 0xf];
329 }
330
331 asprintf(&mParams[0], "UID=%d", uid);
332 mParams[1] = hex;
333 mSubsystem = strdup("strict");
Jeff Sharkeye4f39402015-03-13 13:27:33 -0700334 mAction = Action::kChange;
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700335 return true;
336}
337
338/*
Lorenzo Colittid7ff7ea2014-06-11 17:37:12 +0900339 * Parse a RTM_NEWROUTE or RTM_DELROUTE message.
340 */
341bool NetlinkEvent::parseRtMessage(const struct nlmsghdr *nh) {
342 uint8_t type = nh->nlmsg_type;
343 const char *msgname = rtMessageName(type);
344
345 // Sanity check.
346 if (type != RTM_NEWROUTE && type != RTM_DELROUTE) {
347 SLOGE("%s: incorrect message type %d (%s)\n", __func__, type, msgname);
348 return false;
349 }
350
351 struct rtmsg *rtm = (struct rtmsg *) NLMSG_DATA(nh);
352 if (!checkRtNetlinkLength(nh, sizeof(*rtm)))
353 return false;
354
355 if (// Ignore static routes we've set up ourselves.
356 (rtm->rtm_protocol != RTPROT_KERNEL &&
357 rtm->rtm_protocol != RTPROT_RA) ||
358 // We're only interested in global unicast routes.
359 (rtm->rtm_scope != RT_SCOPE_UNIVERSE) ||
360 (rtm->rtm_type != RTN_UNICAST) ||
361 // We don't support source routing.
362 (rtm->rtm_src_len != 0) ||
363 // Cloned routes aren't real routes.
364 (rtm->rtm_flags & RTM_F_CLONED)) {
365 return false;
366 }
367
368 int family = rtm->rtm_family;
369 int prefixLength = rtm->rtm_dst_len;
370
371 // Currently we only support: destination, (one) next hop, ifindex.
372 char dst[INET6_ADDRSTRLEN] = "";
373 char gw[INET6_ADDRSTRLEN] = "";
374 char dev[IFNAMSIZ] = "";
375
376 size_t len = RTM_PAYLOAD(nh);
377 struct rtattr *rta;
378 for (rta = RTM_RTA(rtm); RTA_OK(rta, len); rta = RTA_NEXT(rta, len)) {
379 switch (rta->rta_type) {
380 case RTA_DST:
381 if (maybeLogDuplicateAttribute(*dst, "RTA_DST", msgname))
382 continue;
383 if (!inet_ntop(family, RTA_DATA(rta), dst, sizeof(dst)))
384 return false;
385 continue;
386 case RTA_GATEWAY:
387 if (maybeLogDuplicateAttribute(*gw, "RTA_GATEWAY", msgname))
388 continue;
389 if (!inet_ntop(family, RTA_DATA(rta), gw, sizeof(gw)))
390 return false;
391 continue;
392 case RTA_OIF:
393 if (maybeLogDuplicateAttribute(*dev, "RTA_OIF", msgname))
394 continue;
395 if (!if_indextoname(* (int *) RTA_DATA(rta), dev))
396 return false;
Chih-Hung Hsiehe6e2b3c2018-10-10 14:39:02 -0700397 continue;
Lorenzo Colittid7ff7ea2014-06-11 17:37:12 +0900398 default:
399 continue;
400 }
401 }
402
403 // If there's no RTA_DST attribute, then:
404 // - If the prefix length is zero, it's the default route.
405 // - If the prefix length is nonzero, there's something we don't understand.
406 // Ignore the event.
407 if (!*dst && !prefixLength) {
408 if (family == AF_INET) {
409 strncpy(dst, "0.0.0.0", sizeof(dst));
410 } else if (family == AF_INET6) {
411 strncpy(dst, "::", sizeof(dst));
412 }
413 }
414
415 // A useful route must have a destination and at least either a gateway or
416 // an interface.
417 if (!*dst || (!*gw && !*dev))
418 return false;
419
420 // Fill in netlink event information.
Jeff Sharkeye4f39402015-03-13 13:27:33 -0700421 mAction = (type == RTM_NEWROUTE) ? Action::kRouteUpdated :
422 Action::kRouteRemoved;
Lorenzo Colittid7ff7ea2014-06-11 17:37:12 +0900423 mSubsystem = strdup("net");
424 asprintf(&mParams[0], "ROUTE=%s/%d", dst, prefixLength);
425 asprintf(&mParams[1], "GATEWAY=%s", (*gw) ? gw : "");
426 asprintf(&mParams[2], "INTERFACE=%s", (*dev) ? dev : "");
427
428 return true;
429}
430
431/*
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900432 * Parse a RTM_NEWNDUSEROPT message.
433 */
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900434bool NetlinkEvent::parseNdUserOptMessage(const struct nlmsghdr *nh) {
435 struct nduseroptmsg *msg = (struct nduseroptmsg *) NLMSG_DATA(nh);
436 if (!checkRtNetlinkLength(nh, sizeof(*msg)))
437 return false;
438
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900439 // Check the length is valid.
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900440 int len = NLMSG_PAYLOAD(nh, sizeof(*msg));
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900441 if (msg->nduseropt_opts_len > len) {
442 SLOGE("RTM_NEWNDUSEROPT invalid length %d > %d\n",
443 msg->nduseropt_opts_len, len);
444 return false;
445 }
446 len = msg->nduseropt_opts_len;
447
448 // Check address family and packet type.
449 if (msg->nduseropt_family != AF_INET6) {
450 SLOGE("RTM_NEWNDUSEROPT message for unknown family %d\n",
451 msg->nduseropt_family);
452 return false;
453 }
454
455 if (msg->nduseropt_icmp_type != ND_ROUTER_ADVERT ||
456 msg->nduseropt_icmp_code != 0) {
457 SLOGE("RTM_NEWNDUSEROPT message for unknown ICMPv6 type/code %d/%d\n",
458 msg->nduseropt_icmp_type, msg->nduseropt_icmp_code);
459 return false;
460 }
461
462 // Find the interface name.
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900463 char ifname[IFNAMSIZ];
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900464 if (!if_indextoname(msg->nduseropt_ifindex, ifname)) {
465 SLOGE("RTM_NEWNDUSEROPT on unknown ifindex %d\n",
466 msg->nduseropt_ifindex);
467 return false;
468 }
469
470 // The kernel sends a separate netlink message for each ND option in the RA.
471 // So only parse the first ND option in the message.
472 struct nd_opt_hdr *opthdr = (struct nd_opt_hdr *) (msg + 1);
473
474 // The length is in multiples of 8 octets.
475 uint16_t optlen = opthdr->nd_opt_len;
476 if (optlen * 8 > len) {
477 SLOGE("Invalid option length %d > %d for ND option %d\n",
478 optlen * 8, len, opthdr->nd_opt_type);
479 return false;
480 }
481
482 if (opthdr->nd_opt_type == ND_OPT_RDNSS) {
483 // DNS Servers (RFC 6106).
484 // Each address takes up 2*8 octets, and the header takes up 8 octets.
485 // So for a valid option with one or more addresses, optlen must be
486 // odd and greater than 1.
487 if ((optlen < 3) || !(optlen & 0x1)) {
488 SLOGE("Invalid optlen %d for RDNSS option\n", optlen);
489 return false;
490 }
Erik Klineba48ff72015-06-17 15:53:29 +0900491 const int numaddrs = (optlen - 1) / 2;
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900492
493 // Find the lifetime.
494 struct nd_opt_rdnss *rndss_opt = (struct nd_opt_rdnss *) opthdr;
Erik Klineba48ff72015-06-17 15:53:29 +0900495 const uint32_t lifetime = ntohl(rndss_opt->nd_opt_rdnss_lifetime);
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900496
Lorenzo Colittid0e49382019-04-10 23:04:41 +0900497 // Construct a comma-separated string of DNS addresses.
Erik Klineba48ff72015-06-17 15:53:29 +0900498 // Reserve sufficient space for an IPv6 link-local address: all but the
499 // last address are followed by ','; the last is followed by '\0'.
Erik Klinecc451782015-07-28 17:31:19 +0900500 static const size_t kMaxSingleAddressLength =
Erik Klineba48ff72015-06-17 15:53:29 +0900501 INET6_ADDRSTRLEN + strlen("%") + IFNAMSIZ + strlen(",");
Lorenzo Colittid0e49382019-04-10 23:04:41 +0900502 const size_t bufsize = numaddrs * kMaxSingleAddressLength;
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900503 char *buf = (char *) malloc(bufsize);
504 if (!buf) {
505 SLOGE("RDNSS option: out of memory\n");
506 return false;
507 }
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900508
509 struct in6_addr *addrs = (struct in6_addr *) (rndss_opt + 1);
Lorenzo Colittid0e49382019-04-10 23:04:41 +0900510 size_t pos = 0;
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900511 for (int i = 0; i < numaddrs; i++) {
512 if (i > 0) {
513 buf[pos++] = ',';
514 }
515 inet_ntop(AF_INET6, addrs + i, buf + pos, bufsize - pos);
516 pos += strlen(buf + pos);
Erik Klineba48ff72015-06-17 15:53:29 +0900517 if (IN6_IS_ADDR_LINKLOCAL(addrs + i)) {
518 buf[pos++] = '%';
519 pos += strlcpy(buf + pos, ifname, bufsize - pos);
520 }
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900521 }
522 buf[pos] = '\0';
523
Jeff Sharkeye4f39402015-03-13 13:27:33 -0700524 mAction = Action::kRdnss;
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900525 mSubsystem = strdup("net");
526 asprintf(&mParams[0], "INTERFACE=%s", ifname);
527 asprintf(&mParams[1], "LIFETIME=%u", lifetime);
Lorenzo Colittid0e49382019-04-10 23:04:41 +0900528 asprintf(&mParams[2], "SERVERS=%s", buf);
529 free(buf);
Lorenzo Colitticbfd65d2017-11-28 15:32:40 +0900530 } else if (opthdr->nd_opt_type == ND_OPT_DNSSL) {
531 // TODO: support DNSSL.
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900532 } else {
533 SLOGD("Unknown ND option type %d\n", opthdr->nd_opt_type);
534 return false;
535 }
536
537 return true;
538}
539
540/*
541 * Parse a binary message from a NETLINK_ROUTE netlink socket.
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900542 *
543 * Note that this function can only parse one message, because the message's
544 * content has to be stored in the class's member variables (mAction,
545 * mSubsystem, etc.). Invalid or unrecognized messages are skipped, but if
546 * there are multiple valid messages in the buffer, only the first one will be
547 * returned.
548 *
549 * TODO: consider only ever looking at the first message.
Mike J. Chenec16b9d2011-06-23 14:55:28 -0700550 */
551bool NetlinkEvent::parseBinaryNetlinkMessage(char *buffer, int size) {
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700552 struct nlmsghdr *nh;
Mike J. Chenec16b9d2011-06-23 14:55:28 -0700553
Lorenzo Colitti96834562013-08-17 03:40:31 +0900554 for (nh = (struct nlmsghdr *) buffer;
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900555 NLMSG_OK(nh, (unsigned) size) && (nh->nlmsg_type != NLMSG_DONE);
Lorenzo Colitti96834562013-08-17 03:40:31 +0900556 nh = NLMSG_NEXT(nh, size)) {
JP Abgralle6f80142011-07-14 16:46:32 -0700557
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900558 if (!rtMessageName(nh->nlmsg_type)) {
559 SLOGD("Unexpected netlink message type %d\n", nh->nlmsg_type);
560 continue;
561 }
562
Mike J. Chenec16b9d2011-06-23 14:55:28 -0700563 if (nh->nlmsg_type == RTM_NEWLINK) {
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900564 if (parseIfInfoMessage(nh))
565 return true;
JP Abgralle6f80142011-07-14 16:46:32 -0700566
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700567 } else if (nh->nlmsg_type == LOCAL_QLOG_NL_EVENT) {
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900568 if (parseUlogPacketMessage(nh))
569 return true;
JP Abgralle6f80142011-07-14 16:46:32 -0700570
Lorenzo Colitti381f70f2013-08-02 05:58:37 +0900571 } else if (nh->nlmsg_type == RTM_NEWADDR ||
572 nh->nlmsg_type == RTM_DELADDR) {
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900573 if (parseIfAddrMessage(nh))
574 return true;
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900575
Lorenzo Colittid7ff7ea2014-06-11 17:37:12 +0900576 } else if (nh->nlmsg_type == RTM_NEWROUTE ||
577 nh->nlmsg_type == RTM_DELROUTE) {
578 if (parseRtMessage(nh))
579 return true;
580
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900581 } else if (nh->nlmsg_type == RTM_NEWNDUSEROPT) {
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900582 if (parseNdUserOptMessage(nh))
583 return true;
Lorenzo Colittic7eec832013-08-12 17:03:32 +0900584
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700585 } else if (nh->nlmsg_type == LOCAL_NFLOG_PACKET) {
586 if (parseNfPacketMessage(nh))
587 return true;
588
JP Abgralle6f80142011-07-14 16:46:32 -0700589 }
Mike J. Chenec16b9d2011-06-23 14:55:28 -0700590 }
591
Lorenzo Colitti9b342932014-06-19 13:16:04 +0900592 return false;
Mike J. Chenec16b9d2011-06-23 14:55:28 -0700593}
594
David 'Digit' Turner3311eea2011-01-17 01:59:22 +0100595/* If the string between 'str' and 'end' begins with 'prefixlen' characters
596 * from the 'prefix' array, then return 'str + prefixlen', otherwise return
597 * NULL.
598 */
599static const char*
600has_prefix(const char* str, const char* end, const char* prefix, size_t prefixlen)
601{
Yunlian Jiang33f67172017-02-07 15:39:25 -0800602 if ((end - str) >= (ptrdiff_t)prefixlen &&
603 (prefixlen == 0 || !memcmp(str, prefix, prefixlen))) {
David 'Digit' Turner3311eea2011-01-17 01:59:22 +0100604 return str + prefixlen;
Yunlian Jiang33f67172017-02-07 15:39:25 -0800605 } else {
Yi Kong48885252018-07-24 16:34:27 -0700606 return nullptr;
Yunlian Jiang33f67172017-02-07 15:39:25 -0800607 }
David 'Digit' Turner3311eea2011-01-17 01:59:22 +0100608}
609
610/* Same as strlen(x) for constant string literals ONLY */
611#define CONST_STRLEN(x) (sizeof(x)-1)
612
613/* Convenience macro to call has_prefix with a constant string literal */
614#define HAS_CONST_PREFIX(str,end,prefix) has_prefix((str),(end),prefix,CONST_STRLEN(prefix))
615
616
Mike J. Chenec16b9d2011-06-23 14:55:28 -0700617/*
618 * Parse an ASCII-formatted message from a NETLINK_KOBJECT_UEVENT
619 * netlink socket.
620 */
621bool NetlinkEvent::parseAsciiNetlinkMessage(char *buffer, int size) {
Mike J. Chen17260b12011-06-23 15:00:30 -0700622 const char *s = buffer;
623 const char *end;
San Mehat168415b2009-05-06 11:14:21 -0700624 int param_idx = 0;
San Mehat168415b2009-05-06 11:14:21 -0700625 int first = 1;
626
David 'Digit' Turner3311eea2011-01-17 01:59:22 +0100627 if (size == 0)
628 return false;
629
630 /* Ensure the buffer is zero-terminated, the code below depends on this */
631 buffer[size-1] = '\0';
632
San Mehat168415b2009-05-06 11:14:21 -0700633 end = s + size;
634 while (s < end) {
635 if (first) {
David 'Digit' Turner3311eea2011-01-17 01:59:22 +0100636 const char *p;
637 /* buffer is 0-terminated, no need to check p < end */
638 for (p = s; *p != '@'; p++) {
639 if (!*p) { /* no '@', should not happen */
640 return false;
641 }
642 }
643 mPath = strdup(p+1);
San Mehat168415b2009-05-06 11:14:21 -0700644 first = 0;
645 } else {
David 'Digit' Turner3311eea2011-01-17 01:59:22 +0100646 const char* a;
Yi Kong48885252018-07-24 16:34:27 -0700647 if ((a = HAS_CONST_PREFIX(s, end, "ACTION=")) != nullptr) {
San Mehat168415b2009-05-06 11:14:21 -0700648 if (!strcmp(a, "add"))
Jeff Sharkeye4f39402015-03-13 13:27:33 -0700649 mAction = Action::kAdd;
San Mehat168415b2009-05-06 11:14:21 -0700650 else if (!strcmp(a, "remove"))
Jeff Sharkeye4f39402015-03-13 13:27:33 -0700651 mAction = Action::kRemove;
San Mehat168415b2009-05-06 11:14:21 -0700652 else if (!strcmp(a, "change"))
Jeff Sharkeye4f39402015-03-13 13:27:33 -0700653 mAction = Action::kChange;
Yi Kong48885252018-07-24 16:34:27 -0700654 } else if ((a = HAS_CONST_PREFIX(s, end, "SEQNUM=")) != nullptr) {
Lorenzo Colittid0e49382019-04-10 23:04:41 +0900655 if (!ParseInt(a, &mSeq)) {
656 SLOGE("NetlinkEvent::parseAsciiNetlinkMessage: failed to parse SEQNUM=%s", a);
657 }
Yi Kong48885252018-07-24 16:34:27 -0700658 } else if ((a = HAS_CONST_PREFIX(s, end, "SUBSYSTEM=")) != nullptr) {
David 'Digit' Turner3311eea2011-01-17 01:59:22 +0100659 mSubsystem = strdup(a);
660 } else if (param_idx < NL_PARAMS_MAX) {
San Mehat168415b2009-05-06 11:14:21 -0700661 mParams[param_idx++] = strdup(s);
David 'Digit' Turner3311eea2011-01-17 01:59:22 +0100662 }
San Mehat168415b2009-05-06 11:14:21 -0700663 }
David 'Digit' Turner3311eea2011-01-17 01:59:22 +0100664 s += strlen(s) + 1;
San Mehat168415b2009-05-06 11:14:21 -0700665 }
666 return true;
667}
668
Mike J. Chenec16b9d2011-06-23 14:55:28 -0700669bool NetlinkEvent::decode(char *buffer, int size, int format) {
Jeff Sharkey9a20e672014-10-30 14:51:59 -0700670 if (format == NetlinkListener::NETLINK_FORMAT_BINARY
671 || format == NetlinkListener::NETLINK_FORMAT_BINARY_UNICAST) {
Mike J. Chen17260b12011-06-23 15:00:30 -0700672 return parseBinaryNetlinkMessage(buffer, size);
673 } else {
674 return parseAsciiNetlinkMessage(buffer, size);
675 }
Mike J. Chenec16b9d2011-06-23 14:55:28 -0700676}
677
San Mehat168415b2009-05-06 11:14:21 -0700678const char *NetlinkEvent::findParam(const char *paramName) {
Chih-Wei Huang80ec37a2010-07-14 14:00:41 +0800679 size_t len = strlen(paramName);
Yi Kong48885252018-07-24 16:34:27 -0700680 for (int i = 0; i < NL_PARAMS_MAX && mParams[i] != nullptr; ++i) {
Chih-Wei Huang80ec37a2010-07-14 14:00:41 +0800681 const char *ptr = mParams[i] + len;
682 if (!strncmp(mParams[i], paramName, len) && *ptr == '=')
683 return ++ptr;
San Mehat168415b2009-05-06 11:14:21 -0700684 }
685
San Mehat7e8529a2010-03-25 09:31:42 -0700686 SLOGE("NetlinkEvent::FindParam(): Parameter '%s' not found", paramName);
Yi Kong48885252018-07-24 16:34:27 -0700687 return nullptr;
San Mehat168415b2009-05-06 11:14:21 -0700688}
Lorenzo Colittie439ffc2017-10-03 18:44:11 +0900689
690nlattr* NetlinkEvent::findNlAttr(const nlmsghdr* nh, size_t hdrlen, uint16_t attr) {
691 if (nh == nullptr || NLMSG_HDRLEN + NLMSG_ALIGN(hdrlen) > SSIZE_MAX) {
692 return nullptr;
693 }
694
695 // Skip header, padding, and family header.
696 const ssize_t NLA_START = NLMSG_HDRLEN + NLMSG_ALIGN(hdrlen);
697 ssize_t left = nh->nlmsg_len - NLA_START;
698 uint8_t* hdr = ((uint8_t*)nh) + NLA_START;
699
700 while (left >= NLA_HDRLEN) {
701 nlattr* nla = (nlattr*)hdr;
702 if (nla->nla_type == attr) {
703 return nla;
704 }
705
706 hdr += NLA_ALIGN(nla->nla_len);
707 left -= NLA_ALIGN(nla->nla_len);
708 }
709
710 return nullptr;
711}