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

This page was automatically generated by LXR 0.3.1.  •  OpenWrt