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