Make dynamic interfaces always autostart
[project/netifd.git] / system-linux.c
1 /*
2  * netifd - network interface daemon
3  * Copyright (C) 2012 Felix Fietkau <nbd@openwrt.org>
4  * Copyright (C) 2013 Jo-Philipp Wich <jow@openwrt.org>
5  * Copyright (C) 2013 Steven Barth <steven@midlink.org>
6  * Copyright (C) 2014 Gioacchino Mazzurco <gio@eigenlab.org>
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License version 2
10  * as published by the Free Software Foundation
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  */
17 #define _GNU_SOURCE
18
19 #include <sys/socket.h>
20 #include <sys/ioctl.h>
21 #include <sys/stat.h>
22 #include <sys/syscall.h>
23
24 #include <net/if.h>
25 #include <net/if_arp.h>
26
27 #include <arpa/inet.h>
28 #include <netinet/in.h>
29
30 #include <linux/rtnetlink.h>
31 #include <linux/sockios.h>
32 #include <linux/ip.h>
33 #include <linux/if_link.h>
34 #include <linux/if_vlan.h>
35 #include <linux/if_bridge.h>
36 #include <linux/if_tunnel.h>
37 #include <linux/ip6_tunnel.h>
38 #include <linux/ethtool.h>
39 #include <linux/fib_rules.h>
40 #include <linux/version.h>
41
42 #ifndef RTN_FAILED_POLICY
43 #define RTN_FAILED_POLICY 12
44 #endif
45
46 #include <string.h>
47 #include <fcntl.h>
48 #include <glob.h>
49 #include <time.h>
50
51 #include <netlink/msg.h>
52 #include <netlink/attr.h>
53 #include <netlink/socket.h>
54 #include <libubox/uloop.h>
55
56 #include "netifd.h"
57 #include "device.h"
58 #include "system.h"
59
60 struct event_socket {
61         struct uloop_fd uloop;
62         struct nl_sock *sock;
63         int bufsize;
64 };
65
66 static int sock_ioctl = -1;
67 static struct nl_sock *sock_rtnl = NULL;
68
69 static int cb_rtnl_event(struct nl_msg *msg, void *arg);
70 static void handle_hotplug_event(struct uloop_fd *u, unsigned int events);
71
72 static char dev_buf[256];
73
74 static void
75 handler_nl_event(struct uloop_fd *u, unsigned int events)
76 {
77         struct event_socket *ev = container_of(u, struct event_socket, uloop);
78         int err;
79         socklen_t errlen = sizeof(err);
80
81         if (!u->error) {
82                 nl_recvmsgs_default(ev->sock);
83                 return;
84         }
85
86         if (getsockopt(u->fd, SOL_SOCKET, SO_ERROR, (void *)&err, &errlen))
87                 goto abort;
88
89         switch(err) {
90         case ENOBUFS:
91                 // Increase rx buffer size on netlink socket
92                 ev->bufsize *= 2;
93                 if (nl_socket_set_buffer_size(ev->sock, ev->bufsize, 0))
94                         goto abort;
95
96                 // Request full dump since some info got dropped
97                 struct rtgenmsg msg = { .rtgen_family = AF_UNSPEC };
98                 nl_send_simple(ev->sock, RTM_GETLINK, NLM_F_DUMP, &msg, sizeof(msg));
99                 break;
100
101         default:
102                 goto abort;
103         }
104         u->error = false;
105         return;
106
107 abort:
108         uloop_fd_delete(&ev->uloop);
109         return;
110 }
111
112 static struct nl_sock *
113 create_socket(int protocol, int groups)
114 {
115         struct nl_sock *sock;
116
117         sock = nl_socket_alloc();
118         if (!sock)
119                 return NULL;
120
121         if (groups)
122                 nl_join_groups(sock, groups);
123
124         if (nl_connect(sock, protocol))
125                 return NULL;
126
127         return sock;
128 }
129
130 static bool
131 create_raw_event_socket(struct event_socket *ev, int protocol, int groups,
132                         uloop_fd_handler cb, int flags)
133 {
134         ev->sock = create_socket(protocol, groups);
135         if (!ev->sock)
136                 return false;
137
138         ev->uloop.fd = nl_socket_get_fd(ev->sock);
139         ev->uloop.cb = cb;
140         if (uloop_fd_add(&ev->uloop, ULOOP_READ|flags))
141                 return false;
142
143         return true;
144 }
145
146 static bool
147 create_event_socket(struct event_socket *ev, int protocol,
148                     int (*cb)(struct nl_msg *msg, void *arg))
149 {
150         if (!create_raw_event_socket(ev, protocol, 0, handler_nl_event, ULOOP_ERROR_CB))
151                 return false;
152
153         // Install the valid custom callback handler
154         nl_socket_modify_cb(ev->sock, NL_CB_VALID, NL_CB_CUSTOM, cb, NULL);
155
156         // Disable sequence number checking on event sockets
157         nl_socket_disable_seq_check(ev->sock);
158
159         // Increase rx buffer size to 65K on event sockets
160         ev->bufsize = 65535;
161         if (nl_socket_set_buffer_size(ev->sock, ev->bufsize, 0))
162                 return false;
163
164         return true;
165 }
166
167 static bool
168 system_rtn_aton(const char *src, unsigned int *dst)
169 {
170         char *e;
171         unsigned int n;
172
173         if (!strcmp(src, "local"))
174                 n = RTN_LOCAL;
175         else if (!strcmp(src, "nat"))
176                 n = RTN_NAT;
177         else if (!strcmp(src, "broadcast"))
178                 n = RTN_BROADCAST;
179         else if (!strcmp(src, "anycast"))
180                 n = RTN_ANYCAST;
181         else if (!strcmp(src, "multicast"))
182                 n = RTN_MULTICAST;
183         else if (!strcmp(src, "prohibit"))
184                 n = RTN_PROHIBIT;
185         else if (!strcmp(src, "unreachable"))
186                 n = RTN_UNREACHABLE;
187         else if (!strcmp(src, "blackhole"))
188                 n = RTN_BLACKHOLE;
189         else if (!strcmp(src, "xresolve"))
190                 n = RTN_XRESOLVE;
191         else if (!strcmp(src, "unicast"))
192                 n = RTN_UNICAST;
193         else if (!strcmp(src, "throw"))
194                 n = RTN_THROW;
195         else if (!strcmp(src, "failed_policy"))
196                 n = RTN_FAILED_POLICY;
197         else {
198                 n = strtoul(src, &e, 0);
199                 if (!e || *e || e == src || n > 255)
200                         return false;
201         }
202
203         *dst = n;
204         return true;
205 }
206
207 int system_init(void)
208 {
209         static struct event_socket rtnl_event;
210         static struct event_socket hotplug_event;
211
212         sock_ioctl = socket(AF_LOCAL, SOCK_DGRAM, 0);
213         system_fd_set_cloexec(sock_ioctl);
214
215         // Prepare socket for routing / address control
216         sock_rtnl = create_socket(NETLINK_ROUTE, 0);
217         if (!sock_rtnl)
218                 return -1;
219
220         if (!create_event_socket(&rtnl_event, NETLINK_ROUTE, cb_rtnl_event))
221                 return -1;
222
223         if (!create_raw_event_socket(&hotplug_event, NETLINK_KOBJECT_UEVENT, 1,
224                                      handle_hotplug_event, 0))
225                 return -1;
226
227         // Receive network link events form kernel
228         nl_socket_add_membership(rtnl_event.sock, RTNLGRP_LINK);
229
230         return 0;
231 }
232
233 static void system_set_sysctl(const char *path, const char *val)
234 {
235         int fd;
236
237         fd = open(path, O_WRONLY);
238         if (fd < 0)
239                 return;
240
241         if (write(fd, val, strlen(val))) {}
242         close(fd);
243 }
244
245 static void system_set_dev_sysctl(const char *path, const char *device, const char *val)
246 {
247         snprintf(dev_buf, sizeof(dev_buf), path, device);
248         system_set_sysctl(dev_buf, val);
249 }
250
251 static void system_set_disable_ipv6(struct device *dev, const char *val)
252 {
253         system_set_dev_sysctl("/proc/sys/net/ipv6/conf/%s/disable_ipv6", dev->ifname, val);
254 }
255
256 static int system_get_sysctl(const char *path, char *buf, const size_t buf_sz)
257 {
258         int fd = -1, ret = -1;
259
260         fd = open(path, O_RDONLY);
261         if (fd < 0)
262                 goto out;
263
264         ssize_t len = read(fd, buf, buf_sz - 1);
265         if (len < 0)
266                 goto out;
267
268         ret = buf[len] = 0;
269
270 out:
271         if (fd >= 0)
272                 close(fd);
273
274         return ret;
275 }
276
277 static int
278 system_get_dev_sysctl(const char *path, const char *device, char *buf, const size_t buf_sz)
279 {
280         snprintf(dev_buf, sizeof(dev_buf), path, device);
281         return system_get_sysctl(dev_buf, buf, buf_sz);
282 }
283
284 static int system_get_disable_ipv6(struct device *dev, char *buf, const size_t buf_sz)
285 {
286         return system_get_dev_sysctl("/proc/sys/net/ipv6/conf/%s/disable_ipv6",
287                         dev->ifname, buf, buf_sz);
288 }
289
290 #ifndef IFF_LOWER_UP
291 #define IFF_LOWER_UP    0x10000
292 #endif
293
294 // Evaluate netlink messages
295 static int cb_rtnl_event(struct nl_msg *msg, void *arg)
296 {
297         struct nlmsghdr *nh = nlmsg_hdr(msg);
298         struct ifinfomsg *ifi = NLMSG_DATA(nh);
299         struct nlattr *nla[__IFLA_MAX];
300
301         if (nh->nlmsg_type != RTM_NEWLINK)
302                 goto out;
303
304         nlmsg_parse(nh, sizeof(*ifi), nla, __IFLA_MAX - 1, NULL);
305         if (!nla[IFLA_IFNAME])
306                 goto out;
307
308         struct device *dev = device_get(nla_data(nla[IFLA_IFNAME]), false);
309         if (!dev)
310                 goto out;
311
312         device_set_ifindex(dev, ifi->ifi_index);
313         device_set_link(dev, ifi->ifi_flags & IFF_LOWER_UP ? true : false);
314
315 out:
316         return 0;
317 }
318
319 static void
320 handle_hotplug_msg(char *data, int size)
321 {
322         const char *subsystem = NULL, *interface = NULL;
323         char *cur, *end, *sep;
324         struct device *dev;
325         int skip;
326         bool add;
327
328         if (!strncmp(data, "add@", 4))
329                 add = true;
330         else if (!strncmp(data, "remove@", 7))
331                 add = false;
332         else
333                 return;
334
335         skip = strlen(data) + 1;
336         end = data + size;
337
338         for (cur = data + skip; cur < end; cur += skip) {
339                 skip = strlen(cur) + 1;
340
341                 sep = strchr(cur, '=');
342                 if (!sep)
343                         continue;
344
345                 *sep = 0;
346                 if (!strcmp(cur, "INTERFACE"))
347                         interface = sep + 1;
348                 else if (!strcmp(cur, "SUBSYSTEM")) {
349                         subsystem = sep + 1;
350                         if (strcmp(subsystem, "net") != 0)
351                                 return;
352                 }
353                 if (subsystem && interface)
354                         goto found;
355         }
356         return;
357
358 found:
359         dev = device_get(interface, false);
360         if (!dev)
361                 return;
362
363         if (dev->type != &simple_device_type)
364                 return;
365
366         if (add && system_if_force_external(dev->ifname))
367                 return;
368
369         device_set_present(dev, add);
370 }
371
372 static void
373 handle_hotplug_event(struct uloop_fd *u, unsigned int events)
374 {
375         struct event_socket *ev = container_of(u, struct event_socket, uloop);
376         struct sockaddr_nl nla;
377         unsigned char *buf = NULL;
378         int size;
379
380         while ((size = nl_recv(ev->sock, &nla, &buf, NULL)) > 0) {
381                 if (nla.nl_pid == 0)
382                         handle_hotplug_msg((char *) buf, size);
383
384                 free(buf);
385         }
386 }
387
388 static int system_rtnl_call(struct nl_msg *msg)
389 {
390         int ret;
391
392         ret = nl_send_auto_complete(sock_rtnl, msg);
393         nlmsg_free(msg);
394
395         if (ret < 0)
396                 return ret;
397
398         return nl_wait_for_ack(sock_rtnl);
399 }
400
401 int system_bridge_delbr(struct device *bridge)
402 {
403         return ioctl(sock_ioctl, SIOCBRDELBR, bridge->ifname);
404 }
405
406 static int system_bridge_if(const char *bridge, struct device *dev, int cmd, void *data)
407 {
408         struct ifreq ifr;
409
410         memset(&ifr, 0, sizeof(ifr));
411         if (dev)
412                 ifr.ifr_ifindex = dev->ifindex;
413         else
414                 ifr.ifr_data = data;
415         strncpy(ifr.ifr_name, bridge, sizeof(ifr.ifr_name));
416         return ioctl(sock_ioctl, cmd, &ifr);
417 }
418
419 static bool system_is_bridge(const char *name, char *buf, int buflen)
420 {
421         struct stat st;
422
423         snprintf(buf, buflen, "/sys/devices/virtual/net/%s/bridge", name);
424         if (stat(buf, &st) < 0)
425                 return false;
426
427         return true;
428 }
429
430 static char *system_get_bridge(const char *name, char *buf, int buflen)
431 {
432         char *path;
433         ssize_t len;
434         glob_t gl;
435
436         snprintf(buf, buflen, "/sys/devices/virtual/net/*/brif/%s/bridge", name);
437         if (glob(buf, GLOB_NOSORT, NULL, &gl) < 0)
438                 return NULL;
439
440         if (gl.gl_pathc == 0)
441                 return NULL;
442
443         len = readlink(gl.gl_pathv[0], buf, buflen);
444         if (len < 0)
445                 return NULL;
446
447         buf[len] = 0;
448         path = strrchr(buf, '/');
449         if (!path)
450                 return NULL;
451
452         return path + 1;
453 }
454
455 static void system_bridge_set_wireless(const char *bridge, const char *dev)
456 {
457         snprintf(dev_buf, sizeof(dev_buf),
458                  "/sys/devices/virtual/net/%s/brif/%s/multicast_to_unicast",
459                  bridge, dev);
460         system_set_sysctl(dev_buf, "1");
461 }
462
463 int system_bridge_addif(struct device *bridge, struct device *dev)
464 {
465         char *oldbr;
466         int ret = 0;
467
468         oldbr = system_get_bridge(dev->ifname, dev_buf, sizeof(dev_buf));
469         if (!oldbr || strcmp(oldbr, bridge->ifname) != 0)
470                 ret = system_bridge_if(bridge->ifname, dev, SIOCBRADDIF, NULL);
471
472         if (dev->wireless)
473                 system_bridge_set_wireless(bridge->ifname, dev->ifname);
474
475         return ret;
476 }
477
478 int system_bridge_delif(struct device *bridge, struct device *dev)
479 {
480         return system_bridge_if(bridge->ifname, dev, SIOCBRDELIF, NULL);
481 }
482
483 static int system_if_resolve(struct device *dev)
484 {
485         struct ifreq ifr;
486         strncpy(ifr.ifr_name, dev->ifname, sizeof(ifr.ifr_name));
487         if (!ioctl(sock_ioctl, SIOCGIFINDEX, &ifr))
488                 return ifr.ifr_ifindex;
489         else
490                 return 0;
491 }
492
493 static int system_if_flags(const char *ifname, unsigned add, unsigned rem)
494 {
495         struct ifreq ifr;
496
497         memset(&ifr, 0, sizeof(ifr));
498         strncpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name));
499         ioctl(sock_ioctl, SIOCGIFFLAGS, &ifr);
500         ifr.ifr_flags |= add;
501         ifr.ifr_flags &= ~rem;
502         return ioctl(sock_ioctl, SIOCSIFFLAGS, &ifr);
503 }
504
505 struct clear_data {
506         struct nl_msg *msg;
507         struct device *dev;
508         int type;
509         int size;
510         int af;
511 };
512
513
514 static bool check_ifaddr(struct nlmsghdr *hdr, int ifindex)
515 {
516         struct ifaddrmsg *ifa = NLMSG_DATA(hdr);
517
518         return ifa->ifa_index == ifindex;
519 }
520
521 static bool check_route(struct nlmsghdr *hdr, int ifindex)
522 {
523         struct rtmsg *r = NLMSG_DATA(hdr);
524         struct nlattr *tb[__RTA_MAX];
525
526         if (r->rtm_protocol == RTPROT_KERNEL &&
527             r->rtm_family == AF_INET6)
528                 return false;
529
530         nlmsg_parse(hdr, sizeof(struct rtmsg), tb, __RTA_MAX - 1, NULL);
531         if (!tb[RTA_OIF])
532                 return false;
533
534         return *(int *)RTA_DATA(tb[RTA_OIF]) == ifindex;
535 }
536
537 static bool check_rule(struct nlmsghdr *hdr, int ifindex)
538 {
539         return true;
540 }
541
542 static int cb_clear_event(struct nl_msg *msg, void *arg)
543 {
544         struct clear_data *clr = arg;
545         struct nlmsghdr *hdr = nlmsg_hdr(msg);
546         bool (*cb)(struct nlmsghdr *, int ifindex);
547         int type;
548
549         switch(clr->type) {
550         case RTM_GETADDR:
551                 type = RTM_DELADDR;
552                 if (hdr->nlmsg_type != RTM_NEWADDR)
553                         return NL_SKIP;
554
555                 cb = check_ifaddr;
556                 break;
557         case RTM_GETROUTE:
558                 type = RTM_DELROUTE;
559                 if (hdr->nlmsg_type != RTM_NEWROUTE)
560                         return NL_SKIP;
561
562                 cb = check_route;
563                 break;
564         case RTM_GETRULE:
565                 type = RTM_DELRULE;
566                 if (hdr->nlmsg_type != RTM_NEWRULE)
567                         return NL_SKIP;
568
569                 cb = check_rule;
570                 break;
571         default:
572                 return NL_SKIP;
573         }
574
575         if (!cb(hdr, clr->dev ? clr->dev->ifindex : 0))
576                 return NL_SKIP;
577
578         if (type == RTM_DELRULE)
579                 D(SYSTEM, "Remove a rule\n");
580         else
581                 D(SYSTEM, "Remove %s from device %s\n",
582                   type == RTM_DELADDR ? "an address" : "a route",
583                   clr->dev->ifname);
584         memcpy(nlmsg_hdr(clr->msg), hdr, hdr->nlmsg_len);
585         hdr = nlmsg_hdr(clr->msg);
586         hdr->nlmsg_type = type;
587         hdr->nlmsg_flags = NLM_F_REQUEST;
588
589         nl_socket_disable_auto_ack(sock_rtnl);
590         nl_send_auto_complete(sock_rtnl, clr->msg);
591         nl_socket_enable_auto_ack(sock_rtnl);
592
593         return NL_SKIP;
594 }
595
596 static int
597 cb_finish_event(struct nl_msg *msg, void *arg)
598 {
599         int *pending = arg;
600         *pending = 0;
601         return NL_STOP;
602 }
603
604 static int
605 error_handler(struct sockaddr_nl *nla, struct nlmsgerr *err, void *arg)
606 {
607         int *pending = arg;
608         *pending = err->error;
609         return NL_STOP;
610 }
611
612 static void
613 system_if_clear_entries(struct device *dev, int type, int af)
614 {
615         struct clear_data clr;
616         struct nl_cb *cb = nl_cb_alloc(NL_CB_DEFAULT);
617         struct rtmsg rtm = {
618                 .rtm_family = af,
619                 .rtm_flags = RTM_F_CLONED,
620         };
621         int flags = NLM_F_DUMP;
622         int pending = 1;
623
624         clr.af = af;
625         clr.dev = dev;
626         clr.type = type;
627         switch (type) {
628         case RTM_GETADDR:
629         case RTM_GETRULE:
630                 clr.size = sizeof(struct rtgenmsg);
631                 break;
632         case RTM_GETROUTE:
633                 clr.size = sizeof(struct rtmsg);
634                 break;
635         default:
636                 return;
637         }
638
639         if (!cb)
640                 return;
641
642         clr.msg = nlmsg_alloc_simple(type, flags);
643         if (!clr.msg)
644                 goto out;
645
646         nlmsg_append(clr.msg, &rtm, clr.size, 0);
647         nl_cb_set(cb, NL_CB_VALID, NL_CB_CUSTOM, cb_clear_event, &clr);
648         nl_cb_set(cb, NL_CB_FINISH, NL_CB_CUSTOM, cb_finish_event, &pending);
649         nl_cb_err(cb, NL_CB_CUSTOM, error_handler, &pending);
650
651         nl_send_auto_complete(sock_rtnl, clr.msg);
652         while (pending > 0)
653                 nl_recvmsgs(sock_rtnl, cb);
654
655         nlmsg_free(clr.msg);
656 out:
657         nl_cb_put(cb);
658 }
659
660 /*
661  * Clear bridge (membership) state and bring down device
662  */
663 void system_if_clear_state(struct device *dev)
664 {
665         static char buf[256];
666         char *bridge;
667
668         device_set_ifindex(dev, system_if_resolve(dev));
669         if (dev->external || !dev->ifindex)
670                 return;
671
672         system_if_flags(dev->ifname, 0, IFF_UP);
673
674         if (system_is_bridge(dev->ifname, buf, sizeof(buf))) {
675                 D(SYSTEM, "Delete existing bridge named '%s'\n", dev->ifname);
676                 system_bridge_delbr(dev);
677                 return;
678         }
679
680         bridge = system_get_bridge(dev->ifname, buf, sizeof(buf));
681         if (bridge) {
682                 D(SYSTEM, "Remove device '%s' from bridge '%s'\n", dev->ifname, bridge);
683                 system_bridge_if(bridge, dev, SIOCBRDELIF, NULL);
684         }
685
686         system_if_clear_entries(dev, RTM_GETROUTE, AF_INET);
687         system_if_clear_entries(dev, RTM_GETADDR, AF_INET);
688         system_if_clear_entries(dev, RTM_GETROUTE, AF_INET6);
689         system_if_clear_entries(dev, RTM_GETADDR, AF_INET6);
690         system_set_disable_ipv6(dev, "0");
691 }
692
693 static inline unsigned long
694 sec_to_jiffies(int val)
695 {
696         return (unsigned long) val * 100;
697 }
698
699 int system_bridge_addbr(struct device *bridge, struct bridge_config *cfg)
700 {
701         unsigned long args[4] = {};
702
703         if (ioctl(sock_ioctl, SIOCBRADDBR, bridge->ifname) < 0)
704                 return -1;
705
706         args[0] = BRCTL_SET_BRIDGE_STP_STATE;
707         args[1] = !!cfg->stp;
708         system_bridge_if(bridge->ifname, NULL, SIOCDEVPRIVATE, &args);
709
710         args[0] = BRCTL_SET_BRIDGE_FORWARD_DELAY;
711         args[1] = sec_to_jiffies(cfg->forward_delay);
712         system_bridge_if(bridge->ifname, NULL, SIOCDEVPRIVATE, &args);
713
714         system_set_dev_sysctl("/sys/devices/virtual/net/%s/bridge/multicast_snooping",
715                 bridge->ifname, cfg->igmp_snoop ? "1" : "0");
716
717         args[0] = BRCTL_SET_BRIDGE_PRIORITY;
718         args[1] = cfg->priority;
719         system_bridge_if(bridge->ifname, NULL, SIOCDEVPRIVATE, &args);
720
721         if (cfg->flags & BRIDGE_OPT_AGEING_TIME) {
722                 args[0] = BRCTL_SET_AGEING_TIME;
723                 args[1] = sec_to_jiffies(cfg->ageing_time);
724                 system_bridge_if(bridge->ifname, NULL, SIOCDEVPRIVATE, &args);
725         }
726
727         if (cfg->flags & BRIDGE_OPT_HELLO_TIME) {
728                 args[0] = BRCTL_SET_BRIDGE_HELLO_TIME;
729                 args[1] = sec_to_jiffies(cfg->hello_time);
730                 system_bridge_if(bridge->ifname, NULL, SIOCDEVPRIVATE, &args);
731         }
732
733         if (cfg->flags & BRIDGE_OPT_MAX_AGE) {
734                 args[0] = BRCTL_SET_BRIDGE_MAX_AGE;
735                 args[1] = sec_to_jiffies(cfg->max_age);
736                 system_bridge_if(bridge->ifname, NULL, SIOCDEVPRIVATE, &args);
737         }
738
739         return 0;
740 }
741
742 int system_macvlan_add(struct device *macvlan, struct device *dev, struct macvlan_config *cfg)
743 {
744         struct nl_msg *msg;
745         struct nlattr *linkinfo, *data;
746         struct ifinfomsg iim = { .ifi_family = AF_UNSPEC, };
747         int ifindex = system_if_resolve(dev);
748         int i, rv;
749         static const struct {
750                 const char *name;
751                 enum macvlan_mode val;
752         } modes[] = {
753                 { "private", MACVLAN_MODE_PRIVATE },
754                 { "vepa", MACVLAN_MODE_VEPA },
755                 { "bridge", MACVLAN_MODE_BRIDGE },
756                 { "passthru", MACVLAN_MODE_PASSTHRU },
757         };
758
759         if (ifindex == 0)
760                 return -ENOENT;
761
762         msg = nlmsg_alloc_simple(RTM_NEWLINK, NLM_F_REQUEST | NLM_F_CREATE | NLM_F_EXCL);
763
764         if (!msg)
765                 return -1;
766
767         nlmsg_append(msg, &iim, sizeof(iim), 0);
768
769         if (cfg->flags & MACVLAN_OPT_MACADDR)
770                 nla_put(msg, IFLA_ADDRESS, sizeof(cfg->macaddr), cfg->macaddr);
771         nla_put_string(msg, IFLA_IFNAME, macvlan->ifname);
772         nla_put_u32(msg, IFLA_LINK, ifindex);
773
774         if (!(linkinfo = nla_nest_start(msg, IFLA_LINKINFO)))
775                 goto nla_put_failure;
776
777         nla_put_string(msg, IFLA_INFO_KIND, "macvlan");
778
779         if (!(data = nla_nest_start(msg, IFLA_INFO_DATA)))
780                 goto nla_put_failure;
781
782         if (cfg->mode) {
783                 for (i = 0; i < ARRAY_SIZE(modes); i++) {
784                         if (strcmp(cfg->mode, modes[i].name) != 0)
785                                 continue;
786
787                         nla_put_u32(msg, IFLA_MACVLAN_MODE, modes[i].val);
788                         break;
789                 }
790         }
791
792         nla_nest_end(msg, data);
793         nla_nest_end(msg, linkinfo);
794
795         rv = system_rtnl_call(msg);
796         if (rv)
797                 D(SYSTEM, "Error adding macvlan '%s' over '%s': %d\n", macvlan->ifname, dev->ifname, rv);
798
799         return rv;
800
801 nla_put_failure:
802         nlmsg_free(msg);
803         return -ENOMEM;
804 }
805
806 static int system_link_del(struct device *dev)
807 {
808         struct nl_msg *msg;
809         struct ifinfomsg iim = {
810                 .ifi_family = AF_UNSPEC,
811                 .ifi_index = 0,
812         };
813
814         msg = nlmsg_alloc_simple(RTM_DELLINK, NLM_F_REQUEST);
815
816         if (!msg)
817                 return -1;
818
819         nlmsg_append(msg, &iim, sizeof(iim), 0);
820         nla_put_string(msg, IFLA_IFNAME, dev->ifname);
821         return system_rtnl_call(msg);
822 }
823
824 int system_macvlan_del(struct device *macvlan)
825 {
826         return system_link_del(macvlan);
827 }
828
829 static int system_vlan(struct device *dev, int id)
830 {
831         struct vlan_ioctl_args ifr = {
832                 .cmd = SET_VLAN_NAME_TYPE_CMD,
833                 .u.name_type = VLAN_NAME_TYPE_RAW_PLUS_VID_NO_PAD,
834         };
835
836         ioctl(sock_ioctl, SIOCSIFVLAN, &ifr);
837
838         if (id < 0) {
839                 ifr.cmd = DEL_VLAN_CMD;
840                 ifr.u.VID = 0;
841         } else {
842                 ifr.cmd = ADD_VLAN_CMD;
843                 ifr.u.VID = id;
844         }
845         strncpy(ifr.device1, dev->ifname, sizeof(ifr.device1));
846         return ioctl(sock_ioctl, SIOCSIFVLAN, &ifr);
847 }
848
849 int system_vlan_add(struct device *dev, int id)
850 {
851         return system_vlan(dev, id);
852 }
853
854 int system_vlan_del(struct device *dev)
855 {
856         return system_vlan(dev, -1);
857 }
858
859 int system_vlandev_add(struct device *vlandev, struct device *dev, struct vlandev_config *cfg)
860 {
861         struct nl_msg *msg;
862         struct nlattr *linkinfo, *data;
863         struct ifinfomsg iim = { .ifi_family = AF_UNSPEC };
864         int ifindex = system_if_resolve(dev);
865         int rv;
866
867         if (ifindex == 0)
868                 return -ENOENT;
869
870         msg = nlmsg_alloc_simple(RTM_NEWLINK, NLM_F_REQUEST | NLM_F_CREATE | NLM_F_EXCL);
871
872         if (!msg)
873                 return -1;
874
875         nlmsg_append(msg, &iim, sizeof(iim), 0);
876         nla_put_string(msg, IFLA_IFNAME, vlandev->ifname);
877         nla_put_u32(msg, IFLA_LINK, ifindex);
878         
879         if (!(linkinfo = nla_nest_start(msg, IFLA_LINKINFO)))
880                 goto nla_put_failure;
881         
882         nla_put_string(msg, IFLA_INFO_KIND, "vlan");
883
884         if (!(data = nla_nest_start(msg, IFLA_INFO_DATA)))
885                 goto nla_put_failure;
886
887         nla_put_u16(msg, IFLA_VLAN_ID, cfg->vid);
888
889 #if LINUX_VERSION_CODE >= KERNEL_VERSION(3,10,0)
890         nla_put_u16(msg, IFLA_VLAN_PROTOCOL, htons(cfg->proto));
891 #else
892         if(cfg->proto == VLAN_PROTO_8021AD)
893                 netifd_log_message(L_WARNING, "%s Your kernel is older than linux 3.10.0, 802.1ad is not supported defaulting to 802.1q", vlandev->type->name);
894 #endif
895
896         nla_nest_end(msg, data);
897         nla_nest_end(msg, linkinfo);
898
899         rv = system_rtnl_call(msg);
900         if (rv)
901                 D(SYSTEM, "Error adding vlandev '%s' over '%s': %d\n", vlandev->ifname, dev->ifname, rv);
902
903         return rv;
904
905 nla_put_failure:
906         nlmsg_free(msg);
907         return -ENOMEM;
908 }
909
910 int system_vlandev_del(struct device *vlandev)
911 {
912         return system_link_del(vlandev);
913 }
914
915 static void
916 system_if_get_settings(struct device *dev, struct device_settings *s)
917 {
918         struct ifreq ifr;
919         char buf[10];
920
921         memset(&ifr, 0, sizeof(ifr));
922         strncpy(ifr.ifr_name, dev->ifname, sizeof(ifr.ifr_name));
923
924         if (ioctl(sock_ioctl, SIOCGIFMTU, &ifr) == 0) {
925                 s->mtu = ifr.ifr_mtu;
926                 s->flags |= DEV_OPT_MTU;
927         }
928
929         if (ioctl(sock_ioctl, SIOCGIFTXQLEN, &ifr) == 0) {
930                 s->txqueuelen = ifr.ifr_qlen;
931                 s->flags |= DEV_OPT_TXQUEUELEN;
932         }
933
934         if (ioctl(sock_ioctl, SIOCGIFHWADDR, &ifr) == 0) {
935                 memcpy(s->macaddr, &ifr.ifr_hwaddr.sa_data, sizeof(s->macaddr));
936                 s->flags |= DEV_OPT_MACADDR;
937         }
938
939         if (!system_get_disable_ipv6(dev, buf, sizeof(buf))) {
940                 s->ipv6 = !strtoul(buf, NULL, 0);
941                 s->flags |= DEV_OPT_IPV6;
942         }
943 }
944
945 void
946 system_if_apply_settings(struct device *dev, struct device_settings *s, unsigned int apply_mask)
947 {
948         struct ifreq ifr;
949
950         if (!apply_mask)
951                 return;
952
953         memset(&ifr, 0, sizeof(ifr));
954         strncpy(ifr.ifr_name, dev->ifname, sizeof(ifr.ifr_name));
955         if (s->flags & DEV_OPT_MTU & apply_mask) {
956                 ifr.ifr_mtu = s->mtu;
957                 if (ioctl(sock_ioctl, SIOCSIFMTU, &ifr) < 0)
958                         s->flags &= ~DEV_OPT_MTU;
959         }
960         if (s->flags & DEV_OPT_TXQUEUELEN & apply_mask) {
961                 ifr.ifr_qlen = s->txqueuelen;
962                 if (ioctl(sock_ioctl, SIOCSIFTXQLEN, &ifr) < 0)
963                         s->flags &= ~DEV_OPT_TXQUEUELEN;
964         }
965         if ((s->flags & DEV_OPT_MACADDR & apply_mask) && !dev->external) {
966                 ifr.ifr_hwaddr.sa_family = ARPHRD_ETHER;
967                 memcpy(&ifr.ifr_hwaddr.sa_data, s->macaddr, sizeof(s->macaddr));
968                 if (ioctl(sock_ioctl, SIOCSIFHWADDR, &ifr) < 0)
969                         s->flags &= ~DEV_OPT_MACADDR;
970         }
971         if (s->flags & DEV_OPT_IPV6 & apply_mask)
972                 system_set_disable_ipv6(dev, s->ipv6 ? "0" : "1");
973 }
974
975 int system_if_up(struct device *dev)
976 {
977         system_if_get_settings(dev, &dev->orig_settings);
978         system_if_apply_settings(dev, &dev->settings, dev->settings.flags);
979         device_set_ifindex(dev, system_if_resolve(dev));
980         return system_if_flags(dev->ifname, IFF_UP, 0);
981 }
982
983 int system_if_down(struct device *dev)
984 {
985         int ret = system_if_flags(dev->ifname, 0, IFF_UP);
986         dev->orig_settings.flags &= dev->settings.flags;
987         system_if_apply_settings(dev, &dev->orig_settings, dev->orig_settings.flags);
988         return ret;
989 }
990
991 struct if_check_data {
992         struct device *dev;
993         int pending;
994         int ret;
995 };
996
997 static int cb_if_check_valid(struct nl_msg *msg, void *arg)
998 {
999         struct nlmsghdr *nh = nlmsg_hdr(msg);
1000         struct ifinfomsg *ifi = NLMSG_DATA(nh);
1001         struct if_check_data *chk = (struct if_check_data *)arg;
1002
1003         if (nh->nlmsg_type != RTM_NEWLINK)
1004                 return NL_SKIP;
1005
1006         device_set_present(chk->dev, ifi->ifi_index > 0 ? true : false);
1007         device_set_link(chk->dev, ifi->ifi_flags & IFF_LOWER_UP ? true : false);
1008
1009         return NL_OK;
1010 }
1011
1012 static int cb_if_check_ack(struct nl_msg *msg, void *arg)
1013 {
1014         struct if_check_data *chk = (struct if_check_data *)arg;
1015         chk->pending = 0;
1016         return NL_STOP;
1017 }
1018
1019 static int cb_if_check_error(struct sockaddr_nl *nla, struct nlmsgerr *err, void *arg)
1020 {
1021         struct if_check_data *chk = (struct if_check_data *)arg;
1022
1023         device_set_present(chk->dev, false);
1024         device_set_link(chk->dev, false);
1025         chk->pending = err->error;
1026
1027         return NL_STOP;
1028 }
1029
1030 int system_if_check(struct device *dev)
1031 {
1032         struct nl_cb *cb = nl_cb_alloc(NL_CB_DEFAULT);
1033         struct nl_msg *msg;
1034         struct ifinfomsg ifi = {
1035                 .ifi_family = AF_UNSPEC,
1036                 .ifi_index = 0,
1037         };
1038         struct if_check_data chk = {
1039                 .dev = dev,
1040                 .pending = 1,
1041         };
1042         int ret = 1;
1043
1044         msg = nlmsg_alloc_simple(RTM_GETLINK, 0);
1045         if (!msg || nlmsg_append(msg, &ifi, sizeof(ifi), 0) ||
1046             nla_put_string(msg, IFLA_IFNAME, dev->ifname))
1047                 goto out;
1048
1049         nl_cb_set(cb, NL_CB_VALID, NL_CB_CUSTOM, cb_if_check_valid, &chk);
1050         nl_cb_set(cb, NL_CB_ACK, NL_CB_CUSTOM, cb_if_check_ack, &chk);
1051         nl_cb_err(cb, NL_CB_CUSTOM, cb_if_check_error, &chk);
1052
1053         nl_send_auto_complete(sock_rtnl, msg);
1054         while (chk.pending > 0)
1055                 nl_recvmsgs(sock_rtnl, cb);
1056
1057         nlmsg_free(msg);
1058         ret = chk.pending;
1059
1060 out:
1061         nl_cb_put(cb);
1062         return ret;
1063 }
1064
1065 struct device *
1066 system_if_get_parent(struct device *dev)
1067 {
1068         char buf[64], *devname;
1069         int ifindex, iflink, len;
1070         FILE *f;
1071
1072         snprintf(buf, sizeof(buf), "/sys/class/net/%s/iflink", dev->ifname);
1073         f = fopen(buf, "r");
1074         if (!f)
1075                 return NULL;
1076
1077         len = fread(buf, 1, sizeof(buf) - 1, f);
1078         fclose(f);
1079
1080         if (len <= 0)
1081                 return NULL;
1082
1083         buf[len] = 0;
1084         iflink = strtoul(buf, NULL, 0);
1085         ifindex = system_if_resolve(dev);
1086         if (!iflink || iflink == ifindex)
1087                 return NULL;
1088
1089         devname = if_indextoname(iflink, buf);
1090         if (!devname)
1091                 return NULL;
1092
1093         return device_get(devname, true);
1094 }
1095
1096 static bool
1097 read_string_file(int dir_fd, const char *file, char *buf, int len)
1098 {
1099         bool ret = false;
1100         char *c;
1101         int fd;
1102
1103         fd = openat(dir_fd, file, O_RDONLY);
1104         if (fd < 0)
1105                 return false;
1106
1107 retry:
1108         len = read(fd, buf, len - 1);
1109         if (len < 0) {
1110                 if (errno == EINTR)
1111                         goto retry;
1112         } else if (len > 0) {
1113                         buf[len] = 0;
1114
1115                         c = strchr(buf, '\n');
1116                         if (c)
1117                                 *c = 0;
1118
1119                         ret = true;
1120         }
1121
1122         close(fd);
1123
1124         return ret;
1125 }
1126
1127 static bool
1128 read_uint64_file(int dir_fd, const char *file, uint64_t *val)
1129 {
1130         char buf[64];
1131         bool ret = false;
1132
1133         ret = read_string_file(dir_fd, file, buf, sizeof(buf));
1134         if (ret)
1135                 *val = strtoull(buf, NULL, 0);
1136
1137         return ret;
1138 }
1139
1140 /* Assume advertised flags == supported flags */
1141 static const struct {
1142         uint32_t mask;
1143         const char *name;
1144 } ethtool_link_modes[] = {
1145         { ADVERTISED_10baseT_Half, "10H" },
1146         { ADVERTISED_10baseT_Full, "10F" },
1147         { ADVERTISED_100baseT_Half, "100H" },
1148         { ADVERTISED_100baseT_Full, "100F" },
1149         { ADVERTISED_1000baseT_Half, "1000H" },
1150         { ADVERTISED_1000baseT_Full, "1000F" },
1151 };
1152
1153 static void system_add_link_modes(struct blob_buf *b, __u32 mask)
1154 {
1155         int i;
1156         for (i = 0; i < ARRAY_SIZE(ethtool_link_modes); i++) {
1157                 if (mask & ethtool_link_modes[i].mask)
1158                         blobmsg_add_string(b, NULL, ethtool_link_modes[i].name);
1159         }
1160 }
1161
1162 bool
1163 system_if_force_external(const char *ifname)
1164 {
1165         char buf[64];
1166         struct stat s;
1167
1168         snprintf(buf, sizeof(buf), "/sys/class/net/%s/phy80211", ifname);
1169         return stat(buf, &s) == 0;
1170 }
1171
1172 int
1173 system_if_dump_info(struct device *dev, struct blob_buf *b)
1174 {
1175         struct ethtool_cmd ecmd;
1176         struct ifreq ifr;
1177         char buf[64], *s;
1178         void *c;
1179         int dir_fd;
1180
1181         snprintf(buf, sizeof(buf), "/sys/class/net/%s", dev->ifname);
1182         dir_fd = open(buf, O_DIRECTORY);
1183
1184         memset(&ecmd, 0, sizeof(ecmd));
1185         memset(&ifr, 0, sizeof(ifr));
1186         strcpy(ifr.ifr_name, dev->ifname);
1187         ifr.ifr_data = (caddr_t) &ecmd;
1188         ecmd.cmd = ETHTOOL_GSET;
1189
1190         if (ioctl(sock_ioctl, SIOCETHTOOL, &ifr) == 0) {
1191                 c = blobmsg_open_array(b, "link-advertising");
1192                 system_add_link_modes(b, ecmd.advertising);
1193                 blobmsg_close_array(b, c);
1194
1195                 c = blobmsg_open_array(b, "link-supported");
1196                 system_add_link_modes(b, ecmd.supported);
1197                 blobmsg_close_array(b, c);
1198
1199                 s = blobmsg_alloc_string_buffer(b, "speed", 8);
1200                 snprintf(s, 8, "%d%c", ethtool_cmd_speed(&ecmd),
1201                         ecmd.duplex == DUPLEX_HALF ? 'H' : 'F');
1202                 blobmsg_add_string_buffer(b);
1203         }
1204
1205         close(dir_fd);
1206         return 0;
1207 }
1208
1209 int
1210 system_if_dump_stats(struct device *dev, struct blob_buf *b)
1211 {
1212         const char *const counters[] = {
1213                 "collisions",     "rx_frame_errors",   "tx_compressed",
1214                 "multicast",      "rx_length_errors",  "tx_dropped",
1215                 "rx_bytes",       "rx_missed_errors",  "tx_errors",
1216                 "rx_compressed",  "rx_over_errors",    "tx_fifo_errors",
1217                 "rx_crc_errors",  "rx_packets",        "tx_heartbeat_errors",
1218                 "rx_dropped",     "tx_aborted_errors", "tx_packets",
1219                 "rx_errors",      "tx_bytes",          "tx_window_errors",
1220                 "rx_fifo_errors", "tx_carrier_errors",
1221         };
1222         char buf[64];
1223         int stats_dir;
1224         int i;
1225         uint64_t val = 0;
1226
1227         snprintf(buf, sizeof(buf), "/sys/class/net/%s/statistics", dev->ifname);
1228         stats_dir = open(buf, O_DIRECTORY);
1229         if (stats_dir < 0)
1230                 return -1;
1231
1232         for (i = 0; i < ARRAY_SIZE(counters); i++)
1233                 if (read_uint64_file(stats_dir, counters[i], &val))
1234                         blobmsg_add_u64(b, counters[i], val);
1235
1236         close(stats_dir);
1237         return 0;
1238 }
1239
1240 static int system_addr(struct device *dev, struct device_addr *addr, int cmd)
1241 {
1242         bool v4 = ((addr->flags & DEVADDR_FAMILY) == DEVADDR_INET4);
1243         int alen = v4 ? 4 : 16;
1244         unsigned int flags = 0;
1245         struct ifaddrmsg ifa = {
1246                 .ifa_family = (alen == 4) ? AF_INET : AF_INET6,
1247                 .ifa_prefixlen = addr->mask,
1248                 .ifa_index = dev->ifindex,
1249         };
1250
1251         struct nl_msg *msg;
1252         if (cmd == RTM_NEWADDR)
1253                 flags |= NLM_F_CREATE | NLM_F_REPLACE;
1254
1255         msg = nlmsg_alloc_simple(cmd, flags);
1256         if (!msg)
1257                 return -1;
1258
1259         nlmsg_append(msg, &ifa, sizeof(ifa), 0);
1260         nla_put(msg, IFA_LOCAL, alen, &addr->addr);
1261         if (v4) {
1262                 if (addr->broadcast)
1263                         nla_put_u32(msg, IFA_BROADCAST, addr->broadcast);
1264                 if (addr->point_to_point)
1265                         nla_put_u32(msg, IFA_ADDRESS, addr->point_to_point);
1266         } else {
1267                 time_t now = system_get_rtime();
1268                 struct ifa_cacheinfo cinfo = {0xffffffffU, 0xffffffffU, 0, 0};
1269
1270                 if (addr->preferred_until) {
1271                         int64_t preferred = addr->preferred_until - now;
1272                         if (preferred < 0)
1273                                 preferred = 0;
1274                         else if (preferred > UINT32_MAX)
1275                                 preferred = UINT32_MAX;
1276
1277                         cinfo.ifa_prefered = preferred;
1278                 }
1279
1280                 if (addr->valid_until) {
1281                         int64_t valid = addr->valid_until - now;
1282                         if (valid <= 0)
1283                                 return -1;
1284                         else if (valid > UINT32_MAX)
1285                                 valid = UINT32_MAX;
1286
1287                         cinfo.ifa_valid = valid;
1288                 }
1289
1290                 nla_put(msg, IFA_CACHEINFO, sizeof(cinfo), &cinfo);
1291         }
1292
1293         return system_rtnl_call(msg);
1294 }
1295
1296 int system_add_address(struct device *dev, struct device_addr *addr)
1297 {
1298         return system_addr(dev, addr, RTM_NEWADDR);
1299 }
1300
1301 int system_del_address(struct device *dev, struct device_addr *addr)
1302 {
1303         return system_addr(dev, addr, RTM_DELADDR);
1304 }
1305
1306 static int system_rt(struct device *dev, struct device_route *route, int cmd)
1307 {
1308         int alen = ((route->flags & DEVADDR_FAMILY) == DEVADDR_INET4) ? 4 : 16;
1309         bool have_gw;
1310         unsigned int flags = 0;
1311
1312         if (alen == 4)
1313                 have_gw = !!route->nexthop.in.s_addr;
1314         else
1315                 have_gw = route->nexthop.in6.s6_addr32[0] ||
1316                         route->nexthop.in6.s6_addr32[1] ||
1317                         route->nexthop.in6.s6_addr32[2] ||
1318                         route->nexthop.in6.s6_addr32[3];
1319
1320         unsigned int table = (route->flags & (DEVROUTE_TABLE | DEVROUTE_SRCTABLE))
1321                         ? route->table : RT_TABLE_MAIN;
1322
1323         struct rtmsg rtm = {
1324                 .rtm_family = (alen == 4) ? AF_INET : AF_INET6,
1325                 .rtm_dst_len = route->mask,
1326                 .rtm_src_len = route->sourcemask,
1327                 .rtm_table = (table < 256) ? table : RT_TABLE_UNSPEC,
1328                 .rtm_protocol = (route->flags & DEVADDR_KERNEL) ? RTPROT_KERNEL : RTPROT_STATIC,
1329                 .rtm_scope = RT_SCOPE_NOWHERE,
1330                 .rtm_type = (cmd == RTM_DELROUTE) ? 0: RTN_UNICAST,
1331                 .rtm_flags = (route->flags & DEVROUTE_ONLINK) ? RTNH_F_ONLINK : 0,
1332         };
1333         struct nl_msg *msg;
1334
1335         if (cmd == RTM_NEWROUTE) {
1336                 flags |= NLM_F_CREATE | NLM_F_REPLACE;
1337
1338                 if (!dev) { // Add null-route
1339                         rtm.rtm_scope = RT_SCOPE_UNIVERSE;
1340                         rtm.rtm_type = RTN_UNREACHABLE;
1341                 }
1342                 else
1343                         rtm.rtm_scope = (have_gw) ? RT_SCOPE_UNIVERSE : RT_SCOPE_LINK;
1344         }
1345
1346         if (route->flags & DEVROUTE_TYPE) {
1347                 rtm.rtm_type = route->type;
1348                 if (!(route->flags & (DEVROUTE_TABLE | DEVROUTE_SRCTABLE))) {
1349                         if (rtm.rtm_type == RTN_LOCAL || rtm.rtm_type == RTN_BROADCAST ||
1350                             rtm.rtm_type == RTN_NAT || rtm.rtm_type == RTN_ANYCAST)
1351                                 rtm.rtm_table = RT_TABLE_LOCAL;
1352                 }
1353
1354                 if (rtm.rtm_type == RTN_LOCAL || rtm.rtm_type == RTN_NAT)
1355                         rtm.rtm_scope = RT_SCOPE_HOST;
1356                 else if (rtm.rtm_type == RTN_BROADCAST || rtm.rtm_type == RTN_MULTICAST ||
1357                         rtm.rtm_type == RTN_ANYCAST)
1358                         rtm.rtm_scope = RT_SCOPE_LINK;
1359         }
1360
1361         msg = nlmsg_alloc_simple(cmd, flags);
1362         if (!msg)
1363                 return -1;
1364
1365         nlmsg_append(msg, &rtm, sizeof(rtm), 0);
1366
1367         if (route->mask)
1368                 nla_put(msg, RTA_DST, alen, &route->addr);
1369
1370         if (route->sourcemask)
1371                 nla_put(msg, RTA_SRC, alen, &route->source);
1372
1373         if (route->metric > 0)
1374                 nla_put_u32(msg, RTA_PRIORITY, route->metric);
1375
1376         if (have_gw)
1377                 nla_put(msg, RTA_GATEWAY, alen, &route->nexthop);
1378
1379         if (dev)
1380                 nla_put_u32(msg, RTA_OIF, dev->ifindex);
1381
1382         if (table >= 256)
1383                 nla_put_u32(msg, RTA_TABLE, table);
1384
1385         if (route->flags & DEVROUTE_MTU) {
1386                 struct nlattr *metrics;
1387
1388                 if (!(metrics = nla_nest_start(msg, RTA_METRICS)))
1389                         goto nla_put_failure;
1390
1391                 nla_put_u32(msg, RTAX_MTU, route->mtu);
1392
1393                 nla_nest_end(msg, metrics);
1394         }
1395
1396         return system_rtnl_call(msg);
1397
1398 nla_put_failure:
1399         nlmsg_free(msg);
1400         return -ENOMEM;
1401 }
1402
1403 int system_add_route(struct device *dev, struct device_route *route)
1404 {
1405         return system_rt(dev, route, RTM_NEWROUTE);
1406 }
1407
1408 int system_del_route(struct device *dev, struct device_route *route)
1409 {
1410         return system_rt(dev, route, RTM_DELROUTE);
1411 }
1412
1413 int system_flush_routes(void)
1414 {
1415         const char *names[] = {
1416                 "/proc/sys/net/ipv4/route/flush",
1417                 "/proc/sys/net/ipv6/route/flush"
1418         };
1419         int fd, i;
1420
1421         for (i = 0; i < ARRAY_SIZE(names); i++) {
1422                 fd = open(names[i], O_WRONLY);
1423                 if (fd < 0)
1424                         continue;
1425
1426                 if (write(fd, "-1", 2)) {}
1427                 close(fd);
1428         }
1429         return 0;
1430 }
1431
1432 bool system_resolve_rt_type(const char *type, unsigned int *id)
1433 {
1434         return system_rtn_aton(type, id);
1435 }
1436
1437 bool system_resolve_rt_table(const char *name, unsigned int *id)
1438 {
1439         FILE *f;
1440         char *e, buf[128];
1441         unsigned int n, table = RT_TABLE_UNSPEC;
1442
1443         /* first try to parse table as number */
1444         if ((n = strtoul(name, &e, 0)) > 0 && !*e)
1445                 table = n;
1446
1447         /* handle well known aliases */
1448         else if (!strcmp(name, "default"))
1449                 table = RT_TABLE_DEFAULT;
1450         else if (!strcmp(name, "main"))
1451                 table = RT_TABLE_MAIN;
1452         else if (!strcmp(name, "local"))
1453                 table = RT_TABLE_LOCAL;
1454
1455         /* try to look up name in /etc/iproute2/rt_tables */
1456         else if ((f = fopen("/etc/iproute2/rt_tables", "r")) != NULL)
1457         {
1458                 while (fgets(buf, sizeof(buf) - 1, f) != NULL)
1459                 {
1460                         if ((e = strtok(buf, " \t\n")) == NULL || *e == '#')
1461                                 continue;
1462
1463                         n = strtoul(e, NULL, 10);
1464                         e = strtok(NULL, " \t\n");
1465
1466                         if (e && !strcmp(e, name))
1467                         {
1468                                 table = n;
1469                                 break;
1470                         }
1471                 }
1472
1473                 fclose(f);
1474         }
1475
1476         if (table == RT_TABLE_UNSPEC)
1477                 return false;
1478
1479         *id = table;
1480         return true;
1481 }
1482
1483 bool system_is_default_rt_table(unsigned int id)
1484 {
1485         return (id == RT_TABLE_MAIN);
1486 }
1487
1488 static int system_iprule(struct iprule *rule, int cmd)
1489 {
1490         int alen = ((rule->flags & IPRULE_FAMILY) == IPRULE_INET4) ? 4 : 16;
1491
1492         struct nl_msg *msg;
1493         struct rtmsg rtm = {
1494                 .rtm_family = (alen == 4) ? AF_INET : AF_INET6,
1495                 .rtm_protocol = RTPROT_STATIC,
1496                 .rtm_scope = RT_SCOPE_UNIVERSE,
1497                 .rtm_table = RT_TABLE_UNSPEC,
1498                 .rtm_type = RTN_UNSPEC,
1499                 .rtm_flags = 0,
1500         };
1501
1502         if (cmd == RTM_NEWRULE) {
1503                 rtm.rtm_type = RTN_UNICAST;
1504                 rtm.rtm_flags |= NLM_F_REPLACE | NLM_F_EXCL;
1505         }
1506
1507         if (rule->invert)
1508                 rtm.rtm_flags |= FIB_RULE_INVERT;
1509
1510         if (rule->flags & IPRULE_SRC)
1511                 rtm.rtm_src_len = rule->src_mask;
1512
1513         if (rule->flags & IPRULE_DEST)
1514                 rtm.rtm_dst_len = rule->dest_mask;
1515
1516         if (rule->flags & IPRULE_TOS)
1517                 rtm.rtm_tos = rule->tos;
1518
1519         if (rule->flags & IPRULE_LOOKUP) {
1520                 if (rule->lookup < 256)
1521                         rtm.rtm_table = rule->lookup;
1522         }
1523
1524         if (rule->flags & IPRULE_ACTION)
1525                 rtm.rtm_type = rule->action;
1526         else if (rule->flags & IPRULE_GOTO)
1527                 rtm.rtm_type = FR_ACT_GOTO;
1528         else if (!(rule->flags & (IPRULE_LOOKUP | IPRULE_ACTION | IPRULE_GOTO)))
1529                 rtm.rtm_type = FR_ACT_NOP;
1530
1531         msg = nlmsg_alloc_simple(cmd, NLM_F_REQUEST);
1532
1533         if (!msg)
1534                 return -1;
1535
1536         nlmsg_append(msg, &rtm, sizeof(rtm), 0);
1537
1538         if (rule->flags & IPRULE_IN)
1539                 nla_put(msg, FRA_IFNAME, strlen(rule->in_dev) + 1, rule->in_dev);
1540
1541         if (rule->flags & IPRULE_OUT)
1542                 nla_put(msg, FRA_OIFNAME, strlen(rule->out_dev) + 1, rule->out_dev);
1543
1544         if (rule->flags & IPRULE_SRC)
1545                 nla_put(msg, FRA_SRC, alen, &rule->src_addr);
1546
1547         if (rule->flags & IPRULE_DEST)
1548                 nla_put(msg, FRA_DST, alen, &rule->dest_addr);
1549
1550         if (rule->flags & IPRULE_PRIORITY)
1551                 nla_put_u32(msg, FRA_PRIORITY, rule->priority);
1552         else if (cmd == RTM_NEWRULE)
1553                 nla_put_u32(msg, FRA_PRIORITY, rule->order);
1554
1555         if (rule->flags & IPRULE_FWMARK)
1556                 nla_put_u32(msg, FRA_FWMARK, rule->fwmark);
1557
1558         if (rule->flags & IPRULE_FWMASK)
1559                 nla_put_u32(msg, FRA_FWMASK, rule->fwmask);
1560
1561         if (rule->flags & IPRULE_LOOKUP) {
1562                 if (rule->lookup >= 256)
1563                         nla_put_u32(msg, FRA_TABLE, rule->lookup);
1564         }
1565
1566         if (rule->flags & IPRULE_GOTO)
1567                 nla_put_u32(msg, FRA_GOTO, rule->gotoid);
1568
1569         return system_rtnl_call(msg);
1570 }
1571
1572 int system_add_iprule(struct iprule *rule)
1573 {
1574         return system_iprule(rule, RTM_NEWRULE);
1575 }
1576
1577 int system_del_iprule(struct iprule *rule)
1578 {
1579         return system_iprule(rule, RTM_DELRULE);
1580 }
1581
1582 int system_flush_iprules(void)
1583 {
1584         int rv = 0;
1585         struct iprule rule;
1586
1587         system_if_clear_entries(NULL, RTM_GETRULE, AF_INET);
1588         system_if_clear_entries(NULL, RTM_GETRULE, AF_INET6);
1589
1590         memset(&rule, 0, sizeof(rule));
1591
1592
1593         rule.flags = IPRULE_INET4 | IPRULE_PRIORITY | IPRULE_LOOKUP;
1594
1595         rule.priority = 0;
1596         rule.lookup = RT_TABLE_LOCAL;
1597         rv |= system_iprule(&rule, RTM_NEWRULE);
1598
1599         rule.priority = 32766;
1600         rule.lookup = RT_TABLE_MAIN;
1601         rv |= system_iprule(&rule, RTM_NEWRULE);
1602
1603         rule.priority = 32767;
1604         rule.lookup = RT_TABLE_DEFAULT;
1605         rv |= system_iprule(&rule, RTM_NEWRULE);
1606
1607
1608         rule.flags = IPRULE_INET6 | IPRULE_PRIORITY | IPRULE_LOOKUP;
1609
1610         rule.priority = 0;
1611         rule.lookup = RT_TABLE_LOCAL;
1612         rv |= system_iprule(&rule, RTM_NEWRULE);
1613
1614         rule.priority = 32766;
1615         rule.lookup = RT_TABLE_MAIN;
1616         rv |= system_iprule(&rule, RTM_NEWRULE);
1617
1618         return rv;
1619 }
1620
1621 bool system_resolve_iprule_action(const char *action, unsigned int *id)
1622 {
1623         return system_rtn_aton(action, id);
1624 }
1625
1626 time_t system_get_rtime(void)
1627 {
1628         struct timespec ts;
1629         struct timeval tv;
1630
1631         if (syscall(__NR_clock_gettime, CLOCK_MONOTONIC, &ts) == 0)
1632                 return ts.tv_sec;
1633
1634         if (gettimeofday(&tv, NULL) == 0)
1635                 return tv.tv_sec;
1636
1637         return 0;
1638 }
1639
1640 #ifndef IP_DF
1641 #define IP_DF       0x4000
1642 #endif
1643
1644 static int tunnel_ioctl(const char *name, int cmd, void *p)
1645 {
1646         struct ifreq ifr;
1647
1648         memset(&ifr, 0, sizeof(ifr));
1649         strncpy(ifr.ifr_name, name, sizeof(ifr.ifr_name));
1650         ifr.ifr_ifru.ifru_data = p;
1651         return ioctl(sock_ioctl, cmd, &ifr);
1652 }
1653
1654 int system_del_ip_tunnel(const char *name)
1655 {
1656         return tunnel_ioctl(name, SIOCDELTUNNEL, NULL);
1657 }
1658
1659 int system_update_ipv6_mtu(struct device *dev, int mtu)
1660 {
1661         int ret = -1;
1662         char buf[64];
1663         snprintf(buf, sizeof(buf), "/proc/sys/net/ipv6/conf/%s/mtu",
1664                         dev->ifname);
1665
1666         int fd = open(buf, O_RDWR);
1667         ssize_t len = read(fd, buf, sizeof(buf) - 1);
1668         if (len < 0)
1669                 goto out;
1670
1671         buf[len] = 0;
1672         ret = atoi(buf);
1673
1674         if (!mtu || ret <= mtu)
1675                 goto out;
1676
1677         lseek(fd, 0, SEEK_SET);
1678         if (write(fd, buf, snprintf(buf, sizeof(buf), "%i", mtu)) <= 0)
1679                 ret = -1;
1680
1681 out:
1682         close(fd);
1683         return ret;
1684 }
1685
1686 int system_add_ip_tunnel(const char *name, struct blob_attr *attr)
1687 {
1688         struct blob_attr *tb[__TUNNEL_ATTR_MAX];
1689         struct blob_attr *cur;
1690         bool set_df = true;
1691         const char *str;
1692
1693         system_del_ip_tunnel(name);
1694
1695         blobmsg_parse(tunnel_attr_list.params, __TUNNEL_ATTR_MAX, tb,
1696                 blob_data(attr), blob_len(attr));
1697
1698         if (!(cur = tb[TUNNEL_ATTR_TYPE]))
1699                 return -EINVAL;
1700         str = blobmsg_data(cur);
1701
1702         if ((cur = tb[TUNNEL_ATTR_DF]))
1703                 set_df = blobmsg_get_bool(cur);
1704
1705         unsigned int ttl = 0;
1706         if ((cur = tb[TUNNEL_ATTR_TTL])) {
1707                 ttl = blobmsg_get_u32(cur);
1708                 if (ttl > 255 || (!set_df && ttl))
1709                         return -EINVAL;
1710         }
1711
1712         unsigned int link = 0;
1713         if ((cur = tb[TUNNEL_ATTR_LINK])) {
1714                 struct interface *iface = vlist_find(&interfaces, blobmsg_data(cur), iface, node);
1715                 if (!iface)
1716                         return -EINVAL;
1717
1718                 if (iface->l3_dev.dev)
1719                         link = iface->l3_dev.dev->ifindex;
1720         }
1721
1722         if (!strcmp(str, "sit")) {
1723                 struct ip_tunnel_parm p = {
1724                         .link = link,
1725                         .iph = {
1726                                 .version = 4,
1727                                 .ihl = 5,
1728                                 .frag_off = set_df ? htons(IP_DF) : 0,
1729                                 .protocol = IPPROTO_IPV6,
1730                                 .ttl = ttl
1731                         }
1732                 };
1733
1734                 if ((cur = tb[TUNNEL_ATTR_LOCAL]) &&
1735                                 inet_pton(AF_INET, blobmsg_data(cur), &p.iph.saddr) < 1)
1736                         return -EINVAL;
1737
1738                 if ((cur = tb[TUNNEL_ATTR_REMOTE]) &&
1739                                 inet_pton(AF_INET, blobmsg_data(cur), &p.iph.daddr) < 1)
1740                         return -EINVAL;
1741
1742                 strncpy(p.name, name, sizeof(p.name));
1743                 if (tunnel_ioctl("sit0", SIOCADDTUNNEL, &p) < 0)
1744                         return -1;
1745
1746 #ifdef SIOCADD6RD
1747                 if ((cur = tb[TUNNEL_ATTR_6RD_PREFIX])) {
1748                         unsigned int mask;
1749                         struct ip_tunnel_6rd p6;
1750
1751                         memset(&p6, 0, sizeof(p6));
1752
1753                         if (!parse_ip_and_netmask(AF_INET6, blobmsg_data(cur),
1754                                                 &p6.prefix, &mask) || mask > 128)
1755                                 return -EINVAL;
1756                         p6.prefixlen = mask;
1757
1758                         if ((cur = tb[TUNNEL_ATTR_6RD_RELAY_PREFIX])) {
1759                                 if (!parse_ip_and_netmask(AF_INET, blobmsg_data(cur),
1760                                                         &p6.relay_prefix, &mask) || mask > 32)
1761                                         return -EINVAL;
1762                                 p6.relay_prefixlen = mask;
1763                         }
1764
1765                         if (tunnel_ioctl(name, SIOCADD6RD, &p6) < 0) {
1766                                 system_del_ip_tunnel(name);
1767                                 return -1;
1768                         }
1769                 }
1770 #endif
1771         } else if (!strcmp(str, "ipip6")) {
1772                 struct nl_msg *nlm = nlmsg_alloc_simple(RTM_NEWLINK,
1773                                 NLM_F_REQUEST | NLM_F_REPLACE | NLM_F_CREATE);
1774                 struct ifinfomsg ifi = { .ifi_family = AF_UNSPEC };
1775                 int ret = 0;
1776
1777                 if (!nlm)
1778                         return -1;
1779
1780                 nlmsg_append(nlm, &ifi, sizeof(ifi), 0);
1781                 nla_put_string(nlm, IFLA_IFNAME, name);
1782
1783                 if (link)
1784                         nla_put_u32(nlm, IFLA_LINK, link);
1785
1786                 struct nlattr *linkinfo = nla_nest_start(nlm, IFLA_LINKINFO);
1787                 if (!linkinfo) {
1788                         ret = -ENOMEM;
1789                         goto failure;
1790                 }
1791                 nla_put_string(nlm, IFLA_INFO_KIND, "ip6tnl");
1792                 struct nlattr *infodata = nla_nest_start(nlm, IFLA_INFO_DATA);
1793                 if (!infodata) {
1794                         ret = -ENOMEM;
1795                         goto failure;
1796                 }
1797
1798                 if (link)
1799                         nla_put_u32(nlm, IFLA_IPTUN_LINK, link);
1800
1801                 nla_put_u8(nlm, IFLA_IPTUN_PROTO, IPPROTO_IPIP);
1802                 nla_put_u8(nlm, IFLA_IPTUN_TTL, (ttl) ? ttl : 64);
1803                 nla_put_u8(nlm, IFLA_IPTUN_ENCAP_LIMIT, 4);
1804
1805                 struct in6_addr in6buf;
1806                 if ((cur = tb[TUNNEL_ATTR_LOCAL])) {
1807                         if (inet_pton(AF_INET6, blobmsg_data(cur), &in6buf) < 1) {
1808                                 ret = -EINVAL;
1809                                 goto failure;
1810                         }
1811                         nla_put(nlm, IFLA_IPTUN_LOCAL, sizeof(in6buf), &in6buf);
1812                 }
1813
1814                 if ((cur = tb[TUNNEL_ATTR_REMOTE])) {
1815                         if (inet_pton(AF_INET6, blobmsg_data(cur), &in6buf) < 1) {
1816                                 ret = -EINVAL;
1817                                 goto failure;
1818                         }
1819                         nla_put(nlm, IFLA_IPTUN_REMOTE, sizeof(in6buf), &in6buf);
1820                 }
1821
1822 #ifdef IFLA_IPTUN_FMR_MAX
1823                 if ((cur = tb[TUNNEL_ATTR_FMRS])) {
1824                         struct nlattr *fmrs = nla_nest_start(nlm, IFLA_IPTUN_FMRS);
1825
1826                         struct blob_attr *fmr;
1827                         unsigned rem, fmrcnt = 0;
1828                         blobmsg_for_each_attr(fmr, cur, rem) {
1829                                 if (blobmsg_type(fmr) != BLOBMSG_TYPE_STRING)
1830                                         continue;
1831
1832                                 unsigned ip4len, ip6len, ealen, offset = 6;
1833                                 char ip6buf[48];
1834                                 char ip4buf[16];
1835
1836                                 if (sscanf(blobmsg_get_string(fmr), "%47[^/]/%u,%15[^/]/%u,%u,%u",
1837                                                 ip6buf, &ip6len, ip4buf, &ip4len, &ealen, &offset) < 5) {
1838                                         ret = -EINVAL;
1839                                         goto failure;
1840                                 }
1841
1842                                 struct in6_addr ip6prefix;
1843                                 struct in_addr ip4prefix;
1844                                 if (inet_pton(AF_INET6, ip6buf, &ip6prefix) != 1 ||
1845                                                 inet_pton(AF_INET, ip4buf, &ip4prefix) != 1) {
1846                                         ret = -EINVAL;
1847                                         goto failure;
1848                                 }
1849
1850                                 struct nlattr *rule = nla_nest_start(nlm, ++fmrcnt);
1851
1852                                 nla_put(nlm, IFLA_IPTUN_FMR_IP6_PREFIX, sizeof(ip6prefix), &ip6prefix);
1853                                 nla_put(nlm, IFLA_IPTUN_FMR_IP4_PREFIX, sizeof(ip4prefix), &ip4prefix);
1854                                 nla_put_u8(nlm, IFLA_IPTUN_FMR_IP6_PREFIX_LEN, ip6len);
1855                                 nla_put_u8(nlm, IFLA_IPTUN_FMR_IP4_PREFIX_LEN, ip4len);
1856                                 nla_put_u8(nlm, IFLA_IPTUN_FMR_EA_LEN, ealen);
1857                                 nla_put_u8(nlm, IFLA_IPTUN_FMR_OFFSET, offset);
1858
1859                                 nla_nest_end(nlm, rule);
1860                         }
1861
1862                         nla_nest_end(nlm, fmrs);
1863                 }
1864 #endif
1865
1866                 nla_nest_end(nlm, infodata);
1867                 nla_nest_end(nlm, linkinfo);
1868
1869                 return system_rtnl_call(nlm);
1870 failure:
1871                 nlmsg_free(nlm);
1872                 return ret;
1873         }
1874         else
1875                 return -EINVAL;
1876
1877         return 0;
1878 }