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