• source navigation  • diff markup  • identifier search  • freetext search  • 

Sources/netifd/system-linux.c

  1 /*
  2  * netifd - network interface daemon
  3  * Copyright (C) 2012 Felix Fietkau <nbd@openwrt.org>
  4  * Copyright (C) 2013 Jo-Philipp Wich <jow@openwrt.org>
  5  * Copyright (C) 2013 Steven Barth <steven@midlink.org>
  6  * Copyright (C) 2014 Gioacchino Mazzurco <gio@eigenlab.org>
  7  * Copyright (C) 2017 Matthias Schiffer <mschiffer@universe-factory.net>
  8  * Copyright (C) 2018 Hans Dedecker <dedeckeh@gmail.com>
  9  *
 10  * This program is free software; you can redistribute it and/or modify
 11  * it under the terms of the GNU General Public License version 2
 12  * as published by the Free Software Foundation
 13  *
 14  * This program is distributed in the hope that it will be useful,
 15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
 16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 17  * GNU General Public License for more details.
 18  */
 19 #define _GNU_SOURCE
 20 
 21 #include <sys/socket.h>
 22 #include <sys/ioctl.h>
 23 #include <sys/stat.h>
 24 #include <sys/syscall.h>
 25 
 26 #include <net/if.h>
 27 #include <net/if_arp.h>
 28 
 29 #include <arpa/inet.h>
 30 #include <netinet/ether.h>
 31 #include <netinet/in.h>
 32 
 33 #include <linux/rtnetlink.h>
 34 #include <linux/neighbour.h>
 35 #include <linux/sockios.h>
 36 #include <linux/ip.h>
 37 #include <linux/if_addr.h>
 38 #include <linux/if_link.h>
 39 #include <linux/if_vlan.h>
 40 #include <linux/if_bridge.h>
 41 #include <linux/if_tunnel.h>
 42 #include <linux/ip6_tunnel.h>
 43 #include <linux/ethtool.h>
 44 #include <linux/fib_rules.h>
 45 #include <linux/veth.h>
 46 #include <linux/version.h>
 47 
 48 #ifndef RTN_FAILED_POLICY
 49 #define RTN_FAILED_POLICY 12
 50 #endif
 51 
 52 #ifndef IFA_F_NOPREFIXROUTE
 53 #define IFA_F_NOPREFIXROUTE 0x200
 54 #endif
 55 
 56 #ifndef IFA_FLAGS
 57 #define IFA_FLAGS (IFA_MULTICAST + 1)
 58 #endif
 59 
 60 #include <string.h>
 61 #include <fcntl.h>
 62 #include <glob.h>
 63 #include <time.h>
 64 #include <unistd.h>
 65 
 66 #include <netlink/msg.h>
 67 #include <netlink/attr.h>
 68 #include <netlink/socket.h>
 69 #include <libubox/uloop.h>
 70 
 71 #include "netifd.h"
 72 #include "device.h"
 73 #include "system.h"
 74 
 75 struct event_socket {
 76         struct uloop_fd uloop;
 77         struct nl_sock *sock;
 78         int bufsize;
 79 };
 80 
 81 static int sock_ioctl = -1;
 82 static struct nl_sock *sock_rtnl = NULL;
 83 
 84 static int cb_rtnl_event(struct nl_msg *msg, void *arg);
 85 static void handle_hotplug_event(struct uloop_fd *u, unsigned int events);
 86 static int system_add_proto_tunnel(const char *name, const uint8_t proto,
 87                                         const unsigned int link, struct blob_attr **tb);
 88 static int __system_del_ip_tunnel(const char *name, struct blob_attr **tb);
 89 
 90 static char dev_buf[256];
 91 
 92 static void
 93 handler_nl_event(struct uloop_fd *u, unsigned int events)
 94 {
 95         struct event_socket *ev = container_of(u, struct event_socket, uloop);
 96         int err;
 97         socklen_t errlen = sizeof(err);
 98 
 99         if (!u->error) {
100                 nl_recvmsgs_default(ev->sock);
101                 return;
102         }
103 
104         if (getsockopt(u->fd, SOL_SOCKET, SO_ERROR, (void *)&err, &errlen))
105                 goto abort;
106 
107         switch(err) {
108         case ENOBUFS:
109                 /* Increase rx buffer size on netlink socket */
110                 ev->bufsize *= 2;
111                 if (nl_socket_set_buffer_size(ev->sock, ev->bufsize, 0))
112                         goto abort;
113 
114                 /* Request full dump since some info got dropped */
115                 struct rtgenmsg msg = { .rtgen_family = AF_UNSPEC };
116                 nl_send_simple(ev->sock, RTM_GETLINK, NLM_F_DUMP, &msg, sizeof(msg));
117                 break;
118 
119         default:
120                 goto abort;
121         }
122         u->error = false;
123         return;
124 
125 abort:
126         uloop_fd_delete(&ev->uloop);
127         return;
128 }
129 
130 static struct nl_sock *
131 create_socket(int protocol, int groups)
132 {
133         struct nl_sock *sock;
134 
135         sock = nl_socket_alloc();
136         if (!sock)
137                 return NULL;
138 
139         if (groups)
140                 nl_join_groups(sock, groups);
141 
142         if (nl_connect(sock, protocol))
143                 return NULL;
144 
145         return sock;
146 }
147 
148 static bool
149 create_raw_event_socket(struct event_socket *ev, int protocol, int groups,
150                         uloop_fd_handler cb, int flags)
151 {
152         ev->sock = create_socket(protocol, groups);
153         if (!ev->sock)
154                 return false;
155 
156         ev->uloop.fd = nl_socket_get_fd(ev->sock);
157         ev->uloop.cb = cb;
158         if (uloop_fd_add(&ev->uloop, ULOOP_READ|flags))
159                 return false;
160 
161         return true;
162 }
163 
164 static bool
165 create_event_socket(struct event_socket *ev, int protocol,
166                     int (*cb)(struct nl_msg *msg, void *arg))
167 {
168         if (!create_raw_event_socket(ev, protocol, 0, handler_nl_event, ULOOP_ERROR_CB))
169                 return false;
170 
171         /* Install the valid custom callback handler */
172         nl_socket_modify_cb(ev->sock, NL_CB_VALID, NL_CB_CUSTOM, cb, NULL);
173 
174         /* Disable sequence number checking on event sockets */
175         nl_socket_disable_seq_check(ev->sock);
176 
177         /* Increase rx buffer size to 65K on event sockets */
178         ev->bufsize = 65535;
179         if (nl_socket_set_buffer_size(ev->sock, ev->bufsize, 0))
180                 return false;
181 
182         return true;
183 }
184 
185 static bool
186 create_hotplug_event_socket(struct event_socket *ev, int protocol,
187                             void (*cb)(struct uloop_fd *u, unsigned int events))
188 {
189         if (!create_raw_event_socket(ev, protocol, 1, cb, ULOOP_ERROR_CB))
190                 return false;
191 
192         /* Increase rx buffer size to 65K on event sockets */
193         ev->bufsize = 65535;
194         if (nl_socket_set_buffer_size(ev->sock, ev->bufsize, 0))
195                 return false;
196 
197         return true;
198 }
199 
200 static bool
201 system_rtn_aton(const char *src, unsigned int *dst)
202 {
203         char *e;
204         unsigned int n;
205 
206         if (!strcmp(src, "local"))
207                 n = RTN_LOCAL;
208         else if (!strcmp(src, "nat"))
209                 n = RTN_NAT;
210         else if (!strcmp(src, "broadcast"))
211                 n = RTN_BROADCAST;
212         else if (!strcmp(src, "anycast"))
213                 n = RTN_ANYCAST;
214         else if (!strcmp(src, "multicast"))
215                 n = RTN_MULTICAST;
216         else if (!strcmp(src, "prohibit"))
217                 n = RTN_PROHIBIT;
218         else if (!strcmp(src, "unreachable"))
219                 n = RTN_UNREACHABLE;
220         else if (!strcmp(src, "blackhole"))
221                 n = RTN_BLACKHOLE;
222         else if (!strcmp(src, "xresolve"))
223                 n = RTN_XRESOLVE;
224         else if (!strcmp(src, "unicast"))
225                 n = RTN_UNICAST;
226         else if (!strcmp(src, "throw"))
227                 n = RTN_THROW;
228         else if (!strcmp(src, "failed_policy"))
229                 n = RTN_FAILED_POLICY;
230         else {
231                 n = strtoul(src, &e, 0);
232                 if (!e || *e || e == src || n > 255)
233                         return false;
234         }
235 
236         *dst = n;
237         return true;
238 }
239 
240 static bool
241 system_tos_aton(const char *src, unsigned *dst)
242 {
243         char *e;
244 
245         *dst = strtoul(src, &e, 16);
246         if (e == src || *e || *dst > 255)
247                 return false;
248 
249         return true;
250 }
251 
252 int system_init(void)
253 {
254         static struct event_socket rtnl_event;
255         static struct event_socket hotplug_event;
256 
257         sock_ioctl = socket(AF_LOCAL, SOCK_DGRAM, 0);
258         system_fd_set_cloexec(sock_ioctl);
259 
260         /* Prepare socket for routing / address control */
261         sock_rtnl = create_socket(NETLINK_ROUTE, 0);
262         if (!sock_rtnl)
263                 return -1;
264 
265         if (!create_event_socket(&rtnl_event, NETLINK_ROUTE, cb_rtnl_event))
266                 return -1;
267 
268         if (!create_hotplug_event_socket(&hotplug_event, NETLINK_KOBJECT_UEVENT,
269                                          handle_hotplug_event))
270                 return -1;
271 
272         /* Receive network link events form kernel */
273         nl_socket_add_membership(rtnl_event.sock, RTNLGRP_LINK);
274 
275         return 0;
276 }
277 
278 static void system_set_sysctl(const char *path, const char *val)
279 {
280         int fd;
281 
282         fd = open(path, O_WRONLY);
283         if (fd < 0)
284                 return;
285 
286         if (write(fd, val, strlen(val))) {}
287         close(fd);
288 }
289 
290 static void system_set_dev_sysctl(const char *path, const char *device, const char *val)
291 {
292         snprintf(dev_buf, sizeof(dev_buf), path, device);
293         system_set_sysctl(dev_buf, val);
294 }
295 
296 static void system_set_disable_ipv6(struct device *dev, const char *val)
297 {
298         system_set_dev_sysctl("/proc/sys/net/ipv6/conf/%s/disable_ipv6", dev->ifname, val);
299 }
300 
301 static void system_set_rpfilter(struct device *dev, const char *val)
302 {
303         system_set_dev_sysctl("/proc/sys/net/ipv4/conf/%s/rp_filter", dev->ifname, val);
304 }
305 
306 static void system_set_acceptlocal(struct device *dev, const char *val)
307 {
308         system_set_dev_sysctl("/proc/sys/net/ipv4/conf/%s/accept_local", dev->ifname, val);
309 }
310 
311 static void system_set_igmpversion(struct device *dev, const char *val)
312 {
313         system_set_dev_sysctl("/proc/sys/net/ipv4/conf/%s/force_igmp_version", dev->ifname, val);
314 }
315 
316 static void system_set_mldversion(struct device *dev, const char *val)
317 {
318         system_set_dev_sysctl("/proc/sys/net/ipv6/conf/%s/force_mld_version", dev->ifname, val);
319 }
320 
321 static void system_set_neigh4reachabletime(struct device *dev, const char *val)
322 {
323         system_set_dev_sysctl("/proc/sys/net/ipv4/neigh/%s/base_reachable_time_ms", dev->ifname, val);
324 }
325 
326 static void system_set_neigh6reachabletime(struct device *dev, const char *val)
327 {
328         system_set_dev_sysctl("/proc/sys/net/ipv6/neigh/%s/base_reachable_time_ms", dev->ifname, val);
329 }
330 
331 static void system_set_neigh4gcstaletime(struct device *dev, const char *val)
332 {
333         system_set_dev_sysctl("/proc/sys/net/ipv4/neigh/%s/gc_stale_time", dev->ifname, val);
334 }
335 
336 static void system_set_neigh6gcstaletime(struct device *dev, const char *val)
337 {
338         system_set_dev_sysctl("/proc/sys/net/ipv6/neigh/%s/gc_stale_time", dev->ifname, val);
339 }
340 
341 static void system_set_neigh4locktime(struct device *dev, const char *val)
342 {
343         system_set_dev_sysctl("/proc/sys/net/ipv4/neigh/%s/locktime", dev->ifname, val);
344 }
345 
346 static void system_set_dadtransmits(struct device *dev, const char *val)
347 {
348         system_set_dev_sysctl("/proc/sys/net/ipv6/conf/%s/dad_transmits", dev->ifname, val);
349 }
350 
351 static void system_bridge_set_multicast_to_unicast(struct device *dev, const char *val)
352 {
353         system_set_dev_sysctl("/sys/class/net/%s/brport/multicast_to_unicast", dev->ifname, val);
354 }
355 
356 static void system_bridge_set_multicast_fast_leave(struct device *dev, const char *val)
357 {
358         system_set_dev_sysctl("/sys/class/net/%s/brport/multicast_fast_leave", dev->ifname, val);
359 }
360 
361 static void system_bridge_set_hairpin_mode(struct device *dev, const char *val)
362 {
363         system_set_dev_sysctl("/sys/class/net/%s/brport/hairpin_mode", dev->ifname, val);
364 }
365 
366 static void system_bridge_set_isolated(struct device *dev, const char *val)
367 {
368         system_set_dev_sysctl("/sys/class/net/%s/brport/isolated", dev->ifname, val);
369 }
370 
371 static void system_bridge_set_multicast_router(struct device *dev, const char *val, bool bridge)
372 {
373         system_set_dev_sysctl(bridge ? "/sys/class/net/%s/bridge/multicast_router" :
374                                        "/sys/class/net/%s/brport/multicast_router",
375                               dev->ifname, val);
376 }
377 
378 static void system_bridge_set_robustness(struct device *dev, const char *val)
379 {
380         system_set_dev_sysctl("/sys/devices/virtual/net/%s/bridge/multicast_startup_query_count",
381                               dev->ifname, val);
382         system_set_dev_sysctl("/sys/devices/virtual/net/%s/bridge/multicast_last_member_count",
383                               dev->ifname, val);
384 }
385 
386 static void system_bridge_set_query_interval(struct device *dev, const char *val)
387 {
388         system_set_dev_sysctl("/sys/devices/virtual/net/%s/bridge/multicast_query_interval",
389                               dev->ifname, val);
390 }
391 
392 static void system_bridge_set_query_response_interval(struct device *dev, const char *val)
393 {
394         system_set_dev_sysctl("/sys/devices/virtual/net/%s/bridge/multicast_query_response_interval",
395                               dev->ifname, val);
396 }
397 
398 static void system_bridge_set_last_member_interval(struct device *dev, const char *val)
399 {
400         system_set_dev_sysctl("/sys/devices/virtual/net/%s/bridge/multicast_last_member_interval",
401                               dev->ifname, val);
402 }
403 
404 static void system_bridge_set_membership_interval(struct device *dev, const char *val)
405 {
406         system_set_dev_sysctl("/sys/devices/virtual/net/%s/bridge/multicast_membership_interval",
407                               dev->ifname, val);
408 }
409 
410 static void system_bridge_set_other_querier_timeout(struct device *dev, const char *val)
411 {
412         system_set_dev_sysctl("/sys/devices/virtual/net/%s/bridge/multicast_querier_interval",
413                               dev->ifname, val);
414 }
415 
416 static void system_bridge_set_startup_query_interval(struct device *dev, const char *val)
417 {
418         system_set_dev_sysctl("/sys/devices/virtual/net/%s/bridge/multicast_startup_query_interval",
419                               dev->ifname, val);
420 }
421 
422 static void system_bridge_set_stp_state(struct device *dev, const char *val)
423 {
424         system_set_dev_sysctl("/sys/devices/virtual/net/%s/bridge/stp_state", dev->ifname, val);
425 }
426 
427 static void system_bridge_set_forward_delay(struct device *dev, const char *val)
428 {
429         system_set_dev_sysctl("/sys/devices/virtual/net/%s/bridge/forward_delay", dev->ifname, val);
430 }
431 
432 static void system_bridge_set_priority(struct device *dev, const char *val)
433 {
434         system_set_dev_sysctl("/sys/devices/virtual/net/%s/bridge/priority", dev->ifname, val);
435 }
436 
437 static void system_bridge_set_ageing_time(struct device *dev, const char *val)
438 {
439         system_set_dev_sysctl("/sys/devices/virtual/net/%s/bridge/ageing_time", dev->ifname, val);
440 }
441 
442 static void system_bridge_set_hello_time(struct device *dev, const char *val)
443 {
444         system_set_dev_sysctl("/sys/devices/virtual/net/%s/bridge/hello_time", dev->ifname, val);
445 }
446 
447 static void system_bridge_set_max_age(struct device *dev, const char *val)
448 {
449         system_set_dev_sysctl("/sys/devices/virtual/net/%s/bridge/max_age", dev->ifname, val);
450 }
451 
452 static void system_bridge_set_learning(struct device *dev, const char *val)
453 {
454         system_set_dev_sysctl("/sys/class/net/%s/brport/learning", dev->ifname, val);
455 }
456 
457 static void system_bridge_set_unicast_flood(struct device *dev, const char *val)
458 {
459         system_set_dev_sysctl("/sys/class/net/%s/brport/unicast_flood", dev->ifname, val);
460 }
461 
462 static void system_set_sendredirects(struct device *dev, const char *val)
463 {
464         system_set_dev_sysctl("/proc/sys/net/ipv4/conf/%s/send_redirects", dev->ifname, val);
465 }
466 
467 static int system_get_sysctl(const char *path, char *buf, const size_t buf_sz)
468 {
469         int fd = -1, ret = -1;
470 
471         fd = open(path, O_RDONLY);
472         if (fd < 0)
473                 goto out;
474 
475         ssize_t len = read(fd, buf, buf_sz - 1);
476         if (len < 0)
477                 goto out;
478 
479         ret = buf[len] = 0;
480 
481 out:
482         if (fd >= 0)
483                 close(fd);
484 
485         return ret;
486 }
487 
488 static int
489 system_get_dev_sysctl(const char *path, const char *device, char *buf, const size_t buf_sz)
490 {
491         snprintf(dev_buf, sizeof(dev_buf), path, device);
492         return system_get_sysctl(dev_buf, buf, buf_sz);
493 }
494 
495 static int system_get_disable_ipv6(struct device *dev, char *buf, const size_t buf_sz)
496 {
497         return system_get_dev_sysctl("/proc/sys/net/ipv6/conf/%s/disable_ipv6",
498                         dev->ifname, buf, buf_sz);
499 }
500 
501 static int system_get_rpfilter(struct device *dev, char *buf, const size_t buf_sz)
502 {
503         return system_get_dev_sysctl("/proc/sys/net/ipv4/conf/%s/rp_filter",
504                         dev->ifname, buf, buf_sz);
505 }
506 
507 static int system_get_acceptlocal(struct device *dev, char *buf, const size_t buf_sz)
508 {
509         return system_get_dev_sysctl("/proc/sys/net/ipv4/conf/%s/accept_local",
510                         dev->ifname, buf, buf_sz);
511 }
512 
513 static int system_get_igmpversion(struct device *dev, char *buf, const size_t buf_sz)
514 {
515         return system_get_dev_sysctl("/proc/sys/net/ipv4/conf/%s/force_igmp_version",
516                         dev->ifname, buf, buf_sz);
517 }
518 
519 static int system_get_mldversion(struct device *dev, char *buf, const size_t buf_sz)
520 {
521         return system_get_dev_sysctl("/proc/sys/net/ipv6/conf/%s/force_mld_version",
522                         dev->ifname, buf, buf_sz);
523 }
524 
525 static int system_get_neigh4reachabletime(struct device *dev, char *buf, const size_t buf_sz)
526 {
527         return system_get_dev_sysctl("/proc/sys/net/ipv4/neigh/%s/base_reachable_time_ms",
528                         dev->ifname, buf, buf_sz);
529 }
530 
531 static int system_get_neigh6reachabletime(struct device *dev, char *buf, const size_t buf_sz)
532 {
533         return system_get_dev_sysctl("/proc/sys/net/ipv6/neigh/%s/base_reachable_time_ms",
534                         dev->ifname, buf, buf_sz);
535 }
536 
537 static int system_get_neigh4gcstaletime(struct device *dev, char *buf, const size_t buf_sz)
538 {
539         return system_get_dev_sysctl("/proc/sys/net/ipv4/neigh/%s/gc_stale_time",
540                         dev->ifname, buf, buf_sz);
541 }
542 
543 static int system_get_neigh6gcstaletime(struct device *dev, char *buf, const size_t buf_sz)
544 {
545         return system_get_dev_sysctl("/proc/sys/net/ipv6/neigh/%s/gc_stale_time",
546                         dev->ifname, buf, buf_sz);
547 }
548 
549 static int system_get_neigh4locktime(struct device *dev, char *buf, const size_t buf_sz)
550 {
551         return system_get_dev_sysctl("/proc/sys/net/ipv4/neigh/%s/locktime",
552                         dev->ifname, buf, buf_sz);
553 }
554 
555 static int system_get_dadtransmits(struct device *dev, char *buf, const size_t buf_sz)
556 {
557         return system_get_dev_sysctl("/proc/sys/net/ipv6/conf/%s/dad_transmits",
558                         dev->ifname, buf, buf_sz);
559 }
560 
561 static int system_get_sendredirects(struct device *dev, char *buf, const size_t buf_sz)
562 {
563         return system_get_dev_sysctl("/proc/sys/net/ipv4/conf/%s/send_redirects",
564                         dev->ifname, buf, buf_sz);
565 }
566 
567 /* Evaluate netlink messages */
568 static int cb_rtnl_event(struct nl_msg *msg, void *arg)
569 {
570         struct nlmsghdr *nh = nlmsg_hdr(msg);
571         struct nlattr *nla[__IFLA_MAX];
572         int link_state = 0;
573         char buf[10];
574 
575         if (nh->nlmsg_type != RTM_NEWLINK)
576                 goto out;
577 
578         nlmsg_parse(nh, sizeof(struct ifinfomsg), nla, __IFLA_MAX - 1, NULL);
579         if (!nla[IFLA_IFNAME])
580                 goto out;
581 
582         struct device *dev = device_find(nla_data(nla[IFLA_IFNAME]));
583         if (!dev)
584                 goto out;
585 
586         if (!system_get_dev_sysctl("/sys/class/net/%s/carrier", dev->ifname, buf, sizeof(buf)))
587                 link_state = strtoul(buf, NULL, 0);
588 
589         device_set_link(dev, link_state ? true : false);
590 
591 out:
592         return 0;
593 }
594 
595 static void
596 handle_hotplug_msg(char *data, int size)
597 {
598         const char *subsystem = NULL, *interface = NULL, *interface_old = NULL;
599         char *cur, *end, *sep;
600         struct device *dev;
601         int skip;
602         bool add, move = false;
603 
604         if (!strncmp(data, "add@", 4))
605                 add = true;
606         else if (!strncmp(data, "remove@", 7))
607                 add = false;
608         else if (!strncmp(data, "move@", 5)) {
609                 add = true;
610                 move = true;
611         }
612         else
613                 return;
614 
615         skip = strlen(data) + 1;
616         end = data + size;
617 
618         for (cur = data + skip; cur < end; cur += skip) {
619                 skip = strlen(cur) + 1;
620 
621                 sep = strchr(cur, '=');
622                 if (!sep)
623                         continue;
624 
625                 *sep = 0;
626                 if (!strcmp(cur, "INTERFACE"))
627                         interface = sep + 1;
628                 else if (!strcmp(cur, "SUBSYSTEM")) {
629                         subsystem = sep + 1;
630                         if (strcmp(subsystem, "net") != 0)
631                                 return;
632                 } else if (!strcmp(cur, "DEVPATH_OLD")) {
633                         interface_old = strrchr(sep + 1, '/');
634                         if (interface_old)
635                                 interface_old++;
636                 }
637         }
638 
639         if (subsystem && interface) {
640                 if (move && interface_old)
641                         goto move;
642                 else
643                         goto found;
644         }
645 
646         return;
647 
648 move:
649         dev = device_find(interface_old);
650         if (!dev)
651                 goto found;
652 
653         if (dev->type != &simple_device_type)
654                 goto found;
655 
656         device_set_present(dev, false);
657 
658 found:
659         dev = device_find(interface);
660         if (!dev)
661                 return;
662 
663         if (dev->type != &simple_device_type)
664                 return;
665 
666         if (add && system_if_force_external(dev->ifname))
667                 return;
668 
669         device_set_present(dev, add);
670 }
671 
672 static void
673 handle_hotplug_event(struct uloop_fd *u, unsigned int events)
674 {
675         struct event_socket *ev = container_of(u, struct event_socket, uloop);
676         struct sockaddr_nl nla;
677         unsigned char *buf = NULL;
678         int size;
679         int err;
680         socklen_t errlen = sizeof(err);
681 
682         if (!u->error) {
683                 while ((size = nl_recv(ev->sock, &nla, &buf, NULL)) > 0) {
684                         if (nla.nl_pid == 0)
685                                 handle_hotplug_msg((char *) buf, size);
686 
687                         free(buf);
688                 }
689                 return;
690         }
691 
692         if (getsockopt(u->fd, SOL_SOCKET, SO_ERROR, (void *)&err, &errlen))
693                 goto abort;
694 
695         switch(err) {
696         case ENOBUFS:
697                 /* Increase rx buffer size on netlink socket */
698                 ev->bufsize *= 2;
699                 if (nl_socket_set_buffer_size(ev->sock, ev->bufsize, 0))
700                         goto abort;
701                 break;
702 
703         default:
704                 goto abort;
705         }
706         u->error = false;
707         return;
708 
709 abort:
710         uloop_fd_delete(&ev->uloop);
711         return;
712 }
713 
714 static int system_rtnl_call(struct nl_msg *msg)
715 {
716         int ret;
717 
718         ret = nl_send_auto_complete(sock_rtnl, msg);
719         nlmsg_free(msg);
720 
721         if (ret < 0)
722                 return ret;
723 
724         return nl_wait_for_ack(sock_rtnl);
725 }
726 
727 int system_bridge_delbr(struct device *bridge)
728 {
729         return ioctl(sock_ioctl, SIOCBRDELBR, bridge->ifname);
730 }
731 
732 static int system_bridge_if(const char *bridge, struct device *dev, int cmd, void *data)
733 {
734         struct ifreq ifr;
735 
736         memset(&ifr, 0, sizeof(ifr));
737         if (dev)
738                 ifr.ifr_ifindex = dev->ifindex;
739         else
740                 ifr.ifr_data = data;
741         strncpy(ifr.ifr_name, bridge, sizeof(ifr.ifr_name) - 1);
742         return ioctl(sock_ioctl, cmd, &ifr);
743 }
744 
745 static bool system_is_bridge(const char *name, char *buf, int buflen)
746 {
747         struct stat st;
748 
749         snprintf(buf, buflen, "/sys/devices/virtual/net/%s/bridge", name);
750         if (stat(buf, &st) < 0)
751                 return false;
752 
753         return true;
754 }
755 
756 static char *system_get_bridge(const char *name, char *buf, int buflen)
757 {
758         char *path;
759         ssize_t len = -1;
760         glob_t gl;
761 
762         snprintf(buf, buflen, "/sys/devices/virtual/net/*/brif/%s/bridge", name);
763         if (glob(buf, GLOB_NOSORT, NULL, &gl) < 0)
764                 return NULL;
765 
766         if (gl.gl_pathc > 0)
767                 len = readlink(gl.gl_pathv[0], buf, buflen);
768 
769         globfree(&gl);
770 
771         if (len < 0)
772                 return NULL;
773 
774         buf[len] = 0;
775         path = strrchr(buf, '/');
776         if (!path)
777                 return NULL;
778 
779         return path + 1;
780 }
781 
782 static void
783 system_bridge_set_wireless(struct device *bridge, struct device *dev)
784 {
785         bool mcast_to_ucast = dev->wireless_ap;
786         bool hairpin = true;
787 
788         if (bridge->settings.flags & DEV_OPT_MULTICAST_TO_UNICAST &&
789             !bridge->settings.multicast_to_unicast)
790                 mcast_to_ucast = false;
791 
792         if (!mcast_to_ucast || dev->wireless_isolate)
793                 hairpin = false;
794 
795         system_bridge_set_multicast_to_unicast(dev, mcast_to_ucast ? "1" : "");
796         system_bridge_set_hairpin_mode(dev, hairpin ? "1" : "");
797 }
798 
799 int system_bridge_addif(struct device *bridge, struct device *dev)
800 {
801         char buf[64];
802         char *oldbr;
803         int ret = 0;
804 
805         oldbr = system_get_bridge(dev->ifname, dev_buf, sizeof(dev_buf));
806         if (!oldbr || strcmp(oldbr, bridge->ifname) != 0)
807                 ret = system_bridge_if(bridge->ifname, dev, SIOCBRADDIF, NULL);
808 
809         if (dev->wireless)
810                 system_bridge_set_wireless(bridge, dev);
811 
812         if (dev->settings.flags & DEV_OPT_MULTICAST_ROUTER) {
813                 snprintf(buf, sizeof(buf), "%u", dev->settings.multicast_router);
814                 system_bridge_set_multicast_router(dev, buf, false);
815         }
816 
817         if (dev->settings.flags & DEV_OPT_MULTICAST_FAST_LEAVE &&
818             dev->settings.multicast_fast_leave)
819                 system_bridge_set_multicast_fast_leave(dev, "1");
820 
821         if (dev->settings.flags & DEV_OPT_LEARNING &&
822             !dev->settings.learning)
823                 system_bridge_set_learning(dev, "");
824 
825         if (dev->settings.flags & DEV_OPT_UNICAST_FLOOD &&
826             !dev->settings.unicast_flood)
827                 system_bridge_set_unicast_flood(dev, "");
828 
829         if (dev->settings.flags & DEV_OPT_ISOLATE &&
830             dev->settings.isolate)
831                 system_bridge_set_isolated(dev, "1");
832 
833         return ret;
834 }
835 
836 int system_bridge_delif(struct device *bridge, struct device *dev)
837 {
838         return system_bridge_if(bridge->ifname, dev, SIOCBRDELIF, NULL);
839 }
840 
841 int system_if_resolve(struct device *dev)
842 {
843         struct ifreq ifr;
844         strncpy(ifr.ifr_name, dev->ifname, sizeof(ifr.ifr_name) - 1);
845         if (!ioctl(sock_ioctl, SIOCGIFINDEX, &ifr))
846                 return ifr.ifr_ifindex;
847         else
848                 return 0;
849 }
850 
851 static int system_if_flags(const char *ifname, unsigned add, unsigned rem)
852 {
853         struct ifreq ifr;
854 
855         memset(&ifr, 0, sizeof(ifr));
856         strncpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name) - 1);
857         if (ioctl(sock_ioctl, SIOCGIFFLAGS, &ifr) < 0)
858                 return -1;
859 
860         ifr.ifr_flags |= add;
861         ifr.ifr_flags &= ~rem;
862         return ioctl(sock_ioctl, SIOCSIFFLAGS, &ifr);
863 }
864 
865 struct clear_data {
866         struct nl_msg *msg;
867         struct device *dev;
868         int type;
869         int size;
870         int af;
871 };
872 
873 
874 static bool check_ifaddr(struct nlmsghdr *hdr, int ifindex)
875 {
876         struct ifaddrmsg *ifa = NLMSG_DATA(hdr);
877 
878         return ifa->ifa_index == ifindex;
879 }
880 
881 static bool check_route(struct nlmsghdr *hdr, int ifindex)
882 {
883         struct rtmsg *r = NLMSG_DATA(hdr);
884         struct nlattr *tb[__RTA_MAX];
885 
886         if (r->rtm_protocol == RTPROT_KERNEL &&
887             r->rtm_family == AF_INET6)
888                 return false;
889 
890         nlmsg_parse(hdr, sizeof(struct rtmsg), tb, __RTA_MAX - 1, NULL);
891         if (!tb[RTA_OIF])
892                 return false;
893 
894         return *(int *)RTA_DATA(tb[RTA_OIF]) == ifindex;
895 }
896 
897 static bool check_rule(struct nlmsghdr *hdr, int ifindex)
898 {
899         return true;
900 }
901 
902 static int cb_clear_event(struct nl_msg *msg, void *arg)
903 {
904         struct clear_data *clr = arg;
905         struct nlmsghdr *hdr = nlmsg_hdr(msg);
906         bool (*cb)(struct nlmsghdr *, int ifindex);
907         int type;
908 
909         switch(clr->type) {
910         case RTM_GETADDR:
911                 type = RTM_DELADDR;
912                 if (hdr->nlmsg_type != RTM_NEWADDR)
913                         return NL_SKIP;
914 
915                 cb = check_ifaddr;
916                 break;
917         case RTM_GETROUTE:
918                 type = RTM_DELROUTE;
919                 if (hdr->nlmsg_type != RTM_NEWROUTE)
920                         return NL_SKIP;
921 
922                 cb = check_route;
923                 break;
924         case RTM_GETRULE:
925                 type = RTM_DELRULE;
926                 if (hdr->nlmsg_type != RTM_NEWRULE)
927                         return NL_SKIP;
928 
929                 cb = check_rule;
930                 break;
931         default:
932                 return NL_SKIP;
933         }
934 
935         if (!cb(hdr, clr->dev ? clr->dev->ifindex : 0))
936                 return NL_SKIP;
937 
938         if (type == RTM_DELRULE)
939                 D(SYSTEM, "Remove a rule\n");
940         else
941                 D(SYSTEM, "Remove %s from device %s\n",
942                   type == RTM_DELADDR ? "an address" : "a route",
943                   clr->dev->ifname);
944         memcpy(nlmsg_hdr(clr->msg), hdr, hdr->nlmsg_len);
945         hdr = nlmsg_hdr(clr->msg);
946         hdr->nlmsg_type = type;
947         hdr->nlmsg_flags = NLM_F_REQUEST;
948 
949         nl_socket_disable_auto_ack(sock_rtnl);
950         nl_send_auto_complete(sock_rtnl, clr->msg);
951         nl_socket_enable_auto_ack(sock_rtnl);
952 
953         return NL_SKIP;
954 }
955 
956 static int
957 cb_finish_event(struct nl_msg *msg, void *arg)
958 {
959         int *pending = arg;
960         *pending = 0;
961         return NL_STOP;
962 }
963 
964 static int
965 error_handler(struct sockaddr_nl *nla, struct nlmsgerr *err, void *arg)
966 {
967         int *pending = arg;
968         *pending = err->error;
969         return NL_STOP;
970 }
971 
972 static void
973 system_if_clear_entries(struct device *dev, int type, int af)
974 {
975         struct clear_data clr;
976         struct nl_cb *cb = nl_cb_alloc(NL_CB_DEFAULT);
977         struct rtmsg rtm = {
978                 .rtm_family = af,
979                 .rtm_flags = RTM_F_CLONED,
980         };
981         int flags = NLM_F_DUMP;
982         int pending = 1;
983 
984         clr.af = af;
985         clr.dev = dev;
986         clr.type = type;
987         switch (type) {
988         case RTM_GETADDR:
989         case RTM_GETRULE:
990                 clr.size = sizeof(struct rtgenmsg);
991                 break;
992         case RTM_GETROUTE:
993                 clr.size = sizeof(struct rtmsg);
994                 break;
995         default:
996                 return;
997         }
998 
999         if (!cb)
1000                 return;
1001 
1002         clr.msg = nlmsg_alloc_simple(type, flags);
1003         if (!clr.msg)
1004                 goto out;
1005 
1006         nlmsg_append(clr.msg, &rtm, clr.size, 0);
1007         nl_cb_set(cb, NL_CB_VALID, NL_CB_CUSTOM, cb_clear_event, &clr);
1008         nl_cb_set(cb, NL_CB_FINISH, NL_CB_CUSTOM, cb_finish_event, &pending);
1009         nl_cb_err(cb, NL_CB_CUSTOM, error_handler, &pending);
1010 
1011         nl_send_auto_complete(sock_rtnl, clr.msg);
1012         while (pending > 0)
1013                 nl_recvmsgs(sock_rtnl, cb);
1014 
1015         nlmsg_free(clr.msg);
1016 out:
1017         nl_cb_put(cb);
1018 }
1019 
1020 /*
1021  * Clear bridge (membership) state and bring down device
1022  */
1023 void system_if_clear_state(struct device *dev)
1024 {
1025         static char buf[256];
1026         char *bridge;
1027         device_set_ifindex(dev, system_if_resolve(dev));
1028 
1029         if (dev->external || !dev->ifindex)
1030                 return;
1031 
1032         system_if_flags(dev->ifname, 0, IFF_UP);
1033 
1034         if (system_is_bridge(dev->ifname, buf, sizeof(buf))) {
1035                 D(SYSTEM, "Delete existing bridge named '%s'\n", dev->ifname);
1036                 system_bridge_delbr(dev);
1037                 return;
1038         }
1039 
1040         bridge = system_get_bridge(dev->ifname, buf, sizeof(buf));
1041         if (bridge) {
1042                 D(SYSTEM, "Remove device '%s' from bridge '%s'\n", dev->ifname, bridge);
1043                 system_bridge_if(bridge, dev, SIOCBRDELIF, NULL);
1044         }
1045 
1046         system_if_clear_entries(dev, RTM_GETROUTE, AF_INET);
1047         system_if_clear_entries(dev, RTM_GETADDR, AF_INET);
1048         system_if_clear_entries(dev, RTM_GETROUTE, AF_INET6);
1049         system_if_clear_entries(dev, RTM_GETADDR, AF_INET6);
1050         system_if_clear_entries(dev, RTM_GETNEIGH, AF_INET);
1051         system_if_clear_entries(dev, RTM_GETNEIGH, AF_INET6);
1052         system_set_disable_ipv6(dev, "");
1053 }
1054 
1055 static inline unsigned long
1056 sec_to_jiffies(int val)
1057 {
1058         return (unsigned long) val * 100;
1059 }
1060 
1061 static void system_bridge_conf_multicast_deps(struct device *bridge,
1062                                               struct bridge_config *cfg,
1063                                               char *buf,
1064                                               int buf_len)
1065 {
1066         int val;
1067 
1068         if (cfg->flags & BRIDGE_OPT_ROBUSTNESS ||
1069             cfg->flags & BRIDGE_OPT_QUERY_INTERVAL ||
1070             cfg->flags & BRIDGE_OPT_QUERY_RESPONSE_INTERVAL) {
1071                 val = cfg->robustness * cfg->query_interval +
1072                         cfg->query_response_interval;
1073 
1074                 snprintf(buf, buf_len, "%i", val);
1075                 system_bridge_set_membership_interval(bridge, buf);
1076 
1077                 val = cfg->robustness * cfg->query_interval +
1078                         cfg->query_response_interval / 2;
1079 
1080                 snprintf(buf, buf_len, "%i", val);
1081                 system_bridge_set_other_querier_timeout(bridge, buf);
1082         }
1083 
1084         if (cfg->flags & BRIDGE_OPT_QUERY_INTERVAL) {
1085                 val = cfg->query_interval / 4;
1086 
1087                 snprintf(buf, buf_len, "%i", val);
1088                 system_bridge_set_startup_query_interval(bridge, buf);
1089         }
1090 }
1091 
1092 static void system_bridge_conf_multicast(struct device *bridge,
1093                                          struct bridge_config *cfg,
1094                                          char *buf,
1095                                          int buf_len)
1096 {
1097         system_set_dev_sysctl("/sys/devices/virtual/net/%s/bridge/multicast_snooping",
1098                 bridge->ifname, cfg->igmp_snoop ? "1" : "");
1099 
1100         system_set_dev_sysctl("/sys/devices/virtual/net/%s/bridge/multicast_querier",
1101                 bridge->ifname, cfg->multicast_querier ? "1" : "");
1102 
1103         snprintf(buf, buf_len, "%i", cfg->hash_max);
1104         system_set_dev_sysctl("/sys/devices/virtual/net/%s/bridge/hash_max",
1105                 bridge->ifname, buf);
1106 
1107         if (bridge->settings.flags & DEV_OPT_MULTICAST_ROUTER) {
1108                 snprintf(buf, buf_len, "%u", bridge->settings.multicast_router);
1109                 system_bridge_set_multicast_router(bridge, buf, true);
1110         }
1111 
1112         if (cfg->flags & BRIDGE_OPT_ROBUSTNESS) {
1113                 snprintf(buf, buf_len, "%i", cfg->robustness);
1114                 system_bridge_set_robustness(bridge, buf);
1115         }
1116 
1117         if (cfg->flags & BRIDGE_OPT_QUERY_INTERVAL) {
1118                 snprintf(buf, buf_len, "%i", cfg->query_interval);
1119                 system_bridge_set_query_interval(bridge, buf);
1120         }
1121 
1122         if (cfg->flags & BRIDGE_OPT_QUERY_RESPONSE_INTERVAL) {
1123                 snprintf(buf, buf_len, "%i", cfg->query_response_interval);
1124                 system_bridge_set_query_response_interval(bridge, buf);
1125         }
1126 
1127         if (cfg->flags & BRIDGE_OPT_LAST_MEMBER_INTERVAL) {
1128                 snprintf(buf, buf_len, "%i", cfg->last_member_interval);
1129                 system_bridge_set_last_member_interval(bridge, buf);
1130         }
1131 
1132         system_bridge_conf_multicast_deps(bridge, cfg, buf, buf_len);
1133 }
1134 
1135 int system_bridge_addbr(struct device *bridge, struct bridge_config *cfg)
1136 {
1137         char buf[64];
1138 
1139         if (ioctl(sock_ioctl, SIOCBRADDBR, bridge->ifname) < 0)
1140                 return -1;
1141 
1142         system_bridge_set_stp_state(bridge, cfg->stp ? "1" : "");
1143 
1144         snprintf(buf, sizeof(buf), "%lu", sec_to_jiffies(cfg->forward_delay));
1145         system_bridge_set_forward_delay(bridge, buf);
1146 
1147         system_bridge_conf_multicast(bridge, cfg, buf, sizeof(buf));
1148 
1149         snprintf(buf, sizeof(buf), "%d", cfg->priority);
1150         system_bridge_set_priority(bridge, buf);
1151 
1152         if (cfg->flags & BRIDGE_OPT_AGEING_TIME) {
1153                 snprintf(buf, sizeof(buf), "%lu", sec_to_jiffies(cfg->ageing_time));
1154                 system_bridge_set_ageing_time(bridge, buf);
1155         }
1156 
1157         if (cfg->flags & BRIDGE_OPT_HELLO_TIME) {
1158                 snprintf(buf, sizeof(buf), "%lu", sec_to_jiffies(cfg->hello_time));
1159                 system_bridge_set_hello_time(bridge, buf);
1160         }
1161 
1162         if (cfg->flags & BRIDGE_OPT_MAX_AGE) {
1163                 snprintf(buf, sizeof(buf), "%lu", sec_to_jiffies(cfg->max_age));
1164                 system_bridge_set_max_age(bridge, buf);
1165         }
1166 
1167         return 0;
1168 }
1169 
1170 int system_macvlan_add(struct device *macvlan, struct device *dev, struct macvlan_config *cfg)
1171 {
1172         struct nl_msg *msg;
1173         struct nlattr *linkinfo, *data;
1174         struct ifinfomsg iim = { .ifi_family = AF_UNSPEC, };
1175         int i, rv;
1176         static const struct {
1177                 const char *name;
1178                 enum macvlan_mode val;
1179         } modes[] = {
1180                 { "private", MACVLAN_MODE_PRIVATE },
1181                 { "vepa", MACVLAN_MODE_VEPA },
1182                 { "bridge", MACVLAN_MODE_BRIDGE },
1183                 { "passthru", MACVLAN_MODE_PASSTHRU },
1184         };
1185 
1186         msg = nlmsg_alloc_simple(RTM_NEWLINK, NLM_F_REQUEST | NLM_F_CREATE | NLM_F_EXCL);
1187 
1188         if (!msg)
1189                 return -1;
1190 
1191         nlmsg_append(msg, &iim, sizeof(iim), 0);
1192 
1193         if (cfg->flags & MACVLAN_OPT_MACADDR)
1194                 nla_put(msg, IFLA_ADDRESS, sizeof(cfg->macaddr), cfg->macaddr);
1195         nla_put_string(msg, IFLA_IFNAME, macvlan->ifname);
1196         nla_put_u32(msg, IFLA_LINK, dev->ifindex);
1197 
1198         if (!(linkinfo = nla_nest_start(msg, IFLA_LINKINFO)))
1199                 goto nla_put_failure;
1200 
1201         nla_put_string(msg, IFLA_INFO_KIND, "macvlan");
1202 
1203         if (!(data = nla_nest_start(msg, IFLA_INFO_DATA)))
1204                 goto nla_put_failure;
1205 
1206         if (cfg->mode) {
1207                 for (i = 0; i < ARRAY_SIZE(modes); i++) {
1208                         if (strcmp(cfg->mode, modes[i].name) != 0)
1209                                 continue;
1210 
1211                         nla_put_u32(msg, IFLA_MACVLAN_MODE, modes[i].val);
1212                         break;
1213                 }
1214         }
1215 
1216         nla_nest_end(msg, data);
1217         nla_nest_end(msg, linkinfo);
1218 
1219         rv = system_rtnl_call(msg);
1220         if (rv)
1221                 D(SYSTEM, "Error adding macvlan '%s' over '%s': %d\n", macvlan->ifname, dev->ifname, rv);
1222 
1223         return rv;
1224 
1225 nla_put_failure:
1226         nlmsg_free(msg);
1227         return -ENOMEM;
1228 }
1229 
1230 static int system_link_del(const char *ifname)
1231 {
1232         struct nl_msg *msg;
1233         struct ifinfomsg iim = {
1234                 .ifi_family = AF_UNSPEC,
1235                 .ifi_index = 0,
1236         };
1237 
1238         msg = nlmsg_alloc_simple(RTM_DELLINK, NLM_F_REQUEST);
1239 
1240         if (!msg)
1241                 return -1;
1242 
1243         nlmsg_append(msg, &iim, sizeof(iim), 0);
1244         nla_put_string(msg, IFLA_IFNAME, ifname);
1245         return system_rtnl_call(msg);
1246 }
1247 
1248 int system_macvlan_del(struct device *macvlan)
1249 {
1250         return system_link_del(macvlan->ifname);
1251 }
1252 
1253 int system_veth_add(struct device *veth, struct veth_config *cfg)
1254 {
1255         struct nl_msg *msg;
1256         struct ifinfomsg empty_iim = {};
1257         struct nlattr *linkinfo, *data, *veth_info;
1258         int rv;
1259 
1260         msg = nlmsg_alloc_simple(RTM_NEWLINK, NLM_F_REQUEST | NLM_F_CREATE | NLM_F_EXCL);
1261 
1262         if (!msg)
1263                 return -1;
1264 
1265         nlmsg_append(msg, &empty_iim, sizeof(empty_iim), 0);
1266 
1267         if (cfg->flags & VETH_OPT_MACADDR)
1268                 nla_put(msg, IFLA_ADDRESS, sizeof(cfg->macaddr), cfg->macaddr);
1269         nla_put_string(msg, IFLA_IFNAME, veth->ifname);
1270 
1271         if (!(linkinfo = nla_nest_start(msg, IFLA_LINKINFO)))
1272                 goto nla_put_failure;
1273 
1274         nla_put_string(msg, IFLA_INFO_KIND, "veth");
1275 
1276         if (!(data = nla_nest_start(msg, IFLA_INFO_DATA)))
1277                 goto nla_put_failure;
1278 
1279         if (!(veth_info = nla_nest_start(msg, VETH_INFO_PEER)))
1280                 goto nla_put_failure;
1281 
1282         nlmsg_append(msg, &empty_iim, sizeof(empty_iim), 0);
1283 
1284         if (cfg->flags & VETH_OPT_PEER_NAME)
1285                 nla_put_string(msg, IFLA_IFNAME, cfg->peer_name);
1286         if (cfg->flags & VETH_OPT_PEER_MACADDR)
1287                 nla_put(msg, IFLA_ADDRESS, sizeof(cfg->peer_macaddr), cfg->peer_macaddr);
1288 
1289         nla_nest_end(msg, veth_info);
1290         nla_nest_end(msg, data);
1291         nla_nest_end(msg, linkinfo);
1292 
1293         rv = system_rtnl_call(msg);
1294         if (rv) {
1295                 if (cfg->flags & VETH_OPT_PEER_NAME)
1296                         D(SYSTEM, "Error adding veth '%s' with peer '%s': %d\n", veth->ifname, cfg->peer_name, rv);
1297                 else
1298                         D(SYSTEM, "Error adding veth '%s': %d\n", veth->ifname, rv);
1299         }
1300 
1301         return rv;
1302 
1303 nla_put_failure:
1304         nlmsg_free(msg);
1305         return -ENOMEM;
1306 }
1307 
1308 int system_veth_del(struct device *veth)
1309 {
1310         return system_link_del(veth->ifname);
1311 }
1312 
1313 static int system_vlan(struct device *dev, int id)
1314 {
1315         struct vlan_ioctl_args ifr = {
1316                 .cmd = SET_VLAN_NAME_TYPE_CMD,
1317                 .u.name_type = VLAN_NAME_TYPE_RAW_PLUS_VID_NO_PAD,
1318         };
1319 
1320         if (ioctl(sock_ioctl, SIOCSIFVLAN, &ifr) < 0)
1321                 return -1;
1322 
1323         if (id < 0) {
1324                 ifr.cmd = DEL_VLAN_CMD;
1325                 ifr.u.VID = 0;
1326         } else {
1327                 ifr.cmd = ADD_VLAN_CMD;
1328                 ifr.u.VID = id;
1329         }
1330         strncpy(ifr.device1, dev->ifname, sizeof(ifr.device1));
1331         return ioctl(sock_ioctl, SIOCSIFVLAN, &ifr);
1332 }
1333 
1334 int system_vlan_add(struct device *dev, int id)
1335 {
1336         return system_vlan(dev, id);
1337 }
1338 
1339 int system_vlan_del(struct device *dev)
1340 {
1341         return system_vlan(dev, -1);
1342 }
1343 
1344 int system_vlandev_add(struct device *vlandev, struct device *dev, struct vlandev_config *cfg)
1345 {
1346         struct nl_msg *msg;
1347         struct nlattr *linkinfo, *data;
1348         struct ifinfomsg iim = { .ifi_family = AF_UNSPEC };
1349         int rv;
1350 
1351         msg = nlmsg_alloc_simple(RTM_NEWLINK, NLM_F_REQUEST | NLM_F_CREATE | NLM_F_EXCL);
1352 
1353         if (!msg)
1354                 return -1;
1355 
1356         nlmsg_append(msg, &iim, sizeof(iim), 0);
1357         nla_put_string(msg, IFLA_IFNAME, vlandev->ifname);
1358         nla_put_u32(msg, IFLA_LINK, dev->ifindex);
1359 
1360         if (!(linkinfo = nla_nest_start(msg, IFLA_LINKINFO)))
1361                 goto nla_put_failure;
1362 
1363         nla_put_string(msg, IFLA_INFO_KIND, "vlan");
1364 
1365         if (!(data = nla_nest_start(msg, IFLA_INFO_DATA)))
1366                 goto nla_put_failure;
1367 
1368         nla_put_u16(msg, IFLA_VLAN_ID, cfg->vid);
1369 
1370 #if LINUX_VERSION_CODE >= KERNEL_VERSION(3,10,0)
1371         nla_put_u16(msg, IFLA_VLAN_PROTOCOL, htons(cfg->proto));
1372 #else
1373         if(cfg->proto == VLAN_PROTO_8021AD)
1374                 netifd_log_message(L_WARNING, "%s Your kernel is older than linux 3.10.0, 802.1ad is not supported defaulting to 802.1q", vlandev->type->name);
1375 #endif
1376 
1377         nla_nest_end(msg, data);
1378         nla_nest_end(msg, linkinfo);
1379 
1380         rv = system_rtnl_call(msg);
1381         if (rv)
1382                 D(SYSTEM, "Error adding vlandev '%s' over '%s': %d\n", vlandev->ifname, dev->ifname, rv);
1383 
1384         return rv;
1385 
1386 nla_put_failure:
1387         nlmsg_free(msg);
1388         return -ENOMEM;
1389 }
1390 
1391 int system_vlandev_del(struct device *vlandev)
1392 {
1393         return system_link_del(vlandev->ifname);
1394 }
1395 
1396 void
1397 system_if_get_settings(struct device *dev, struct device_settings *s)
1398 {
1399         struct ifreq ifr;
1400         char buf[10];
1401 
1402         memset(&ifr, 0, sizeof(ifr));
1403         strncpy(ifr.ifr_name, dev->ifname, sizeof(ifr.ifr_name) - 1);
1404 
1405         if (ioctl(sock_ioctl, SIOCGIFMTU, &ifr) == 0) {
1406                 s->mtu = ifr.ifr_mtu;
1407                 s->flags |= DEV_OPT_MTU;
1408         }
1409 
1410         s->mtu6 = system_update_ipv6_mtu(dev, 0);
1411         if (s->mtu6 > 0)
1412                 s->flags |= DEV_OPT_MTU6;
1413 
1414         if (ioctl(sock_ioctl, SIOCGIFTXQLEN, &ifr) == 0) {
1415                 s->txqueuelen = ifr.ifr_qlen;
1416                 s->flags |= DEV_OPT_TXQUEUELEN;
1417         }
1418 
1419         if (ioctl(sock_ioctl, SIOCGIFHWADDR, &ifr) == 0) {
1420                 memcpy(s->macaddr, &ifr.ifr_hwaddr.sa_data, sizeof(s->macaddr));
1421                 s->flags |= DEV_OPT_MACADDR;
1422         }
1423 
1424         if (!system_get_disable_ipv6(dev, buf, sizeof(buf))) {
1425                 s->ipv6 = !strtoul(buf, NULL, 0);
1426                 s->flags |= DEV_OPT_IPV6;
1427         }
1428 
1429         if (ioctl(sock_ioctl, SIOCGIFFLAGS, &ifr) == 0) {
1430                 s->promisc = ifr.ifr_flags & IFF_PROMISC;
1431                 s->flags |= DEV_OPT_PROMISC;
1432 
1433                 s->multicast = ifr.ifr_flags & IFF_MULTICAST;
1434                 s->flags |= DEV_OPT_MULTICAST;
1435         }
1436 
1437         if (!system_get_rpfilter(dev, buf, sizeof(buf))) {
1438                 s->rpfilter = strtoul(buf, NULL, 0);
1439                 s->flags |= DEV_OPT_RPFILTER;
1440         }
1441 
1442         if (!system_get_acceptlocal(dev, buf, sizeof(buf))) {
1443                 s->acceptlocal = strtoul(buf, NULL, 0);
1444                 s->flags |= DEV_OPT_ACCEPTLOCAL;
1445         }
1446 
1447         if (!system_get_igmpversion(dev, buf, sizeof(buf))) {
1448                 s->igmpversion = strtoul(buf, NULL, 0);
1449                 s->flags |= DEV_OPT_IGMPVERSION;
1450         }
1451 
1452         if (!system_get_mldversion(dev, buf, sizeof(buf))) {
1453                 s->mldversion = strtoul(buf, NULL, 0);
1454                 s->flags |= DEV_OPT_MLDVERSION;
1455         }
1456 
1457         if (!system_get_neigh4reachabletime(dev, buf, sizeof(buf))) {
1458                 s->neigh4reachabletime = strtoul(buf, NULL, 0);
1459                 s->flags |= DEV_OPT_NEIGHREACHABLETIME;
1460         }
1461 
1462         if (!system_get_neigh6reachabletime(dev, buf, sizeof(buf))) {
1463                 s->neigh6reachabletime = strtoul(buf, NULL, 0);
1464                 s->flags |= DEV_OPT_NEIGHREACHABLETIME;
1465         }
1466 
1467         if (!system_get_neigh4locktime(dev, buf, sizeof(buf))) {
1468                 s->neigh4locktime = strtol(buf, NULL, 0);
1469                 s->flags |= DEV_OPT_NEIGHLOCKTIME;
1470         }
1471 
1472         if (!system_get_neigh4gcstaletime(dev, buf, sizeof(buf))) {
1473                 s->neigh4gcstaletime = strtoul(buf, NULL, 0);
1474                 s->flags |= DEV_OPT_NEIGHGCSTALETIME;
1475         }
1476 
1477         if (!system_get_neigh6gcstaletime(dev, buf, sizeof(buf))) {
1478                 s->neigh6gcstaletime = strtoul(buf, NULL, 0);
1479                 s->flags |= DEV_OPT_NEIGHGCSTALETIME;
1480         }
1481 
1482         if (!system_get_dadtransmits(dev, buf, sizeof(buf))) {
1483                 s->dadtransmits = strtoul(buf, NULL, 0);
1484                 s->flags |= DEV_OPT_DADTRANSMITS;
1485         }
1486 
1487         if (!system_get_sendredirects(dev, buf, sizeof(buf))) {
1488                 s->sendredirects = strtoul(buf, NULL, 0);
1489                 s->flags |= DEV_OPT_SENDREDIRECTS;
1490         }
1491 }
1492 
1493 void
1494 system_if_apply_settings(struct device *dev, struct device_settings *s, unsigned int apply_mask)
1495 {
1496         struct ifreq ifr;
1497         char buf[12];
1498 
1499         memset(&ifr, 0, sizeof(ifr));
1500         strncpy(ifr.ifr_name, dev->ifname, sizeof(ifr.ifr_name) - 1);
1501         if (s->flags & DEV_OPT_MTU & apply_mask) {
1502                 ifr.ifr_mtu = s->mtu;
1503                 if (ioctl(sock_ioctl, SIOCSIFMTU, &ifr) < 0)
1504                         s->flags &= ~DEV_OPT_MTU;
1505         }
1506         if (s->flags & DEV_OPT_MTU6 & apply_mask) {
1507                 system_update_ipv6_mtu(dev, s->mtu6);
1508         }
1509         if (s->flags & DEV_OPT_TXQUEUELEN & apply_mask) {
1510                 ifr.ifr_qlen = s->txqueuelen;
1511                 if (ioctl(sock_ioctl, SIOCSIFTXQLEN, &ifr) < 0)
1512                         s->flags &= ~DEV_OPT_TXQUEUELEN;
1513         }
1514         if ((s->flags & DEV_OPT_MACADDR & apply_mask) && !dev->external) {
1515                 ifr.ifr_hwaddr.sa_family = ARPHRD_ETHER;
1516                 memcpy(&ifr.ifr_hwaddr.sa_data, s->macaddr, sizeof(s->macaddr));
1517                 if (ioctl(sock_ioctl, SIOCSIFHWADDR, &ifr) < 0)
1518                         s->flags &= ~DEV_OPT_MACADDR;
1519         }
1520         if (s->flags & DEV_OPT_IPV6 & apply_mask)
1521                 system_set_disable_ipv6(dev, s->ipv6 ? "" : "1");
1522         if (s->flags & DEV_OPT_PROMISC & apply_mask) {
1523                 if (system_if_flags(dev->ifname, s->promisc ? IFF_PROMISC : 0,
1524                                     !s->promisc ? IFF_PROMISC : 0) < 0)
1525                         s->flags &= ~DEV_OPT_PROMISC;
1526         }
1527         if (s->flags & DEV_OPT_RPFILTER & apply_mask) {
1528                 snprintf(buf, sizeof(buf), "%u", s->rpfilter);
1529                 system_set_rpfilter(dev, buf);
1530         }
1531         if (s->flags & DEV_OPT_ACCEPTLOCAL & apply_mask)
1532                 system_set_acceptlocal(dev, s->acceptlocal ? "1" : "");
1533         if (s->flags & DEV_OPT_IGMPVERSION & apply_mask) {
1534                 snprintf(buf, sizeof(buf), "%u", s->igmpversion);
1535                 system_set_igmpversion(dev, buf);
1536         }
1537         if (s->flags & DEV_OPT_MLDVERSION & apply_mask) {
1538                 snprintf(buf, sizeof(buf), "%u", s->mldversion);
1539                 system_set_mldversion(dev, buf);
1540         }
1541         if (s->flags & DEV_OPT_NEIGHREACHABLETIME & apply_mask) {
1542                 snprintf(buf, sizeof(buf), "%u", s->neigh4reachabletime);
1543                 system_set_neigh4reachabletime(dev, buf);
1544                 snprintf(buf, sizeof(buf), "%u", s->neigh6reachabletime);
1545                 system_set_neigh6reachabletime(dev, buf);
1546         }
1547         if (s->flags & DEV_OPT_NEIGHLOCKTIME & apply_mask) {
1548                 snprintf(buf, sizeof(buf), "%d", s->neigh4locktime);
1549                 system_set_neigh4locktime(dev, buf);
1550         }
1551         if (s->flags & DEV_OPT_NEIGHGCSTALETIME & apply_mask) {
1552                 snprintf(buf, sizeof(buf), "%u", s->neigh4gcstaletime);
1553                 system_set_neigh4gcstaletime(dev, buf);
1554                 snprintf(buf, sizeof(buf), "%u", s->neigh6gcstaletime);
1555                 system_set_neigh6gcstaletime(dev, buf);
1556         }
1557         if (s->flags & DEV_OPT_DADTRANSMITS & apply_mask) {
1558                 snprintf(buf, sizeof(buf), "%u", s->dadtransmits);
1559                 system_set_dadtransmits(dev, buf);
1560         }
1561         if (s->flags & DEV_OPT_MULTICAST & apply_mask) {
1562                 if (system_if_flags(dev->ifname, s->multicast ? IFF_MULTICAST : 0,
1563                                     !s->multicast ? IFF_MULTICAST : 0) < 0)
1564                         s->flags &= ~DEV_OPT_MULTICAST;
1565         }
1566         if (s->flags & DEV_OPT_SENDREDIRECTS & apply_mask)
1567                 system_set_sendredirects(dev, s->sendredirects ? "1" : "");
1568 }
1569 
1570 int system_if_up(struct device *dev)
1571 {
1572         system_if_get_settings(dev, &dev->orig_settings);
1573         /* Only keep orig settings based on what needs to be set */
1574         dev->orig_settings.valid_flags = dev->orig_settings.flags;
1575         dev->orig_settings.flags &= dev->settings.flags;
1576         system_if_apply_settings(dev, &dev->settings, dev->settings.flags);
1577         return system_if_flags(dev->ifname, IFF_UP, 0);
1578 }
1579 
1580 int system_if_down(struct device *dev)
1581 {
1582         int ret = system_if_flags(dev->ifname, 0, IFF_UP);
1583         system_if_apply_settings(dev, &dev->orig_settings, dev->orig_settings.flags);
1584         return ret;
1585 }
1586 
1587 struct if_check_data {
1588         struct device *dev;
1589         int pending;
1590         int ret;
1591 };
1592 
1593 #ifndef IFF_LOWER_UP
1594 #define IFF_LOWER_UP    0x10000
1595 #endif
1596 
1597 static int cb_if_check_valid(struct nl_msg *msg, void *arg)
1598 {
1599         struct nlmsghdr *nh = nlmsg_hdr(msg);
1600         struct ifinfomsg *ifi = NLMSG_DATA(nh);
1601         struct if_check_data *chk = (struct if_check_data *)arg;
1602 
1603         if (nh->nlmsg_type != RTM_NEWLINK)
1604                 return NL_SKIP;
1605 
1606         device_set_present(chk->dev, ifi->ifi_index > 0 ? true : false);
1607         device_set_link(chk->dev, ifi->ifi_flags & IFF_LOWER_UP ? true : false);
1608 
1609         return NL_OK;
1610 }
1611 
1612 static int cb_if_check_ack(struct nl_msg *msg, void *arg)
1613 {
1614         struct if_check_data *chk = (struct if_check_data *)arg;
1615         chk->pending = 0;
1616         return NL_STOP;
1617 }
1618 
1619 static int cb_if_check_error(struct sockaddr_nl *nla, struct nlmsgerr *err, void *arg)
1620 {
1621         struct if_check_data *chk = (struct if_check_data *)arg;
1622 
1623         device_set_present(chk->dev, false);
1624         device_set_link(chk->dev, false);
1625         chk->pending = err->error;
1626 
1627         return NL_STOP;
1628 }
1629 
1630 int system_if_check(struct device *dev)
1631 {
1632         struct nl_cb *cb = nl_cb_alloc(NL_CB_DEFAULT);
1633         struct nl_msg *msg;
1634         struct ifinfomsg ifi = {
1635                 .ifi_family = AF_UNSPEC,
1636                 .ifi_index = 0,
1637         };
1638         struct if_check_data chk = {
1639                 .dev = dev,
1640                 .pending = 1,
1641         };
1642         int ret = 1;
1643 
1644         if (!cb)
1645                 return ret;
1646 
1647         msg = nlmsg_alloc_simple(RTM_GETLINK, 0);
1648         if (!msg)
1649                 goto out;
1650 
1651         if (nlmsg_append(msg, &ifi, sizeof(ifi), 0) ||
1652             nla_put_string(msg, IFLA_IFNAME, dev->ifname))
1653                 goto free;
1654 
1655         nl_cb_set(cb, NL_CB_VALID, NL_CB_CUSTOM, cb_if_check_valid, &chk);
1656         nl_cb_set(cb, NL_CB_ACK, NL_CB_CUSTOM, cb_if_check_ack, &chk);
1657         nl_cb_err(cb, NL_CB_CUSTOM, cb_if_check_error, &chk);
1658 
1659         nl_send_auto_complete(sock_rtnl, msg);
1660         while (chk.pending > 0)
1661                 nl_recvmsgs(sock_rtnl, cb);
1662 
1663         ret = chk.pending;
1664 
1665 free:
1666         nlmsg_free(msg);
1667 out:
1668         nl_cb_put(cb);
1669         return ret;
1670 }
1671 
1672 struct device *
1673 system_if_get_parent(struct device *dev)
1674 {
1675         char buf[64], *devname;
1676         int ifindex, iflink, len;
1677         FILE *f;
1678 
1679         snprintf(buf, sizeof(buf), "/sys/class/net/%s/iflink", dev->ifname);
1680         f = fopen(buf, "r");
1681         if (!f)
1682                 return NULL;
1683 
1684         len = fread(buf, 1, sizeof(buf) - 1, f);
1685         fclose(f);
1686 
1687         if (len <= 0)
1688                 return NULL;
1689 
1690         buf[len] = 0;
1691         iflink = strtoul(buf, NULL, 0);
1692         ifindex = system_if_resolve(dev);
1693         if (!iflink || iflink == ifindex)
1694                 return NULL;
1695 
1696         devname = if_indextoname(iflink, buf);
1697         if (!devname)
1698                 return NULL;
1699 
1700         return device_get(devname, true);
1701 }
1702 
1703 static bool
1704 read_string_file(int dir_fd, const char *file, char *buf, int len)
1705 {
1706         bool ret = false;
1707         char *c;
1708         int fd;
1709 
1710         fd = openat(dir_fd, file, O_RDONLY);
1711         if (fd < 0)
1712                 return false;
1713 
1714 retry:
1715         len = read(fd, buf, len - 1);
1716         if (len < 0) {
1717                 if (errno == EINTR)
1718                         goto retry;
1719         } else if (len > 0) {
1720                         buf[len] = 0;
1721 
1722                         c = strchr(buf, '\n');
1723                         if (c)
1724                                 *c = 0;
1725 
1726                         ret = true;
1727         }
1728 
1729         close(fd);
1730 
1731         return ret;
1732 }
1733 
1734 static bool
1735 read_uint64_file(int dir_fd, const char *file, uint64_t *val)
1736 {
1737         char buf[64];
1738         bool ret = false;
1739 
1740         ret = read_string_file(dir_fd, file, buf, sizeof(buf));
1741         if (ret)
1742                 *val = strtoull(buf, NULL, 0);
1743 
1744         return ret;
1745 }
1746 
1747 /* Assume advertised flags == supported flags */
1748 static const struct {
1749         uint32_t mask;
1750         const char *name;
1751 } ethtool_link_modes[] = {
1752         { ADVERTISED_10baseT_Half, "10baseT-H" },
1753         { ADVERTISED_10baseT_Full, "10baseT-F" },
1754         { ADVERTISED_100baseT_Half, "100baseT-H" },
1755         { ADVERTISED_100baseT_Full, "100baseT-F" },
1756         { ADVERTISED_1000baseT_Half, "1000baseT-H" },
1757         { ADVERTISED_1000baseT_Full, "1000baseT-F" },
1758         { ADVERTISED_1000baseKX_Full, "1000baseKX-F" },
1759         { ADVERTISED_2500baseX_Full, "2500baseX-F" },
1760         { ADVERTISED_10000baseT_Full, "10000baseT-F" },
1761         { ADVERTISED_10000baseKX4_Full, "10000baseKX4-F" },
1762         { ADVERTISED_10000baseKR_Full, "10000baseKR-F" },
1763         { ADVERTISED_20000baseMLD2_Full, "20000baseMLD2-F" },
1764         { ADVERTISED_20000baseKR2_Full, "20000baseKR2-F" },
1765         { ADVERTISED_40000baseKR4_Full, "40000baseKR4-F" },
1766         { ADVERTISED_40000baseCR4_Full, "40000baseCR4-F" },
1767         { ADVERTISED_40000baseSR4_Full, "40000baseSR4-F" },
1768         { ADVERTISED_40000baseLR4_Full, "40000baseLR4-F" },
1769 #ifdef ADVERTISED_56000baseKR4_Full
1770         { ADVERTISED_56000baseKR4_Full, "56000baseKR4-F" },
1771         { ADVERTISED_56000baseCR4_Full, "56000baseCR4-F" },
1772         { ADVERTISED_56000baseSR4_Full, "56000baseSR4-F" },
1773         { ADVERTISED_56000baseLR4_Full, "56000baseLR4-F" },
1774 #endif
1775 };
1776 
1777 static void system_add_link_modes(struct blob_buf *b, __u32 mask)
1778 {
1779         int i;
1780         for (i = 0; i < ARRAY_SIZE(ethtool_link_modes); i++) {
1781                 if (mask & ethtool_link_modes[i].mask)
1782                         blobmsg_add_string(b, NULL, ethtool_link_modes[i].name);
1783         }
1784 }
1785 
1786 bool
1787 system_if_force_external(const char *ifname)
1788 {
1789         char buf[64];
1790         struct stat s;
1791 
1792         snprintf(buf, sizeof(buf), "/sys/class/net/%s/phy80211", ifname);
1793         return stat(buf, &s) == 0;
1794 }
1795 
1796 int
1797 system_if_dump_info(struct device *dev, struct blob_buf *b)
1798 {
1799         struct ethtool_cmd ecmd;
1800         struct ifreq ifr;
1801         char *s;
1802         void *c;
1803 
1804         memset(&ecmd, 0, sizeof(ecmd));
1805         memset(&ifr, 0, sizeof(ifr));
1806         strncpy(ifr.ifr_name, dev->ifname, sizeof(ifr.ifr_name) - 1);
1807         ifr.ifr_data = (caddr_t) &ecmd;
1808         ecmd.cmd = ETHTOOL_GSET;
1809 
1810         if (ioctl(sock_ioctl, SIOCETHTOOL, &ifr) == 0) {
1811                 c = blobmsg_open_array(b, "link-advertising");
1812                 system_add_link_modes(b, ecmd.advertising);
1813                 blobmsg_close_array(b, c);
1814 
1815                 c = blobmsg_open_array(b, "link-partner-advertising");
1816                 system_add_link_modes(b, ecmd.lp_advertising);
1817                 blobmsg_close_array(b, c);
1818 
1819                 c = blobmsg_open_array(b, "link-supported");
1820                 system_add_link_modes(b, ecmd.supported);
1821                 blobmsg_close_array(b, c);
1822 
1823                 s = blobmsg_alloc_string_buffer(b, "speed", 8);
1824                 snprintf(s, 8, "%d%c", ethtool_cmd_speed(&ecmd),
1825                         ecmd.duplex == DUPLEX_HALF ? 'H' : 'F');
1826                 blobmsg_add_string_buffer(b);
1827 
1828                 blobmsg_add_u8(b, "autoneg", !!ecmd.autoneg);
1829         }
1830 
1831         return 0;
1832 }
1833 
1834 int
1835 system_if_dump_stats(struct device *dev, struct blob_buf *b)
1836 {
1837         const char *const counters[] = {
1838                 "collisions",     "rx_frame_errors",   "tx_compressed",
1839                 "multicast",      "rx_length_errors",  "tx_dropped",
1840                 "rx_bytes",       "rx_missed_errors",  "tx_errors",
1841                 "rx_compressed",  "rx_over_errors",    "tx_fifo_errors",
1842                 "rx_crc_errors",  "rx_packets",        "tx_heartbeat_errors",
1843                 "rx_dropped",     "tx_aborted_errors", "tx_packets",
1844                 "rx_errors",      "tx_bytes",          "tx_window_errors",
1845                 "rx_fifo_errors", "tx_carrier_errors",
1846         };
1847         char buf[64];
1848         int stats_dir;
1849         int i;
1850         uint64_t val = 0;
1851 
1852         snprintf(buf, sizeof(buf), "/sys/class/net/%s/statistics", dev->ifname);
1853         stats_dir = open(buf, O_DIRECTORY);
1854         if (stats_dir < 0)
1855                 return -1;
1856 
1857         for (i = 0; i < ARRAY_SIZE(counters); i++)
1858                 if (read_uint64_file(stats_dir, counters[i], &val))
1859                         blobmsg_add_u64(b, counters[i], val);
1860 
1861         close(stats_dir);
1862         return 0;
1863 }
1864 
1865 static int system_addr(struct device *dev, struct device_addr *addr, int cmd)
1866 {
1867         bool v4 = ((addr->flags & DEVADDR_FAMILY) == DEVADDR_INET4);
1868         int alen = v4 ? 4 : 16;
1869         unsigned int flags = 0;
1870         struct ifaddrmsg ifa = {
1871                 .ifa_family = (alen == 4) ? AF_INET : AF_INET6,
1872                 .ifa_prefixlen = addr->mask,
1873                 .ifa_index = dev->ifindex,
1874         };
1875 
1876         struct nl_msg *msg;
1877         if (cmd == RTM_NEWADDR)
1878                 flags |= NLM_F_CREATE | NLM_F_REPLACE;
1879 
1880         msg = nlmsg_alloc_simple(cmd, flags);
1881         if (!msg)
1882                 return -1;
1883 
1884         nlmsg_append(msg, &ifa, sizeof(ifa), 0);
1885         nla_put(msg, IFA_LOCAL, alen, &addr->addr);
1886         if (v4) {
1887                 if (addr->broadcast)
1888                         nla_put_u32(msg, IFA_BROADCAST, addr->broadcast);
1889                 if (addr->point_to_point)
1890                         nla_put_u32(msg, IFA_ADDRESS, addr->point_to_point);
1891         } else {
1892                 time_t now = system_get_rtime();
1893                 struct ifa_cacheinfo cinfo = {0xffffffffU, 0xffffffffU, 0, 0};
1894 
1895                 if (addr->preferred_until) {
1896                         int64_t preferred = addr->preferred_until - now;
1897                         if (preferred < 0)
1898                                 preferred = 0;
1899                         else if (preferred > UINT32_MAX)
1900                                 preferred = UINT32_MAX;
1901 
1902                         cinfo.ifa_prefered = preferred;
1903                 }
1904 
1905                 if (addr->valid_until) {
1906                         int64_t valid = addr->valid_until - now;
1907                         if (valid <= 0) {
1908                                 nlmsg_free(msg);
1909                                 return -1;
1910                         }
1911                         else if (valid > UINT32_MAX)
1912                                 valid = UINT32_MAX;
1913 
1914                         cinfo.ifa_valid = valid;
1915                 }
1916 
1917                 nla_put(msg, IFA_CACHEINFO, sizeof(cinfo), &cinfo);
1918 
1919                 if (cmd == RTM_NEWADDR && (addr->flags & DEVADDR_OFFLINK))
1920                         nla_put_u32(msg, IFA_FLAGS, IFA_F_NOPREFIXROUTE);
1921         }
1922 
1923         return system_rtnl_call(msg);
1924 }
1925 
1926 int system_add_address(struct device *dev, struct device_addr *addr)
1927 {
1928         return system_addr(dev, addr, RTM_NEWADDR);
1929 }
1930 
1931 int system_del_address(struct device *dev, struct device_addr *addr)
1932 {
1933         return system_addr(dev, addr, RTM_DELADDR);
1934 }
1935 
1936 static int system_neigh(struct device *dev, struct device_neighbor *neighbor, int cmd)
1937 {
1938         int alen = ((neighbor->flags & DEVADDR_FAMILY) == DEVADDR_INET4) ? 4 : 16;
1939         unsigned int flags = 0;
1940         struct ndmsg ndm = {
1941                 .ndm_family = (alen == 4) ? AF_INET : AF_INET6,
1942                 .ndm_ifindex = dev->ifindex,
1943                 .ndm_state = NUD_PERMANENT,
1944                 .ndm_flags = (neighbor->proxy ? NTF_PROXY : 0) | (neighbor->router ? NTF_ROUTER : 0),
1945         };
1946         struct nl_msg *msg;
1947 
1948         if (!dev)
1949                 return 1;
1950 
1951         if (cmd == RTM_NEWNEIGH)
1952                 flags |= NLM_F_CREATE | NLM_F_REPLACE;
1953 
1954         msg = nlmsg_alloc_simple(cmd, flags);
1955 
1956         if (!msg)
1957                 return -1;
1958 
1959         nlmsg_append(msg, &ndm, sizeof(ndm), 0);
1960 
1961         nla_put(msg, NDA_DST, alen, &neighbor->addr);
1962         if (neighbor->flags & DEVNEIGH_MAC)
1963                 nla_put(msg, NDA_LLADDR, sizeof(neighbor->macaddr), &neighbor->macaddr);
1964 
1965 
1966         return system_rtnl_call(msg);
1967 }
1968 
1969 int system_add_neighbor(struct device *dev, struct device_neighbor *neighbor)
1970 {
1971         return system_neigh(dev, neighbor, RTM_NEWNEIGH);
1972 }
1973 
1974 int system_del_neighbor(struct device *dev, struct device_neighbor *neighbor)
1975 {
1976         return system_neigh(dev, neighbor, RTM_DELNEIGH);
1977 }
1978 
1979 static int system_rt(struct device *dev, struct device_route *route, int cmd)
1980 {
1981         int alen = ((route->flags & DEVADDR_FAMILY) == DEVADDR_INET4) ? 4 : 16;
1982         bool have_gw;
1983         unsigned int flags = 0;
1984 
1985         if (alen == 4)
1986                 have_gw = !!route->nexthop.in.s_addr;
1987         else
1988                 have_gw = route->nexthop.in6.s6_addr32[0] ||
1989                         route->nexthop.in6.s6_addr32[1] ||
1990                         route->nexthop.in6.s6_addr32[2] ||
1991                         route->nexthop.in6.s6_addr32[3];
1992 
1993         unsigned int table = (route->flags & (DEVROUTE_TABLE | DEVROUTE_SRCTABLE))
1994                         ? route->table : RT_TABLE_MAIN;
1995 
1996         struct rtmsg rtm = {
1997                 .rtm_family = (alen == 4) ? AF_INET : AF_INET6,
1998                 .rtm_dst_len = route->mask,
1999                 .rtm_src_len = route->sourcemask,
2000                 .rtm_table = (table < 256) ? table : RT_TABLE_UNSPEC,
2001                 .rtm_protocol = (route->flags & DEVROUTE_PROTO) ? route->proto : RTPROT_STATIC,
2002                 .rtm_scope = RT_SCOPE_NOWHERE,
2003                 .rtm_type = (cmd == RTM_DELROUTE) ? 0: RTN_UNICAST,
2004                 .rtm_flags = (route->flags & DEVROUTE_ONLINK) ? RTNH_F_ONLINK : 0,
2005         };
2006         struct nl_msg *msg;
2007 
2008         if (cmd == RTM_NEWROUTE) {
2009                 flags |= NLM_F_CREATE | NLM_F_REPLACE;
2010 
2011                 if (!dev) { /* Add null-route */
2012                         rtm.rtm_scope = RT_SCOPE_UNIVERSE;
2013                         rtm.rtm_type = RTN_UNREACHABLE;
2014                 }
2015                 else
2016                         rtm.rtm_scope = (have_gw) ? RT_SCOPE_UNIVERSE : RT_SCOPE_LINK;
2017         }
2018 
2019         if (route->flags & DEVROUTE_TYPE) {
2020                 rtm.rtm_type = route->type;
2021                 if (!(route->flags & (DEVROUTE_TABLE | DEVROUTE_SRCTABLE))) {
2022                         if (rtm.rtm_type == RTN_LOCAL || rtm.rtm_type == RTN_BROADCAST ||
2023                             rtm.rtm_type == RTN_NAT || rtm.rtm_type == RTN_ANYCAST)
2024                                 rtm.rtm_table = RT_TABLE_LOCAL;
2025                 }
2026 
2027                 if (rtm.rtm_type == RTN_LOCAL || rtm.rtm_type == RTN_NAT) {
2028                         rtm.rtm_scope = RT_SCOPE_HOST;
2029                 } else if (rtm.rtm_type == RTN_BROADCAST || rtm.rtm_type == RTN_MULTICAST ||
2030                                 rtm.rtm_type == RTN_ANYCAST) {
2031                         rtm.rtm_scope = RT_SCOPE_LINK;
2032                 } else if (rtm.rtm_type == RTN_BLACKHOLE || rtm.rtm_type == RTN_UNREACHABLE ||
2033                                 rtm.rtm_type == RTN_PROHIBIT || rtm.rtm_type == RTN_FAILED_POLICY ||
2034                                 rtm.rtm_type == RTN_THROW) {
2035                         rtm.rtm_scope = RT_SCOPE_UNIVERSE;
2036                         dev = NULL;
2037                 }
2038         }
2039 
2040         msg = nlmsg_alloc_simple(cmd, flags);
2041         if (!msg)
2042                 return -1;
2043 
2044         nlmsg_append(msg, &rtm, sizeof(rtm), 0);
2045 
2046         if (route->mask)
2047                 nla_put(msg, RTA_DST, alen, &route->addr);
2048 
2049         if (route->sourcemask) {
2050                 if (rtm.rtm_family == AF_INET)
2051                         nla_put(msg, RTA_PREFSRC, alen, &route->source);
2052                 else
2053                         nla_put(msg, RTA_SRC, alen, &route->source);
2054         }
2055 
2056         if (route->metric > 0)
2057                 nla_put_u32(msg, RTA_PRIORITY, route->metric);
2058 
2059         if (have_gw)
2060                 nla_put(msg, RTA_GATEWAY, alen, &route->nexthop);
2061 
2062         if (dev)
2063                 nla_put_u32(msg, RTA_OIF, dev->ifindex);
2064 
2065         if (table >= 256)
2066                 nla_put_u32(msg, RTA_TABLE, table);
2067 
2068         if (route->flags & DEVROUTE_MTU) {
2069                 struct nlattr *metrics;
2070 
2071                 if (!(metrics = nla_nest_start(msg, RTA_METRICS)))
2072                         goto nla_put_failure;
2073 
2074                 nla_put_u32(msg, RTAX_MTU, route->mtu);
2075 
2076                 nla_nest_end(msg, metrics);
2077         }
2078 
2079         return system_rtnl_call(msg);
2080 
2081 nla_put_failure:
2082         nlmsg_free(msg);
2083         return -ENOMEM;
2084 }
2085 
2086 int system_add_route(struct device *dev, struct device_route *route)
2087 {
2088         return system_rt(dev, route, RTM_NEWROUTE);
2089 }
2090 
2091 int system_del_route(struct device *dev, struct device_route *route)
2092 {
2093         return system_rt(dev, route, RTM_DELROUTE);
2094 }
2095 
2096 int system_flush_routes(void)
2097 {
2098         const char *names[] = {
2099                 "/proc/sys/net/ipv4/route/flush",
2100                 "/proc/sys/net/ipv6/route/flush"
2101         };
2102         int fd, i;
2103 
2104         for (i = 0; i < ARRAY_SIZE(names); i++) {
2105                 fd = open(names[i], O_WRONLY);
2106                 if (fd < 0)
2107                         continue;
2108 
2109                 if (write(fd, "-1", 2)) {}
2110                 close(fd);
2111         }
2112         return 0;
2113 }
2114 
2115 bool system_resolve_rt_type(const char *type, unsigned int *id)
2116 {
2117         return system_rtn_aton(type, id);
2118 }
2119 
2120 bool system_resolve_rt_proto(const char *type, unsigned int *id)
2121 {
2122         FILE *f;
2123         char *e, buf[128];
2124         unsigned int n, proto = 256;
2125         n = strtoul(type, &e, 0);
2126         if (!*e && e != type)
2127                 proto = n;
2128         else if (!strcmp(type, "unspec"))
2129                 proto = RTPROT_UNSPEC;
2130         else if (!strcmp(type, "kernel"))
2131                 proto = RTPROT_KERNEL;
2132         else if (!strcmp(type, "boot"))
2133                 proto = RTPROT_BOOT;
2134         else if (!strcmp(type, "static"))
2135                 proto = RTPROT_STATIC;
2136         else if ((f = fopen("/etc/iproute2/rt_protos", "r")) != NULL) {
2137                 while (fgets(buf, sizeof(buf) - 1, f) != NULL) {
2138                         if ((e = strtok(buf, " \t\n")) == NULL || *e == '#')
2139                                 continue;
2140 
2141                         n = strtoul(e, NULL, 10);
2142                         e = strtok(NULL, " \t\n");
2143 
2144                         if (e && !strcmp(e, type)) {
2145                                 proto = n;
2146                                 break;
2147                         }
2148                 }
2149                 fclose(f);
2150         }
2151 
2152         if (proto > 255)
2153                 return false;
2154 
2155         *id = proto;
2156         return true;
2157 }
2158 
2159 bool system_resolve_rt_table(const char *name, unsigned int *id)
2160 {
2161         FILE *f;
2162         char *e, buf[128];
2163         unsigned int n, table = RT_TABLE_UNSPEC;
2164 
2165         /* first try to parse table as number */
2166         if ((n = strtoul(name, &e, 0)) > 0 && !*e)
2167                 table = n;
2168 
2169         /* handle well known aliases */
2170         else if (!strcmp(name, "default"))
2171                 table = RT_TABLE_DEFAULT;
2172         else if (!strcmp(name, "main"))
2173                 table = RT_TABLE_MAIN;
2174         else if (!strcmp(name, "local"))
2175                 table = RT_TABLE_LOCAL;
2176 
2177         /* try to look up name in /etc/iproute2/rt_tables */
2178         else if ((f = fopen("/etc/iproute2/rt_tables", "r")) != NULL)
2179         {
2180                 while (fgets(buf, sizeof(buf) - 1, f) != NULL)
2181                 {
2182                         if ((e = strtok(buf, " \t\n")) == NULL || *e == '#')
2183                                 continue;
2184 
2185                         n = strtoul(e, NULL, 10);
2186                         e = strtok(NULL, " \t\n");
2187 
2188                         if (e && !strcmp(e, name))
2189                         {
2190                                 table = n;
2191                                 break;
2192                         }
2193                 }
2194 
2195                 fclose(f);
2196         }
2197 
2198         if (table == RT_TABLE_UNSPEC)
2199                 return false;
2200 
2201         *id = table;
2202         return true;
2203 }
2204 
2205 bool system_is_default_rt_table(unsigned int id)
2206 {
2207         return (id == RT_TABLE_MAIN);
2208 }
2209 
2210 bool system_resolve_rpfilter(const char *filter, unsigned int *id)
2211 {
2212         char *e;
2213         unsigned int n;
2214 
2215         if (!strcmp(filter, "strict"))
2216                 n = 1;
2217         else if (!strcmp(filter, "loose"))
2218                 n = 2;
2219         else {
2220                 n = strtoul(filter, &e, 0);
2221                 if (*e || e == filter || n > 2)
2222                         return false;
2223         }
2224 
2225         *id = n;
2226         return true;
2227 }
2228 
2229 static int system_iprule(struct iprule *rule, int cmd)
2230 {
2231         int alen = ((rule->flags & IPRULE_FAMILY) == IPRULE_INET4) ? 4 : 16;
2232 
2233         struct nl_msg *msg;
2234         struct rtmsg rtm = {
2235                 .rtm_family = (alen == 4) ? AF_INET : AF_INET6,
2236                 .rtm_protocol = RTPROT_STATIC,
2237                 .rtm_scope = RT_SCOPE_UNIVERSE,
2238                 .rtm_table = RT_TABLE_UNSPEC,
2239                 .rtm_type = RTN_UNSPEC,
2240                 .rtm_flags = 0,
2241         };
2242 
2243         if (cmd == RTM_NEWRULE)
2244                 rtm.rtm_type = RTN_UNICAST;
2245 
2246         if (rule->invert)
2247                 rtm.rtm_flags |= FIB_RULE_INVERT;
2248 
2249         if (rule->flags & IPRULE_SRC)
2250                 rtm.rtm_src_len = rule->src_mask;
2251 
2252         if (rule->flags & IPRULE_DEST)
2253                 rtm.rtm_dst_len = rule->dest_mask;
2254 
2255         if (rule->flags & IPRULE_TOS)
2256                 rtm.rtm_tos = rule->tos;
2257 
2258         if (rule->flags & IPRULE_LOOKUP) {
2259                 if (rule->lookup < 256)
2260                         rtm.rtm_table = rule->lookup;
2261         }
2262 
2263         if (rule->flags & IPRULE_ACTION)
2264                 rtm.rtm_type = rule->action;
2265         else if (rule->flags & IPRULE_GOTO)
2266                 rtm.rtm_type = FR_ACT_GOTO;
2267         else if (!(rule->flags & (IPRULE_LOOKUP | IPRULE_ACTION | IPRULE_GOTO)))
2268                 rtm.rtm_type = FR_ACT_NOP;
2269 
2270         msg = nlmsg_alloc_simple(cmd, NLM_F_REQUEST);
2271 
2272         if (!msg)
2273                 return -1;
2274 
2275         nlmsg_append(msg, &rtm, sizeof(rtm), 0);
2276 
2277         if (rule->flags & IPRULE_IN)
2278                 nla_put(msg, FRA_IFNAME, strlen(rule->in_dev) + 1, rule->in_dev);
2279 
2280         if (rule->flags & IPRULE_OUT)
2281                 nla_put(msg, FRA_OIFNAME, strlen(rule->out_dev) + 1, rule->out_dev);
2282 
2283         if (rule->flags & IPRULE_SRC)
2284                 nla_put(msg, FRA_SRC, alen, &rule->src_addr);
2285 
2286         if (rule->flags & IPRULE_DEST)
2287                 nla_put(msg, FRA_DST, alen, &rule->dest_addr);
2288 
2289         if (rule->flags & IPRULE_PRIORITY)
2290                 nla_put_u32(msg, FRA_PRIORITY, rule->priority);
2291         else if (cmd == RTM_NEWRULE)
2292                 nla_put_u32(msg, FRA_PRIORITY, rule->order);
2293 
2294         if (rule->flags & IPRULE_FWMARK)
2295                 nla_put_u32(msg, FRA_FWMARK, rule->fwmark);
2296 
2297         if (rule->flags & IPRULE_FWMASK)
2298                 nla_put_u32(msg, FRA_FWMASK, rule->fwmask);
2299 
2300         if (rule->flags & IPRULE_LOOKUP) {
2301                 if (rule->lookup >= 256)
2302                         nla_put_u32(msg, FRA_TABLE, rule->lookup);
2303         }
2304 
2305         if (rule->flags & IPRULE_SUP_PREFIXLEN)
2306                 nla_put_u32(msg, FRA_SUPPRESS_PREFIXLEN, rule->sup_prefixlen);
2307 
2308         if (rule->flags & IPRULE_GOTO)
2309                 nla_put_u32(msg, FRA_GOTO, rule->gotoid);
2310 
2311         return system_rtnl_call(msg);
2312 }
2313 
2314 int system_add_iprule(struct iprule *rule)
2315 {
2316         return system_iprule(rule, RTM_NEWRULE);
2317 }
2318 
2319 int system_del_iprule(struct iprule *rule)
2320 {
2321         return system_iprule(rule, RTM_DELRULE);
2322 }
2323 
2324 int system_flush_iprules(void)
2325 {
2326         int rv = 0;
2327         struct iprule rule;
2328 
2329         system_if_clear_entries(NULL, RTM_GETRULE, AF_INET);
2330         system_if_clear_entries(NULL, RTM_GETRULE, AF_INET6);
2331 
2332         memset(&rule, 0, sizeof(rule));
2333 
2334 
2335         rule.flags = IPRULE_INET4 | IPRULE_PRIORITY | IPRULE_LOOKUP;
2336 
2337         rule.priority = 0;
2338         rule.lookup = RT_TABLE_LOCAL;
2339         rv |= system_iprule(&rule, RTM_NEWRULE);
2340 
2341         rule.priority = 32766;
2342         rule.lookup = RT_TABLE_MAIN;
2343         rv |= system_iprule(&rule, RTM_NEWRULE);
2344 
2345         rule.priority = 32767;
2346         rule.lookup = RT_TABLE_DEFAULT;
2347         rv |= system_iprule(&rule, RTM_NEWRULE);
2348 
2349 
2350         rule.flags = IPRULE_INET6 | IPRULE_PRIORITY | IPRULE_LOOKUP;
2351 
2352         rule.priority = 0;
2353         rule.lookup = RT_TABLE_LOCAL;
2354         rv |= system_iprule(&rule, RTM_NEWRULE);
2355 
2356         rule.priority = 32766;
2357         rule.lookup = RT_TABLE_MAIN;
2358         rv |= system_iprule(&rule, RTM_NEWRULE);
2359 
2360         return rv;
2361 }
2362 
2363 bool system_resolve_iprule_action(const char *action, unsigned int *id)
2364 {
2365         return system_rtn_aton(action, id);
2366 }
2367 
2368 time_t system_get_rtime(void)
2369 {
2370         struct timespec ts;
2371         struct timeval tv;
2372 
2373         if (syscall(__NR_clock_gettime, CLOCK_MONOTONIC, &ts) == 0)
2374                 return ts.tv_sec;
2375 
2376         if (gettimeofday(&tv, NULL) == 0)
2377                 return tv.tv_sec;
2378 
2379         return 0;
2380 }
2381 
2382 #ifndef IP_DF
2383 #define IP_DF       0x4000
2384 #endif
2385 
2386 static int tunnel_ioctl(const char *name, int cmd, void *p)
2387 {
2388         struct ifreq ifr;
2389 
2390         memset(&ifr, 0, sizeof(ifr));
2391         strncpy(ifr.ifr_name, name, sizeof(ifr.ifr_name) - 1);
2392         ifr.ifr_ifru.ifru_data = p;
2393         return ioctl(sock_ioctl, cmd, &ifr);
2394 }
2395 
2396 #ifdef IFLA_IPTUN_MAX
2397 static int system_add_ip6_tunnel(const char *name, const unsigned int link,
2398                                  struct blob_attr **tb)
2399 {
2400         struct nl_msg *nlm = nlmsg_alloc_simple(RTM_NEWLINK,
2401                                 NLM_F_REQUEST | NLM_F_REPLACE | NLM_F_CREATE);
2402         struct ifinfomsg ifi = { .ifi_family = AF_UNSPEC };
2403         struct blob_attr *cur;
2404         int ret = 0, ttl = 0;
2405 
2406         if (!nlm)
2407                 return -1;
2408 
2409         nlmsg_append(nlm, &ifi, sizeof(ifi), 0);
2410         nla_put_string(nlm, IFLA_IFNAME, name);
2411 
2412         if (link)
2413                 nla_put_u32(nlm, IFLA_LINK, link);
2414 
2415         struct nlattr *linkinfo = nla_nest_start(nlm, IFLA_LINKINFO);
2416         if (!linkinfo) {
2417                 ret = -ENOMEM;
2418                 goto failure;
2419         }
2420 
2421         nla_put_string(nlm, IFLA_INFO_KIND, "ip6tnl");
2422         struct nlattr *infodata = nla_nest_start(nlm, IFLA_INFO_DATA);
2423         if (!infodata) {
2424                 ret = -ENOMEM;
2425                 goto failure;
2426         }
2427 
2428         if (link)
2429                 nla_put_u32(nlm, IFLA_IPTUN_LINK, link);
2430 
2431         if ((cur = tb[TUNNEL_ATTR_TTL]))
2432                 ttl = blobmsg_get_u32(cur);
2433 
2434         nla_put_u8(nlm, IFLA_IPTUN_PROTO, IPPROTO_IPIP);
2435         nla_put_u8(nlm, IFLA_IPTUN_TTL, (ttl) ? ttl : 64);
2436 
2437         struct in6_addr in6buf;
2438         if ((cur = tb[TUNNEL_ATTR_LOCAL])) {
2439                 if (inet_pton(AF_INET6, blobmsg_data(cur), &in6buf) < 1) {
2440                         ret = -EINVAL;
2441                         goto failure;
2442                 }
2443                 nla_put(nlm, IFLA_IPTUN_LOCAL, sizeof(in6buf), &in6buf);
2444         }
2445 
2446         if ((cur = tb[TUNNEL_ATTR_REMOTE])) {
2447                 if (inet_pton(AF_INET6, blobmsg_data(cur), &in6buf) < 1) {
2448                         ret = -EINVAL;
2449                         goto failure;
2450                 }
2451                 nla_put(nlm, IFLA_IPTUN_REMOTE, sizeof(in6buf), &in6buf);
2452         }
2453 
2454         if ((cur = tb[TUNNEL_ATTR_DATA])) {
2455                 struct blob_attr *tb_data[__IPIP6_DATA_ATTR_MAX];
2456                 uint32_t tun_flags = IP6_TNL_F_IGN_ENCAP_LIMIT;
2457 
2458                 blobmsg_parse(ipip6_data_attr_list.params, __IPIP6_DATA_ATTR_MAX, tb_data,
2459                         blobmsg_data(cur), blobmsg_len(cur));
2460 
2461                 if ((cur = tb_data[IPIP6_DATA_ENCAPLIMIT])) {
2462                         char *str = blobmsg_get_string(cur);
2463 
2464                         if (strcmp(str, "ignore")) {
2465                                 char *e;
2466                                 unsigned encap_limit = strtoul(str, &e, 0);
2467 
2468                                 if (e == str || *e || encap_limit > 255) {
2469                                         ret = -EINVAL;
2470                                         goto failure;
2471                                 }
2472 
2473                                 nla_put_u8(nlm, IFLA_IPTUN_ENCAP_LIMIT, encap_limit);
2474                                 tun_flags &= ~IP6_TNL_F_IGN_ENCAP_LIMIT;
2475                         }
2476                 }
2477 
2478 #ifdef IFLA_IPTUN_FMR_MAX
2479                 if ((cur = tb_data[IPIP6_DATA_FMRS])) {
2480                         struct blob_attr *rcur;
2481                         unsigned rrem, fmrcnt = 0;
2482                         struct nlattr *fmrs = nla_nest_start(nlm, IFLA_IPTUN_FMRS);
2483 
2484                         if (!fmrs) {
2485                                 ret = -ENOMEM;
2486                                 goto failure;
2487                         }
2488 
2489                         blobmsg_for_each_attr(rcur, cur, rrem) {
2490                                 struct blob_attr *tb_fmr[__FMR_DATA_ATTR_MAX], *tb_cur;
2491                                 struct in6_addr ip6prefix;
2492                                 struct in_addr ip4prefix;
2493                                 unsigned ip4len, ip6len, ealen, offset;
2494 
2495                                 blobmsg_parse(fmr_data_attr_list.params, __FMR_DATA_ATTR_MAX, tb_fmr,
2496                                                 blobmsg_data(rcur), blobmsg_len(rcur));
2497 
2498                                 if (!(tb_cur = tb_fmr[FMR_DATA_PREFIX6]) ||
2499                                                 !parse_ip_and_netmask(AF_INET6,
2500                                                         blobmsg_data(tb_cur), &ip6prefix,
2501                                                         &ip6len)) {
2502                                         ret = -EINVAL;
2503                                         goto failure;
2504                                 }
2505 
2506                                 if (!(tb_cur = tb_fmr[FMR_DATA_PREFIX4]) ||
2507                                                 !parse_ip_and_netmask(AF_INET,
2508                                                         blobmsg_data(tb_cur), &ip4prefix,
2509                                                         &ip4len)) {
2510                                         ret = -EINVAL;
2511                                         goto failure;
2512                                 }
2513 
2514                                 if (!(tb_cur = tb_fmr[FMR_DATA_EALEN])) {
2515                                         ret = -EINVAL;
2516                                         goto failure;
2517                                 }
2518                                 ealen = blobmsg_get_u32(tb_cur);
2519 
2520                                 if (!(tb_cur = tb_fmr[FMR_DATA_OFFSET])) {
2521                                         ret = -EINVAL;
2522                                         goto failure;
2523                                 }
2524                                 offset = blobmsg_get_u32(tb_cur);
2525 
2526                                 struct nlattr *rule = nla_nest_start(nlm, ++fmrcnt);
2527                                 if (!rule) {
2528                                         ret = -ENOMEM;
2529                                         goto failure;
2530                                 }
2531 
2532                                 nla_put(nlm, IFLA_IPTUN_FMR_IP6_PREFIX, sizeof(ip6prefix), &ip6prefix);
2533                                 nla_put(nlm, IFLA_IPTUN_FMR_IP4_PREFIX, sizeof(ip4prefix), &ip4prefix);
2534                                 nla_put_u8(nlm, IFLA_IPTUN_FMR_IP6_PREFIX_LEN, ip6len);
2535                                 nla_put_u8(nlm, IFLA_IPTUN_FMR_IP4_PREFIX_LEN, ip4len);
2536                                 nla_put_u8(nlm, IFLA_IPTUN_FMR_EA_LEN, ealen);
2537                                 nla_put_u8(nlm, IFLA_IPTUN_FMR_OFFSET, offset);
2538 
2539                                 nla_nest_end(nlm, rule);
2540                         }
2541 
2542                         nla_nest_end(nlm, fmrs);
2543                 }
2544 #endif
2545                 if (tun_flags)
2546                         nla_put_u32(nlm, IFLA_IPTUN_FLAGS, tun_flags);
2547         }
2548 
2549         nla_nest_end(nlm, infodata);
2550         nla_nest_end(nlm, linkinfo);
2551 
2552         return system_rtnl_call(nlm);
2553 
2554 failure:
2555         nlmsg_free(nlm);
2556         return ret;
2557 }
2558 #endif
2559 
2560 #ifdef IFLA_IPTUN_MAX
2561 #define IP6_FLOWINFO_TCLASS     htonl(0x0FF00000)
2562 static int system_add_gre_tunnel(const char *name, const char *kind,
2563                                  const unsigned int link, struct blob_attr **tb, bool v6)
2564 {
2565         struct nl_msg *nlm;
2566         struct ifinfomsg ifi = { .ifi_family = AF_UNSPEC, };
2567         struct blob_attr *cur;
2568         uint32_t ikey = 0, okey = 0, flowinfo = 0, flags6 = IP6_TNL_F_IGN_ENCAP_LIMIT;
2569         uint16_t iflags = 0, oflags = 0;
2570         uint8_t tos = 0;
2571         int ret = 0, ttl = 0;
2572         unsigned encap_limit = 0;
2573 
2574         nlm = nlmsg_alloc_simple(RTM_NEWLINK, NLM_F_REQUEST | NLM_F_REPLACE | NLM_F_CREATE);
2575         if (!nlm)
2576                 return -1;
2577 
2578         nlmsg_append(nlm, &ifi, sizeof(ifi), 0);
2579         nla_put_string(nlm, IFLA_IFNAME, name);
2580 
2581         struct nlattr *linkinfo = nla_nest_start(nlm, IFLA_LINKINFO);
2582         if (!linkinfo) {
2583                 ret = -ENOMEM;
2584                 goto failure;
2585         }
2586 
2587         nla_put_string(nlm, IFLA_INFO_KIND, kind);
2588         struct nlattr *infodata = nla_nest_start(nlm, IFLA_INFO_DATA);
2589         if (!infodata) {
2590                 ret = -ENOMEM;
2591                 goto failure;
2592         }
2593 
2594         if (link)
2595                 nla_put_u32(nlm, IFLA_GRE_LINK, link);
2596 
2597         if ((cur = tb[TUNNEL_ATTR_TTL]))
2598                 ttl = blobmsg_get_u32(cur);
2599 
2600         if ((cur = tb[TUNNEL_ATTR_TOS])) {
2601                 char *str = blobmsg_get_string(cur);
2602                 if (strcmp(str, "inherit")) {
2603                         unsigned uval;
2604 
2605                         if (!system_tos_aton(str, &uval)) {
2606                                 ret = -EINVAL;
2607                                 goto failure;
2608                         }
2609 
2610                         if (v6)
2611                                 flowinfo |= htonl(uval << 20) & IP6_FLOWINFO_TCLASS;
2612                         else
2613                                 tos = uval;
2614                 } else {
2615                         if (v6)
2616                                 flags6 |= IP6_TNL_F_USE_ORIG_TCLASS;
2617                         else
2618                                 tos = 1;
2619                 }
2620         }
2621 
2622         if ((cur = tb[TUNNEL_ATTR_DATA])) {
2623                 struct blob_attr *tb_data[__GRE_DATA_ATTR_MAX];
2624 
2625                 blobmsg_parse(gre_data_attr_list.params, __GRE_DATA_ATTR_MAX, tb_data,
2626                         blobmsg_data(cur), blobmsg_len(cur));
2627 
2628                 if ((cur = tb_data[GRE_DATA_IKEY])) {
2629                         if ((ikey = blobmsg_get_u32(cur)))
2630                                 iflags |= GRE_KEY;
2631                 }
2632 
2633                 if ((cur = tb_data[GRE_DATA_OKEY])) {
2634                         if ((okey = blobmsg_get_u32(cur)))
2635                                 oflags |= GRE_KEY;
2636                 }
2637 
2638                 if ((cur = tb_data[GRE_DATA_ICSUM])) {
2639                         if (blobmsg_get_bool(cur))
2640                                 iflags |= GRE_CSUM;
2641                 }
2642 
2643                 if ((cur = tb_data[GRE_DATA_OCSUM])) {
2644                         if (blobmsg_get_bool(cur))
2645                                 oflags |= GRE_CSUM;
2646                 }
2647 
2648                 if ((cur = tb_data[GRE_DATA_ISEQNO])) {
2649                         if (blobmsg_get_bool(cur))
2650                                 iflags |= GRE_SEQ;
2651                 }
2652 
2653                 if ((cur = tb_data[GRE_DATA_OSEQNO])) {
2654                         if (blobmsg_get_bool(cur))
2655                                 oflags |= GRE_SEQ;
2656                 }
2657 
2658                 if ((cur = tb_data[GRE_DATA_ENCAPLIMIT])) {
2659                         char *str = blobmsg_get_string(cur);
2660 
2661                         if (strcmp(str, "ignore")) {
2662                                 char *e;
2663 
2664                                 encap_limit = strtoul(str, &e, 0);
2665 
2666                                 if (e == str || *e || encap_limit > 255) {
2667                                         ret = -EINVAL;
2668                                         goto failure;
2669                                 }
2670 
2671                                 flags6 &= ~IP6_TNL_F_IGN_ENCAP_LIMIT;
2672                         }
2673                 }
2674         }
2675 
2676         if (v6) {
2677                 struct in6_addr in6buf;
2678                 if ((cur = tb[TUNNEL_ATTR_LOCAL])) {
2679                         if (inet_pton(AF_INET6, blobmsg_data(cur), &in6buf) < 1) {
2680                                 ret = -EINVAL;
2681                                 goto failure;
2682                         }
2683                         nla_put(nlm, IFLA_GRE_LOCAL, sizeof(in6buf), &in6buf);
2684                 }
2685 
2686                 if ((cur = tb[TUNNEL_ATTR_REMOTE])) {
2687                         if (inet_pton(AF_INET6, blobmsg_data(cur), &in6buf) < 1) {
2688                                 ret = -EINVAL;
2689                                 goto failure;
2690                         }
2691                         nla_put(nlm, IFLA_GRE_REMOTE, sizeof(in6buf), &in6buf);
2692                 }
2693 
2694                 if (!(flags6 & IP6_TNL_F_IGN_ENCAP_LIMIT))
2695                         nla_put_u8(nlm, IFLA_GRE_ENCAP_LIMIT, encap_limit);
2696 
2697                 if (flowinfo)
2698                         nla_put_u32(nlm, IFLA_GRE_FLOWINFO, flowinfo);
2699 
2700                 if (flags6)
2701                         nla_put_u32(nlm, IFLA_GRE_FLAGS, flags6);
2702 
2703                 if (!ttl)
2704                         ttl = 64;
2705         } else {
2706                 struct in_addr inbuf;
2707                 bool set_df = true;
2708 
2709                 if ((cur = tb[TUNNEL_ATTR_LOCAL])) {
2710                         if (inet_pton(AF_INET, blobmsg_data(cur), &inbuf) < 1) {
2711                                 ret = -EINVAL;
2712                                 goto failure;
2713                         }
2714                         nla_put(nlm, IFLA_GRE_LOCAL, sizeof(inbuf), &inbuf);
2715                 }
2716 
2717                 if ((cur = tb[TUNNEL_ATTR_REMOTE])) {
2718                         if (inet_pton(AF_INET, blobmsg_data(cur), &inbuf) < 1) {
2719                                 ret = -EINVAL;
2720                                 goto failure;
2721                         }
2722                         nla_put(nlm, IFLA_GRE_REMOTE, sizeof(inbuf), &inbuf);
2723 
2724                         if (IN_MULTICAST(ntohl(inbuf.s_addr))) {
2725                                 if (!okey) {
2726                                         okey = inbuf.s_addr;
2727                                         oflags |= GRE_KEY;
2728                                 }
2729 
2730                                 if (!ikey) {
2731                                         ikey = inbuf.s_addr;
2732                                         iflags |= GRE_KEY;
2733                                 }
2734                         }
2735                 }
2736 
2737                 if ((cur = tb[TUNNEL_ATTR_DF]))
2738                         set_df = blobmsg_get_bool(cur);
2739 
2740                 if (!set_df) {
2741                         /* ttl != 0 and nopmtudisc are incompatible */
2742                         if (ttl) {
2743                                 ret = -EINVAL;
2744                                 goto failure;
2745                         }
2746                 } else if (!ttl)
2747                         ttl = 64;
2748 
2749                 nla_put_u8(nlm, IFLA_GRE_PMTUDISC, set_df ? 1 : 0);
2750 
2751                 nla_put_u8(nlm, IFLA_GRE_TOS, tos);
2752         }
2753 
2754         if (ttl)
2755                 nla_put_u8(nlm, IFLA_GRE_TTL, ttl);
2756 
2757         if (oflags)
2758                 nla_put_u16(nlm, IFLA_GRE_OFLAGS, oflags);
2759 
2760         if (iflags)
2761                 nla_put_u16(nlm, IFLA_GRE_IFLAGS, iflags);
2762 
2763         if (okey)
2764                 nla_put_u32(nlm, IFLA_GRE_OKEY, htonl(okey));
2765 
2766         if (ikey)
2767                 nla_put_u32(nlm, IFLA_GRE_IKEY, htonl(ikey));
2768 
2769         nla_nest_end(nlm, infodata);
2770         nla_nest_end(nlm, linkinfo);
2771 
2772         return system_rtnl_call(nlm);
2773 
2774 failure:
2775         nlmsg_free(nlm);
2776         return ret;
2777 }
2778 #endif
2779 
2780 #ifdef IFLA_VTI_MAX
2781 static int system_add_vti_tunnel(const char *name, const char *kind,
2782                                  const unsigned int link, struct blob_attr **tb, bool v6)
2783 {
2784         struct nl_msg *nlm;
2785         struct ifinfomsg ifi = { .ifi_family = AF_UNSPEC, };
2786         struct blob_attr *cur;
2787         int ret = 0;
2788 
2789         nlm = nlmsg_alloc_simple(RTM_NEWLINK, NLM_F_REQUEST | NLM_F_REPLACE | NLM_F_CREATE);
2790         if (!nlm)
2791                 return -1;
2792 
2793         nlmsg_append(nlm, &ifi, sizeof(ifi), 0);
2794         nla_put_string(nlm, IFLA_IFNAME, name);
2795 
2796         struct nlattr *linkinfo = nla_nest_start(nlm, IFLA_LINKINFO);
2797         if (!linkinfo) {
2798                 ret = -ENOMEM;
2799                 goto failure;
2800         }
2801 
2802         nla_put_string(nlm, IFLA_INFO_KIND, kind);
2803         struct nlattr *infodata = nla_nest_start(nlm, IFLA_INFO_DATA);
2804         if (!infodata) {
2805                 ret = -ENOMEM;
2806                 goto failure;
2807         }
2808 
2809         if (link)
2810                 nla_put_u32(nlm, IFLA_VTI_LINK, link);
2811 
2812         if (v6) {
2813                 struct in6_addr in6buf;
2814                 if ((cur = tb[TUNNEL_ATTR_LOCAL])) {
2815                         if (inet_pton(AF_INET6, blobmsg_data(cur), &in6buf) < 1) {
2816                                 ret = -EINVAL;
2817                                 goto failure;
2818                         }
2819                         nla_put(nlm, IFLA_VTI_LOCAL, sizeof(in6buf), &in6buf);
2820                 }
2821 
2822                 if ((cur = tb[TUNNEL_ATTR_REMOTE])) {
2823                         if (inet_pton(AF_INET6, blobmsg_data(cur), &in6buf) < 1) {
2824                                 ret = -EINVAL;
2825                                 goto failure;
2826                         }
2827                         nla_put(nlm, IFLA_VTI_REMOTE, sizeof(in6buf), &in6buf);
2828                 }
2829 
2830         } else {
2831                 struct in_addr inbuf;
2832 
2833                 if ((cur = tb[TUNNEL_ATTR_LOCAL])) {
2834                         if (inet_pton(AF_INET, blobmsg_data(cur), &inbuf) < 1) {
2835                                 ret = -EINVAL;
2836                                 goto failure;
2837                         }
2838                         nla_put(nlm, IFLA_VTI_LOCAL, sizeof(inbuf), &inbuf);
2839                 }
2840 
2841                 if ((cur = tb[TUNNEL_ATTR_REMOTE])) {
2842                         if (inet_pton(AF_INET, blobmsg_data(cur), &inbuf) < 1) {
2843                                 ret = -EINVAL;
2844                                 goto failure;
2845                         }
2846                         nla_put(nlm, IFLA_VTI_REMOTE, sizeof(inbuf), &inbuf);
2847                 }
2848 
2849         }
2850 
2851         if ((cur = tb[TUNNEL_ATTR_DATA])) {
2852                 struct blob_attr *tb_data[__VTI_DATA_ATTR_MAX];
2853                 uint32_t ikey = 0, okey = 0;
2854 
2855                 blobmsg_parse(vti_data_attr_list.params, __VTI_DATA_ATTR_MAX, tb_data,
2856                         blobmsg_data(cur), blobmsg_len(cur));
2857 
2858                 if ((cur = tb_data[VTI_DATA_IKEY])) {
2859                         if ((ikey = blobmsg_get_u32(cur)))
2860                                 nla_put_u32(nlm, IFLA_VTI_IKEY, htonl(ikey));
2861                 }
2862 
2863                 if ((cur = tb_data[VTI_DATA_OKEY])) {
2864                         if ((okey = blobmsg_get_u32(cur)))
2865                                 nla_put_u32(nlm, IFLA_VTI_OKEY, htonl(okey));
2866                 }
2867         }
2868 
2869         nla_nest_end(nlm, infodata);
2870         nla_nest_end(nlm, linkinfo);
2871 
2872         return system_rtnl_call(nlm);
2873 
2874 failure:
2875         nlmsg_free(nlm);
2876         return ret;
2877 }
2878 #endif
2879 
2880 #ifdef IFLA_VXLAN_MAX
2881 static int system_add_vxlan(const char *name, const unsigned int link, struct blob_attr **tb, bool v6)
2882 {
2883         struct blob_attr *tb_data[__VXLAN_DATA_ATTR_MAX];
2884         struct nl_msg *msg;
2885         struct nlattr *linkinfo, *data;
2886         struct ifinfomsg iim = { .ifi_family = AF_UNSPEC, };
2887         struct blob_attr *cur;
2888         int ret = 0;
2889 
2890         if ((cur = tb[TUNNEL_ATTR_DATA]))
2891                 blobmsg_parse(vxlan_data_attr_list.params, __VXLAN_DATA_ATTR_MAX, tb_data,
2892                         blobmsg_data(cur), blobmsg_len(cur));
2893         else
2894                 return -EINVAL;
2895 
2896         msg = nlmsg_alloc_simple(RTM_NEWLINK, NLM_F_REQUEST | NLM_F_CREATE | NLM_F_EXCL);
2897 
2898         if (!msg)
2899                 return -1;
2900 
2901         nlmsg_append(msg, &iim, sizeof(iim), 0);
2902 
2903         nla_put_string(msg, IFLA_IFNAME, name);
2904 
2905         if ((cur = tb_data[VXLAN_DATA_ATTR_MACADDR])) {
2906                 struct ether_addr *ea = ether_aton(blobmsg_get_string(cur));
2907                 if (!ea) {
2908                         ret = -EINVAL;
2909                         goto failure;
2910                 }
2911 
2912                 nla_put(msg, IFLA_ADDRESS, ETH_ALEN, ea);
2913         }
2914 
2915         if ((cur = tb[TUNNEL_ATTR_MTU])) {
2916                 uint32_t mtu = blobmsg_get_u32(cur);
2917                 nla_put_u32(msg, IFLA_MTU, mtu);
2918         }
2919 
2920         if (!(linkinfo = nla_nest_start(msg, IFLA_LINKINFO))) {
2921                 ret = -ENOMEM;
2922                 goto failure;
2923         }
2924 
2925         nla_put_string(msg, IFLA_INFO_KIND, "vxlan");
2926 
2927         if (!(data = nla_nest_start(msg, IFLA_INFO_DATA))) {
2928                 ret = -ENOMEM;
2929                 goto failure;
2930         }
2931 
2932         if (link)
2933                 nla_put_u32(msg, IFLA_VXLAN_LINK, link);
2934 
2935         if ((cur = tb_data[VXLAN_DATA_ATTR_ID])) {
2936                 uint32_t id = blobmsg_get_u32(cur);
2937                 if (id >= (1u << 24) - 1) {
2938                         ret = -EINVAL;
2939                         goto failure;
2940                 }
2941 
2942                 nla_put_u32(msg, IFLA_VXLAN_ID, id);
2943         }
2944 
2945         if (v6) {
2946                 struct in6_addr in6buf;
2947                 if ((cur = tb[TUNNEL_ATTR_LOCAL])) {
2948                         if (inet_pton(AF_INET6, blobmsg_data(cur), &in6buf) < 1) {
2949                                 ret = -EINVAL;
2950                                 goto failure;
2951                         }
2952                         nla_put(msg, IFLA_VXLAN_LOCAL6, sizeof(in6buf), &in6buf);
2953                 }
2954 
2955                 if ((cur = tb[TUNNEL_ATTR_REMOTE])) {
2956                         if (inet_pton(AF_INET6, blobmsg_data(cur), &in6buf) < 1) {
2957                                 ret = -EINVAL;
2958                                 goto failure;
2959                         }
2960                         nla_put(msg, IFLA_VXLAN_GROUP6, sizeof(in6buf), &in6buf);
2961                 }
2962         } else {
2963                 struct in_addr inbuf;
2964 
2965                 if ((cur = tb[TUNNEL_ATTR_LOCAL])) {
2966                         if (inet_pton(AF_INET, blobmsg_data(cur), &inbuf) < 1) {
2967                                 ret = -EINVAL;
2968                                 goto failure;
2969                         }
2970                         nla_put(msg, IFLA_VXLAN_LOCAL, sizeof(inbuf), &inbuf);
2971                 }
2972 
2973                 if ((cur = tb[TUNNEL_ATTR_REMOTE])) {
2974                         if (inet_pton(AF_INET, blobmsg_data(cur), &inbuf) < 1) {
2975                                 ret = -EINVAL;
2976                                 goto failure;
2977                         }
2978                         nla_put(msg, IFLA_VXLAN_GROUP, sizeof(inbuf), &inbuf);
2979                 }
2980         }
2981 
2982         uint32_t port = 4789;
2983         if ((cur = tb_data[VXLAN_DATA_ATTR_PORT])) {
2984                 port = blobmsg_get_u32(cur);
2985                 if (port < 1 || port > 65535) {
2986                         ret = -EINVAL;
2987                         goto failure;
2988                 }
2989         }
2990         nla_put_u16(msg, IFLA_VXLAN_PORT, htons(port));
2991 
2992         if ((cur = tb_data[VXLAN_DATA_ATTR_RXCSUM])) {
2993                 bool rxcsum = blobmsg_get_bool(cur);
2994                 nla_put_u8(msg, IFLA_VXLAN_UDP_ZERO_CSUM6_RX, !rxcsum);
2995         }
2996 
2997         if ((cur = tb_data[VXLAN_DATA_ATTR_TXCSUM])) {
2998                 bool txcsum = blobmsg_get_bool(cur);
2999                 nla_put_u8(msg, IFLA_VXLAN_UDP_CSUM, txcsum);
3000                 nla_put_u8(msg, IFLA_VXLAN_UDP_ZERO_CSUM6_TX, !txcsum);
3001         }
3002 
3003         if ((cur = tb[TUNNEL_ATTR_TOS])) {
3004                 char *str = blobmsg_get_string(cur);
3005                 unsigned tos = 1;
3006 
3007                 if (strcmp(str, "inherit")) {
3008                         if (!system_tos_aton(str, &tos)) {
3009                                 ret = -EINVAL;
3010                                 goto failure;
3011                         }
3012                 }
3013 
3014                 nla_put_u8(msg, IFLA_VXLAN_TOS, tos);
3015         }
3016 
3017         if ((cur = tb[TUNNEL_ATTR_TTL])) {
3018                 uint32_t ttl = blobmsg_get_u32(cur);
3019                 if (ttl < 1 || ttl > 255) {
3020                         ret = -EINVAL;
3021                         goto failure;
3022                 }
3023 
3024                 nla_put_u8(msg, IFLA_VXLAN_TTL, ttl);
3025         }
3026 
3027         nla_nest_end(msg, data);
3028         nla_nest_end(msg, linkinfo);
3029 
3030         ret = system_rtnl_call(msg);
3031         if (ret)
3032                 D(SYSTEM, "Error adding vxlan '%s': %d\n", name, ret);
3033 
3034         return ret;
3035 
3036 failure:
3037         nlmsg_free(msg);
3038         return ret;
3039 }
3040 #endif
3041 
3042 static int system_add_sit_tunnel(const char *name, const unsigned int link, struct blob_attr **tb)
3043 {
3044         struct blob_attr *cur;
3045         int ret = 0;
3046 
3047         if (system_add_proto_tunnel(name, IPPROTO_IPV6, link, tb) < 0)
3048                 return -1;
3049 
3050 #ifdef SIOCADD6RD
3051         if ((cur = tb[TUNNEL_ATTR_DATA])) {
3052                 struct blob_attr *tb_data[__SIXRD_DATA_ATTR_MAX];
3053                 unsigned int mask;
3054                 struct ip_tunnel_6rd p6;
3055 
3056                 blobmsg_parse(sixrd_data_attr_list.params, __SIXRD_DATA_ATTR_MAX, tb_data,
3057                         blobmsg_data(cur), blobmsg_len(cur));
3058 
3059                 memset(&p6, 0, sizeof(p6));
3060 
3061                 if ((cur = tb_data[SIXRD_DATA_PREFIX])) {
3062                         if (!parse_ip_and_netmask(AF_INET6, blobmsg_data(cur),
3063                                                 &p6.prefix, &mask) || mask > 128) {
3064                                 ret = -EINVAL;
3065                                 goto failure;
3066                         }
3067 
3068                         p6.prefixlen = mask;
3069                 }
3070 
3071                 if ((cur = tb_data[SIXRD_DATA_RELAY_PREFIX])) {
3072                         if (!parse_ip_and_netmask(AF_INET, blobmsg_data(cur),
3073                                                 &p6.relay_prefix, &mask) || mask > 32) {
3074                                 ret = -EINVAL;
3075                                 goto failure;
3076                         }
3077 
3078                         p6.relay_prefixlen = mask;
3079                 }
3080 
3081                 if (tunnel_ioctl(name, SIOCADD6RD, &p6) < 0) {
3082                         ret = -1;
3083                         goto failure;
3084                 }
3085         }
3086 #endif
3087 
3088         return ret;
3089 
3090 failure:
3091         __system_del_ip_tunnel(name, tb);
3092         return ret;
3093 }
3094 
3095 static int system_add_proto_tunnel(const char *name, const uint8_t proto, const unsigned int link, struct blob_attr **tb)
3096 {
3097         struct blob_attr *cur;
3098         bool set_df = true;
3099         struct ip_tunnel_parm p  = {
3100                 .link = link,
3101                 .iph = {
3102                         .version = 4,
3103                         .ihl = 5,
3104                         .protocol = proto,
3105                 }
3106         };
3107 
3108         if ((cur = tb[TUNNEL_ATTR_LOCAL]) &&
3109                         inet_pton(AF_INET, blobmsg_data(cur), &p.iph.saddr) < 1)
3110                 return -EINVAL;
3111 
3112         if ((cur = tb[TUNNEL_ATTR_REMOTE]) &&
3113                         inet_pton(AF_INET, blobmsg_data(cur), &p.iph.daddr) < 1)
3114                 return -EINVAL;
3115 
3116         if ((cur = tb[TUNNEL_ATTR_DF]))
3117                 set_df = blobmsg_get_bool(cur);
3118 
3119         if ((cur = tb[TUNNEL_ATTR_TTL]))
3120                 p.iph.ttl = blobmsg_get_u32(cur);
3121 
3122         if ((cur = tb[TUNNEL_ATTR_TOS])) {
3123                 char *str = blobmsg_get_string(cur);
3124                 if (strcmp(str, "inherit")) {
3125                         unsigned uval;
3126 
3127                         if (!system_tos_aton(str, &uval))
3128                                 return -EINVAL;
3129 
3130                         p.iph.tos = uval;
3131                 } else
3132                         p.iph.tos = 1;
3133         }
3134 
3135         p.iph.frag_off = set_df ? htons(IP_DF) : 0;
3136         /* ttl !=0 and nopmtudisc are incompatible */
3137         if (p.iph.ttl && p.iph.frag_off == 0)
3138                 return -EINVAL;
3139 
3140         strncpy(p.name, name, sizeof(p.name) - 1);
3141 
3142         switch (p.iph.protocol) {
3143         case IPPROTO_IPIP:
3144                 return tunnel_ioctl("tunl0", SIOCADDTUNNEL, &p);
3145         case IPPROTO_IPV6:
3146                 return tunnel_ioctl("sit0", SIOCADDTUNNEL, &p);
3147         default:
3148                 break;
3149         }
3150         return -1;
3151 }
3152 
3153 static int __system_del_ip_tunnel(const char *name, struct blob_attr **tb)
3154 {
3155         struct blob_attr *cur;
3156         const char *str;
3157 
3158         if (!(cur = tb[TUNNEL_ATTR_TYPE]))
3159                 return -EINVAL;
3160         str = blobmsg_data(cur);
3161 
3162         if (!strcmp(str, "greip") || !strcmp(str, "gretapip") ||
3163             !strcmp(str, "greip6") || !strcmp(str, "gretapip6") ||
3164             !strcmp(str, "vtiip") || !strcmp(str, "vtiip6") ||
3165             !strcmp(str, "vxlan") || !strcmp(str, "vxlan6"))
3166                 return system_link_del(name);
3167         else
3168                 return tunnel_ioctl(name, SIOCDELTUNNEL, NULL);
3169 }
3170 
3171 int system_del_ip_tunnel(const char *name, struct blob_attr *attr)
3172 {
3173         struct blob_attr *tb[__TUNNEL_ATTR_MAX];
3174 
3175         blobmsg_parse(tunnel_attr_list.params, __TUNNEL_ATTR_MAX, tb,
3176                 blob_data(attr), blob_len(attr));
3177 
3178         return __system_del_ip_tunnel(name, tb);
3179 }
3180 
3181 int system_update_ipv6_mtu(struct device *dev, int mtu)
3182 {
3183         int ret = -1;
3184         char buf[64];
3185         int fd;
3186 
3187         snprintf(buf, sizeof(buf), "/proc/sys/net/ipv6/conf/%s/mtu",
3188                         dev->ifname);
3189 
3190         fd = open(buf, O_RDWR);
3191         if (fd < 0)
3192                 return ret;
3193 
3194         if (!mtu) {
3195                 ssize_t len = read(fd, buf, sizeof(buf) - 1);
3196                 if (len < 0)
3197                         goto out;
3198 
3199                 buf[len] = 0;
3200                 ret = atoi(buf);
3201         } else {
3202                 if (write(fd, buf, snprintf(buf, sizeof(buf), "%i", mtu)) > 0)
3203                         ret = mtu;
3204         }
3205 
3206 out:
3207         close(fd);
3208         return ret;
3209 }
3210 
3211 int system_add_ip_tunnel(const char *name, struct blob_attr *attr)
3212 {
3213         struct blob_attr *tb[__TUNNEL_ATTR_MAX];
3214         struct blob_attr *cur;
3215         const char *str;
3216 
3217         blobmsg_parse(tunnel_attr_list.params, __TUNNEL_ATTR_MAX, tb,
3218                 blob_data(attr), blob_len(attr));
3219 
3220         __system_del_ip_tunnel(name, tb);
3221 
3222         if (!(cur = tb[TUNNEL_ATTR_TYPE]))
3223                 return -EINVAL;
3224         str = blobmsg_data(cur);
3225 
3226         unsigned int ttl = 0;
3227         if ((cur = tb[TUNNEL_ATTR_TTL])) {
3228                 ttl = blobmsg_get_u32(cur);
3229                 if (ttl > 255)
3230                         return -EINVAL;
3231         }
3232 
3233         unsigned int link = 0;
3234         if ((cur = tb[TUNNEL_ATTR_LINK])) {
3235                 struct interface *iface = vlist_find(&interfaces, blobmsg_data(cur), iface, node);
3236                 if (!iface)
3237                         return -EINVAL;
3238 
3239                 if (iface->l3_dev.dev)
3240                         link = iface->l3_dev.dev->ifindex;
3241         }
3242 
3243         if (!strcmp(str, "sit"))
3244                 return system_add_sit_tunnel(name, link, tb);
3245 #ifdef IFLA_IPTUN_MAX
3246         else if (!strcmp(str, "ipip6")) {
3247                 return system_add_ip6_tunnel(name, link, tb);
3248         } else if (!strcmp(str, "greip")) {
3249                 return system_add_gre_tunnel(name, "gre", link, tb, false);
3250         } else if (!strcmp(str, "gretapip"))  {
3251                 return system_add_gre_tunnel(name, "gretap", link, tb, false);
3252         } else if (!strcmp(str, "greip6")) {
3253                 return system_add_gre_tunnel(name, "ip6gre", link, tb, true);
3254         } else if (!strcmp(str, "gretapip6")) {
3255                 return system_add_gre_tunnel(name, "ip6gretap", link, tb, true);
3256 #ifdef IFLA_VTI_MAX
3257         } else if (!strcmp(str, "vtiip")) {
3258                 return system_add_vti_tunnel(name, "vti", link, tb, false);
3259         } else if (!strcmp(str, "vtiip6")) {
3260                 return system_add_vti_tunnel(name, "vti6", link, tb, true);
3261 #endif
3262 #ifdef IFLA_VXLAN_MAX
3263         } else if(!strcmp(str, "vxlan")) {
3264                 return system_add_vxlan(name, link, tb, false);
3265         } else if(!strcmp(str, "vxlan6")) {
3266                 return system_add_vxlan(name, link, tb, true);
3267 #endif
3268 #endif
3269         } else if (!strcmp(str, "ipip")) {
3270                 return system_add_proto_tunnel(name, IPPROTO_IPIP, link, tb);
3271         }
3272         else
3273                 return -EINVAL;
3274 
3275         return 0;
3276 }
3277 

This page was automatically generated by LXR 0.3.1.  •  OpenWrt