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