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