Implement support for route / route6 table attribute
[project/netifd.git] / system-linux.c
1 /*
2 * netifd - network interface daemon
3 * Copyright (C) 2012 Felix Fietkau <nbd@openwrt.org>
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2
7 * as published by the Free Software Foundation
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 */
14 #define _GNU_SOURCE
15
16 #include <sys/socket.h>
17 #include <sys/ioctl.h>
18 #include <sys/stat.h>
19 #include <sys/syscall.h>
20
21 #include <net/if.h>
22 #include <net/if_arp.h>
23
24 #include <arpa/inet.h>
25 #include <netinet/in.h>
26
27 #include <linux/rtnetlink.h>
28 #include <linux/sockios.h>
29 #include <linux/ip.h>
30 #include <linux/if_vlan.h>
31 #include <linux/if_bridge.h>
32 #include <linux/if_tunnel.h>
33 #include <linux/ethtool.h>
34
35 #include <unistd.h>
36 #include <string.h>
37 #include <fcntl.h>
38 #include <glob.h>
39 #include <time.h>
40
41 #include <netlink/msg.h>
42 #include <netlink/attr.h>
43 #include <netlink/socket.h>
44 #include <libubox/uloop.h>
45
46 #include "netifd.h"
47 #include "device.h"
48 #include "system.h"
49
50 struct event_socket {
51 struct uloop_fd uloop;
52 struct nl_sock *sock;
53 struct nl_cb *cb;
54 };
55
56 static int sock_ioctl = -1;
57 static struct nl_sock *sock_rtnl = NULL;
58
59 static int cb_rtnl_event(struct nl_msg *msg, void *arg);
60 static void handle_hotplug_event(struct uloop_fd *u, unsigned int events);
61
62 static char dev_buf[256];
63
64 static void
65 handler_nl_event(struct uloop_fd *u, unsigned int events)
66 {
67 struct event_socket *ev = container_of(u, struct event_socket, uloop);
68 nl_recvmsgs(ev->sock, ev->cb);
69 }
70
71 static struct nl_sock *
72 create_socket(int protocol, int groups)
73 {
74 struct nl_sock *sock;
75
76 sock = nl_socket_alloc();
77 if (!sock)
78 return NULL;
79
80 if (groups)
81 nl_join_groups(sock, groups);
82
83 if (nl_connect(sock, protocol))
84 return NULL;
85
86 return sock;
87 }
88
89 static bool
90 create_raw_event_socket(struct event_socket *ev, int protocol, int groups,
91 uloop_fd_handler cb)
92 {
93 ev->sock = create_socket(protocol, groups);
94 if (!ev->sock)
95 return false;
96
97 ev->uloop.fd = nl_socket_get_fd(ev->sock);
98 ev->uloop.cb = cb;
99 uloop_fd_add(&ev->uloop, ULOOP_READ | ULOOP_EDGE_TRIGGER);
100 return true;
101 }
102
103 static bool
104 create_event_socket(struct event_socket *ev, int protocol,
105 int (*cb)(struct nl_msg *msg, void *arg))
106 {
107 // Prepare socket for link events
108 ev->cb = nl_cb_alloc(NL_CB_DEFAULT);
109 if (!ev->cb)
110 return false;
111
112 nl_cb_set(ev->cb, NL_CB_VALID, NL_CB_CUSTOM, cb, NULL);
113
114 return create_raw_event_socket(ev, protocol, 0, handler_nl_event);
115 }
116
117 int system_init(void)
118 {
119 static struct event_socket rtnl_event;
120 static struct event_socket hotplug_event;
121
122 sock_ioctl = socket(AF_LOCAL, SOCK_DGRAM, 0);
123 fcntl(sock_ioctl, F_SETFD, fcntl(sock_ioctl, F_GETFD) | FD_CLOEXEC);
124
125 // Prepare socket for routing / address control
126 sock_rtnl = create_socket(NETLINK_ROUTE, 0);
127 if (!sock_rtnl)
128 return -1;
129
130 if (!create_event_socket(&rtnl_event, NETLINK_ROUTE, cb_rtnl_event))
131 return -1;
132
133 if (!create_raw_event_socket(&hotplug_event, NETLINK_KOBJECT_UEVENT, 1,
134 handle_hotplug_event))
135 return -1;
136
137 // Receive network link events form kernel
138 nl_socket_add_membership(rtnl_event.sock, RTNLGRP_LINK);
139
140 return 0;
141 }
142
143 static void system_set_sysctl(const char *path, const char *val)
144 {
145 int fd;
146
147 fd = open(path, O_WRONLY);
148 if (fd < 0)
149 return;
150
151 write(fd, val, strlen(val));
152 close(fd);
153 }
154
155 static void system_set_dev_sysctl(const char *path, const char *device, const char *val)
156 {
157 snprintf(dev_buf, sizeof(dev_buf), path, device);
158 system_set_sysctl(dev_buf, val);
159 }
160
161 static void system_set_disable_ipv6(struct device *dev, const char *val)
162 {
163 system_set_dev_sysctl("/proc/sys/net/ipv6/conf/%s/disable_ipv6", dev->ifname, val);
164 }
165
166 // Evaluate netlink messages
167 static int cb_rtnl_event(struct nl_msg *msg, void *arg)
168 {
169 struct nlmsghdr *nh = nlmsg_hdr(msg);
170 struct ifinfomsg *ifi = NLMSG_DATA(nh);
171 struct nlattr *nla[__IFLA_MAX];
172
173 if (nh->nlmsg_type != RTM_DELLINK && nh->nlmsg_type != RTM_NEWLINK)
174 goto out;
175
176 nlmsg_parse(nh, sizeof(*ifi), nla, __IFLA_MAX - 1, NULL);
177 if (!nla[IFLA_IFNAME])
178 goto out;
179
180 struct device *dev = device_get(RTA_DATA(nla[IFLA_IFNAME]), false);
181 if (!dev)
182 goto out;
183
184 dev->ifindex = ifi->ifi_index;
185 /* TODO: parse link status */
186
187 out:
188 return 0;
189 }
190
191 static void
192 handle_hotplug_msg(char *data, int size)
193 {
194 const char *subsystem = NULL, *interface = NULL;
195 char *cur, *end, *sep;
196 struct device *dev;
197 int skip;
198 bool add;
199
200 if (!strncmp(data, "add@", 4))
201 add = true;
202 else if (!strncmp(data, "remove@", 7))
203 add = false;
204 else
205 return;
206
207 skip = strlen(data) + 1;
208 end = data + size;
209
210 for (cur = data + skip; cur < end; cur += skip) {
211 skip = strlen(cur) + 1;
212
213 sep = strchr(cur, '=');
214 if (!sep)
215 continue;
216
217 *sep = 0;
218 if (!strcmp(cur, "INTERFACE"))
219 interface = sep + 1;
220 else if (!strcmp(cur, "SUBSYSTEM")) {
221 subsystem = sep + 1;
222 if (strcmp(subsystem, "net") != 0)
223 return;
224 }
225 if (subsystem && interface)
226 goto found;
227 }
228 return;
229
230 found:
231 dev = device_get(interface, false);
232 if (!dev)
233 return;
234
235 if (dev->type != &simple_device_type)
236 return;
237
238 if (add && system_if_force_external(dev->ifname))
239 return;
240
241 device_set_present(dev, add);
242 }
243
244 static void
245 handle_hotplug_event(struct uloop_fd *u, unsigned int events)
246 {
247 struct event_socket *ev = container_of(u, struct event_socket, uloop);
248 struct sockaddr_nl nla;
249 unsigned char *buf = NULL;
250 int size;
251
252 while ((size = nl_recv(ev->sock, &nla, &buf, NULL)) > 0) {
253 if (nla.nl_pid == 0)
254 handle_hotplug_msg((char *) buf, size);
255
256 free(buf);
257 }
258 }
259
260 static int system_rtnl_call(struct nl_msg *msg)
261 {
262 int ret;
263
264 ret = nl_send_auto_complete(sock_rtnl, msg);
265 nlmsg_free(msg);
266
267 if (ret < 0)
268 return ret;
269
270 return nl_wait_for_ack(sock_rtnl);
271 }
272
273 int system_bridge_delbr(struct device *bridge)
274 {
275 return ioctl(sock_ioctl, SIOCBRDELBR, bridge->ifname);
276 }
277
278 static int system_bridge_if(const char *bridge, struct device *dev, int cmd, void *data)
279 {
280 struct ifreq ifr;
281
282 memset(&ifr, 0, sizeof(ifr));
283 if (dev)
284 ifr.ifr_ifindex = dev->ifindex;
285 else
286 ifr.ifr_data = data;
287 strncpy(ifr.ifr_name, bridge, sizeof(ifr.ifr_name));
288 return ioctl(sock_ioctl, cmd, &ifr);
289 }
290
291 static bool system_is_bridge(const char *name, char *buf, int buflen)
292 {
293 struct stat st;
294
295 snprintf(buf, buflen, "/sys/devices/virtual/net/%s/bridge", name);
296 if (stat(buf, &st) < 0)
297 return false;
298
299 return true;
300 }
301
302 static char *system_get_bridge(const char *name, char *buf, int buflen)
303 {
304 char *path;
305 ssize_t len;
306 glob_t gl;
307
308 snprintf(buf, buflen, "/sys/devices/virtual/net/*/brif/%s/bridge", name);
309 if (glob(buf, GLOB_NOSORT, NULL, &gl) < 0)
310 return NULL;
311
312 if (gl.gl_pathc == 0)
313 return NULL;
314
315 len = readlink(gl.gl_pathv[0], buf, buflen);
316 if (len < 0)
317 return NULL;
318
319 buf[len] = 0;
320 path = strrchr(buf, '/');
321 if (!path)
322 return NULL;
323
324 return path + 1;
325 }
326
327 int system_bridge_addif(struct device *bridge, struct device *dev)
328 {
329 char *oldbr;
330
331 system_set_disable_ipv6(dev, "1");
332 oldbr = system_get_bridge(dev->ifname, dev_buf, sizeof(dev_buf));
333 if (oldbr && !strcmp(oldbr, bridge->ifname))
334 return 0;
335
336 return system_bridge_if(bridge->ifname, dev, SIOCBRADDIF, NULL);
337 }
338
339 int system_bridge_delif(struct device *bridge, struct device *dev)
340 {
341 system_set_disable_ipv6(dev, "0");
342 return system_bridge_if(bridge->ifname, dev, SIOCBRDELIF, NULL);
343 }
344
345 static int system_if_resolve(struct device *dev)
346 {
347 struct ifreq ifr;
348 strncpy(ifr.ifr_name, dev->ifname, sizeof(ifr.ifr_name));
349 if (!ioctl(sock_ioctl, SIOCGIFINDEX, &ifr))
350 return ifr.ifr_ifindex;
351 else
352 return 0;
353 }
354
355 static int system_if_flags(const char *ifname, unsigned add, unsigned rem)
356 {
357 struct ifreq ifr;
358
359 memset(&ifr, 0, sizeof(ifr));
360 strncpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name));
361 ioctl(sock_ioctl, SIOCGIFFLAGS, &ifr);
362 ifr.ifr_flags |= add;
363 ifr.ifr_flags &= ~rem;
364 return ioctl(sock_ioctl, SIOCSIFFLAGS, &ifr);
365 }
366
367 struct clear_data {
368 struct nl_msg *msg;
369 struct device *dev;
370 int type;
371 int size;
372 int af;
373 };
374
375
376 static bool check_ifaddr(struct nlmsghdr *hdr, int ifindex)
377 {
378 struct ifaddrmsg *ifa = NLMSG_DATA(hdr);
379
380 return ifa->ifa_index == ifindex;
381 }
382
383 static bool check_route(struct nlmsghdr *hdr, int ifindex)
384 {
385 struct rtmsg *r = NLMSG_DATA(hdr);
386 struct nlattr *tb[__RTA_MAX];
387
388 if (r->rtm_protocol == RTPROT_KERNEL &&
389 r->rtm_family == AF_INET6)
390 return false;
391
392 nlmsg_parse(hdr, sizeof(struct rtmsg), tb, __RTA_MAX - 1, NULL);
393 if (!tb[RTA_OIF])
394 return false;
395
396 return *(int *)RTA_DATA(tb[RTA_OIF]) == ifindex;
397 }
398
399 static int cb_clear_event(struct nl_msg *msg, void *arg)
400 {
401 struct clear_data *clr = arg;
402 struct nlmsghdr *hdr = nlmsg_hdr(msg);
403 bool (*cb)(struct nlmsghdr *, int ifindex);
404 int type;
405
406 switch(clr->type) {
407 case RTM_GETADDR:
408 type = RTM_DELADDR;
409 if (hdr->nlmsg_type != RTM_NEWADDR)
410 return NL_SKIP;
411
412 cb = check_ifaddr;
413 break;
414 case RTM_GETROUTE:
415 type = RTM_DELROUTE;
416 if (hdr->nlmsg_type != RTM_NEWROUTE)
417 return NL_SKIP;
418
419 cb = check_route;
420 break;
421 default:
422 return NL_SKIP;
423 }
424
425 if (!cb(hdr, clr->dev->ifindex))
426 return NL_SKIP;
427
428 D(SYSTEM, "Remove %s from device %s\n",
429 type == RTM_DELADDR ? "an address" : "a route",
430 clr->dev->ifname);
431 memcpy(nlmsg_hdr(clr->msg), hdr, hdr->nlmsg_len);
432 hdr = nlmsg_hdr(clr->msg);
433 hdr->nlmsg_type = type;
434 hdr->nlmsg_flags = NLM_F_REQUEST;
435
436 if (!nl_send_auto_complete(sock_rtnl, clr->msg))
437 nl_wait_for_ack(sock_rtnl);
438
439 return NL_SKIP;
440 }
441
442 static int
443 cb_finish_event(struct nl_msg *msg, void *arg)
444 {
445 int *pending = arg;
446 *pending = 0;
447 return NL_STOP;
448 }
449
450 static int
451 error_handler(struct sockaddr_nl *nla, struct nlmsgerr *err, void *arg)
452 {
453 int *pending = arg;
454 *pending = err->error;
455 return NL_STOP;
456 }
457
458 static void
459 system_if_clear_entries(struct device *dev, int type, int af)
460 {
461 struct clear_data clr;
462 struct nl_cb *cb = nl_cb_alloc(NL_CB_DEFAULT);
463 struct rtmsg rtm = {
464 .rtm_family = af,
465 .rtm_flags = RTM_F_CLONED,
466 };
467 int flags = NLM_F_DUMP;
468 int pending = 1;
469
470 clr.af = af;
471 clr.dev = dev;
472 clr.type = type;
473 switch (type) {
474 case RTM_GETADDR:
475 clr.size = sizeof(struct rtgenmsg);
476 break;
477 case RTM_GETROUTE:
478 clr.size = sizeof(struct rtmsg);
479 break;
480 default:
481 return;
482 }
483
484 if (!cb)
485 return;
486
487 clr.msg = nlmsg_alloc_simple(type, flags);
488 if (!clr.msg)
489 goto out;
490
491 nlmsg_append(clr.msg, &rtm, clr.size, 0);
492 nl_cb_set(cb, NL_CB_VALID, NL_CB_CUSTOM, cb_clear_event, &clr);
493 nl_cb_set(cb, NL_CB_FINISH, NL_CB_CUSTOM, cb_finish_event, &pending);
494 nl_cb_err(cb, NL_CB_CUSTOM, error_handler, &pending);
495
496 nl_send_auto_complete(sock_rtnl, clr.msg);
497 while (pending > 0)
498 nl_recvmsgs(sock_rtnl, cb);
499
500 nlmsg_free(clr.msg);
501 out:
502 nl_cb_put(cb);
503 }
504
505 /*
506 * Clear bridge (membership) state and bring down device
507 */
508 void system_if_clear_state(struct device *dev)
509 {
510 static char buf[256];
511 char *bridge;
512
513 if (dev->external)
514 return;
515
516 dev->ifindex = system_if_resolve(dev);
517 if (!dev->ifindex)
518 return;
519
520 system_if_flags(dev->ifname, 0, IFF_UP);
521
522 if (system_is_bridge(dev->ifname, buf, sizeof(buf))) {
523 D(SYSTEM, "Delete existing bridge named '%s'\n", dev->ifname);
524 system_bridge_delbr(dev);
525 return;
526 }
527
528 bridge = system_get_bridge(dev->ifname, buf, sizeof(buf));
529 if (bridge) {
530 D(SYSTEM, "Remove device '%s' from bridge '%s'\n", dev->ifname, bridge);
531 system_bridge_if(bridge, dev, SIOCBRDELIF, NULL);
532 }
533
534 system_if_clear_entries(dev, RTM_GETROUTE, AF_INET);
535 system_if_clear_entries(dev, RTM_GETADDR, AF_INET);
536 system_if_clear_entries(dev, RTM_GETROUTE, AF_INET6);
537 system_if_clear_entries(dev, RTM_GETADDR, AF_INET6);
538 system_set_disable_ipv6(dev, "0");
539 }
540
541 static inline unsigned long
542 sec_to_jiffies(int val)
543 {
544 return (unsigned long) val * 100;
545 }
546
547 int system_bridge_addbr(struct device *bridge, struct bridge_config *cfg)
548 {
549 unsigned long args[4] = {};
550
551 if (ioctl(sock_ioctl, SIOCBRADDBR, bridge->ifname) < 0)
552 return -1;
553
554 args[0] = BRCTL_SET_BRIDGE_STP_STATE;
555 args[1] = !!cfg->stp;
556 system_bridge_if(bridge->ifname, NULL, SIOCDEVPRIVATE, &args);
557
558 args[0] = BRCTL_SET_BRIDGE_FORWARD_DELAY;
559 args[1] = sec_to_jiffies(cfg->forward_delay);
560 system_bridge_if(bridge->ifname, NULL, SIOCDEVPRIVATE, &args);
561
562 system_set_dev_sysctl("/sys/devices/virtual/net/%s/bridge/multicast_snooping",
563 bridge->ifname, cfg->igmp_snoop ? "1" : "0");
564
565 if (cfg->flags & BRIDGE_OPT_AGEING_TIME) {
566 args[0] = BRCTL_SET_AGEING_TIME;
567 args[1] = sec_to_jiffies(cfg->ageing_time);
568 system_bridge_if(bridge->ifname, NULL, SIOCDEVPRIVATE, &args);
569 }
570
571 if (cfg->flags & BRIDGE_OPT_HELLO_TIME) {
572 args[0] = BRCTL_SET_BRIDGE_HELLO_TIME;
573 args[1] = sec_to_jiffies(cfg->hello_time);
574 system_bridge_if(bridge->ifname, NULL, SIOCDEVPRIVATE, &args);
575 }
576
577 if (cfg->flags & BRIDGE_OPT_MAX_AGE) {
578 args[0] = BRCTL_SET_BRIDGE_MAX_AGE;
579 args[1] = sec_to_jiffies(cfg->max_age);
580 system_bridge_if(bridge->ifname, NULL, SIOCDEVPRIVATE, &args);
581 }
582
583 return 0;
584 }
585
586 static int system_vlan(struct device *dev, int id)
587 {
588 struct vlan_ioctl_args ifr = {
589 .cmd = SET_VLAN_NAME_TYPE_CMD,
590 .u.name_type = VLAN_NAME_TYPE_RAW_PLUS_VID_NO_PAD,
591 };
592
593 ioctl(sock_ioctl, SIOCSIFVLAN, &ifr);
594
595 if (id < 0) {
596 ifr.cmd = DEL_VLAN_CMD;
597 ifr.u.VID = 0;
598 } else {
599 ifr.cmd = ADD_VLAN_CMD;
600 ifr.u.VID = id;
601 }
602 strncpy(ifr.device1, dev->ifname, sizeof(ifr.device1));
603 return ioctl(sock_ioctl, SIOCSIFVLAN, &ifr);
604 }
605
606 int system_vlan_add(struct device *dev, int id)
607 {
608 return system_vlan(dev, id);
609 }
610
611 int system_vlan_del(struct device *dev)
612 {
613 return system_vlan(dev, -1);
614 }
615
616 static void
617 system_if_get_settings(struct device *dev, struct device_settings *s)
618 {
619 struct ifreq ifr;
620
621 memset(&ifr, 0, sizeof(ifr));
622 strncpy(ifr.ifr_name, dev->ifname, sizeof(ifr.ifr_name));
623
624 if (ioctl(sock_ioctl, SIOCGIFMTU, &ifr) == 0) {
625 s->mtu = ifr.ifr_mtu;
626 s->flags |= DEV_OPT_MTU;
627 }
628
629 if (ioctl(sock_ioctl, SIOCGIFTXQLEN, &ifr) == 0) {
630 s->txqueuelen = ifr.ifr_qlen;
631 s->flags |= DEV_OPT_TXQUEUELEN;
632 }
633
634 if (ioctl(sock_ioctl, SIOCGIFHWADDR, &ifr) == 0) {
635 memcpy(s->macaddr, &ifr.ifr_hwaddr.sa_data, sizeof(s->macaddr));
636 s->flags |= DEV_OPT_MACADDR;
637 }
638 }
639
640 void
641 system_if_apply_settings(struct device *dev, struct device_settings *s)
642 {
643 struct ifreq ifr;
644
645 memset(&ifr, 0, sizeof(ifr));
646 strncpy(ifr.ifr_name, dev->ifname, sizeof(ifr.ifr_name));
647 if (s->flags & DEV_OPT_MTU) {
648 ifr.ifr_mtu = s->mtu;
649 if (ioctl(sock_ioctl, SIOCSIFMTU, &ifr) < 0)
650 s->flags &= ~DEV_OPT_MTU;
651 }
652 if (s->flags & DEV_OPT_TXQUEUELEN) {
653 ifr.ifr_qlen = s->txqueuelen;
654 if (ioctl(sock_ioctl, SIOCSIFTXQLEN, &ifr) < 0)
655 s->flags &= ~DEV_OPT_TXQUEUELEN;
656 }
657 if ((s->flags & DEV_OPT_MACADDR) && !dev->external) {
658 ifr.ifr_hwaddr.sa_family = ARPHRD_ETHER;
659 memcpy(&ifr.ifr_hwaddr.sa_data, s->macaddr, sizeof(s->macaddr));
660 if (ioctl(sock_ioctl, SIOCSIFHWADDR, &ifr) < 0)
661 s->flags &= ~DEV_OPT_MACADDR;
662 }
663 }
664
665 int system_if_up(struct device *dev)
666 {
667 system_if_get_settings(dev, &dev->orig_settings);
668 system_if_apply_settings(dev, &dev->settings);
669 dev->ifindex = system_if_resolve(dev);
670 return system_if_flags(dev->ifname, IFF_UP, 0);
671 }
672
673 int system_if_down(struct device *dev)
674 {
675 int ret = system_if_flags(dev->ifname, 0, IFF_UP);
676 dev->orig_settings.flags &= dev->settings.flags;
677 system_if_apply_settings(dev, &dev->orig_settings);
678 return ret;
679 }
680
681 int system_if_check(struct device *dev)
682 {
683 device_set_present(dev, (system_if_resolve(dev) > 0));
684 return 0;
685 }
686
687 struct device *
688 system_if_get_parent(struct device *dev)
689 {
690 char buf[64], *devname;
691 int ifindex, iflink, len;
692 FILE *f;
693
694 snprintf(buf, sizeof(buf), "/sys/class/net/%s/iflink", dev->ifname);
695 f = fopen(buf, "r");
696 if (!f)
697 return NULL;
698
699 len = fread(buf, 1, sizeof(buf) - 1, f);
700 fclose(f);
701
702 if (len <= 0)
703 return NULL;
704
705 buf[len] = 0;
706 iflink = strtoul(buf, NULL, 0);
707 ifindex = system_if_resolve(dev);
708 if (!iflink || iflink == ifindex)
709 return NULL;
710
711 devname = if_indextoname(iflink, buf);
712 if (!devname)
713 return NULL;
714
715 return device_get(devname, true);
716 }
717
718 static bool
719 read_string_file(int dir_fd, const char *file, char *buf, int len)
720 {
721 bool ret = false;
722 char *c;
723 int fd;
724
725 fd = openat(dir_fd, file, O_RDONLY);
726 if (fd < 0)
727 return false;
728
729 retry:
730 len = read(fd, buf, len - 1);
731 if (len < 0) {
732 if (errno == EINTR)
733 goto retry;
734 } else if (len > 0) {
735 buf[len] = 0;
736
737 c = strchr(buf, '\n');
738 if (c)
739 *c = 0;
740
741 ret = true;
742 }
743
744 close(fd);
745
746 return ret;
747 }
748
749 static bool
750 read_uint64_file(int dir_fd, const char *file, uint64_t *val)
751 {
752 char buf[64];
753 bool ret = false;
754
755 ret = read_string_file(dir_fd, file, buf, sizeof(buf));
756 if (ret)
757 *val = strtoull(buf, NULL, 0);
758
759 return ret;
760 }
761
762 /* Assume advertised flags == supported flags */
763 static const struct {
764 uint32_t mask;
765 const char *name;
766 } ethtool_link_modes[] = {
767 { ADVERTISED_10baseT_Half, "10H" },
768 { ADVERTISED_10baseT_Full, "10F" },
769 { ADVERTISED_100baseT_Half, "100H" },
770 { ADVERTISED_100baseT_Full, "100F" },
771 { ADVERTISED_1000baseT_Half, "1000H" },
772 { ADVERTISED_1000baseT_Full, "1000F" },
773 };
774
775 static void system_add_link_modes(struct blob_buf *b, __u32 mask)
776 {
777 int i;
778 for (i = 0; i < ARRAY_SIZE(ethtool_link_modes); i++) {
779 if (mask & ethtool_link_modes[i].mask)
780 blobmsg_add_string(b, NULL, ethtool_link_modes[i].name);
781 }
782 }
783
784 bool
785 system_if_force_external(const char *ifname)
786 {
787 char buf[64];
788 struct stat s;
789
790 snprintf(buf, sizeof(buf), "/sys/class/net/%s/phy80211", ifname);
791 return stat(buf, &s) == 0;
792 }
793
794 int
795 system_if_dump_info(struct device *dev, struct blob_buf *b)
796 {
797 struct ethtool_cmd ecmd;
798 struct ifreq ifr;
799 char buf[64], *s;
800 void *c;
801 int dir_fd;
802 uint64_t val = 0;
803
804 snprintf(buf, sizeof(buf), "/sys/class/net/%s", dev->ifname);
805 dir_fd = open(buf, O_DIRECTORY);
806
807 if (read_uint64_file(dir_fd, "carrier", &val))
808 blobmsg_add_u8(b, "link", !!val);
809
810 memset(&ecmd, 0, sizeof(ecmd));
811 memset(&ifr, 0, sizeof(ifr));
812 strcpy(ifr.ifr_name, dev->ifname);
813 ifr.ifr_data = (caddr_t) &ecmd;
814 ecmd.cmd = ETHTOOL_GSET;
815
816 if (ioctl(sock_ioctl, SIOCETHTOOL, &ifr) == 0) {
817 c = blobmsg_open_array(b, "link-advertising");
818 system_add_link_modes(b, ecmd.advertising);
819 blobmsg_close_array(b, c);
820
821 c = blobmsg_open_array(b, "link-supported");
822 system_add_link_modes(b, ecmd.supported);
823 blobmsg_close_array(b, c);
824
825 s = blobmsg_alloc_string_buffer(b, "speed", 8);
826 snprintf(s, 8, "%d%c", ethtool_cmd_speed(&ecmd),
827 ecmd.duplex == DUPLEX_HALF ? 'H' : 'F');
828 blobmsg_add_string_buffer(b);
829 }
830
831 close(dir_fd);
832 return 0;
833 }
834
835 int
836 system_if_dump_stats(struct device *dev, struct blob_buf *b)
837 {
838 const char *const counters[] = {
839 "collisions", "rx_frame_errors", "tx_compressed",
840 "multicast", "rx_length_errors", "tx_dropped",
841 "rx_bytes", "rx_missed_errors", "tx_errors",
842 "rx_compressed", "rx_over_errors", "tx_fifo_errors",
843 "rx_crc_errors", "rx_packets", "tx_heartbeat_errors",
844 "rx_dropped", "tx_aborted_errors", "tx_packets",
845 "rx_errors", "tx_bytes", "tx_window_errors",
846 "rx_fifo_errors", "tx_carrier_errors",
847 };
848 char buf[64];
849 int stats_dir;
850 int i;
851 uint64_t val = 0;
852
853 snprintf(buf, sizeof(buf), "/sys/class/net/%s/statistics", dev->ifname);
854 stats_dir = open(buf, O_DIRECTORY);
855 if (stats_dir < 0)
856 return -1;
857
858 for (i = 0; i < ARRAY_SIZE(counters); i++)
859 if (read_uint64_file(stats_dir, counters[i], &val))
860 blobmsg_add_u64(b, counters[i], val);
861
862 close(stats_dir);
863 return 0;
864 }
865
866 static int system_addr(struct device *dev, struct device_addr *addr, int cmd)
867 {
868 bool v4 = ((addr->flags & DEVADDR_FAMILY) == DEVADDR_INET4);
869 int alen = v4 ? 4 : 16;
870 unsigned int flags = 0;
871 struct ifaddrmsg ifa = {
872 .ifa_family = (alen == 4) ? AF_INET : AF_INET6,
873 .ifa_prefixlen = addr->mask,
874 .ifa_index = dev->ifindex,
875 };
876
877 struct nl_msg *msg;
878 if (cmd == RTM_NEWADDR)
879 flags |= NLM_F_CREATE | NLM_F_REPLACE;
880
881 msg = nlmsg_alloc_simple(cmd, flags);
882 if (!msg)
883 return -1;
884
885 nlmsg_append(msg, &ifa, sizeof(ifa), 0);
886 nla_put(msg, IFA_LOCAL, alen, &addr->addr);
887 if (v4) {
888 if (addr->broadcast)
889 nla_put_u32(msg, IFA_BROADCAST, addr->broadcast);
890 if (addr->point_to_point)
891 nla_put_u32(msg, IFA_ADDRESS, addr->point_to_point);
892 } else {
893 time_t now = system_get_rtime();
894 struct ifa_cacheinfo cinfo = {0xffffffffU, 0xffffffffU, 0, 0};
895
896 if (addr->preferred_until) {
897 int preferred = addr->preferred_until - now;
898 if (preferred < 0)
899 preferred = 0;
900
901 cinfo.ifa_prefered = preferred;
902 }
903
904 if (addr->valid_until) {
905 int valid = addr->valid_until - now;
906 if (valid <= 0)
907 return -1;
908
909 cinfo.ifa_valid = valid;
910 }
911
912 nla_put(msg, IFA_CACHEINFO, sizeof(cinfo), &cinfo);
913 }
914
915 return system_rtnl_call(msg);
916 }
917
918 int system_add_address(struct device *dev, struct device_addr *addr)
919 {
920 return system_addr(dev, addr, RTM_NEWADDR);
921 }
922
923 int system_del_address(struct device *dev, struct device_addr *addr)
924 {
925 return system_addr(dev, addr, RTM_DELADDR);
926 }
927
928 static int system_rt(struct device *dev, struct device_route *route, int cmd)
929 {
930 int alen = ((route->flags & DEVADDR_FAMILY) == DEVADDR_INET4) ? 4 : 16;
931 bool have_gw;
932 unsigned int flags = 0;
933
934 if (alen == 4)
935 have_gw = !!route->nexthop.in.s_addr;
936 else
937 have_gw = route->nexthop.in6.s6_addr32[0] ||
938 route->nexthop.in6.s6_addr32[1] ||
939 route->nexthop.in6.s6_addr32[2] ||
940 route->nexthop.in6.s6_addr32[3];
941
942 unsigned char scope = (cmd == RTM_DELROUTE) ? RT_SCOPE_NOWHERE :
943 (have_gw) ? RT_SCOPE_UNIVERSE : RT_SCOPE_LINK;
944
945 unsigned int table = (route->flags & DEVROUTE_TABLE) ? route->table : RT_TABLE_MAIN;
946
947 struct rtmsg rtm = {
948 .rtm_family = (alen == 4) ? AF_INET : AF_INET6,
949 .rtm_dst_len = route->mask,
950 .rtm_table = (table < 256) ? table : RT_TABLE_UNSPEC,
951 .rtm_protocol = (route->flags & DEVADDR_KERNEL) ? RTPROT_KERNEL : RTPROT_STATIC,
952 .rtm_scope = scope,
953 .rtm_type = (cmd == RTM_DELROUTE) ? 0: RTN_UNICAST,
954 };
955 struct nl_msg *msg;
956
957 if (cmd == RTM_NEWROUTE) {
958 flags |= NLM_F_CREATE | NLM_F_REPLACE;
959
960 if (!dev) { // Add null-route
961 rtm.rtm_scope = RT_SCOPE_UNIVERSE;
962 rtm.rtm_type = RTN_UNREACHABLE;
963 }
964 }
965
966 msg = nlmsg_alloc_simple(cmd, flags);
967 if (!msg)
968 return -1;
969
970 nlmsg_append(msg, &rtm, sizeof(rtm), 0);
971
972 if (route->mask)
973 nla_put(msg, RTA_DST, alen, &route->addr);
974
975 if (route->metric > 0)
976 nla_put_u32(msg, RTA_PRIORITY, route->metric);
977
978 if (have_gw)
979 nla_put(msg, RTA_GATEWAY, alen, &route->nexthop);
980
981 if (dev)
982 nla_put_u32(msg, RTA_OIF, dev->ifindex);
983
984 if (table >= 256)
985 nla_put_u32(msg, RTA_TABLE, table);
986
987 return system_rtnl_call(msg);
988 }
989
990 int system_add_route(struct device *dev, struct device_route *route)
991 {
992 return system_rt(dev, route, RTM_NEWROUTE);
993 }
994
995 int system_del_route(struct device *dev, struct device_route *route)
996 {
997 return system_rt(dev, route, RTM_DELROUTE);
998 }
999
1000 int system_flush_routes(void)
1001 {
1002 const char *names[] = {
1003 "/proc/sys/net/ipv4/route/flush",
1004 "/proc/sys/net/ipv6/route/flush"
1005 };
1006 int fd, i;
1007
1008 for (i = 0; i < ARRAY_SIZE(names); i++) {
1009 fd = open(names[i], O_WRONLY);
1010 if (fd < 0)
1011 continue;
1012
1013 write(fd, "-1", 2);
1014 close(fd);
1015 }
1016 return 0;
1017 }
1018
1019 bool system_resolve_rt_table(const char *name, unsigned int *id)
1020 {
1021 FILE *f;
1022 char *e, buf[128];
1023 unsigned int n, table = RT_TABLE_UNSPEC;
1024
1025 /* first try to parse table as number */
1026 if ((n = strtoul(name, &e, 0)) > 0 && !*e)
1027 table = n;
1028
1029 /* handle well known aliases */
1030 else if (!strcmp(name, "default"))
1031 table = RT_TABLE_DEFAULT;
1032 else if (!strcmp(name, "main"))
1033 table = RT_TABLE_MAIN;
1034 else if (!strcmp(name, "local"))
1035 table = RT_TABLE_LOCAL;
1036
1037 /* try to look up name in /etc/iproute2/rt_tables */
1038 else if ((f = fopen("/etc/iproute2/rt_tables", "r")) != NULL)
1039 {
1040 while (fgets(buf, sizeof(buf) - 1, f) != NULL)
1041 {
1042 if ((e = strtok(buf, " \t\n")) == NULL || *e == '#')
1043 continue;
1044
1045 n = strtoul(e, NULL, 10);
1046 e = strtok(NULL, " \t\n");
1047
1048 if (e && !strcmp(e, name))
1049 {
1050 table = n;
1051 break;
1052 }
1053 }
1054
1055 fclose(f);
1056 }
1057
1058 if (table == RT_TABLE_UNSPEC)
1059 return false;
1060
1061 /* do not consider main table special */
1062 if (table == RT_TABLE_MAIN)
1063 table = RT_TABLE_UNSPEC;
1064
1065 *id = table;
1066 return true;
1067 }
1068
1069 time_t system_get_rtime(void)
1070 {
1071 struct timespec ts;
1072 struct timeval tv;
1073
1074 if (syscall(__NR_clock_gettime, CLOCK_MONOTONIC, &ts) == 0)
1075 return ts.tv_sec;
1076
1077 if (gettimeofday(&tv, NULL) == 0)
1078 return tv.tv_sec;
1079
1080 return 0;
1081 }
1082
1083 #ifndef IP_DF
1084 #define IP_DF 0x4000
1085 #endif
1086
1087 static void tunnel_parm_init(struct ip_tunnel_parm *p)
1088 {
1089 memset(p, 0, sizeof(*p));
1090 p->iph.version = 4;
1091 p->iph.ihl = 5;
1092 p->iph.frag_off = htons(IP_DF);
1093 }
1094
1095 static int tunnel_ioctl(const char *name, int cmd, void *p)
1096 {
1097 struct ifreq ifr;
1098
1099 memset(&ifr, 0, sizeof(ifr));
1100 strncpy(ifr.ifr_name, name, sizeof(ifr.ifr_name));
1101 ifr.ifr_ifru.ifru_data = p;
1102 return ioctl(sock_ioctl, cmd, &ifr);
1103 }
1104
1105 int system_del_ip_tunnel(const char *name)
1106 {
1107 struct ip_tunnel_parm p;
1108
1109 tunnel_parm_init(&p);
1110 return tunnel_ioctl(name, SIOCDELTUNNEL, &p);
1111 }
1112
1113 int system_update_ipv6_mtu(struct device *dev, int mtu)
1114 {
1115 int ret = -1;
1116 char buf[64];
1117 snprintf(buf, sizeof(buf), "/proc/sys/net/ipv6/conf/%s/mtu",
1118 dev->ifname);
1119
1120 int fd = open(buf, O_RDWR);
1121 ssize_t len = read(fd, buf, sizeof(buf) - 1);
1122 if (len < 0)
1123 goto out;
1124
1125 buf[len] = 0;
1126 ret = atoi(buf);
1127
1128 if (!mtu || ret <= mtu)
1129 goto out;
1130
1131 lseek(fd, 0, SEEK_SET);
1132 if (write(fd, buf, snprintf(buf, sizeof(buf), "%i", mtu)) <= 0)
1133 ret = -1;
1134
1135 out:
1136 close(fd);
1137 return ret;
1138 }
1139
1140 static int parse_ipaddr(struct blob_attr *attr, __be32 *addr)
1141 {
1142 if (!attr)
1143 return 1;
1144
1145 return inet_pton(AF_INET, blobmsg_data(attr), (void *) addr);
1146 }
1147
1148
1149 int system_add_ip_tunnel(const char *name, struct blob_attr *attr)
1150 {
1151 struct blob_attr *tb[__TUNNEL_ATTR_MAX];
1152 struct blob_attr *cur;
1153 struct ip_tunnel_parm p;
1154 const char *base, *str;
1155 bool is_sit;
1156
1157 system_del_ip_tunnel(name);
1158
1159 tunnel_parm_init(&p);
1160
1161 blobmsg_parse(tunnel_attr_list.params, __TUNNEL_ATTR_MAX, tb,
1162 blob_data(attr), blob_len(attr));
1163
1164 if (!(cur = tb[TUNNEL_ATTR_TYPE]))
1165 return -EINVAL;
1166 str = blobmsg_data(cur);
1167 is_sit = !strcmp(str, "sit");
1168
1169 if (is_sit) {
1170 p.iph.protocol = IPPROTO_IPV6;
1171 base = "sit0";
1172 } else
1173 return -EINVAL;
1174
1175 if (!parse_ipaddr(tb[TUNNEL_ATTR_LOCAL], &p.iph.saddr))
1176 return -EINVAL;
1177
1178 if (!parse_ipaddr(tb[TUNNEL_ATTR_REMOTE], &p.iph.daddr))
1179 return -EINVAL;
1180
1181 if ((cur = tb[TUNNEL_ATTR_TTL])) {
1182 unsigned int val = blobmsg_get_u32(cur);
1183
1184 if (val > 255)
1185 return -EINVAL;
1186
1187 p.iph.ttl = val;
1188 }
1189
1190 strncpy(p.name, name, sizeof(p.name));
1191 if (tunnel_ioctl(base, SIOCADDTUNNEL, &p) < 0)
1192 return -1;
1193
1194 #ifdef SIOCADD6RD
1195 cur = tb[TUNNEL_ATTR_6RD_PREFIX];
1196 if (cur && is_sit) {
1197 unsigned int mask;
1198 struct ip_tunnel_6rd p6;
1199
1200 memset(&p6, 0, sizeof(p6));
1201
1202 if (!parse_ip_and_netmask(AF_INET6, blobmsg_data(cur),
1203 &p6.prefix, &mask) || mask > 128)
1204 return -EINVAL;
1205 p6.prefixlen = mask;
1206
1207 if ((cur = tb[TUNNEL_ATTR_6RD_RELAY_PREFIX])) {
1208 if (!parse_ip_and_netmask(AF_INET, blobmsg_data(cur),
1209 &p6.relay_prefix, &mask) || mask > 32)
1210 return -EINVAL;
1211 p6.relay_prefixlen = mask;
1212 }
1213
1214 if (tunnel_ioctl(name, SIOCADD6RD, &p6) < 0) {
1215 system_del_ip_tunnel(name);
1216 return -1;
1217 }
1218 }
1219 #endif
1220
1221 return 0;
1222 }