44dd63dd928c031d1304feb1775d7f17eeaf5faf
[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                         list_add_tail(&c->head, &assign_later);
733                 }
734
735                 if (c->assigned != -1)
736                         assigned_any = true;
737         }
738
739         // Then try to assign all other + failed custom assignments
740         while (!list_empty(&assign_later)) {
741                 c = list_first_entry(&assign_later, struct device_prefix_assignment, head);
742                 list_del(&c->head);
743
744                 bool assigned = false;
745                 do {
746                         assigned = interface_prefix_assign(&prefix->assignments, c);
747                 } while (!assigned && ++c->length <= 64);
748
749                 if (!assigned) {
750                         netifd_log_message(L_WARNING, "Failed to assign subprefix "
751                                         "of size %hhu for %s\n", c->length, c->name);
752                         free(c);
753                 } else {
754                         assigned_any = true;
755                 }
756         }
757
758         list_for_each_entry(c, &prefix->assignments, head)
759                 if ((iface = vlist_find(&interfaces, c->name, iface, node)))
760                         interface_set_prefix_address(c, prefix, iface, true);
761
762         if (!assigned_any)
763                 netifd_log_message(L_WARNING, "You have delegated IPv6-prefixes but haven't assigned them "
764                                 "to any interface. Did you forget to set option ip6assign on your lan-interfaces?");
765 }
766
767
768 void interface_refresh_assignments(bool hint)
769 {
770         static bool refresh = false;
771         if (!hint && refresh) {
772                 struct device_prefix *p;
773                 list_for_each_entry(p, &prefixes, head)
774                         interface_update_prefix_assignments(p, true);
775         }
776         refresh = hint;
777 }
778
779
780 static void
781 interface_update_prefix(struct vlist_tree *tree,
782                              struct vlist_node *node_new,
783                              struct vlist_node *node_old)
784 {
785         struct device_prefix *prefix_old, *prefix_new;
786         prefix_old = container_of(node_old, struct device_prefix, node);
787         prefix_new = container_of(node_new, struct device_prefix, node);
788
789         struct device_route route;
790         memset(&route, 0, sizeof(route));
791         route.flags = DEVADDR_INET6;
792         route.metric = INT32_MAX;
793         route.mask = (node_new) ? prefix_new->length : prefix_old->length;
794         route.addr.in6 = (node_new) ? prefix_new->addr : prefix_old->addr;
795
796
797         struct device_prefix_assignment *c;
798         struct interface *iface;
799
800         if (node_old && node_new) {
801                 // Move assignments and refresh addresses to update valid times
802                 list_splice(&prefix_old->assignments, &prefix_new->assignments);
803
804                 list_for_each_entry(c, &prefix_new->assignments, head)
805                         if ((iface = vlist_find(&interfaces, c->name, iface, node)))
806                                 interface_set_prefix_address(c, prefix_new, iface, true);
807         } else if (node_new) {
808                 // Set null-route to avoid routing loops
809                 system_add_route(NULL, &route);
810                 interface_update_prefix_assignments(prefix_new, true);
811         } else if (node_old) {
812                 // Remove null-route
813                 interface_update_prefix_assignments(prefix_old, false);
814                 system_del_route(NULL, &route);
815         }
816
817         if (node_old) {
818                 list_del(&prefix_old->head);
819                 free(prefix_old);
820         }
821
822         if (node_new)
823                 list_add(&prefix_new->head, &prefixes);
824
825 }
826
827 struct device_prefix*
828 interface_ip_add_device_prefix(struct interface *iface, struct in6_addr *addr,
829                 uint8_t length, time_t valid_until, time_t preferred_until,
830                 struct in6_addr *excl_addr, uint8_t excl_length, const char *pclass)
831 {
832         if (!pclass)
833                 pclass = (iface) ? iface->name : "local";
834
835         struct device_prefix *prefix = calloc(1, sizeof(*prefix) + strlen(pclass) + 1);
836         prefix->length = length;
837         prefix->addr = *addr;
838         prefix->preferred_until = preferred_until;
839         prefix->valid_until = valid_until;
840         prefix->iface = iface;
841         INIT_LIST_HEAD(&prefix->assignments);
842
843         if (excl_addr) {
844                 prefix->excl_addr = *excl_addr;
845                 prefix->excl_length = excl_length;
846         }
847
848         strcpy(prefix->pclass, pclass);
849
850         if (iface)
851                 vlist_add(&iface->proto_ip.prefix, &prefix->node, &prefix->addr);
852         else
853                 interface_update_prefix(NULL, &prefix->node, NULL);
854
855         return prefix;
856 }
857
858 void
859 interface_ip_set_ula_prefix(const char *prefix)
860 {
861         char buf[INET6_ADDRSTRLEN + 4] = {0}, *saveptr;
862         if (prefix)
863                 strncpy(buf, prefix, sizeof(buf) - 1);
864         char *prefixaddr = strtok_r(buf, "/", &saveptr);
865
866         struct in6_addr addr;
867         if (!prefixaddr || inet_pton(AF_INET6, prefixaddr, &addr) < 1) {
868                 if (ula_prefix) {
869                         interface_update_prefix(NULL, NULL, &ula_prefix->node);
870                         ula_prefix = NULL;
871                 }
872                 return;
873         }
874
875         int length;
876         char *prefixlen = strtok_r(NULL, ",", &saveptr);
877         if (!prefixlen || (length = atoi(prefixlen)) < 1 || length > 64)
878                 return;
879
880         if (!ula_prefix || !IN6_ARE_ADDR_EQUAL(&addr, &ula_prefix->addr) ||
881                         ula_prefix->length != length) {
882                 if (ula_prefix)
883                         interface_update_prefix(NULL, NULL, &ula_prefix->node);
884
885                 ula_prefix = interface_ip_add_device_prefix(NULL, &addr, length,
886                                 0, 0, NULL, 0, NULL);
887         }
888 }
889
890 void
891 interface_add_dns_server(struct interface_ip_settings *ip, const char *str)
892 {
893         struct dns_server *s;
894
895         s = calloc(1, sizeof(*s));
896         if (!s)
897                 return;
898
899         s->af = AF_INET;
900         if (inet_pton(s->af, str, &s->addr.in))
901                 goto add;
902
903         s->af = AF_INET6;
904         if (inet_pton(s->af, str, &s->addr.in))
905                 goto add;
906
907         free(s);
908         return;
909
910 add:
911         D(INTERFACE, "Add IPv%c DNS server: %s\n",
912           s->af == AF_INET6 ? '6' : '4', str);
913         vlist_simple_add(&ip->dns_servers, &s->node);
914 }
915
916 void
917 interface_add_dns_server_list(struct interface_ip_settings *ip, struct blob_attr *list)
918 {
919         struct blob_attr *cur;
920         int rem;
921
922         blobmsg_for_each_attr(cur, list, rem) {
923                 if (blobmsg_type(cur) != BLOBMSG_TYPE_STRING)
924                         continue;
925
926                 if (!blobmsg_check_attr(cur, NULL))
927                         continue;
928
929                 interface_add_dns_server(ip, blobmsg_data(cur));
930         }
931 }
932
933 static void
934 interface_add_dns_search_domain(struct interface_ip_settings *ip, const char *str)
935 {
936         struct dns_search_domain *s;
937         int len = strlen(str);
938
939         s = calloc(1, sizeof(*s) + len + 1);
940         if (!s)
941                 return;
942
943         D(INTERFACE, "Add DNS search domain: %s\n", str);
944         memcpy(s->name, str, len);
945         vlist_simple_add(&ip->dns_search, &s->node);
946 }
947
948 void
949 interface_add_dns_search_list(struct interface_ip_settings *ip, struct blob_attr *list)
950 {
951         struct blob_attr *cur;
952         int rem;
953
954         blobmsg_for_each_attr(cur, list, rem) {
955                 if (blobmsg_type(cur) != BLOBMSG_TYPE_STRING)
956                         continue;
957
958                 if (!blobmsg_check_attr(cur, NULL))
959                         continue;
960
961                 interface_add_dns_search_domain(ip, blobmsg_data(cur));
962         }
963 }
964
965 static void
966 write_resolv_conf_entries(FILE *f, struct interface_ip_settings *ip)
967 {
968         struct dns_server *s;
969         struct dns_search_domain *d;
970         const char *str;
971         char buf[INET6_ADDRSTRLEN];
972
973         vlist_simple_for_each_element(&ip->dns_servers, s, node) {
974                 str = inet_ntop(s->af, &s->addr, buf, sizeof(buf));
975                 if (!str)
976                         continue;
977
978                 fprintf(f, "nameserver %s\n", str);
979         }
980
981         vlist_simple_for_each_element(&ip->dns_search, d, node) {
982                 fprintf(f, "search %s\n", d->name);
983         }
984 }
985
986 void
987 interface_write_resolv_conf(void)
988 {
989         struct interface *iface;
990         char *path = alloca(strlen(resolv_conf) + 5);
991         FILE *f;
992         uint32_t crcold, crcnew;
993
994         sprintf(path, "%s.tmp", resolv_conf);
995         unlink(path);
996         f = fopen(path, "w+");
997         if (!f) {
998                 D(INTERFACE, "Failed to open %s for writing\n", path);
999                 return;
1000         }
1001
1002         vlist_for_each_element(&interfaces, iface, node) {
1003                 if (iface->state != IFS_UP)
1004                         continue;
1005
1006                 if (vlist_simple_empty(&iface->proto_ip.dns_search) &&
1007                     vlist_simple_empty(&iface->proto_ip.dns_servers) &&
1008                         vlist_simple_empty(&iface->config_ip.dns_search) &&
1009                     vlist_simple_empty(&iface->config_ip.dns_servers))
1010                         continue;
1011
1012                 fprintf(f, "# Interface %s\n", iface->name);
1013                 write_resolv_conf_entries(f, &iface->config_ip);
1014                 if (!iface->proto_ip.no_dns)
1015                         write_resolv_conf_entries(f, &iface->proto_ip);
1016         }
1017         fflush(f);
1018         rewind(f);
1019         crcnew = crc32_file(f);
1020         fclose(f);
1021
1022         crcold = crcnew + 1;
1023         f = fopen(resolv_conf, "r");
1024         if (f) {
1025                 crcold = crc32_file(f);
1026                 fclose(f);
1027         }
1028
1029         if (crcold == crcnew) {
1030                 unlink(path);
1031         } else if (rename(path, resolv_conf) < 0) {
1032                 D(INTERFACE, "Failed to replace %s\n", resolv_conf);
1033                 unlink(path);
1034         }
1035 }
1036
1037 void interface_ip_set_enabled(struct interface_ip_settings *ip, bool enabled)
1038 {
1039         struct device_addr *addr;
1040         struct device_route *route;
1041         struct device *dev;
1042
1043         ip->enabled = enabled;
1044         dev = ip->iface->l3_dev.dev;
1045         if (!dev)
1046                 return;
1047
1048         vlist_for_each_element(&ip->addr, addr, node) {
1049                 if (addr->enabled == enabled)
1050                         continue;
1051
1052                 if (enabled)
1053                         system_add_address(dev, addr);
1054                 else
1055                         system_del_address(dev, addr);
1056                 addr->enabled = enabled;
1057         }
1058
1059         vlist_for_each_element(&ip->route, route, node) {
1060                 bool _enabled = enabled;
1061
1062                 if (!enable_route(ip, route))
1063                         _enabled = false;
1064
1065                 if (route->enabled == _enabled)
1066                         continue;
1067
1068                 if (_enabled) {
1069                         if (!(route->flags & DEVROUTE_METRIC))
1070                                 route->metric = ip->iface->metric;
1071
1072                         system_add_route(dev, route);
1073                 } else
1074                         system_del_route(dev, route);
1075                 route->enabled = _enabled;
1076         }
1077
1078         struct device_prefix *c;
1079         struct device_prefix_assignment *a;
1080         list_for_each_entry(c, &prefixes, head)
1081                 list_for_each_entry(a, &c->assignments, head)
1082                         if (!strcmp(a->name, ip->iface->name))
1083                                 interface_set_prefix_address(a, c, ip->iface, enabled);
1084
1085         if (ip->iface && ip->iface->l3_dev.dev) {
1086                 set_ip_lo_policy(enabled, true, ip->iface);
1087                 set_ip_lo_policy(enabled, false, ip->iface);
1088
1089                 set_ip_source_policy(enabled, true, IPRULE_PRIORITY_REJECT + ip->iface->l3_dev.dev->ifindex,
1090                         NULL, 0, NULL, ip->iface, "failed_policy");
1091         }
1092 }
1093
1094 void
1095 interface_ip_update_start(struct interface_ip_settings *ip)
1096 {
1097         if (ip != &ip->iface->config_ip) {
1098                 vlist_simple_update(&ip->dns_servers);
1099                 vlist_simple_update(&ip->dns_search);
1100         }
1101         vlist_update(&ip->route);
1102         vlist_update(&ip->addr);
1103         vlist_update(&ip->prefix);
1104 }
1105
1106 void
1107 interface_ip_update_complete(struct interface_ip_settings *ip)
1108 {
1109         vlist_simple_flush(&ip->dns_servers);
1110         vlist_simple_flush(&ip->dns_search);
1111         vlist_flush(&ip->route);
1112         vlist_flush(&ip->addr);
1113         vlist_flush(&ip->prefix);
1114         interface_write_resolv_conf();
1115 }
1116
1117 void
1118 interface_ip_flush(struct interface_ip_settings *ip)
1119 {
1120         if (ip == &ip->iface->proto_ip)
1121                 vlist_flush_all(&ip->iface->host_routes);
1122         vlist_simple_flush_all(&ip->dns_servers);
1123         vlist_simple_flush_all(&ip->dns_search);
1124         vlist_flush_all(&ip->route);
1125         vlist_flush_all(&ip->addr);
1126         vlist_flush_all(&ip->prefix);
1127 }
1128
1129 static void
1130 __interface_ip_init(struct interface_ip_settings *ip, struct interface *iface)
1131 {
1132         ip->iface = iface;
1133         ip->enabled = true;
1134         vlist_simple_init(&ip->dns_search, struct dns_search_domain, node);
1135         vlist_simple_init(&ip->dns_servers, struct dns_server, node);
1136         vlist_init(&ip->route, route_cmp, interface_update_proto_route);
1137         vlist_init(&ip->addr, addr_cmp, interface_update_proto_addr);
1138         vlist_init(&ip->prefix, prefix_cmp, interface_update_prefix);
1139 }
1140
1141 void
1142 interface_ip_init(struct interface *iface)
1143 {
1144         __interface_ip_init(&iface->proto_ip, iface);
1145         __interface_ip_init(&iface->config_ip, iface);
1146         vlist_init(&iface->host_routes, route_cmp, interface_update_host_route);
1147
1148 }
1149
1150 static void
1151 interface_ip_valid_until_handler(struct uloop_timeout *t)
1152 {
1153         time_t now = system_get_rtime();
1154         struct interface *iface;
1155         vlist_for_each_element(&interfaces, iface, node) {
1156                 if (iface->state != IFS_UP)
1157                         continue;
1158
1159                 struct device_addr *addr, *addrp;
1160                 struct device_route *route, *routep;
1161                 struct device_prefix *pref, *prefp;
1162
1163                 vlist_for_each_element_safe(&iface->proto_ip.addr, addr, node, addrp)
1164                         if (addr->valid_until && addr->valid_until < now)
1165                                 vlist_delete(&iface->proto_ip.addr, &addr->node);
1166
1167                 vlist_for_each_element_safe(&iface->proto_ip.route, route, node, routep)
1168                         if (route->valid_until && route->valid_until < now)
1169                                 vlist_delete(&iface->proto_ip.route, &route->node);
1170
1171                 vlist_for_each_element_safe(&iface->proto_ip.prefix, pref, node, prefp)
1172                         if (pref->valid_until && pref->valid_until < now)
1173                                 vlist_delete(&iface->proto_ip.prefix, &pref->node);
1174
1175         }
1176
1177         uloop_timeout_set(t, 1000);
1178 }
1179
1180 static void __init
1181 interface_ip_init_worker(void)
1182 {
1183         valid_until_timeout.cb = interface_ip_valid_until_handler;
1184         uloop_timeout_set(&valid_until_timeout, 1000);
1185 }