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

This page was automatically generated by LXR 0.3.1.  •  OpenWrt