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