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