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