Add ubus methods for global interface status
[project/netifd.git] / interface-ip.c
1 /*
2  * netifd - network interface daemon
3  * Copyright (C) 2012 Felix Fietkau <nbd@openwrt.org>
4  * Copyright (C) 2012 Steven Barth <steven@midlink.org>
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2
8  * as published by the Free Software Foundation
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  */
15 #include <string.h>
16 #include <stdlib.h>
17 #include <stdio.h>
18 #include <unistd.h>
19
20 #include <limits.h>
21 #include <arpa/inet.h>
22
23 #include "netifd.h"
24 #include "device.h"
25 #include "interface.h"
26 #include "interface-ip.h"
27 #include "proto.h"
28 #include "ubus.h"
29 #include "system.h"
30
31 enum {
32         ROUTE_INTERFACE,
33         ROUTE_TARGET,
34         ROUTE_MASK,
35         ROUTE_GATEWAY,
36         ROUTE_METRIC,
37         ROUTE_MTU,
38         ROUTE_VALID,
39         ROUTE_TABLE,
40         __ROUTE_MAX
41 };
42
43 static const struct blobmsg_policy route_attr[__ROUTE_MAX] = {
44         [ROUTE_INTERFACE] = { .name = "interface", .type = BLOBMSG_TYPE_STRING },
45         [ROUTE_TARGET] = { .name = "target", .type = BLOBMSG_TYPE_STRING },
46         [ROUTE_MASK] = { .name = "netmask", .type = BLOBMSG_TYPE_STRING },
47         [ROUTE_GATEWAY] = { .name = "gateway", .type = BLOBMSG_TYPE_STRING },
48         [ROUTE_METRIC] = { .name = "metric", .type = BLOBMSG_TYPE_INT32 },
49         [ROUTE_MTU] = { .name = "mtu", .type = BLOBMSG_TYPE_INT32 },
50         [ROUTE_TABLE] = { .name = "table", .type = BLOBMSG_TYPE_STRING },
51         [ROUTE_VALID] = { .name = "valid", .type = BLOBMSG_TYPE_INT32 },
52 };
53
54 const struct uci_blob_param_list route_attr_list = {
55         .n_params = __ROUTE_MAX,
56         .params = route_attr,
57 };
58
59
60 struct list_head prefixes = LIST_HEAD_INIT(prefixes);
61 static struct device_prefix *ula_prefix = NULL;
62 static struct uloop_timeout valid_until_timeout;
63
64
65 static void
66 clear_if_addr(union if_addr *a, int mask)
67 {
68         int m_bytes = (mask + 7) / 8;
69         uint8_t m_clear = (1 << (m_bytes * 8 - mask)) - 1;
70         uint8_t *p = (uint8_t *) a;
71
72         if (m_bytes < sizeof(a))
73                 memset(p + m_bytes, 0, sizeof(a) - m_bytes);
74
75         p[m_bytes - 1] &= ~m_clear;
76 }
77
78 static bool
79 match_if_addr(union if_addr *a1, union if_addr *a2, int mask)
80 {
81         union if_addr *p1, *p2;
82
83         p1 = alloca(sizeof(*a1));
84         p2 = alloca(sizeof(*a2));
85
86         memcpy(p1, a1, sizeof(*a1));
87         clear_if_addr(p1, mask);
88         memcpy(p2, a2, sizeof(*a2));
89         clear_if_addr(p2, mask);
90
91         return !memcmp(p1, p2, sizeof(*p1));
92 }
93
94 static int set_ip_source_policy(bool add, bool v6, unsigned int priority,
95                 const union if_addr *addr, uint8_t mask, struct interface *iface,
96                 struct interface *in_iface, const char *action)
97 {
98         struct iprule rule = {
99                 .flags = IPRULE_PRIORITY,
100                 .priority = priority
101         };
102
103         if (addr) {
104                 rule.flags |= IPRULE_SRC;
105                 rule.src_addr = *addr;
106                 rule.src_mask = mask;
107         }
108
109         if (iface) {
110                 rule.flags |= IPRULE_LOOKUP;
111                 rule.lookup = (v6) ? iface->ip6table : iface->ip4table;
112
113                 if (!rule.lookup)
114                         return 0;
115         } else if (action) {
116                 rule.flags |= IPRULE_ACTION;
117                 system_resolve_iprule_action(action, &rule.action);
118         }
119
120         if (in_iface && in_iface->l3_dev.dev) {
121                 rule.flags |= IPRULE_IN;
122                 strcpy(rule.in_dev, in_iface->l3_dev.dev->ifname);
123         }
124
125         rule.flags |= (v6) ? IPRULE_INET6 : IPRULE_INET4;
126
127         return (add) ? system_add_iprule(&rule) : system_del_iprule(&rule);
128 }
129
130 static int set_ip_lo_policy(bool add, bool v6, struct interface *iface)
131 {
132         struct iprule rule = {
133                 .flags = IPRULE_IN | IPRULE_LOOKUP | IPRULE_PRIORITY,
134                 .priority = IPRULE_PRIORITY_NW + iface->l3_dev.dev->ifindex,
135                 .lookup = (v6) ? iface->ip6table : iface->ip4table,
136                 .in_dev = "lo"
137         };
138
139         if (!rule.lookup)
140                 return 0;
141
142         rule.flags |= (v6) ? IPRULE_INET6 : IPRULE_INET4;
143
144         return (add) ? system_add_iprule(&rule) : system_del_iprule(&rule);
145 }
146
147 static bool
148 __find_ip_addr_target(struct interface_ip_settings *ip, union if_addr *a, bool v6)
149 {
150         struct device_addr *addr;
151
152         vlist_for_each_element(&ip->addr, addr, node) {
153                 if (!addr->enabled)
154                         continue;
155
156                 if (v6 != ((addr->flags & DEVADDR_FAMILY) == DEVADDR_INET6))
157                         continue;
158
159                 // Handle offlink addresses correctly
160                 unsigned int mask = addr->mask;
161                 if ((addr->flags & DEVADDR_FAMILY) == DEVADDR_INET6 &&
162                                 (addr->flags & DEVADDR_OFFLINK))
163                         mask = 128;
164
165                 if (!match_if_addr(&addr->addr, a, mask))
166                         continue;
167
168                 return true;
169         }
170
171         return false;
172 }
173
174 static void
175 __find_ip_route_target(struct interface_ip_settings *ip, union if_addr *a,
176                        bool v6, struct device_route **res)
177 {
178         struct device_route *route;
179
180         vlist_for_each_element(&ip->route, route, node) {
181                 if (!route->enabled)
182                         continue;
183
184                 if (v6 != ((route->flags & DEVADDR_FAMILY) == DEVADDR_INET6))
185                         continue;
186
187                 if (!match_if_addr(&route->addr, a, route->mask))
188                         continue;
189
190                 if (route->flags & DEVROUTE_TABLE)
191                         continue;
192
193                 if (!*res || route->mask < (*res)->mask)
194                         *res = route;
195         }
196 }
197
198 static bool
199 interface_ip_find_addr_target(struct interface *iface, union if_addr *a, bool v6)
200 {
201         return __find_ip_addr_target(&iface->proto_ip, a, v6) ||
202                __find_ip_addr_target(&iface->config_ip, a, v6);
203 }
204
205 static void
206 interface_ip_find_route_target(struct interface *iface, union if_addr *a,
207                                bool v6, struct device_route **route)
208 {
209         __find_ip_route_target(&iface->proto_ip, a, v6, route);
210         __find_ip_route_target(&iface->config_ip, a, v6, route);
211 }
212
213 struct interface *
214 interface_ip_add_target_route(union if_addr *addr, bool v6, struct interface *iface)
215 {
216         struct device_route *route, *r_next = NULL;
217         bool defaultroute_target = false;
218         int addrsize = v6 ? sizeof(addr->in6) : sizeof(addr->in);
219
220         route = calloc(1, sizeof(*route));
221         if (!route)
222                 return NULL;
223
224         route->flags = v6 ? DEVADDR_INET6 : DEVADDR_INET4;
225         route->mask = v6 ? 128 : 32;
226         if (memcmp(&route->addr, addr, addrsize) == 0)
227                 defaultroute_target = true;
228         else
229                 memcpy(&route->addr, addr, addrsize);
230
231         if (iface) {
232                 /* look for locally addressable target first */
233                 if (interface_ip_find_addr_target(iface, addr, v6))
234                         goto done;
235
236                 /* do not stop at the first route, let the lookup compare
237                  * masks to find the best match */
238                 interface_ip_find_route_target(iface, addr, v6, &r_next);
239         } else {
240                 vlist_for_each_element(&interfaces, iface, node) {
241                         /* look for locally addressable target first */
242                         if (interface_ip_find_addr_target(iface, addr, v6))
243                                 goto done;
244
245                         /* do not stop at the first route, let the lookup compare
246                          * masks to find the best match */
247                         interface_ip_find_route_target(iface, addr, v6, &r_next);
248                 }
249         }
250
251         if (!r_next) {
252                 free(route);
253                 return NULL;
254         }
255
256         iface = r_next->iface;
257         memcpy(&route->nexthop, &r_next->nexthop, sizeof(route->nexthop));
258         route->mtu = r_next->mtu;
259         route->metric = r_next->metric;
260         route->table = r_next->table;
261
262 done:
263         route->iface = iface;
264         if (defaultroute_target)
265                 free(route);
266         else
267                 vlist_add(&iface->host_routes, &route->node, route);
268         return iface;
269 }
270
271 void
272 interface_ip_add_route(struct interface *iface, struct blob_attr *attr, bool v6)
273 {
274         struct interface_ip_settings *ip;
275         struct blob_attr *tb[__ROUTE_MAX], *cur;
276         struct device_route *route;
277         int af = v6 ? AF_INET6 : AF_INET;
278         bool is_proto_route = !!iface;
279
280         blobmsg_parse(route_attr, __ROUTE_MAX, tb, blobmsg_data(attr), blobmsg_data_len(attr));
281
282         if (!iface) {
283                 if ((cur = tb[ROUTE_INTERFACE]) == NULL)
284                         return;
285
286                 iface = vlist_find(&interfaces, blobmsg_data(cur), iface, node);
287                 if (!iface)
288                         return;
289
290                 ip = &iface->config_ip;
291         } else {
292                 ip = &iface->proto_ip;
293         }
294
295         route = calloc(1, sizeof(*route));
296         if (!route)
297                 return;
298
299         route->flags = v6 ? DEVADDR_INET6 : DEVADDR_INET4;
300         route->mask = v6 ? 128 : 32;
301         if ((cur = tb[ROUTE_MASK]) != NULL) {
302                 route->mask = parse_netmask_string(blobmsg_data(cur), v6);
303                 if (route->mask > (v6 ? 128 : 32))
304                         goto error;
305         }
306
307         if ((cur = tb[ROUTE_TARGET]) != NULL) {
308                 if (!parse_ip_and_netmask(af, blobmsg_data(cur), &route->addr, &route->mask)) {
309                         DPRINTF("Failed to parse route target: %s\n", (char *) blobmsg_data(cur));
310                         goto error;
311                 }
312         }
313
314         if ((cur = tb[ROUTE_GATEWAY]) != NULL) {
315                 if (!inet_pton(af, blobmsg_data(cur), &route->nexthop)) {
316                         DPRINTF("Failed to parse route gateway: %s\n", (char *) blobmsg_data(cur));
317                         goto error;
318                 }
319         }
320
321         if ((cur = tb[ROUTE_METRIC]) != NULL) {
322                 route->metric = blobmsg_get_u32(cur);
323                 route->flags |= DEVROUTE_METRIC;
324         }
325
326         if ((cur = tb[ROUTE_MTU]) != NULL) {
327                 route->mtu = blobmsg_get_u32(cur);
328                 route->flags |= DEVROUTE_MTU;
329         }
330
331         // Use source-based routing
332         if (is_proto_route) {
333                 route->table = (v6) ? iface->ip6table : iface->ip4table;
334                 route->flags |= DEVROUTE_SRCTABLE;
335         }
336
337         if ((cur = tb[ROUTE_TABLE]) != NULL) {
338                 if (!system_resolve_rt_table(blobmsg_data(cur), &route->table)) {
339                         DPRINTF("Failed to resolve routing table: %s\n", (char *) blobmsg_data(cur));
340                         goto error;
341                 }
342
343                 if (route->table)
344                         route->flags |= DEVROUTE_TABLE;
345         }
346
347         if ((cur = tb[ROUTE_VALID]) != NULL) {
348                 int64_t valid = blobmsg_get_u32(cur);
349                 int64_t valid_until = valid + (int64_t)system_get_rtime();
350                 if (valid_until <= LONG_MAX && valid != 0xffffffffLL) // Catch overflow
351                         route->valid_until = valid_until;
352         }
353
354         vlist_add(&ip->route, &route->node, route);
355         return;
356
357 error:
358         free(route);
359 }
360
361 static int
362 addr_cmp(const void *k1, const void *k2, void *ptr)
363 {
364         return memcmp(k1, k2, sizeof(struct device_addr) -
365                       offsetof(struct device_addr, flags));
366 }
367
368 static int
369 route_cmp(const void *k1, const void *k2, void *ptr)
370 {
371         const struct device_route *r1 = k1, *r2 = k2;
372
373         if (r1->mask != r2->mask)
374                 return r2->mask - r1->mask;
375
376         if (r1->metric != r2->metric)
377                 return r1->metric - r2->metric;
378
379         if (r1->flags != r2->flags)
380                 return r2->flags - r1->flags;
381
382         return memcmp(&r1->addr, &r2->addr, sizeof(r1->addr));
383 }
384
385 static int
386 prefix_cmp(const void *k1, const void *k2, void *ptr)
387 {
388         return memcmp(k1, k2, offsetof(struct device_prefix, pclass) -
389                         offsetof(struct device_prefix, addr));
390 }
391
392 static void
393 interface_handle_subnet_route(struct interface *iface, struct device_addr *addr, bool add)
394 {
395         struct device *dev = iface->l3_dev.dev;
396         struct device_route route;
397
398         memset(&route, 0, sizeof(route));
399         route.iface = iface;
400         route.flags = addr->flags;
401         route.mask = addr->mask;
402         memcpy(&route.addr, &addr->addr, sizeof(route.addr));
403         clear_if_addr(&route.addr, route.mask);
404
405         if (add) {
406                 route.flags |= DEVADDR_KERNEL;
407                 system_del_route(dev, &route);
408
409                 if (!(addr->flags & DEVADDR_OFFLINK)) {
410                         route.flags &= ~DEVADDR_KERNEL;
411                         route.metric = iface->metric;
412                         system_add_route(dev, &route);
413                 }
414         } else {
415                 if (!(addr->flags & DEVADDR_OFFLINK))
416                         system_del_route(dev, &route);
417         }
418 }
419
420 static void
421 interface_update_proto_addr(struct vlist_tree *tree,
422                             struct vlist_node *node_new,
423                             struct vlist_node *node_old)
424 {
425         struct interface_ip_settings *ip;
426         struct interface *iface;
427         struct device *dev;
428         struct device_addr *a_new = NULL, *a_old = NULL;
429         bool replace = false;
430         bool keep = false;
431         bool v6 = false;
432
433         ip = container_of(tree, struct interface_ip_settings, addr);
434         iface = ip->iface;
435         dev = iface->l3_dev.dev;
436
437         if (node_new) {
438                 a_new = container_of(node_new, struct device_addr, node);
439
440                 if ((a_new->flags & DEVADDR_FAMILY) == DEVADDR_INET4 &&
441                     !a_new->broadcast) {
442
443                         uint32_t mask = ~0;
444                         uint32_t *a = (uint32_t *) &a_new->addr;
445
446                         mask >>= a_new->mask;
447                         a_new->broadcast = *a | htonl(mask);
448                 }
449         }
450
451         if (node_old)
452                 a_old = container_of(node_old, struct device_addr, node);
453
454         if (a_new && a_old) {
455                 keep = true;
456
457                 if (a_old->flags != a_new->flags)
458                         keep = false;
459
460                 if (a_old->valid_until != a_new->valid_until ||
461                                 a_old->preferred_until != a_new->preferred_until)
462                         replace = true;
463
464                 if ((a_new->flags & DEVADDR_FAMILY) == DEVADDR_INET4 &&
465                     a_new->broadcast != a_old->broadcast)
466                         keep = false;
467         }
468
469         if (node_old) {
470                 if (!(a_old->flags & DEVADDR_EXTERNAL) && a_old->enabled && !keep) {
471                         interface_handle_subnet_route(iface, a_old, false);
472
473                         if ((a_old->flags & DEVADDR_FAMILY) == DEVADDR_INET6)
474                                 v6 = true;
475
476                         //This is needed for source routing to work correctly. If a device
477                         //has two connections to a network using the same subnet, adding
478                         //only the network-rule will cause packets to be routed through the
479                         //first matching network (source IP matches both masks).
480                         set_ip_source_policy(false, v6, IPRULE_PRIORITY_ADDR, &a_old->addr,
481                                 (v6) ? 128 : 32, iface, NULL, NULL);
482                         set_ip_source_policy(false, v6, IPRULE_PRIORITY_NW, &a_old->addr,
483                                 a_old->mask, iface, NULL, NULL);
484
485                         system_del_address(dev, a_old);
486                 }
487                 free(a_old);
488         }
489
490         if (node_new) {
491                 a_new->enabled = true;
492                 if (!(a_new->flags & DEVADDR_EXTERNAL) && (!keep || replace)) {
493                         system_add_address(dev, a_new);
494
495                         if (!keep) {
496                                 if ((a_new->flags & DEVADDR_FAMILY) == DEVADDR_INET6)
497                                         v6 = true;
498
499                                 set_ip_source_policy(true, v6, IPRULE_PRIORITY_ADDR, &a_new->addr,
500                                                 (v6) ? 128 : 32, iface, NULL, NULL);
501                                 set_ip_source_policy(true, v6, IPRULE_PRIORITY_NW, &a_new->addr,
502                                                 a_new->mask, iface, NULL, NULL);
503                         }
504
505                         if ((a_new->flags & DEVADDR_OFFLINK) || iface->metric)
506                                 interface_handle_subnet_route(iface, a_new, true);
507                 }
508         }
509 }
510
511 static bool
512 enable_route(struct interface_ip_settings *ip, struct device_route *route)
513 {
514         if (ip->no_defaultroute && !route->mask)
515                 return false;
516
517         return ip->enabled;
518 }
519
520 static void
521 interface_update_proto_route(struct vlist_tree *tree,
522                              struct vlist_node *node_new,
523                              struct vlist_node *node_old)
524 {
525         struct interface_ip_settings *ip;
526         struct interface *iface;
527         struct device *dev;
528         struct device_route *route_old, *route_new;
529         bool keep = false;
530
531         ip = container_of(tree, struct interface_ip_settings, route);
532         iface = ip->iface;
533         dev = iface->l3_dev.dev;
534
535         route_old = container_of(node_old, struct device_route, node);
536         route_new = container_of(node_new, struct device_route, node);
537
538         if (node_old && node_new)
539                 keep = !memcmp(&route_old->nexthop, &route_new->nexthop, sizeof(route_old->nexthop));
540
541         if (node_old) {
542                 if (!(route_old->flags & DEVADDR_EXTERNAL) && route_old->enabled && !keep)
543                         system_del_route(dev, route_old);
544                 free(route_old);
545         }
546
547         if (node_new) {
548                 bool _enabled = enable_route(ip, route_new);
549
550                 if (!(route_new->flags & DEVROUTE_METRIC))
551                         route_new->metric = iface->metric;
552
553                 if (!(route_new->flags & DEVADDR_EXTERNAL) && !keep && _enabled)
554                         system_add_route(dev, route_new);
555
556                 route_new->iface = iface;
557                 route_new->enabled = _enabled;
558         }
559 }
560
561 static void
562 interface_update_host_route(struct vlist_tree *tree,
563                              struct vlist_node *node_new,
564                              struct vlist_node *node_old)
565 {
566         struct interface *iface;
567         struct device *dev;
568         struct device_route *route_old, *route_new;
569
570         iface = container_of(tree, struct interface, host_routes);
571         dev = iface->l3_dev.dev;
572
573         route_old = container_of(node_old, struct device_route, node);
574         route_new = container_of(node_new, struct device_route, node);
575
576         if (node_old) {
577                 system_del_route(dev, route_old);
578                 free(route_old);
579         }
580
581         if (node_new)
582                 system_add_route(dev, route_new);
583 }
584
585
586 static void
587 interface_set_prefix_address(struct device_prefix_assignment *assignment,
588                 const struct device_prefix *prefix, struct interface *iface, bool add)
589 {
590         const struct interface *uplink = prefix->iface;
591         if (!iface->l3_dev.dev)
592                 return;
593
594         struct device *l3_downlink = iface->l3_dev.dev;
595
596         struct device_addr addr;
597         memset(&addr, 0, sizeof(addr));
598         addr.addr.in6 = prefix->addr;
599         addr.addr.in6.s6_addr32[1] |= htonl(assignment->assigned);
600         addr.addr.in6.s6_addr[15] += 1;
601         addr.mask = assignment->length;
602         addr.flags = DEVADDR_INET6;
603         addr.preferred_until = prefix->preferred_until;
604         addr.valid_until = prefix->valid_until;
605
606         if (!add && assignment->enabled) {
607                 time_t now = system_get_rtime();
608                 addr.preferred_until = now;
609                 if (!addr.valid_until || addr.valid_until - now > 7200)
610                         addr.valid_until = now + 7200;
611                 system_add_address(l3_downlink, &addr);
612                 if (prefix->iface) {
613                         set_ip_source_policy(false, true, IPRULE_PRIORITY_NW, &addr.addr,
614                                                         addr.mask, prefix->iface, iface, NULL);
615
616                         set_ip_source_policy(false, true, IPRULE_PRIORITY_REJECT, &addr.addr,
617                                                         addr.mask, NULL, iface, "unreachable");
618                 }
619
620                 assignment->enabled = false;
621         } else if (add && (iface->state == IFS_UP || iface->state == IFS_SETUP)) {
622                 system_add_address(l3_downlink, &addr);
623                 if (prefix->iface && !assignment->enabled) {
624                         set_ip_source_policy(true, true, IPRULE_PRIORITY_REJECT, &addr.addr,
625                                         addr.mask, NULL, iface, "unreachable");
626
627                         set_ip_source_policy(true, true, IPRULE_PRIORITY_NW, &addr.addr,
628                                         addr.mask, prefix->iface, iface, NULL);
629                 }
630                 if (uplink && uplink->l3_dev.dev) {
631                         int mtu = system_update_ipv6_mtu(
632                                         uplink->l3_dev.dev, 0);
633                         if (mtu > 0)
634                                 system_update_ipv6_mtu(l3_downlink, mtu);
635                 }
636                 assignment->enabled = true;
637         }
638 }
639
640 static bool interface_prefix_assign(struct list_head *list,
641                 struct device_prefix_assignment *assign)
642 {
643         int32_t current = 0, asize = (1 << (64 - assign->length)) - 1;
644         struct device_prefix_assignment *c;
645         list_for_each_entry(c, list, head) {
646                 if (assign->assigned != -1) {
647                         if (assign->assigned >= current && assign->assigned + asize < c->assigned) {
648                                 list_add_tail(&assign->head, &c->head);
649                                 return true;
650                         }
651                 } else if (assign->assigned == -1) {
652                         current = (current + asize) & (~asize);
653                         if (current + asize < c->assigned) {
654                                 assign->assigned = current;
655                                 list_add_tail(&assign->head, &c->head);
656                                 return true;
657                         }
658                 }
659                 current = (c->assigned + (1 << (64 - c->length)));
660         }
661         return false;
662 }
663
664 static void interface_update_prefix_assignments(struct device_prefix *prefix, bool setup)
665 {
666         struct device_prefix_assignment *c;
667         struct interface *iface;
668
669         // Delete all assignments
670         while (!list_empty(&prefix->assignments)) {
671                 c = list_first_entry(&prefix->assignments,
672                                 struct device_prefix_assignment, head);
673                 if ((iface = vlist_find(&interfaces, c->name, iface, node)))
674                         interface_set_prefix_address(c, prefix, iface, false);
675                 list_del(&c->head);
676                 free(c);
677         }
678
679         if (!setup)
680                 return;
681
682         // End-of-assignment sentinel
683         c = malloc(sizeof(*c) + 1);
684         c->assigned = 1 << (64 - prefix->length);
685         c->length = 64;
686         c->name[0] = 0;
687         list_add(&c->head, &prefix->assignments);
688
689         // Excluded prefix
690         if (prefix->excl_length > 0) {
691                 const char name[] = "!excluded";
692                 c = malloc(sizeof(*c) + sizeof(name));
693                 c->assigned = ntohl(prefix->excl_addr.s6_addr32[1]) &
694                                 ((1 << (64 - prefix->length)) - 1);
695                 c->length = prefix->excl_length;
696                 memcpy(c->name, name, sizeof(name));
697                 list_add(&c->head, &prefix->assignments);
698         }
699
700         bool assigned_any = false;
701         struct list_head assign_later = LIST_HEAD_INIT(assign_later);
702         vlist_for_each_element(&interfaces, iface, node) {
703                 if (iface->assignment_length < 48 ||
704                                 iface->assignment_length > 64)
705                         continue;
706
707                 // Test whether there is a matching class
708                 if (!list_empty(&iface->assignment_classes)) {
709                         bool found = false;
710
711                         struct interface_assignment_class *c;
712                         list_for_each_entry(c, &iface->assignment_classes, head) {
713                                 if (!strcmp(c->name, prefix->pclass)) {
714                                         found = true;
715                                         break;
716                                 }
717                         }
718
719                         if (!found)
720                                 continue;
721                 }
722
723                 size_t namelen = strlen(iface->name) + 1;
724                 c = malloc(sizeof(*c) + namelen);
725                 c->length = iface->assignment_length;
726                 c->assigned = iface->assignment_hint;
727                 c->enabled = false;
728                 memcpy(c->name, iface->name, namelen);
729
730                 // First process all custom assignments, put all others in later-list
731                 if (c->assigned == -1 || !interface_prefix_assign(&prefix->assignments, c)) {
732                         if (c->assigned != -1) {
733                                 c->assigned = -1;
734                                 netifd_log_message(L_WARNING, "Failed to assign requested subprefix "
735                                                 "of size %hhu for %s, trying other\n", c->length, c->name);
736                         }
737
738                         struct list_head *next = &assign_later;
739                         struct device_prefix_assignment *n;
740                         list_for_each_entry(n, &assign_later, head) {
741                                 if (n->length < c->length) {
742                                         next = &n->head;
743                                         break;
744                                 }
745                         }
746                         list_add_tail(&c->head, next);
747                 }
748
749                 if (c->assigned != -1)
750                         assigned_any = true;
751         }
752
753         // Then try to assign all other + failed custom assignments
754         while (!list_empty(&assign_later)) {
755                 c = list_first_entry(&assign_later, struct device_prefix_assignment, head);
756                 list_del(&c->head);
757
758                 bool assigned = false;
759                 do {
760                         assigned = interface_prefix_assign(&prefix->assignments, c);
761                 } while (!assigned && ++c->length <= 64);
762
763                 if (!assigned) {
764                         netifd_log_message(L_WARNING, "Failed to assign subprefix "
765                                         "of size %hhu for %s\n", c->length, c->name);
766                         free(c);
767                 } else {
768                         assigned_any = true;
769                 }
770         }
771
772         list_for_each_entry(c, &prefix->assignments, head)
773                 if ((iface = vlist_find(&interfaces, c->name, iface, node)))
774                         interface_set_prefix_address(c, prefix, iface, true);
775
776         if (!assigned_any)
777                 netifd_log_message(L_WARNING, "You have delegated IPv6-prefixes but haven't assigned them "
778                                 "to any interface. Did you forget to set option ip6assign on your lan-interfaces?");
779 }
780
781
782 void interface_refresh_assignments(bool hint)
783 {
784         static bool refresh = false;
785         if (!hint && refresh) {
786                 struct device_prefix *p;
787                 list_for_each_entry(p, &prefixes, head)
788                         interface_update_prefix_assignments(p, true);
789         }
790         refresh = hint;
791 }
792
793
794 static void
795 interface_update_prefix(struct vlist_tree *tree,
796                              struct vlist_node *node_new,
797                              struct vlist_node *node_old)
798 {
799         struct device_prefix *prefix_old, *prefix_new;
800         prefix_old = container_of(node_old, struct device_prefix, node);
801         prefix_new = container_of(node_new, struct device_prefix, node);
802
803         struct device_route route;
804         memset(&route, 0, sizeof(route));
805         route.flags = DEVADDR_INET6;
806         route.metric = INT32_MAX;
807         route.mask = (node_new) ? prefix_new->length : prefix_old->length;
808         route.addr.in6 = (node_new) ? prefix_new->addr : prefix_old->addr;
809
810
811         struct device_prefix_assignment *c;
812         struct interface *iface;
813
814         if (node_old && node_new) {
815                 // Move assignments and refresh addresses to update valid times
816                 list_splice(&prefix_old->assignments, &prefix_new->assignments);
817
818                 list_for_each_entry(c, &prefix_new->assignments, head)
819                         if ((iface = vlist_find(&interfaces, c->name, iface, node)))
820                                 interface_set_prefix_address(c, prefix_new, iface, true);
821         } else if (node_new) {
822                 // Set null-route to avoid routing loops
823                 system_add_route(NULL, &route);
824                 interface_update_prefix_assignments(prefix_new, true);
825         } else if (node_old) {
826                 // Remove null-route
827                 interface_update_prefix_assignments(prefix_old, false);
828                 system_del_route(NULL, &route);
829         }
830
831         if (node_old) {
832                 list_del(&prefix_old->head);
833                 free(prefix_old);
834         }
835
836         if (node_new)
837                 list_add(&prefix_new->head, &prefixes);
838
839 }
840
841 struct device_prefix*
842 interface_ip_add_device_prefix(struct interface *iface, struct in6_addr *addr,
843                 uint8_t length, time_t valid_until, time_t preferred_until,
844                 struct in6_addr *excl_addr, uint8_t excl_length, const char *pclass)
845 {
846         if (!pclass)
847                 pclass = (iface) ? iface->name : "local";
848
849         struct device_prefix *prefix = calloc(1, sizeof(*prefix) + strlen(pclass) + 1);
850         prefix->length = length;
851         prefix->addr = *addr;
852         prefix->preferred_until = preferred_until;
853         prefix->valid_until = valid_until;
854         prefix->iface = iface;
855         INIT_LIST_HEAD(&prefix->assignments);
856
857         if (excl_addr) {
858                 prefix->excl_addr = *excl_addr;
859                 prefix->excl_length = excl_length;
860         }
861
862         strcpy(prefix->pclass, pclass);
863
864         if (iface)
865                 vlist_add(&iface->proto_ip.prefix, &prefix->node, &prefix->addr);
866         else
867                 interface_update_prefix(NULL, &prefix->node, NULL);
868
869         return prefix;
870 }
871
872 void
873 interface_ip_set_ula_prefix(const char *prefix)
874 {
875         char buf[INET6_ADDRSTRLEN + 4] = {0}, *saveptr;
876         if (prefix)
877                 strncpy(buf, prefix, sizeof(buf) - 1);
878         char *prefixaddr = strtok_r(buf, "/", &saveptr);
879
880         struct in6_addr addr;
881         if (!prefixaddr || inet_pton(AF_INET6, prefixaddr, &addr) < 1) {
882                 if (ula_prefix) {
883                         interface_update_prefix(NULL, NULL, &ula_prefix->node);
884                         ula_prefix = NULL;
885                 }
886                 return;
887         }
888
889         int length;
890         char *prefixlen = strtok_r(NULL, ",", &saveptr);
891         if (!prefixlen || (length = atoi(prefixlen)) < 1 || length > 64)
892                 return;
893
894         if (!ula_prefix || !IN6_ARE_ADDR_EQUAL(&addr, &ula_prefix->addr) ||
895                         ula_prefix->length != length) {
896                 if (ula_prefix)
897                         interface_update_prefix(NULL, NULL, &ula_prefix->node);
898
899                 ula_prefix = interface_ip_add_device_prefix(NULL, &addr, length,
900                                 0, 0, NULL, 0, NULL);
901         }
902 }
903
904 void
905 interface_add_dns_server(struct interface_ip_settings *ip, const char *str)
906 {
907         struct dns_server *s;
908
909         s = calloc(1, sizeof(*s));
910         if (!s)
911                 return;
912
913         s->af = AF_INET;
914         if (inet_pton(s->af, str, &s->addr.in))
915                 goto add;
916
917         s->af = AF_INET6;
918         if (inet_pton(s->af, str, &s->addr.in))
919                 goto add;
920
921         free(s);
922         return;
923
924 add:
925         D(INTERFACE, "Add IPv%c DNS server: %s\n",
926           s->af == AF_INET6 ? '6' : '4', str);
927         vlist_simple_add(&ip->dns_servers, &s->node);
928 }
929
930 void
931 interface_add_dns_server_list(struct interface_ip_settings *ip, struct blob_attr *list)
932 {
933         struct blob_attr *cur;
934         int rem;
935
936         blobmsg_for_each_attr(cur, list, rem) {
937                 if (blobmsg_type(cur) != BLOBMSG_TYPE_STRING)
938                         continue;
939
940                 if (!blobmsg_check_attr(cur, NULL))
941                         continue;
942
943                 interface_add_dns_server(ip, blobmsg_data(cur));
944         }
945 }
946
947 static void
948 interface_add_dns_search_domain(struct interface_ip_settings *ip, const char *str)
949 {
950         struct dns_search_domain *s;
951         int len = strlen(str);
952
953         s = calloc(1, sizeof(*s) + len + 1);
954         if (!s)
955                 return;
956
957         D(INTERFACE, "Add DNS search domain: %s\n", str);
958         memcpy(s->name, str, len);
959         vlist_simple_add(&ip->dns_search, &s->node);
960 }
961
962 void
963 interface_add_dns_search_list(struct interface_ip_settings *ip, struct blob_attr *list)
964 {
965         struct blob_attr *cur;
966         int rem;
967
968         blobmsg_for_each_attr(cur, list, rem) {
969                 if (blobmsg_type(cur) != BLOBMSG_TYPE_STRING)
970                         continue;
971
972                 if (!blobmsg_check_attr(cur, NULL))
973                         continue;
974
975                 interface_add_dns_search_domain(ip, blobmsg_data(cur));
976         }
977 }
978
979 static void
980 write_resolv_conf_entries(FILE *f, struct interface_ip_settings *ip)
981 {
982         struct dns_server *s;
983         struct dns_search_domain *d;
984         const char *str;
985         char buf[INET6_ADDRSTRLEN];
986
987         vlist_simple_for_each_element(&ip->dns_servers, s, node) {
988                 str = inet_ntop(s->af, &s->addr, buf, sizeof(buf));
989                 if (!str)
990                         continue;
991
992                 fprintf(f, "nameserver %s\n", str);
993         }
994
995         vlist_simple_for_each_element(&ip->dns_search, d, node) {
996                 fprintf(f, "search %s\n", d->name);
997         }
998 }
999
1000 void
1001 interface_write_resolv_conf(void)
1002 {
1003         struct interface *iface;
1004         char *path = alloca(strlen(resolv_conf) + 5);
1005         FILE *f;
1006         uint32_t crcold, crcnew;
1007
1008         sprintf(path, "%s.tmp", resolv_conf);
1009         unlink(path);
1010         f = fopen(path, "w+");
1011         if (!f) {
1012                 D(INTERFACE, "Failed to open %s for writing\n", path);
1013                 return;
1014         }
1015
1016         vlist_for_each_element(&interfaces, iface, node) {
1017                 if (iface->state != IFS_UP)
1018                         continue;
1019
1020                 if (vlist_simple_empty(&iface->proto_ip.dns_search) &&
1021                     vlist_simple_empty(&iface->proto_ip.dns_servers) &&
1022                         vlist_simple_empty(&iface->config_ip.dns_search) &&
1023                     vlist_simple_empty(&iface->config_ip.dns_servers))
1024                         continue;
1025
1026                 fprintf(f, "# Interface %s\n", iface->name);
1027                 write_resolv_conf_entries(f, &iface->config_ip);
1028                 if (!iface->proto_ip.no_dns)
1029                         write_resolv_conf_entries(f, &iface->proto_ip);
1030         }
1031         fflush(f);
1032         rewind(f);
1033         crcnew = crc32_file(f);
1034         fclose(f);
1035
1036         crcold = crcnew + 1;
1037         f = fopen(resolv_conf, "r");
1038         if (f) {
1039                 crcold = crc32_file(f);
1040                 fclose(f);
1041         }
1042
1043         if (crcold == crcnew) {
1044                 unlink(path);
1045         } else if (rename(path, resolv_conf) < 0) {
1046                 D(INTERFACE, "Failed to replace %s\n", resolv_conf);
1047                 unlink(path);
1048         }
1049 }
1050
1051 void interface_ip_set_enabled(struct interface_ip_settings *ip, bool enabled)
1052 {
1053         struct device_addr *addr;
1054         struct device_route *route;
1055         struct device *dev;
1056
1057         ip->enabled = enabled;
1058         dev = ip->iface->l3_dev.dev;
1059         if (!dev)
1060                 return;
1061
1062         vlist_for_each_element(&ip->addr, addr, node) {
1063                 if (addr->enabled == enabled)
1064                         continue;
1065
1066                 if (enabled)
1067                         system_add_address(dev, addr);
1068                 else
1069                         system_del_address(dev, addr);
1070                 addr->enabled = enabled;
1071         }
1072
1073         vlist_for_each_element(&ip->route, route, node) {
1074                 bool _enabled = enabled;
1075
1076                 if (!enable_route(ip, route))
1077                         _enabled = false;
1078
1079                 if (route->enabled == _enabled)
1080                         continue;
1081
1082                 if (_enabled) {
1083                         if (!(route->flags & DEVROUTE_METRIC))
1084                                 route->metric = ip->iface->metric;
1085
1086                         system_add_route(dev, route);
1087                 } else
1088                         system_del_route(dev, route);
1089                 route->enabled = _enabled;
1090         }
1091
1092         struct device_prefix *c;
1093         struct device_prefix_assignment *a;
1094         list_for_each_entry(c, &prefixes, head)
1095                 list_for_each_entry(a, &c->assignments, head)
1096                         if (!strcmp(a->name, ip->iface->name))
1097                                 interface_set_prefix_address(a, c, ip->iface, enabled);
1098
1099         if (ip->iface && ip->iface->l3_dev.dev) {
1100                 set_ip_lo_policy(enabled, true, ip->iface);
1101                 set_ip_lo_policy(enabled, false, ip->iface);
1102
1103                 set_ip_source_policy(enabled, true, IPRULE_PRIORITY_REJECT + ip->iface->l3_dev.dev->ifindex,
1104                         NULL, 0, NULL, ip->iface, "failed_policy");
1105         }
1106 }
1107
1108 void
1109 interface_ip_update_start(struct interface_ip_settings *ip)
1110 {
1111         if (ip != &ip->iface->config_ip) {
1112                 vlist_simple_update(&ip->dns_servers);
1113                 vlist_simple_update(&ip->dns_search);
1114         }
1115         vlist_update(&ip->route);
1116         vlist_update(&ip->addr);
1117         vlist_update(&ip->prefix);
1118 }
1119
1120 void
1121 interface_ip_update_complete(struct interface_ip_settings *ip)
1122 {
1123         vlist_simple_flush(&ip->dns_servers);
1124         vlist_simple_flush(&ip->dns_search);
1125         vlist_flush(&ip->route);
1126         vlist_flush(&ip->addr);
1127         vlist_flush(&ip->prefix);
1128         interface_write_resolv_conf();
1129 }
1130
1131 void
1132 interface_ip_flush(struct interface_ip_settings *ip)
1133 {
1134         if (ip == &ip->iface->proto_ip)
1135                 vlist_flush_all(&ip->iface->host_routes);
1136         vlist_simple_flush_all(&ip->dns_servers);
1137         vlist_simple_flush_all(&ip->dns_search);
1138         vlist_flush_all(&ip->route);
1139         vlist_flush_all(&ip->addr);
1140         vlist_flush_all(&ip->prefix);
1141 }
1142
1143 static void
1144 __interface_ip_init(struct interface_ip_settings *ip, struct interface *iface)
1145 {
1146         ip->iface = iface;
1147         ip->enabled = true;
1148         vlist_simple_init(&ip->dns_search, struct dns_search_domain, node);
1149         vlist_simple_init(&ip->dns_servers, struct dns_server, node);
1150         vlist_init(&ip->route, route_cmp, interface_update_proto_route);
1151         vlist_init(&ip->addr, addr_cmp, interface_update_proto_addr);
1152         vlist_init(&ip->prefix, prefix_cmp, interface_update_prefix);
1153 }
1154
1155 void
1156 interface_ip_init(struct interface *iface)
1157 {
1158         __interface_ip_init(&iface->proto_ip, iface);
1159         __interface_ip_init(&iface->config_ip, iface);
1160         vlist_init(&iface->host_routes, route_cmp, interface_update_host_route);
1161
1162 }
1163
1164 static void
1165 interface_ip_valid_until_handler(struct uloop_timeout *t)
1166 {
1167         time_t now = system_get_rtime();
1168         struct interface *iface;
1169         vlist_for_each_element(&interfaces, iface, node) {
1170                 if (iface->state != IFS_UP)
1171                         continue;
1172
1173                 struct device_addr *addr, *addrp;
1174                 struct device_route *route, *routep;
1175                 struct device_prefix *pref, *prefp;
1176
1177                 vlist_for_each_element_safe(&iface->proto_ip.addr, addr, node, addrp)
1178                         if (addr->valid_until && addr->valid_until < now)
1179                                 vlist_delete(&iface->proto_ip.addr, &addr->node);
1180
1181                 vlist_for_each_element_safe(&iface->proto_ip.route, route, node, routep)
1182                         if (route->valid_until && route->valid_until < now)
1183                                 vlist_delete(&iface->proto_ip.route, &route->node);
1184
1185                 vlist_for_each_element_safe(&iface->proto_ip.prefix, pref, node, prefp)
1186                         if (pref->valid_until && pref->valid_until < now)
1187                                 vlist_delete(&iface->proto_ip.prefix, &pref->node);
1188
1189         }
1190
1191         uloop_timeout_set(t, 1000);
1192 }
1193
1194 static void __init
1195 interface_ip_init_worker(void)
1196 {
1197         valid_until_timeout.cb = interface_ip_valid_until_handler;
1198         uloop_timeout_set(&valid_until_timeout, 1000);
1199 }