1/*
2 * Copyright 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#include <stdio.h>
18#include <stdlib.h>
19#include <unistd.h>
20#include <string.h>
21#include <errno.h>
22
23#include <sys/socket.h>
24#include <sys/select.h>
25#include <sys/types.h>
26#include <netinet/in.h>
27#include <arpa/inet.h>
28#include <net/if.h>
29#include <netdb.h>
30
31#include <linux/if.h>
32#include <linux/if_ether.h>
33#include <linux/if_arp.h>
34#include <linux/netlink.h>
35#include <linux/route.h>
36#include <linux/ipv6_route.h>
37#include <linux/rtnetlink.h>
38#include <linux/sockios.h>
39
40#include "netutils/ifc.h"
41
42#ifdef ANDROID
43#define LOG_TAG "NetUtils"
44#include <cutils/log.h>
45#include <cutils/properties.h>
46#else
47#include <stdio.h>
48#include <string.h>
49#define ALOGD printf
50#define ALOGW printf
51#endif
52
53static int ifc_ctl_sock = -1;
54static int ifc_ctl_sock6 = -1;
55void printerr(char *fmt, ...);
56
57#define DBG 0
58#define INET_ADDRLEN 4
59#define INET6_ADDRLEN 16
60
61in_addr_t prefixLengthToIpv4Netmask(int prefix_length)
62{
63    in_addr_t mask = 0;
64
65    // C99 (6.5.7): shifts of 32 bits have undefined results
66    if (prefix_length <= 0 || prefix_length > 32) {
67        return 0;
68    }
69
70    mask = ~mask << (32 - prefix_length);
71    mask = htonl(mask);
72
73    return mask;
74}
75
76int ipv4NetmaskToPrefixLength(in_addr_t mask)
77{
78    int prefixLength = 0;
79    uint32_t m = (uint32_t)ntohl(mask);
80    while (m & 0x80000000) {
81        prefixLength++;
82        m = m << 1;
83    }
84    return prefixLength;
85}
86
87static const char *ipaddr_to_string(in_addr_t addr)
88{
89    struct in_addr in_addr;
90
91    in_addr.s_addr = addr;
92    return inet_ntoa(in_addr);
93}
94
95int string_to_ip(const char *string, struct sockaddr_storage *ss) {
96    struct addrinfo hints, *ai;
97    int ret;
98
99    if (ss == NULL) {
100        return -EFAULT;
101    }
102
103    memset(&hints, 0, sizeof(hints));
104    hints.ai_family = AF_UNSPEC;
105    hints.ai_flags = AI_NUMERICHOST;
106    hints.ai_socktype = SOCK_DGRAM;
107
108    ret = getaddrinfo(string, NULL, &hints, &ai);
109    if (ret == 0) {
110        memcpy(ss, ai->ai_addr, ai->ai_addrlen);
111        freeaddrinfo(ai);
112    }
113
114    return ret;
115}
116
117int ifc_init(void)
118{
119    int ret;
120    if (ifc_ctl_sock == -1) {
121        ifc_ctl_sock = socket(AF_INET, SOCK_DGRAM, 0);
122        if (ifc_ctl_sock < 0) {
123            printerr("socket() failed: %s\n", strerror(errno));
124        }
125    }
126
127    ret = ifc_ctl_sock < 0 ? -1 : 0;
128    if (DBG) printerr("ifc_init_returning %d", ret);
129    return ret;
130}
131
132int ifc_init6(void)
133{
134    if (ifc_ctl_sock6 == -1) {
135        ifc_ctl_sock6 = socket(AF_INET6, SOCK_DGRAM, 0);
136        if (ifc_ctl_sock6 < 0) {
137            printerr("socket() failed: %s\n", strerror(errno));
138        }
139    }
140    return ifc_ctl_sock6 < 0 ? -1 : 0;
141}
142
143void ifc_close(void)
144{
145    if (DBG) printerr("ifc_close");
146    if (ifc_ctl_sock != -1) {
147        (void)close(ifc_ctl_sock);
148        ifc_ctl_sock = -1;
149    }
150}
151
152void ifc_close6(void)
153{
154    if (ifc_ctl_sock6 != -1) {
155        (void)close(ifc_ctl_sock6);
156        ifc_ctl_sock6 = -1;
157    }
158}
159
160static void ifc_init_ifr(const char *name, struct ifreq *ifr)
161{
162    memset(ifr, 0, sizeof(struct ifreq));
163    strncpy(ifr->ifr_name, name, IFNAMSIZ);
164    ifr->ifr_name[IFNAMSIZ - 1] = 0;
165}
166
167int ifc_get_hwaddr(const char *name, void *ptr)
168{
169    int r;
170    struct ifreq ifr;
171    ifc_init_ifr(name, &ifr);
172
173    r = ioctl(ifc_ctl_sock, SIOCGIFHWADDR, &ifr);
174    if(r < 0) return -1;
175
176    memcpy(ptr, &ifr.ifr_hwaddr.sa_data, ETH_ALEN);
177    return 0;
178}
179
180int ifc_get_ifindex(const char *name, int *if_indexp)
181{
182    int r;
183    struct ifreq ifr;
184    ifc_init_ifr(name, &ifr);
185
186    r = ioctl(ifc_ctl_sock, SIOCGIFINDEX, &ifr);
187    if(r < 0) return -1;
188
189    *if_indexp = ifr.ifr_ifindex;
190    return 0;
191}
192
193static int ifc_set_flags(const char *name, unsigned set, unsigned clr)
194{
195    struct ifreq ifr;
196    ifc_init_ifr(name, &ifr);
197
198    if(ioctl(ifc_ctl_sock, SIOCGIFFLAGS, &ifr) < 0) return -1;
199    ifr.ifr_flags = (ifr.ifr_flags & (~clr)) | set;
200    return ioctl(ifc_ctl_sock, SIOCSIFFLAGS, &ifr);
201}
202
203int ifc_up(const char *name)
204{
205    int ret = ifc_set_flags(name, IFF_UP, 0);
206    if (DBG) printerr("ifc_up(%s) = %d", name, ret);
207    return ret;
208}
209
210int ifc_down(const char *name)
211{
212    int ret = ifc_set_flags(name, 0, IFF_UP);
213    if (DBG) printerr("ifc_down(%s) = %d", name, ret);
214    return ret;
215}
216
217static void init_sockaddr_in(struct sockaddr *sa, in_addr_t addr)
218{
219    struct sockaddr_in *sin = (struct sockaddr_in *) sa;
220    sin->sin_family = AF_INET;
221    sin->sin_port = 0;
222    sin->sin_addr.s_addr = addr;
223}
224
225int ifc_set_addr(const char *name, in_addr_t addr)
226{
227    struct ifreq ifr;
228    int ret;
229
230    ifc_init_ifr(name, &ifr);
231    init_sockaddr_in(&ifr.ifr_addr, addr);
232
233    ret = ioctl(ifc_ctl_sock, SIOCSIFADDR, &ifr);
234    if (DBG) printerr("ifc_set_addr(%s, xx) = %d", name, ret);
235    return ret;
236}
237
238/*
239 * Adds or deletes an IP address on an interface.
240 *
241 * Action is one of:
242 * - RTM_NEWADDR (to add a new address)
243 * - RTM_DELADDR (to delete an existing address)
244 *
245 * Returns zero on success and negative errno on failure.
246 */
247int ifc_act_on_address(int action, const char *name, const char *address,
248                       int prefixlen) {
249    int ifindex, s, len, ret;
250    struct sockaddr_storage ss;
251    void *addr;
252    size_t addrlen;
253    struct {
254        struct nlmsghdr n;
255        struct ifaddrmsg r;
256        // Allow for IPv6 address, headers, and padding.
257        char attrbuf[NLMSG_ALIGN(sizeof(struct nlmsghdr)) +
258                     NLMSG_ALIGN(sizeof(struct rtattr)) +
259                     NLMSG_ALIGN(INET6_ADDRLEN)];
260    } req;
261    struct rtattr *rta;
262    struct nlmsghdr *nh;
263    struct nlmsgerr *err;
264    char buf[NLMSG_ALIGN(sizeof(struct nlmsghdr)) +
265             NLMSG_ALIGN(sizeof(struct nlmsgerr)) +
266             NLMSG_ALIGN(sizeof(struct nlmsghdr))];
267
268    // Get interface ID.
269    ifindex = if_nametoindex(name);
270    if (ifindex == 0) {
271        return -errno;
272    }
273
274    // Convert string representation to sockaddr_storage.
275    ret = string_to_ip(address, &ss);
276    if (ret) {
277        return ret;
278    }
279
280    // Determine address type and length.
281    if (ss.ss_family == AF_INET) {
282        struct sockaddr_in *sin = (struct sockaddr_in *) &ss;
283        addr = &sin->sin_addr;
284        addrlen = INET_ADDRLEN;
285    } else if (ss.ss_family == AF_INET6) {
286        struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) &ss;
287        addr = &sin6->sin6_addr;
288        addrlen = INET6_ADDRLEN;
289    } else {
290        return -EAFNOSUPPORT;
291    }
292
293    // Fill in netlink structures.
294    memset(&req, 0, sizeof(req));
295
296    // Netlink message header.
297    req.n.nlmsg_len = NLMSG_LENGTH(sizeof(req.r));
298    req.n.nlmsg_type = action;
299    req.n.nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
300    req.n.nlmsg_pid = getpid();
301
302    // Interface address message header.
303    req.r.ifa_family = ss.ss_family;
304    req.r.ifa_prefixlen = prefixlen;
305    req.r.ifa_index = ifindex;
306
307    // Routing attribute. Contains the actual IP address.
308    rta = (struct rtattr *) (((char *) &req) + NLMSG_ALIGN(req.n.nlmsg_len));
309    rta->rta_type = IFA_LOCAL;
310    rta->rta_len = RTA_LENGTH(addrlen);
311    req.n.nlmsg_len = NLMSG_ALIGN(req.n.nlmsg_len) + RTA_LENGTH(addrlen);
312    memcpy(RTA_DATA(rta), addr, addrlen);
313
314    s = socket(PF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
315    if (send(s, &req, req.n.nlmsg_len, 0) < 0) {
316        close(s);
317        return -errno;
318    }
319
320    len = recv(s, buf, sizeof(buf), 0);
321    close(s);
322    if (len < 0) {
323        return -errno;
324    }
325
326    // Parse the acknowledgement to find the return code.
327    nh = (struct nlmsghdr *) buf;
328    if (!NLMSG_OK(nh, (unsigned) len) || nh->nlmsg_type != NLMSG_ERROR) {
329        return -EINVAL;
330    }
331    err = NLMSG_DATA(nh);
332
333    // Return code is negative errno.
334    return err->error;
335}
336
337int ifc_add_address(const char *name, const char *address, int prefixlen) {
338    return ifc_act_on_address(RTM_NEWADDR, name, address, prefixlen);
339}
340
341int ifc_del_address(const char *name, const char * address, int prefixlen) {
342    return ifc_act_on_address(RTM_DELADDR, name, address, prefixlen);
343}
344
345/*
346 * Clears IPv6 addresses on the specified interface.
347 */
348int ifc_clear_ipv6_addresses(const char *name) {
349    char rawaddrstr[INET6_ADDRSTRLEN], addrstr[INET6_ADDRSTRLEN];
350    unsigned int prefixlen;
351    int lasterror = 0, i, j, ret;
352    char ifname[64];  // Currently, IFNAMSIZ = 16.
353    FILE *f = fopen("/proc/net/if_inet6", "r");
354    if (!f) {
355        return -errno;
356    }
357
358    // Format:
359    // 20010db8000a0001fc446aa4b5b347ed 03 40 00 01    wlan0
360    while (fscanf(f, "%32s %*02x %02x %*02x %*02x %63s\n",
361                  rawaddrstr, &prefixlen, ifname) == 3) {
362        // Is this the interface we're looking for?
363        if (strcmp(name, ifname)) {
364            continue;
365        }
366
367        // Put the colons back into the address.
368        for (i = 0, j = 0; i < 32; i++, j++) {
369            addrstr[j] = rawaddrstr[i];
370            if (i % 4 == 3) {
371                addrstr[++j] = ':';
372            }
373        }
374        addrstr[j - 1] = '\0';
375
376        // Don't delete the link-local address as well, or it will disable IPv6
377        // on the interface.
378        if (strncmp(addrstr, "fe80:", 5) == 0) {
379            continue;
380        }
381
382        ret = ifc_del_address(ifname, addrstr, prefixlen);
383        if (ret) {
384            ALOGE("Deleting address %s/%d on %s: %s", addrstr, prefixlen, ifname,
385                 strerror(-ret));
386            lasterror = ret;
387        }
388    }
389
390    fclose(f);
391    return lasterror;
392}
393
394/*
395 * Clears IPv4 addresses on the specified interface.
396 */
397void ifc_clear_ipv4_addresses(const char *name) {
398    unsigned count, addr;
399    ifc_init();
400    for (count=0, addr=1;((addr != 0) && (count < 255)); count++) {
401        if (ifc_get_addr(name, &addr) < 0)
402            break;
403        if (addr)
404            ifc_set_addr(name, 0);
405    }
406    ifc_close();
407}
408
409/*
410 * Clears all IP addresses on the specified interface.
411 */
412int ifc_clear_addresses(const char *name) {
413    ifc_clear_ipv4_addresses(name);
414    return ifc_clear_ipv6_addresses(name);
415}
416
417int ifc_set_hwaddr(const char *name, const void *ptr)
418{
419    int r;
420    struct ifreq ifr;
421    ifc_init_ifr(name, &ifr);
422
423    ifr.ifr_hwaddr.sa_family = ARPHRD_ETHER;
424    memcpy(&ifr.ifr_hwaddr.sa_data, ptr, ETH_ALEN);
425    return ioctl(ifc_ctl_sock, SIOCSIFHWADDR, &ifr);
426}
427
428int ifc_set_mask(const char *name, in_addr_t mask)
429{
430    struct ifreq ifr;
431    int ret;
432
433    ifc_init_ifr(name, &ifr);
434    init_sockaddr_in(&ifr.ifr_addr, mask);
435
436    ret = ioctl(ifc_ctl_sock, SIOCSIFNETMASK, &ifr);
437    if (DBG) printerr("ifc_set_mask(%s, xx) = %d", name, ret);
438    return ret;
439}
440
441int ifc_set_prefixLength(const char *name, int prefixLength)
442{
443    struct ifreq ifr;
444    // TODO - support ipv6
445    if (prefixLength > 32 || prefixLength < 0) return -1;
446
447    in_addr_t mask = prefixLengthToIpv4Netmask(prefixLength);
448    ifc_init_ifr(name, &ifr);
449    init_sockaddr_in(&ifr.ifr_addr, mask);
450
451    return ioctl(ifc_ctl_sock, SIOCSIFNETMASK, &ifr);
452}
453
454int ifc_get_addr(const char *name, in_addr_t *addr)
455{
456    struct ifreq ifr;
457    int ret = 0;
458
459    ifc_init_ifr(name, &ifr);
460    if (addr != NULL) {
461        ret = ioctl(ifc_ctl_sock, SIOCGIFADDR, &ifr);
462        if (ret < 0) {
463            *addr = 0;
464        } else {
465            *addr = ((struct sockaddr_in*) &ifr.ifr_addr)->sin_addr.s_addr;
466        }
467    }
468    return ret;
469}
470
471int ifc_get_info(const char *name, in_addr_t *addr, int *prefixLength, unsigned *flags)
472{
473    struct ifreq ifr;
474    ifc_init_ifr(name, &ifr);
475
476    if (addr != NULL) {
477        if(ioctl(ifc_ctl_sock, SIOCGIFADDR, &ifr) < 0) {
478            *addr = 0;
479        } else {
480            *addr = ((struct sockaddr_in*) &ifr.ifr_addr)->sin_addr.s_addr;
481        }
482    }
483
484    if (prefixLength != NULL) {
485        if(ioctl(ifc_ctl_sock, SIOCGIFNETMASK, &ifr) < 0) {
486            *prefixLength = 0;
487        } else {
488            *prefixLength = ipv4NetmaskToPrefixLength(
489                    ((struct sockaddr_in*) &ifr.ifr_addr)->sin_addr.s_addr);
490        }
491    }
492
493    if (flags != NULL) {
494        if(ioctl(ifc_ctl_sock, SIOCGIFFLAGS, &ifr) < 0) {
495            *flags = 0;
496        } else {
497            *flags = ifr.ifr_flags;
498        }
499    }
500
501    return 0;
502}
503
504int ifc_act_on_ipv4_route(int action, const char *ifname, struct in_addr dst, int prefix_length,
505      struct in_addr gw)
506{
507    struct rtentry rt;
508    int result;
509    in_addr_t netmask;
510
511    memset(&rt, 0, sizeof(rt));
512
513    rt.rt_dst.sa_family = AF_INET;
514    rt.rt_dev = (void*) ifname;
515
516    netmask = prefixLengthToIpv4Netmask(prefix_length);
517    init_sockaddr_in(&rt.rt_genmask, netmask);
518    init_sockaddr_in(&rt.rt_dst, dst.s_addr);
519    rt.rt_flags = RTF_UP;
520
521    if (prefix_length == 32) {
522        rt.rt_flags |= RTF_HOST;
523    }
524
525    if (gw.s_addr != 0) {
526        rt.rt_flags |= RTF_GATEWAY;
527        init_sockaddr_in(&rt.rt_gateway, gw.s_addr);
528    }
529
530    ifc_init();
531
532    if (ifc_ctl_sock < 0) {
533        return -errno;
534    }
535
536    result = ioctl(ifc_ctl_sock, action, &rt);
537    if (result < 0) {
538        if (errno == EEXIST) {
539            result = 0;
540        } else {
541            result = -errno;
542        }
543    }
544    ifc_close();
545    return result;
546}
547
548/* deprecated - v4 only */
549int ifc_create_default_route(const char *name, in_addr_t gw)
550{
551    struct in_addr in_dst, in_gw;
552
553    in_dst.s_addr = 0;
554    in_gw.s_addr = gw;
555
556    int ret = ifc_act_on_ipv4_route(SIOCADDRT, name, in_dst, 0, in_gw);
557    if (DBG) printerr("ifc_create_default_route(%s, %d) = %d", name, gw, ret);
558    return ret;
559}
560
561/* deprecated v4-only */
562int ifc_add_host_route(const char *name, in_addr_t dst)
563{
564    struct in_addr in_dst, in_gw;
565
566    in_dst.s_addr = dst;
567    in_gw.s_addr = 0;
568
569    return ifc_act_on_ipv4_route(SIOCADDRT, name, in_dst, 32, in_gw);
570}
571
572int ifc_enable(const char *ifname)
573{
574    int result;
575
576    ifc_init();
577    result = ifc_up(ifname);
578    ifc_close();
579    return result;
580}
581
582int ifc_disable(const char *ifname)
583{
584    unsigned addr, count;
585    int result;
586
587    ifc_init();
588    result = ifc_down(ifname);
589
590    ifc_set_addr(ifname, 0);
591    for (count=0, addr=1;((addr != 0) && (count < 255)); count++) {
592       if (ifc_get_addr(ifname, &addr) < 0)
593            break;
594       if (addr)
595          ifc_set_addr(ifname, 0);
596    }
597
598    ifc_close();
599    return result;
600}
601
602int ifc_reset_connections(const char *ifname, const int reset_mask)
603{
604#ifdef HAVE_ANDROID_OS
605    int result, success;
606    in_addr_t myaddr;
607    struct ifreq ifr;
608    struct in6_ifreq ifr6;
609
610    if (reset_mask & RESET_IPV4_ADDRESSES) {
611        /* IPv4. Clear connections on the IP address. */
612        ifc_init();
613        ifc_get_info(ifname, &myaddr, NULL, NULL);
614        ifc_init_ifr(ifname, &ifr);
615        init_sockaddr_in(&ifr.ifr_addr, myaddr);
616        result = ioctl(ifc_ctl_sock, SIOCKILLADDR,  &ifr);
617        ifc_close();
618    } else {
619        result = 0;
620    }
621
622    if (reset_mask & RESET_IPV6_ADDRESSES) {
623        /*
624         * IPv6. On Linux, when an interface goes down it loses all its IPv6
625         * addresses, so we don't know which connections belonged to that interface
626         * So we clear all unused IPv6 connections on the device by specifying an
627         * empty IPv6 address.
628         */
629        ifc_init6();
630        // This implicitly specifies an address of ::, i.e., kill all IPv6 sockets.
631        memset(&ifr6, 0, sizeof(ifr6));
632        success = ioctl(ifc_ctl_sock6, SIOCKILLADDR,  &ifr6);
633        if (result == 0) {
634            result = success;
635        }
636        ifc_close6();
637    }
638
639    return result;
640#else
641    return 0;
642#endif
643}
644
645/*
646 * Remove the routes associated with the named interface.
647 */
648int ifc_remove_host_routes(const char *name)
649{
650    char ifname[64];
651    in_addr_t dest, gway, mask;
652    int flags, refcnt, use, metric, mtu, win, irtt;
653    struct rtentry rt;
654    FILE *fp;
655    struct in_addr addr;
656
657    fp = fopen("/proc/net/route", "r");
658    if (fp == NULL)
659        return -1;
660    /* Skip the header line */
661    if (fscanf(fp, "%*[^\n]\n") < 0) {
662        fclose(fp);
663        return -1;
664    }
665    ifc_init();
666    for (;;) {
667        int nread = fscanf(fp, "%63s%X%X%X%d%d%d%X%d%d%d\n",
668                           ifname, &dest, &gway, &flags, &refcnt, &use, &metric, &mask,
669                           &mtu, &win, &irtt);
670        if (nread != 11) {
671            break;
672        }
673        if ((flags & (RTF_UP|RTF_HOST)) != (RTF_UP|RTF_HOST)
674                || strcmp(ifname, name) != 0) {
675            continue;
676        }
677        memset(&rt, 0, sizeof(rt));
678        rt.rt_dev = (void *)name;
679        init_sockaddr_in(&rt.rt_dst, dest);
680        init_sockaddr_in(&rt.rt_gateway, gway);
681        init_sockaddr_in(&rt.rt_genmask, mask);
682        addr.s_addr = dest;
683        if (ioctl(ifc_ctl_sock, SIOCDELRT, &rt) < 0) {
684            ALOGD("failed to remove route for %s to %s: %s",
685                 ifname, inet_ntoa(addr), strerror(errno));
686        }
687    }
688    fclose(fp);
689    ifc_close();
690    return 0;
691}
692
693/*
694 * Return the address of the default gateway
695 *
696 * TODO: factor out common code from this and remove_host_routes()
697 * so that we only scan /proc/net/route in one place.
698 *
699 * DEPRECATED
700 */
701int ifc_get_default_route(const char *ifname)
702{
703    char name[64];
704    in_addr_t dest, gway, mask;
705    int flags, refcnt, use, metric, mtu, win, irtt;
706    int result;
707    FILE *fp;
708
709    fp = fopen("/proc/net/route", "r");
710    if (fp == NULL)
711        return 0;
712    /* Skip the header line */
713    if (fscanf(fp, "%*[^\n]\n") < 0) {
714        fclose(fp);
715        return 0;
716    }
717    ifc_init();
718    result = 0;
719    for (;;) {
720        int nread = fscanf(fp, "%63s%X%X%X%d%d%d%X%d%d%d\n",
721                           name, &dest, &gway, &flags, &refcnt, &use, &metric, &mask,
722                           &mtu, &win, &irtt);
723        if (nread != 11) {
724            break;
725        }
726        if ((flags & (RTF_UP|RTF_GATEWAY)) == (RTF_UP|RTF_GATEWAY)
727                && dest == 0
728                && strcmp(ifname, name) == 0) {
729            result = gway;
730            break;
731        }
732    }
733    fclose(fp);
734    ifc_close();
735    return result;
736}
737
738/*
739 * Sets the specified gateway as the default route for the named interface.
740 * DEPRECATED
741 */
742int ifc_set_default_route(const char *ifname, in_addr_t gateway)
743{
744    struct in_addr addr;
745    int result;
746
747    ifc_init();
748    addr.s_addr = gateway;
749    if ((result = ifc_create_default_route(ifname, gateway)) < 0) {
750        ALOGD("failed to add %s as default route for %s: %s",
751             inet_ntoa(addr), ifname, strerror(errno));
752    }
753    ifc_close();
754    return result;
755}
756
757/*
758 * Removes the default route for the named interface.
759 */
760int ifc_remove_default_route(const char *ifname)
761{
762    struct rtentry rt;
763    int result;
764
765    ifc_init();
766    memset(&rt, 0, sizeof(rt));
767    rt.rt_dev = (void *)ifname;
768    rt.rt_flags = RTF_UP|RTF_GATEWAY;
769    init_sockaddr_in(&rt.rt_dst, 0);
770    if ((result = ioctl(ifc_ctl_sock, SIOCDELRT, &rt)) < 0) {
771        ALOGD("failed to remove default route for %s: %s", ifname, strerror(errno));
772    }
773    ifc_close();
774    return result;
775}
776
777int
778ifc_configure(const char *ifname,
779        in_addr_t address,
780        uint32_t prefixLength,
781        in_addr_t gateway,
782        in_addr_t dns1,
783        in_addr_t dns2) {
784
785    char dns_prop_name[PROPERTY_KEY_MAX];
786
787    ifc_init();
788
789    if (ifc_up(ifname)) {
790        printerr("failed to turn on interface %s: %s\n", ifname, strerror(errno));
791        ifc_close();
792        return -1;
793    }
794    if (ifc_set_addr(ifname, address)) {
795        printerr("failed to set ipaddr %s: %s\n", ipaddr_to_string(address), strerror(errno));
796        ifc_close();
797        return -1;
798    }
799    if (ifc_set_prefixLength(ifname, prefixLength)) {
800        printerr("failed to set prefixLength %d: %s\n", prefixLength, strerror(errno));
801        ifc_close();
802        return -1;
803    }
804    if (ifc_create_default_route(ifname, gateway)) {
805        printerr("failed to set default route %s: %s\n", ipaddr_to_string(gateway), strerror(errno));
806        ifc_close();
807        return -1;
808    }
809
810    ifc_close();
811
812    snprintf(dns_prop_name, sizeof(dns_prop_name), "net.%s.dns1", ifname);
813    property_set(dns_prop_name, dns1 ? ipaddr_to_string(dns1) : "");
814    snprintf(dns_prop_name, sizeof(dns_prop_name), "net.%s.dns2", ifname);
815    property_set(dns_prop_name, dns2 ? ipaddr_to_string(dns2) : "");
816
817    return 0;
818}
819
820int ifc_act_on_ipv6_route(int action, const char *ifname, struct in6_addr dst, int prefix_length,
821      struct in6_addr gw)
822{
823    struct in6_rtmsg rtmsg;
824    int result;
825    int ifindex;
826
827    memset(&rtmsg, 0, sizeof(rtmsg));
828
829    ifindex = if_nametoindex(ifname);
830    if (ifindex == 0) {
831        printerr("if_nametoindex() failed: interface %s\n", ifname);
832        return -ENXIO;
833    }
834
835    rtmsg.rtmsg_ifindex = ifindex;
836    rtmsg.rtmsg_dst = dst;
837    rtmsg.rtmsg_dst_len = prefix_length;
838    rtmsg.rtmsg_flags = RTF_UP;
839
840    if (prefix_length == 128) {
841        rtmsg.rtmsg_flags |= RTF_HOST;
842    }
843
844    if (memcmp(&gw, &in6addr_any, sizeof(in6addr_any))) {
845        rtmsg.rtmsg_flags |= RTF_GATEWAY;
846        rtmsg.rtmsg_gateway = gw;
847    }
848
849    ifc_init6();
850
851    if (ifc_ctl_sock6 < 0) {
852        return -errno;
853    }
854
855    result = ioctl(ifc_ctl_sock6, action, &rtmsg);
856    if (result < 0) {
857        if (errno == EEXIST) {
858            result = 0;
859        } else {
860            result = -errno;
861        }
862    }
863    ifc_close6();
864    return result;
865}
866
867int ifc_act_on_route(int action, const char *ifname, const char *dst, int prefix_length,
868        const char *gw)
869{
870    int ret = 0;
871    struct sockaddr_in ipv4_dst, ipv4_gw;
872    struct sockaddr_in6 ipv6_dst, ipv6_gw;
873    struct addrinfo hints, *addr_ai, *gw_ai;
874
875    memset(&hints, 0, sizeof(hints));
876    hints.ai_family = AF_UNSPEC;  /* Allow IPv4 or IPv6 */
877    hints.ai_flags = AI_NUMERICHOST;
878
879    ret = getaddrinfo(dst, NULL, &hints, &addr_ai);
880
881    if (ret != 0) {
882        printerr("getaddrinfo failed: invalid address %s\n", dst);
883        return -EINVAL;
884    }
885
886    if (gw == NULL || (strlen(gw) == 0)) {
887        if (addr_ai->ai_family == AF_INET6) {
888            gw = "::";
889        } else if (addr_ai->ai_family == AF_INET) {
890            gw = "0.0.0.0";
891        }
892    }
893
894    if (((addr_ai->ai_family == AF_INET6) && (prefix_length < 0 || prefix_length > 128)) ||
895            ((addr_ai->ai_family == AF_INET) && (prefix_length < 0 || prefix_length > 32))) {
896        printerr("ifc_add_route: invalid prefix length");
897        freeaddrinfo(addr_ai);
898        return -EINVAL;
899    }
900
901    ret = getaddrinfo(gw, NULL, &hints, &gw_ai);
902    if (ret != 0) {
903        printerr("getaddrinfo failed: invalid gateway %s\n", gw);
904        freeaddrinfo(addr_ai);
905        return -EINVAL;
906    }
907
908    if (addr_ai->ai_family != gw_ai->ai_family) {
909        printerr("ifc_add_route: different address families: %s and %s\n", dst, gw);
910        freeaddrinfo(addr_ai);
911        freeaddrinfo(gw_ai);
912        return -EINVAL;
913    }
914
915    if (addr_ai->ai_family == AF_INET6) {
916        memcpy(&ipv6_dst, addr_ai->ai_addr, sizeof(struct sockaddr_in6));
917        memcpy(&ipv6_gw, gw_ai->ai_addr, sizeof(struct sockaddr_in6));
918        ret = ifc_act_on_ipv6_route(action, ifname, ipv6_dst.sin6_addr,
919                prefix_length, ipv6_gw.sin6_addr);
920    } else if (addr_ai->ai_family == AF_INET) {
921        memcpy(&ipv4_dst, addr_ai->ai_addr, sizeof(struct sockaddr_in));
922        memcpy(&ipv4_gw, gw_ai->ai_addr, sizeof(struct sockaddr_in));
923        ret = ifc_act_on_ipv4_route(action, ifname, ipv4_dst.sin_addr,
924                prefix_length, ipv4_gw.sin_addr);
925    } else {
926        printerr("ifc_add_route: getaddrinfo returned un supported address family %d\n",
927                  addr_ai->ai_family);
928        ret = -EAFNOSUPPORT;
929    }
930
931    freeaddrinfo(addr_ai);
932    freeaddrinfo(gw_ai);
933    return ret;
934}
935
936/*
937 * DEPRECATED
938 */
939int ifc_add_ipv4_route(const char *ifname, struct in_addr dst, int prefix_length,
940      struct in_addr gw)
941{
942    int i =ifc_act_on_ipv4_route(SIOCADDRT, ifname, dst, prefix_length, gw);
943    if (DBG) printerr("ifc_add_ipv4_route(%s, xx, %d, xx) = %d", ifname, prefix_length, i);
944    return i;
945}
946
947/*
948 * DEPRECATED
949 */
950int ifc_add_ipv6_route(const char *ifname, struct in6_addr dst, int prefix_length,
951      struct in6_addr gw)
952{
953    return ifc_act_on_ipv6_route(SIOCADDRT, ifname, dst, prefix_length, gw);
954}
955
956int ifc_add_route(const char *ifname, const char *dst, int prefix_length, const char *gw)
957{
958    int i = ifc_act_on_route(SIOCADDRT, ifname, dst, prefix_length, gw);
959    if (DBG) printerr("ifc_add_route(%s, %s, %d, %s) = %d", ifname, dst, prefix_length, gw, i);
960    return i;
961}
962
963int ifc_remove_route(const char *ifname, const char*dst, int prefix_length, const char *gw)
964{
965    return ifc_act_on_route(SIOCDELRT, ifname, dst, prefix_length, gw);
966}
967