NetlinkEvent.cpp revision 96834569343f38dc006492fccdf6dad68521b005
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#include <stdlib.h>
17#include <string.h>
18
19#define LOG_TAG "NetlinkEvent"
20#include <cutils/log.h>
21
22#include <sysutils/NetlinkEvent.h>
23
24#include <sys/types.h>
25#include <sys/socket.h>
26#include <netinet/in.h>
27#include <arpa/inet.h>
28#include <net/if.h>
29
30#include <linux/if.h>
31#include <linux/netfilter/nfnetlink.h>
32#include <linux/netfilter_ipv4/ipt_ULOG.h>
33/* From kernel's net/netfilter/xt_quota2.c */
34const int QLOG_NL_EVENT  = 112;
35
36#include <linux/netlink.h>
37#include <linux/rtnetlink.h>
38
39const int NetlinkEvent::NlActionUnknown = 0;
40const int NetlinkEvent::NlActionAdd = 1;
41const int NetlinkEvent::NlActionRemove = 2;
42const int NetlinkEvent::NlActionChange = 3;
43const int NetlinkEvent::NlActionLinkUp = 4;
44const int NetlinkEvent::NlActionLinkDown = 5;
45
46NetlinkEvent::NetlinkEvent() {
47    mAction = NlActionUnknown;
48    memset(mParams, 0, sizeof(mParams));
49    mPath = NULL;
50    mSubsystem = NULL;
51}
52
53NetlinkEvent::~NetlinkEvent() {
54    int i;
55    if (mPath)
56        free(mPath);
57    if (mSubsystem)
58        free(mSubsystem);
59    for (i = 0; i < NL_PARAMS_MAX; i++) {
60        if (!mParams[i])
61            break;
62        free(mParams[i]);
63    }
64}
65
66void NetlinkEvent::dump() {
67    int i;
68
69    for (i = 0; i < NL_PARAMS_MAX; i++) {
70        if (!mParams[i])
71            break;
72        SLOGD("NL param '%s'\n", mParams[i]);
73    }
74}
75
76/*
77 * Decode a RTM_NEWADDR or RTM_DELADDR message.
78 */
79bool NetlinkEvent::parseIfAddrMessage(int type, struct ifaddrmsg *ifaddr,
80                                      int rtasize) {
81    struct rtattr *rta;
82    struct ifa_cacheinfo *cacheinfo = NULL;
83    char addrstr[INET6_ADDRSTRLEN] = "";
84
85    // Sanity check.
86    if (type != RTM_NEWADDR && type != RTM_DELADDR) {
87        SLOGE("parseIfAddrMessage on incorrect message type 0x%x\n", type);
88        return false;
89    }
90
91    // For log messages.
92    const char *msgtype = (type == RTM_NEWADDR) ? "RTM_NEWADDR" : "RTM_DELADDR";
93
94    for (rta = IFA_RTA(ifaddr); RTA_OK(rta, rtasize);
95         rta = RTA_NEXT(rta, rtasize)) {
96        if (rta->rta_type == IFA_ADDRESS) {
97            // Only look at the first address, because we only support notifying
98            // one change at a time.
99            if (*addrstr != '\0') {
100                SLOGE("Multiple IFA_ADDRESSes in %s, ignoring\n", msgtype);
101                continue;
102            }
103
104            // Convert the IP address to a string.
105            if (ifaddr->ifa_family == AF_INET) {
106                struct in_addr *addr4 = (struct in_addr *) RTA_DATA(rta);
107                if (RTA_PAYLOAD(rta) < sizeof(*addr4)) {
108                    SLOGE("Short IPv4 address (%d bytes) in %s",
109                          RTA_PAYLOAD(rta), msgtype);
110                    continue;
111                }
112                inet_ntop(AF_INET, addr4, addrstr, sizeof(addrstr));
113            } else if (ifaddr->ifa_family == AF_INET6) {
114                struct in6_addr *addr6 = (struct in6_addr *) RTA_DATA(rta);
115                if (RTA_PAYLOAD(rta) < sizeof(*addr6)) {
116                    SLOGE("Short IPv6 address (%d bytes) in %s",
117                          RTA_PAYLOAD(rta), msgtype);
118                    continue;
119                }
120                inet_ntop(AF_INET6, addr6, addrstr, sizeof(addrstr));
121            } else {
122                SLOGE("Unknown address family %d\n", ifaddr->ifa_family);
123                continue;
124            }
125
126            // Find the interface name.
127            char ifname[IFNAMSIZ + 1];
128            if (!if_indextoname(ifaddr->ifa_index, ifname)) {
129                SLOGE("Unknown ifindex %d in %s", ifaddr->ifa_index, msgtype);
130                return false;
131            }
132
133            // Fill in interface information.
134            mAction = (type == RTM_NEWADDR) ? NlActionAdd : NlActionRemove;
135            mSubsystem = strdup("address");
136            asprintf(&mParams[0], "ADDRESS=%s/%d", addrstr,
137                     ifaddr->ifa_prefixlen);
138            asprintf(&mParams[1], "IFACE=%s", ifname);
139            asprintf(&mParams[2], "FLAGS=%u", ifaddr->ifa_flags);
140            asprintf(&mParams[3], "SCOPE=%u", ifaddr->ifa_scope);
141        } else if (rta->rta_type == IFA_CACHEINFO) {
142            // Address lifetime information.
143            if (cacheinfo) {
144                // We only support one address.
145                SLOGE("Multiple IFA_CACHEINFOs in %s, ignoring\n", msgtype);
146                continue;
147            }
148
149            if (RTA_PAYLOAD(rta) < sizeof(*cacheinfo)) {
150                SLOGE("Short IFA_CACHEINFO (%d vs. %d bytes) in %s",
151                      RTA_PAYLOAD(rta), sizeof(cacheinfo), msgtype);
152                continue;
153            }
154
155            cacheinfo = (struct ifa_cacheinfo *) RTA_DATA(rta);
156            asprintf(&mParams[4], "PREFERRED=%u", cacheinfo->ifa_prefered);
157            asprintf(&mParams[5], "VALID=%u", cacheinfo->ifa_valid);
158            asprintf(&mParams[6], "CSTAMP=%u", cacheinfo->cstamp);
159            asprintf(&mParams[7], "TSTAMP=%u", cacheinfo->tstamp);
160        }
161    }
162
163    if (addrstr[0] == '\0') {
164        SLOGE("No IFA_ADDRESS in %s\n", msgtype);
165        return false;
166    }
167
168    return true;
169}
170
171/*
172 * Parse an binary message from a NETLINK_ROUTE netlink socket.
173 */
174bool NetlinkEvent::parseBinaryNetlinkMessage(char *buffer, int size) {
175    const struct nlmsghdr *nh;
176
177    for (nh = (struct nlmsghdr *) buffer;
178         NLMSG_OK(nh, size) && (nh->nlmsg_type != NLMSG_DONE);
179         nh = NLMSG_NEXT(nh, size)) {
180
181        if (nh->nlmsg_type == RTM_NEWLINK) {
182            int len = nh->nlmsg_len - sizeof(*nh);
183            struct ifinfomsg *ifi;
184
185            if (sizeof(*ifi) > (size_t) len) {
186                SLOGE("Got a short RTM_NEWLINK message\n");
187                continue;
188            }
189
190            ifi = (ifinfomsg *)NLMSG_DATA(nh);
191            if ((ifi->ifi_flags & IFF_LOOPBACK) != 0) {
192                continue;
193            }
194
195            struct rtattr *rta = (struct rtattr *)
196              ((char *) ifi + NLMSG_ALIGN(sizeof(*ifi)));
197            len = NLMSG_PAYLOAD(nh, sizeof(*ifi));
198
199            while(RTA_OK(rta, len)) {
200                switch(rta->rta_type) {
201                case IFLA_IFNAME:
202                    char buffer[16 + IFNAMSIZ];
203                    snprintf(buffer, sizeof(buffer), "INTERFACE=%s",
204                             (char *) RTA_DATA(rta));
205                    mParams[0] = strdup(buffer);
206                    mAction = (ifi->ifi_flags & IFF_LOWER_UP) ?
207                      NlActionLinkUp : NlActionLinkDown;
208                    mSubsystem = strdup("interface");
209                    break;
210                }
211
212                rta = RTA_NEXT(rta, len);
213            }
214
215        } else if (nh->nlmsg_type == QLOG_NL_EVENT) {
216            char *devname;
217            ulog_packet_msg_t *pm;
218            size_t len = nh->nlmsg_len - sizeof(*nh);
219            if (sizeof(*pm) > len) {
220                SLOGE("Got a short QLOG message\n");
221                continue;
222            }
223            pm = (ulog_packet_msg_t *)NLMSG_DATA(nh);
224            devname = pm->indev_name[0] ? pm->indev_name : pm->outdev_name;
225            asprintf(&mParams[0], "ALERT_NAME=%s", pm->prefix);
226            asprintf(&mParams[1], "INTERFACE=%s", devname);
227            mSubsystem = strdup("qlog");
228            mAction = NlActionChange;
229
230        } else if (nh->nlmsg_type == RTM_NEWADDR ||
231                   nh->nlmsg_type == RTM_DELADDR) {
232            int len = nh->nlmsg_len - sizeof(*nh);
233            struct ifaddrmsg *ifa;
234
235            if (sizeof(*ifa) > (size_t) len) {
236                SLOGE("Got a short RTM_xxxADDR message\n");
237                continue;
238            }
239
240            ifa = (ifaddrmsg *)NLMSG_DATA(nh);
241            size_t rtasize = IFA_PAYLOAD(nh);
242            if (!parseIfAddrMessage(nh->nlmsg_type, ifa, rtasize)) {
243                continue;
244            }
245        } else {
246                SLOGD("Unexpected netlink message. type=0x%x\n", nh->nlmsg_type);
247        }
248    }
249
250    return true;
251}
252
253/* If the string between 'str' and 'end' begins with 'prefixlen' characters
254 * from the 'prefix' array, then return 'str + prefixlen', otherwise return
255 * NULL.
256 */
257static const char*
258has_prefix(const char* str, const char* end, const char* prefix, size_t prefixlen)
259{
260    if ((end-str) >= (ptrdiff_t)prefixlen && !memcmp(str, prefix, prefixlen))
261        return str + prefixlen;
262    else
263        return NULL;
264}
265
266/* Same as strlen(x) for constant string literals ONLY */
267#define CONST_STRLEN(x)  (sizeof(x)-1)
268
269/* Convenience macro to call has_prefix with a constant string literal  */
270#define HAS_CONST_PREFIX(str,end,prefix)  has_prefix((str),(end),prefix,CONST_STRLEN(prefix))
271
272
273/*
274 * Parse an ASCII-formatted message from a NETLINK_KOBJECT_UEVENT
275 * netlink socket.
276 */
277bool NetlinkEvent::parseAsciiNetlinkMessage(char *buffer, int size) {
278    const char *s = buffer;
279    const char *end;
280    int param_idx = 0;
281    int i;
282    int first = 1;
283
284    if (size == 0)
285        return false;
286
287    /* Ensure the buffer is zero-terminated, the code below depends on this */
288    buffer[size-1] = '\0';
289
290    end = s + size;
291    while (s < end) {
292        if (first) {
293            const char *p;
294            /* buffer is 0-terminated, no need to check p < end */
295            for (p = s; *p != '@'; p++) {
296                if (!*p) { /* no '@', should not happen */
297                    return false;
298                }
299            }
300            mPath = strdup(p+1);
301            first = 0;
302        } else {
303            const char* a;
304            if ((a = HAS_CONST_PREFIX(s, end, "ACTION=")) != NULL) {
305                if (!strcmp(a, "add"))
306                    mAction = NlActionAdd;
307                else if (!strcmp(a, "remove"))
308                    mAction = NlActionRemove;
309                else if (!strcmp(a, "change"))
310                    mAction = NlActionChange;
311            } else if ((a = HAS_CONST_PREFIX(s, end, "SEQNUM=")) != NULL) {
312                mSeq = atoi(a);
313            } else if ((a = HAS_CONST_PREFIX(s, end, "SUBSYSTEM=")) != NULL) {
314                mSubsystem = strdup(a);
315            } else if (param_idx < NL_PARAMS_MAX) {
316                mParams[param_idx++] = strdup(s);
317            }
318        }
319        s += strlen(s) + 1;
320    }
321    return true;
322}
323
324bool NetlinkEvent::decode(char *buffer, int size, int format) {
325    if (format == NetlinkListener::NETLINK_FORMAT_BINARY) {
326        return parseBinaryNetlinkMessage(buffer, size);
327    } else {
328        return parseAsciiNetlinkMessage(buffer, size);
329    }
330}
331
332const char *NetlinkEvent::findParam(const char *paramName) {
333    size_t len = strlen(paramName);
334    for (int i = 0; i < NL_PARAMS_MAX && mParams[i] != NULL; ++i) {
335        const char *ptr = mParams[i] + len;
336        if (!strncmp(mParams[i], paramName, len) && *ptr == '=')
337            return ++ptr;
338    }
339
340    SLOGE("NetlinkEvent::FindParam(): Parameter '%s' not found", paramName);
341    return NULL;
342}
343