IPv6: Reverse assignment sorting order
[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 keep = false;
430         bool v6 = false;
431
432         ip = container_of(tree, struct interface_ip_settings, addr);
433         iface = ip->iface;
434         dev = iface->l3_dev.dev;
435
436         if (node_new) {
437                 a_new = container_of(node_new, struct device_addr, node);
438
439                 if ((a_new->flags & DEVADDR_FAMILY) == DEVADDR_INET4 &&
440                     !a_new->broadcast) {
441
442                         uint32_t mask = ~0;
443                         uint32_t *a = (uint32_t *) &a_new->addr;
444
445                         mask >>= a_new->mask;
446                         a_new->broadcast = *a | htonl(mask);
447                 }
448         }
449
450         if (node_old)
451                 a_old = container_of(node_old, struct device_addr, node);
452
453         if (a_new && a_old) {
454                 keep = true;
455
456                 if (a_old->flags != a_new->flags ||
457                                 a_old->valid_until != a_new->valid_until ||
458                                 a_old->preferred_until != a_new->preferred_until)
459                         keep = false;
460
461                 if ((a_new->flags & DEVADDR_FAMILY) == DEVADDR_INET4 &&
462                     a_new->broadcast != a_old->broadcast)
463                         keep = false;
464         }
465
466         if (node_old) {
467                 if (!(a_old->flags & DEVADDR_EXTERNAL) && a_old->enabled && !keep) {
468                         interface_handle_subnet_route(iface, a_old, false);
469
470                         if ((a_old->flags & DEVADDR_FAMILY) == DEVADDR_INET6)
471                                 v6 = true;
472
473                         //This is needed for source routing to work correctly. If a device
474                         //has two connections to a network using the same subnet, adding
475                         //only the network-rule will cause packets to be routed through the
476                         //first matching network (source IP matches both masks).
477                         set_ip_source_policy(false, v6, IPRULE_PRIORITY_ADDR, &a_old->addr,
478                                 (v6) ? 128 : 32, iface, NULL, NULL);
479                         set_ip_source_policy(false, v6, IPRULE_PRIORITY_NW, &a_old->addr,
480                                 a_old->mask, iface, NULL, NULL);
481
482                         system_del_address(dev, a_old);
483                 }
484                 free(a_old);
485         }
486
487         if (node_new) {
488                 a_new->enabled = true;
489                 if (!(a_new->flags & DEVADDR_EXTERNAL) && !keep) {
490                         system_add_address(dev, a_new);
491
492                         if ((a_new->flags & DEVADDR_FAMILY) == DEVADDR_INET6)
493                                 v6 = true;
494
495                         set_ip_source_policy(true, v6, IPRULE_PRIORITY_ADDR, &a_new->addr,
496                                 (v6) ? 128 : 32, iface, NULL, NULL);
497                         set_ip_source_policy(true, v6, IPRULE_PRIORITY_NW, &a_new->addr,
498                                 a_new->mask, iface, NULL, NULL);
499
500                         if ((a_new->flags & DEVADDR_OFFLINK) || iface->metric)
501                                 interface_handle_subnet_route(iface, a_new, true);
502                 }
503         }
504 }
505
506 static bool
507 enable_route(struct interface_ip_settings *ip, struct device_route *route)
508 {
509         if (ip->no_defaultroute && !route->mask)
510                 return false;
511
512         return ip->enabled;
513 }
514
515 static void
516 interface_update_proto_route(struct vlist_tree *tree,
517                              struct vlist_node *node_new,
518                              struct vlist_node *node_old)
519 {
520         struct interface_ip_settings *ip;
521         struct interface *iface;
522         struct device *dev;
523         struct device_route *route_old, *route_new;
524         bool keep = false;
525
526         ip = container_of(tree, struct interface_ip_settings, route);
527         iface = ip->iface;
528         dev = iface->l3_dev.dev;
529
530         route_old = container_of(node_old, struct device_route, node);
531         route_new = container_of(node_new, struct device_route, node);
532
533         if (node_old && node_new)
534                 keep = !memcmp(&route_old->nexthop, &route_new->nexthop, sizeof(route_old->nexthop));
535
536         if (node_old) {
537                 if (!(route_old->flags & DEVADDR_EXTERNAL) && route_old->enabled && !keep)
538                         system_del_route(dev, route_old);
539                 free(route_old);
540         }
541
542         if (node_new) {
543                 bool _enabled = enable_route(ip, route_new);
544
545                 if (!(route_new->flags & DEVROUTE_METRIC))
546                         route_new->metric = iface->metric;
547
548                 if (!(route_new->flags & DEVADDR_EXTERNAL) && !keep && _enabled)
549                         system_add_route(dev, route_new);
550
551                 route_new->iface = iface;
552                 route_new->enabled = _enabled;
553         }
554 }
555
556 static void
557 interface_update_host_route(struct vlist_tree *tree,
558                              struct vlist_node *node_new,
559                              struct vlist_node *node_old)
560 {
561         struct interface *iface;
562         struct device *dev;
563         struct device_route *route_old, *route_new;
564
565         iface = container_of(tree, struct interface, host_routes);
566         dev = iface->l3_dev.dev;
567
568         route_old = container_of(node_old, struct device_route, node);
569         route_new = container_of(node_new, struct device_route, node);
570
571         if (node_old) {
572                 system_del_route(dev, route_old);
573                 free(route_old);
574         }
575
576         if (node_new)
577                 system_add_route(dev, route_new);
578 }
579
580
581 static void
582 interface_set_prefix_address(struct device_prefix_assignment *assignment,
583                 const struct device_prefix *prefix, struct interface *iface, bool add)
584 {
585         const struct interface *uplink = prefix->iface;
586         if (!iface->l3_dev.dev)
587                 return;
588
589         struct device *l3_downlink = iface->l3_dev.dev;
590
591         struct device_addr addr;
592         memset(&addr, 0, sizeof(addr));
593         addr.addr.in6 = prefix->addr;
594         addr.addr.in6.s6_addr32[1] |= htonl(assignment->assigned);
595         addr.addr.in6.s6_addr[15] += 1;
596         addr.mask = assignment->length;
597         addr.flags = DEVADDR_INET6;
598         addr.preferred_until = prefix->preferred_until;
599         addr.valid_until = prefix->valid_until;
600
601         if (!add && assignment->enabled) {
602                 time_t now = system_get_rtime();
603                 addr.preferred_until = now;
604                 if (!addr.valid_until || addr.valid_until - now > 7200)
605                         addr.valid_until = now + 7200;
606                 system_add_address(l3_downlink, &addr);
607                 if (prefix->iface) {
608                         set_ip_source_policy(false, true, IPRULE_PRIORITY_NW, &addr.addr,
609                                                         addr.mask, prefix->iface, iface, NULL);
610
611                         set_ip_source_policy(false, true, IPRULE_PRIORITY_REJECT, &addr.addr,
612                                                         addr.mask, NULL, iface, "unreachable");
613                 }
614
615                 assignment->enabled = false;
616         } else if (add && (iface->state == IFS_UP || iface->state == IFS_SETUP)) {
617                 system_add_address(l3_downlink, &addr);
618                 if (prefix->iface && !assignment->enabled) {
619                         set_ip_source_policy(true, true, IPRULE_PRIORITY_REJECT, &addr.addr,
620                                         addr.mask, NULL, iface, "unreachable");
621
622                         set_ip_source_policy(true, true, IPRULE_PRIORITY_NW, &addr.addr,
623                                         addr.mask, prefix->iface, iface, NULL);
624                 }
625                 if (uplink && uplink->l3_dev.dev) {
626                         int mtu = system_update_ipv6_mtu(
627                                         uplink->l3_dev.dev, 0);
628                         if (mtu > 0)
629                                 system_update_ipv6_mtu(l3_downlink, mtu);
630                 }
631                 assignment->enabled = true;
632         }
633 }
634
635 static bool interface_prefix_assign(struct list_head *list,
636                 struct device_prefix_assignment *assign)
637 {
638         int32_t current = 0, asize = (1 << (64 - assign->length)) - 1;
639         struct device_prefix_assignment *c;
640         list_for_each_entry(c, list, head) {
641                 if (assign->assigned != -1) {
642                         if (assign->assigned > current && assign->assigned + asize < c->assigned) {
643                                 list_add_tail(&assign->head, &c->head);
644                                 return true;
645                         }
646                 } else if (assign->assigned == -1) {
647                         current = (current + asize) & (~asize);
648                         if (current + asize < c->assigned) {
649                                 assign->assigned = current;
650                                 list_add_tail(&assign->head, &c->head);
651                                 return true;
652                         }
653                 }
654                 current = (c->assigned + (1 << (64 - c->length)));
655         }
656         return false;
657 }
658
659 static void interface_update_prefix_assignments(struct device_prefix *prefix, bool setup)
660 {
661         struct device_prefix_assignment *c;
662         struct interface *iface;
663
664         // Delete all assignments
665         while (!list_empty(&prefix->assignments)) {
666                 c = list_first_entry(&prefix->assignments,
667                                 struct device_prefix_assignment, head);
668                 if ((iface = vlist_find(&interfaces, c->name, iface, node)))
669                         interface_set_prefix_address(c, prefix, iface, false);
670                 list_del(&c->head);
671                 free(c);
672         }
673
674         if (!setup)
675                 return;
676
677         // End-of-assignment sentinel
678         c = malloc(sizeof(*c) + 1);
679         c->assigned = 1 << (64 - prefix->length);
680         c->length = 64;
681         c->name[0] = 0;
682         list_add(&c->head, &prefix->assignments);
683
684         // Excluded prefix
685         if (prefix->excl_length > 0) {
686                 const char name[] = "!excluded";
687                 c = malloc(sizeof(*c) + sizeof(name));
688                 c->assigned = ntohl(prefix->excl_addr.s6_addr32[1]) &
689                                 ((1 << (64 - prefix->length)) - 1);
690                 c->length = prefix->excl_length;
691                 memcpy(c->name, name, sizeof(name));
692                 list_add(&c->head, &prefix->assignments);
693         }
694
695         bool assigned_any = false;
696         struct list_head assign_later = LIST_HEAD_INIT(assign_later);
697         vlist_for_each_element(&interfaces, iface, node) {
698                 if (iface->assignment_length < 48 ||
699                                 iface->assignment_length > 64)
700                         continue;
701
702                 // Test whether there is a matching class
703                 if (!list_empty(&iface->assignment_classes)) {
704                         bool found = false;
705
706                         struct interface_assignment_class *c;
707                         list_for_each_entry(c, &iface->assignment_classes, head) {
708                                 if (!strcmp(c->name, prefix->pclass)) {
709                                         found = true;
710                                         break;
711                                 }
712                         }
713
714                         if (!found)
715                                 continue;
716                 }
717
718                 size_t namelen = strlen(iface->name) + 1;
719                 c = malloc(sizeof(*c) + namelen);
720                 c->length = iface->assignment_length;
721                 c->assigned = iface->assignment_hint;
722                 c->enabled = false;
723                 memcpy(c->name, iface->name, namelen);
724
725                 // First process all custom assignments, put all others in later-list
726                 if (c->assigned == -1 || !interface_prefix_assign(&prefix->assignments, c)) {
727                         if (c->assigned != -1) {
728                                 c->assigned = -1;
729                                 netifd_log_message(L_WARNING, "Failed to assign requested subprefix "
730                                                 "of size %hhu for %s, trying other\n", c->length, c->name);
731                         }
732
733                         struct list_head *next = &assign_later;
734                         struct device_prefix_assignment *n;
735                         list_for_each_entry(n, &assign_later, head) {
736                                 if (n->length < c->length) {
737                                         next = &n->head;
738                                         break;
739                                 }
740                         }
741                         list_add_tail(&c->head, next);
742                 }
743
744                 if (c->assigned != -1)
745                         assigned_any = true;
746         }
747
748         // Then try to assign all other + failed custom assignments
749         while (!list_empty(&assign_later)) {
750                 c = list_first_entry(&assign_later, struct device_prefix_assignment, head);
751                 list_del(&c->head);
752
753                 bool assigned = false;
754                 do {
755                         assigned = interface_prefix_assign(&prefix->assignments, c);
756                 } while (!assigned && ++c->length <= 64);
757
758                 if (!assigned) {
759                         netifd_log_message(L_WARNING, "Failed to assign subprefix "
760                                         "of size %hhu for %s\n", c->length, c->name);
761                         free(c);
762                 } else {
763                         assigned_any = true;
764                 }
765         }
766
767         list_for_each_entry(c, &prefix->assignments, head)
768                 if ((iface = vlist_find(&interfaces, c->name, iface, node)))
769                         interface_set_prefix_address(c, prefix, iface, true);
770
771         if (!assigned_any)
772                 netifd_log_message(L_WARNING, "You have delegated IPv6-prefixes but haven't assigned them "
773                                 "to any interface. Did you forget to set option ip6assign on your lan-interfaces?");
774 }
775
776
777 void interface_refresh_assignments(bool hint)
778 {
779         static bool refresh = false;
780         if (!hint && refresh) {
781                 struct device_prefix *p;
782                 list_for_each_entry(p, &prefixes, head)
783                         interface_update_prefix_assignments(p, true);
784         }
785         refresh = hint;
786 }
787
788
789 static void
790 interface_update_prefix(struct vlist_tree *tree,
791                              struct vlist_node *node_new,
792                              struct vlist_node *node_old)
793 {
794         struct device_prefix *prefix_old, *prefix_new;
795         prefix_old = container_of(node_old, struct device_prefix, node);
796         prefix_new = container_of(node_new, struct device_prefix, node);
797
798         struct device_route route;
799         memset(&route, 0, sizeof(route));
800         route.flags = DEVADDR_INET6;
801         route.metric = INT32_MAX;
802         route.mask = (node_new) ? prefix_new->length : prefix_old->length;
803         route.addr.in6 = (node_new) ? prefix_new->addr : prefix_old->addr;
804
805
806         struct device_prefix_assignment *c;
807         struct interface *iface;
808
809         if (node_old && node_new) {
810                 // Move assignments and refresh addresses to update valid times
811                 list_splice(&prefix_old->assignments, &prefix_new->assignments);
812
813                 list_for_each_entry(c, &prefix_new->assignments, head)
814                         if ((iface = vlist_find(&interfaces, c->name, iface, node)))
815                                 interface_set_prefix_address(c, prefix_new, iface, true);
816         } else if (node_new) {
817                 // Set null-route to avoid routing loops
818                 system_add_route(NULL, &route);
819                 interface_update_prefix_assignments(prefix_new, true);
820         } else if (node_old) {
821                 // Remove null-route
822                 interface_update_prefix_assignments(prefix_old, false);
823                 system_del_route(NULL, &route);
824         }
825
826         if (node_old) {
827                 list_del(&prefix_old->head);
828                 free(prefix_old);
829         }
830
831         if (node_new)
832                 list_add(&prefix_new->head, &prefixes);
833
834 }
835
836 struct device_prefix*
837 interface_ip_add_device_prefix(struct interface *iface, struct in6_addr *addr,
838                 uint8_t length, time_t valid_until, time_t preferred_until,
839                 struct in6_addr *excl_addr, uint8_t excl_length, const char *pclass)
840 {
841         if (!pclass)
842                 pclass = (iface) ? iface->name : "local";
843
844         struct device_prefix *prefix = calloc(1, sizeof(*prefix) + strlen(pclass) + 1);
845         prefix->length = length;
846         prefix->addr = *addr;
847         prefix->preferred_until = preferred_until;
848         prefix->valid_until = valid_until;
849         prefix->iface = iface;
850         INIT_LIST_HEAD(&prefix->assignments);
851
852         if (excl_addr) {
853                 prefix->excl_addr = *excl_addr;
854                 prefix->excl_length = excl_length;
855         }
856
857         strcpy(prefix->pclass, pclass);
858
859         if (iface)
860                 vlist_add(&iface->proto_ip.prefix, &prefix->node, &prefix->addr);
861         else
862                 interface_update_prefix(NULL, &prefix->node, NULL);
863
864         return prefix;
865 }
866
867 void
868 interface_ip_set_ula_prefix(const char *prefix)
869 {
870         char buf[INET6_ADDRSTRLEN + 4] = {0}, *saveptr;
871         if (prefix)
872                 strncpy(buf, prefix, sizeof(buf) - 1);
873         char *prefixaddr = strtok_r(buf, "/", &saveptr);
874
875         struct in6_addr addr;
876         if (!prefixaddr || inet_pton(AF_INET6, prefixaddr, &addr) < 1) {
877                 if (ula_prefix) {
878                         interface_update_prefix(NULL, NULL, &ula_prefix->node);
879                         ula_prefix = NULL;
880                 }
881                 return;
882         }
883
884         int length;
885         char *prefixlen = strtok_r(NULL, ",", &saveptr);
886         if (!prefixlen || (length = atoi(prefixlen)) < 1 || length > 64)
887                 return;
888
889         if (!ula_prefix || !IN6_ARE_ADDR_EQUAL(&addr, &ula_prefix->addr) ||
890                         ula_prefix->length != length) {
891                 if (ula_prefix)
892                         interface_update_prefix(NULL, NULL, &ula_prefix->node);
893
894                 ula_prefix = interface_ip_add_device_prefix(NULL, &addr, length,
895                                 0, 0, NULL, 0, NULL);
896         }
897 }
898
899 void
900 interface_add_dns_server(struct interface_ip_settings *ip, const char *str)
901 {
902         struct dns_server *s;
903
904         s = calloc(1, sizeof(*s));
905         if (!s)
906                 return;
907
908         s->af = AF_INET;
909         if (inet_pton(s->af, str, &s->addr.in))
910                 goto add;
911
912         s->af = AF_INET6;
913         if (inet_pton(s->af, str, &s->addr.in))
914                 goto add;
915
916         free(s);
917         return;
918
919 add:
920         D(INTERFACE, "Add IPv%c DNS server: %s\n",
921           s->af == AF_INET6 ? '6' : '4', str);
922         vlist_simple_add(&ip->dns_servers, &s->node);
923 }
924
925 void
926 interface_add_dns_server_list(struct interface_ip_settings *ip, struct blob_attr *list)
927 {
928         struct blob_attr *cur;
929         int rem;
930
931         blobmsg_for_each_attr(cur, list, rem) {
932                 if (blobmsg_type(cur) != BLOBMSG_TYPE_STRING)
933                         continue;
934
935                 if (!blobmsg_check_attr(cur, NULL))
936                         continue;
937
938                 interface_add_dns_server(ip, blobmsg_data(cur));
939         }
940 }
941
942 static void
943 interface_add_dns_search_domain(struct interface_ip_settings *ip, const char *str)
944 {
945         struct dns_search_domain *s;
946         int len = strlen(str);
947
948         s = calloc(1, sizeof(*s) + len + 1);
949         if (!s)
950                 return;
951
952         D(INTERFACE, "Add DNS search domain: %s\n", str);
953         memcpy(s->name, str, len);
954         vlist_simple_add(&ip->dns_search, &s->node);
955 }
956
957 void
958 interface_add_dns_search_list(struct interface_ip_settings *ip, struct blob_attr *list)
959 {
960         struct blob_attr *cur;
961         int rem;
962
963         blobmsg_for_each_attr(cur, list, rem) {
964                 if (blobmsg_type(cur) != BLOBMSG_TYPE_STRING)
965                         continue;
966
967                 if (!blobmsg_check_attr(cur, NULL))
968                         continue;
969
970                 interface_add_dns_search_domain(ip, blobmsg_data(cur));
971         }
972 }
973
974 static void
975 write_resolv_conf_entries(FILE *f, struct interface_ip_settings *ip)
976 {
977         struct dns_server *s;
978         struct dns_search_domain *d;
979         const char *str;
980         char buf[INET6_ADDRSTRLEN];
981
982         vlist_simple_for_each_element(&ip->dns_servers, s, node) {
983                 str = inet_ntop(s->af, &s->addr, buf, sizeof(buf));
984                 if (!str)
985                         continue;
986
987                 fprintf(f, "nameserver %s\n", str);
988         }
989
990         vlist_simple_for_each_element(&ip->dns_search, d, node) {
991                 fprintf(f, "search %s\n", d->name);
992         }
993 }
994
995 void
996 interface_write_resolv_conf(void)
997 {
998         struct interface *iface;
999         char *path = alloca(strlen(resolv_conf) + 5);
1000         FILE *f;
1001         uint32_t crcold, crcnew;
1002
1003         sprintf(path, "%s.tmp", resolv_conf);
1004         unlink(path);
1005         f = fopen(path, "w+");
1006         if (!f) {
1007                 D(INTERFACE, "Failed to open %s for writing\n", path);
1008                 return;
1009         }
1010
1011         vlist_for_each_element(&interfaces, iface, node) {
1012                 if (iface->state != IFS_UP)
1013                         continue;
1014
1015                 if (vlist_simple_empty(&iface->proto_ip.dns_search) &&
1016                     vlist_simple_empty(&iface->proto_ip.dns_servers) &&
1017                         vlist_simple_empty(&iface->config_ip.dns_search) &&
1018                     vlist_simple_empty(&iface->config_ip.dns_servers))
1019                         continue;
1020
1021                 fprintf(f, "# Interface %s\n", iface->name);
1022                 write_resolv_conf_entries(f, &iface->config_ip);
1023                 if (!iface->proto_ip.no_dns)
1024                         write_resolv_conf_entries(f, &iface->proto_ip);
1025         }
1026         fflush(f);
1027         rewind(f);
1028         crcnew = crc32_file(f);
1029         fclose(f);
1030
1031         crcold = crcnew + 1;
1032         f = fopen(resolv_conf, "r");
1033         if (f) {
1034                 crcold = crc32_file(f);
1035                 fclose(f);
1036         }
1037
1038         if (crcold == crcnew) {
1039                 unlink(path);
1040         } else if (rename(path, resolv_conf) < 0) {
1041                 D(INTERFACE, "Failed to replace %s\n", resolv_conf);
1042                 unlink(path);
1043         }
1044 }
1045
1046 void interface_ip_set_enabled(struct interface_ip_settings *ip, bool enabled)
1047 {
1048         struct device_addr *addr;
1049         struct device_route *route;
1050         struct device *dev;
1051
1052         ip->enabled = enabled;
1053         dev = ip->iface->l3_dev.dev;
1054         if (!dev)
1055                 return;
1056
1057         vlist_for_each_element(&ip->addr, addr, node) {
1058                 if (addr->enabled == enabled)
1059                         continue;
1060
1061                 if (enabled)
1062                         system_add_address(dev, addr);
1063                 else
1064                         system_del_address(dev, addr);
1065                 addr->enabled = enabled;
1066         }
1067
1068         vlist_for_each_element(&ip->route, route, node) {
1069                 bool _enabled = enabled;
1070
1071                 if (!enable_route(ip, route))
1072                         _enabled = false;
1073
1074                 if (route->enabled == _enabled)
1075                         continue;
1076
1077                 if (_enabled) {
1078                         if (!(route->flags & DEVROUTE_METRIC))
1079                                 route->metric = ip->iface->metric;
1080
1081                         system_add_route(dev, route);
1082                 } else
1083                         system_del_route(dev, route);
1084                 route->enabled = _enabled;
1085         }
1086
1087         struct device_prefix *c;
1088         struct device_prefix_assignment *a;
1089         list_for_each_entry(c, &prefixes, head)
1090                 list_for_each_entry(a, &c->assignments, head)
1091                         if (!strcmp(a->name, ip->iface->name))
1092                                 interface_set_prefix_address(a, c, ip->iface, enabled);
1093
1094         if (ip->iface && ip->iface->l3_dev.dev) {
1095                 set_ip_lo_policy(enabled, true, ip->iface);
1096                 set_ip_lo_policy(enabled, false, ip->iface);
1097
1098                 set_ip_source_policy(enabled, true, IPRULE_PRIORITY_REJECT + ip->iface->l3_dev.dev->ifindex,
1099                         NULL, 0, NULL, ip->iface, "failed_policy");
1100         }
1101 }
1102
1103 void
1104 interface_ip_update_start(struct interface_ip_settings *ip)
1105 {
1106         if (ip != &ip->iface->config_ip) {
1107                 vlist_simple_update(&ip->dns_servers);
1108                 vlist_simple_update(&ip->dns_search);
1109         }
1110         vlist_update(&ip->route);
1111         vlist_update(&ip->addr);
1112         vlist_update(&ip->prefix);
1113 }
1114
1115 void
1116 interface_ip_update_complete(struct interface_ip_settings *ip)
1117 {
1118         vlist_simple_flush(&ip->dns_servers);
1119         vlist_simple_flush(&ip->dns_search);
1120         vlist_flush(&ip->route);
1121         vlist_flush(&ip->addr);
1122         vlist_flush(&ip->prefix);
1123         interface_write_resolv_conf();
1124 }
1125
1126 void
1127 interface_ip_flush(struct interface_ip_settings *ip)
1128 {
1129         if (ip == &ip->iface->proto_ip)
1130                 vlist_flush_all(&ip->iface->host_routes);
1131         vlist_simple_flush_all(&ip->dns_servers);
1132         vlist_simple_flush_all(&ip->dns_search);
1133         vlist_flush_all(&ip->route);
1134         vlist_flush_all(&ip->addr);
1135         vlist_flush_all(&ip->prefix);
1136 }
1137
1138 static void
1139 __interface_ip_init(struct interface_ip_settings *ip, struct interface *iface)
1140 {
1141         ip->iface = iface;
1142         ip->enabled = true;
1143         vlist_simple_init(&ip->dns_search, struct dns_search_domain, node);
1144         vlist_simple_init(&ip->dns_servers, struct dns_server, node);
1145         vlist_init(&ip->route, route_cmp, interface_update_proto_route);
1146         vlist_init(&ip->addr, addr_cmp, interface_update_proto_addr);
1147         vlist_init(&ip->prefix, prefix_cmp, interface_update_prefix);
1148 }
1149
1150 void
1151 interface_ip_init(struct interface *iface)
1152 {
1153         __interface_ip_init(&iface->proto_ip, iface);
1154         __interface_ip_init(&iface->config_ip, iface);
1155         vlist_init(&iface->host_routes, route_cmp, interface_update_host_route);
1156
1157 }
1158
1159 static void
1160 interface_ip_valid_until_handler(struct uloop_timeout *t)
1161 {
1162         time_t now = system_get_rtime();
1163         struct interface *iface;
1164         vlist_for_each_element(&interfaces, iface, node) {
1165                 if (iface->state != IFS_UP)
1166                         continue;
1167
1168                 struct device_addr *addr, *addrp;
1169                 struct device_route *route, *routep;
1170                 struct device_prefix *pref, *prefp;
1171
1172                 vlist_for_each_element_safe(&iface->proto_ip.addr, addr, node, addrp)
1173                         if (addr->valid_until && addr->valid_until < now)
1174                                 vlist_delete(&iface->proto_ip.addr, &addr->node);
1175
1176                 vlist_for_each_element_safe(&iface->proto_ip.route, route, node, routep)
1177                         if (route->valid_until && route->valid_until < now)
1178                                 vlist_delete(&iface->proto_ip.route, &route->node);
1179
1180                 vlist_for_each_element_safe(&iface->proto_ip.prefix, pref, node, prefp)
1181                         if (pref->valid_until && pref->valid_until < now)
1182                                 vlist_delete(&iface->proto_ip.prefix, &pref->node);
1183
1184         }
1185
1186         uloop_timeout_set(t, 1000);
1187 }
1188
1189 static void __init
1190 interface_ip_init_worker(void)
1191 {
1192         valid_until_timeout.cb = interface_ip_valid_until_handler;
1193         uloop_timeout_set(&valid_until_timeout, 1000);
1194 }