43b63c7980793136b1ff5a1271af96c2134fe658
[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
19 #include <limits.h>
20 #include <arpa/inet.h>
21 #include <netinet/in.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_SOURCE,
41         ROUTE_ONLINK,
42         ROUTE_TYPE,
43         __ROUTE_MAX
44 };
45
46 static const struct blobmsg_policy route_attr[__ROUTE_MAX] = {
47         [ROUTE_INTERFACE] = { .name = "interface", .type = BLOBMSG_TYPE_STRING },
48         [ROUTE_TARGET] = { .name = "target", .type = BLOBMSG_TYPE_STRING },
49         [ROUTE_MASK] = { .name = "netmask", .type = BLOBMSG_TYPE_STRING },
50         [ROUTE_GATEWAY] = { .name = "gateway", .type = BLOBMSG_TYPE_STRING },
51         [ROUTE_METRIC] = { .name = "metric", .type = BLOBMSG_TYPE_INT32 },
52         [ROUTE_MTU] = { .name = "mtu", .type = BLOBMSG_TYPE_INT32 },
53         [ROUTE_TABLE] = { .name = "table", .type = BLOBMSG_TYPE_STRING },
54         [ROUTE_VALID] = { .name = "valid", .type = BLOBMSG_TYPE_INT32 },
55         [ROUTE_SOURCE] = { .name = "source", .type = BLOBMSG_TYPE_STRING },
56         [ROUTE_ONLINK] = { .name = "onlink", .type = BLOBMSG_TYPE_BOOL },
57         [ROUTE_TYPE] = { .name = "type", .type = BLOBMSG_TYPE_STRING }
58 };
59
60 const struct uci_blob_param_list route_attr_list = {
61         .n_params = __ROUTE_MAX,
62         .params = route_attr,
63 };
64
65
66 struct list_head prefixes = LIST_HEAD_INIT(prefixes);
67 static struct device_prefix *ula_prefix = NULL;
68 static struct uloop_timeout valid_until_timeout;
69
70
71 static void
72 clear_if_addr(union if_addr *a, int mask)
73 {
74         int m_bytes = (mask + 7) / 8;
75         uint8_t m_clear = (1 << (m_bytes * 8 - mask)) - 1;
76         uint8_t *p = (uint8_t *) a;
77
78         if (m_bytes < sizeof(*a))
79                 memset(p + m_bytes, 0, sizeof(*a) - m_bytes);
80
81         p[m_bytes - 1] &= ~m_clear;
82 }
83
84 static bool
85 match_if_addr(union if_addr *a1, union if_addr *a2, int mask)
86 {
87         union if_addr *p1, *p2;
88
89         p1 = alloca(sizeof(*a1));
90         p2 = alloca(sizeof(*a2));
91
92         memcpy(p1, a1, sizeof(*a1));
93         clear_if_addr(p1, mask);
94         memcpy(p2, a2, sizeof(*a2));
95         clear_if_addr(p2, mask);
96
97         return !memcmp(p1, p2, sizeof(*p1));
98 }
99
100 static int set_ip_source_policy(bool add, bool v6, unsigned int priority,
101                 const union if_addr *addr, uint8_t mask, unsigned int table,
102                 struct interface *in_iface, const char *action)
103 {
104         struct iprule rule = {
105                 .flags = IPRULE_PRIORITY,
106                 .priority = priority
107         };
108
109         if (addr) {
110                 rule.flags |= IPRULE_SRC;
111                 rule.src_addr = *addr;
112                 rule.src_mask = mask;
113         }
114
115         if (table) {
116                 rule.flags |= IPRULE_LOOKUP;
117                 rule.lookup = table;
118
119                 if (!rule.lookup)
120                         return 0;
121         } else if (action) {
122                 rule.flags |= IPRULE_ACTION;
123                 system_resolve_iprule_action(action, &rule.action);
124         }
125
126         if (in_iface && in_iface->l3_dev.dev) {
127                 rule.flags |= IPRULE_IN;
128                 strcpy(rule.in_dev, in_iface->l3_dev.dev->ifname);
129         }
130
131         rule.flags |= (v6) ? IPRULE_INET6 : IPRULE_INET4;
132
133         return (add) ? system_add_iprule(&rule) : system_del_iprule(&rule);
134 }
135
136 static bool
137 __find_ip_addr_target(struct interface_ip_settings *ip, union if_addr *a, bool v6)
138 {
139         struct device_addr *addr;
140
141         vlist_for_each_element(&ip->addr, addr, node) {
142                 if (!addr->enabled)
143                         continue;
144
145                 if (v6 != ((addr->flags & DEVADDR_FAMILY) == DEVADDR_INET6))
146                         continue;
147
148                 // Handle offlink addresses correctly
149                 unsigned int mask = addr->mask;
150                 if ((addr->flags & DEVADDR_FAMILY) == DEVADDR_INET6 &&
151                                 (addr->flags & DEVADDR_OFFLINK))
152                         mask = 128;
153
154                 if (!match_if_addr(&addr->addr, a, mask))
155                         continue;
156
157                 return true;
158         }
159
160         return false;
161 }
162
163 static void
164 __find_ip_route_target(struct interface_ip_settings *ip, union if_addr *a,
165                        bool v6, struct device_route **res)
166 {
167         struct device_route *route;
168
169         vlist_for_each_element(&ip->route, route, node) {
170                 if (!route->enabled)
171                         continue;
172
173                 if (v6 != ((route->flags & DEVADDR_FAMILY) == DEVADDR_INET6))
174                         continue;
175
176                 if (!match_if_addr(&route->addr, a, route->mask))
177                         continue;
178
179                 if (route->flags & DEVROUTE_TABLE)
180                         continue;
181
182                 if (!*res || route->mask < (*res)->mask)
183                         *res = route;
184         }
185 }
186
187 static bool
188 interface_ip_find_addr_target(struct interface *iface, union if_addr *a, bool v6)
189 {
190         return __find_ip_addr_target(&iface->proto_ip, a, v6) ||
191                __find_ip_addr_target(&iface->config_ip, a, v6);
192 }
193
194 static void
195 interface_ip_find_route_target(struct interface *iface, union if_addr *a,
196                                bool v6, struct device_route **route)
197 {
198         __find_ip_route_target(&iface->proto_ip, a, v6, route);
199         __find_ip_route_target(&iface->config_ip, a, v6, route);
200 }
201
202 struct interface *
203 interface_ip_add_target_route(union if_addr *addr, bool v6, struct interface *iface)
204 {
205         struct device_route *route, *r_next = NULL;
206         bool defaultroute_target = false;
207         int addrsize = v6 ? sizeof(addr->in6) : sizeof(addr->in);
208
209         route = calloc(1, sizeof(*route));
210         if (!route)
211                 return NULL;
212
213         route->flags = v6 ? DEVADDR_INET6 : DEVADDR_INET4;
214         route->mask = v6 ? 128 : 32;
215         if (memcmp(&route->addr, addr, addrsize) == 0)
216                 defaultroute_target = true;
217         else
218                 memcpy(&route->addr, addr, addrsize);
219
220         if (iface) {
221                 /* look for locally addressable target first */
222                 if (interface_ip_find_addr_target(iface, addr, v6))
223                         goto done;
224
225                 /* do not stop at the first route, let the lookup compare
226                  * masks to find the best match */
227                 interface_ip_find_route_target(iface, addr, v6, &r_next);
228         } else {
229                 vlist_for_each_element(&interfaces, iface, node) {
230                         /* look for locally addressable target first */
231                         if (interface_ip_find_addr_target(iface, addr, v6))
232                                 goto done;
233
234                         /* do not stop at the first route, let the lookup compare
235                          * masks to find the best match */
236                         interface_ip_find_route_target(iface, addr, v6, &r_next);
237                 }
238         }
239
240         if (!r_next) {
241                 free(route);
242                 return NULL;
243         }
244
245         iface = r_next->iface;
246         memcpy(&route->nexthop, &r_next->nexthop, sizeof(route->nexthop));
247         route->mtu = r_next->mtu;
248         route->metric = r_next->metric;
249         route->table = r_next->table;
250
251 done:
252         route->iface = iface;
253         if (defaultroute_target)
254                 free(route);
255         else
256                 vlist_add(&iface->host_routes, &route->node, route);
257         return iface;
258 }
259
260 void
261 interface_ip_add_route(struct interface *iface, struct blob_attr *attr, bool v6)
262 {
263         struct interface_ip_settings *ip;
264         struct blob_attr *tb[__ROUTE_MAX], *cur;
265         struct device_route *route;
266         int af = v6 ? AF_INET6 : AF_INET;
267         bool is_proto_route = !!iface;
268
269         blobmsg_parse(route_attr, __ROUTE_MAX, tb, blobmsg_data(attr), blobmsg_data_len(attr));
270
271         if (!iface) {
272                 if ((cur = tb[ROUTE_INTERFACE]) == NULL)
273                         return;
274
275                 iface = vlist_find(&interfaces, blobmsg_data(cur), iface, node);
276                 if (!iface)
277                         return;
278
279                 ip = &iface->config_ip;
280         } else {
281                 ip = &iface->proto_ip;
282         }
283
284         route = calloc(1, sizeof(*route));
285         if (!route)
286                 return;
287
288         route->flags = v6 ? DEVADDR_INET6 : DEVADDR_INET4;
289         route->mask = v6 ? 128 : 32;
290         if ((cur = tb[ROUTE_MASK]) != NULL) {
291                 route->mask = parse_netmask_string(blobmsg_data(cur), v6);
292                 if (route->mask > (v6 ? 128 : 32))
293                         goto error;
294         }
295
296         if ((cur = tb[ROUTE_TARGET]) != NULL) {
297                 if (!parse_ip_and_netmask(af, blobmsg_data(cur), &route->addr, &route->mask)) {
298                         DPRINTF("Failed to parse route target: %s\n", (char *) blobmsg_data(cur));
299                         goto error;
300                 }
301         }
302
303         if ((cur = tb[ROUTE_GATEWAY]) != NULL) {
304                 if (!inet_pton(af, blobmsg_data(cur), &route->nexthop)) {
305                         DPRINTF("Failed to parse route gateway: %s\n", (char *) blobmsg_data(cur));
306                         goto error;
307                 }
308         }
309
310         if ((cur = tb[ROUTE_METRIC]) != NULL) {
311                 route->metric = blobmsg_get_u32(cur);
312                 route->flags |= DEVROUTE_METRIC;
313         } else
314                 route->metric = iface->metric;
315
316         if ((cur = tb[ROUTE_MTU]) != NULL) {
317                 route->mtu = blobmsg_get_u32(cur);
318                 route->flags |= DEVROUTE_MTU;
319         }
320
321         // Use source-based routing
322         if ((cur = tb[ROUTE_SOURCE]) != NULL) {
323                 char *saveptr, *source = alloca(blobmsg_data_len(cur));
324                 memcpy(source, blobmsg_data(cur), blobmsg_data_len(cur));
325
326                 const char *addr = strtok_r(source, "/", &saveptr);
327                 const char *mask = strtok_r(NULL, "/", &saveptr);
328
329                 if (!addr || inet_pton(af, addr, &route->source) < 1) {
330                         DPRINTF("Failed to parse route source: %s\n", addr);
331                         goto error;
332                 }
333
334                 route->sourcemask = (mask) ? atoi(mask) : ((af == AF_INET6) ? 128 : 32);
335         }
336
337         if ((cur = tb[ROUTE_ONLINK]) != NULL && blobmsg_get_bool(cur))
338                 route->flags |= DEVROUTE_ONLINK;
339
340         if (is_proto_route) {
341                 route->table = (v6) ? iface->ip6table : iface->ip4table;
342                 route->flags |= DEVROUTE_SRCTABLE;
343         }
344
345         if ((cur = tb[ROUTE_TABLE]) != NULL) {
346                 if (!system_resolve_rt_table(blobmsg_data(cur), &route->table)) {
347                         DPRINTF("Failed to resolve routing table: %s\n", (char *) blobmsg_data(cur));
348                         goto error;
349                 }
350
351                 /* only set the table flag if not using the main (default) table */
352                 if (system_is_default_rt_table(route->table))
353                         route->table = 0;
354
355                 if (route->table)
356                         route->flags |= DEVROUTE_TABLE;
357         }
358
359         if ((cur = tb[ROUTE_VALID]) != NULL) {
360                 int64_t valid = blobmsg_get_u32(cur);
361                 int64_t valid_until = valid + (int64_t)system_get_rtime();
362                 if (valid_until <= LONG_MAX && valid != 0xffffffffLL) // Catch overflow
363                         route->valid_until = valid_until;
364         }
365
366         if ((cur = tb[ROUTE_TYPE]) != NULL) {
367                 if (!system_resolve_rt_type(blobmsg_data(cur), &route->type)) {
368                         DPRINTF("Failed to resolve routing type: %s\n", (char *) blobmsg_data(cur));
369                         goto error;
370                 }
371                 route->flags |= DEVROUTE_TYPE;
372         }
373
374         vlist_add(&ip->route, &route->node, route);
375         return;
376
377 error:
378         free(route);
379 }
380
381 static int
382 addr_cmp(const void *k1, const void *k2, void *ptr)
383 {
384         return memcmp(k1, k2, sizeof(struct device_addr) -
385                       offsetof(struct device_addr, flags));
386 }
387
388 static int
389 route_cmp(const void *k1, const void *k2, void *ptr)
390 {
391         const struct device_route *r1 = k1, *r2 = k2;
392
393         if (r1->mask != r2->mask)
394                 return r2->mask - r1->mask;
395
396         if (r1->metric != r2->metric)
397                 return r1->metric - r2->metric;
398
399         if (r1->flags != r2->flags)
400                 return r2->flags - r1->flags;
401
402         if (r1->sourcemask != r2->sourcemask)
403                 return r1->sourcemask - r2->sourcemask;
404
405         if (r1->table != r2->table)
406                 return r1->table - r2->table;
407
408         int maskcmp = memcmp(&r1->source, &r2->source, sizeof(r1->source));
409         if (maskcmp)
410                 return maskcmp;
411
412         return memcmp(&r1->addr, &r2->addr, sizeof(r1->addr));
413 }
414
415 static int
416 prefix_cmp(const void *k1, const void *k2, void *ptr)
417 {
418         return memcmp(k1, k2, offsetof(struct device_prefix, pclass) -
419                         offsetof(struct device_prefix, addr));
420 }
421
422 static void
423 interface_handle_subnet_route(struct interface *iface, struct device_addr *addr, bool add)
424 {
425         struct device *dev = iface->l3_dev.dev;
426         struct device_route route;
427
428         if (addr->flags & DEVADDR_OFFLINK)
429                 return;
430
431         memset(&route, 0, sizeof(route));
432         route.iface = iface;
433         route.flags = addr->flags;
434         route.mask = addr->mask;
435         memcpy(&route.addr, &addr->addr, sizeof(route.addr));
436         clear_if_addr(&route.addr, route.mask);
437
438         if (add) {
439                 route.flags |= DEVADDR_KERNEL;
440                 system_del_route(dev, &route);
441
442                 route.flags &= ~DEVADDR_KERNEL;
443                 route.metric = iface->metric;
444                 system_add_route(dev, &route);
445         } else {
446                 system_del_route(dev, &route);
447         }
448 }
449
450 static void
451 interface_update_proto_addr(struct vlist_tree *tree,
452                             struct vlist_node *node_new,
453                             struct vlist_node *node_old)
454 {
455         struct interface_ip_settings *ip;
456         struct interface *iface;
457         struct device *dev;
458         struct device_addr *a_new = NULL, *a_old = NULL;
459         bool replace = false;
460         bool keep = false;
461         bool v6 = false;
462
463         ip = container_of(tree, struct interface_ip_settings, addr);
464         iface = ip->iface;
465         dev = iface->l3_dev.dev;
466
467         if (!node_new || !node_old)
468                 iface->updated |= IUF_ADDRESS;
469
470         if (node_new) {
471                 a_new = container_of(node_new, struct device_addr, node);
472
473                 if ((a_new->flags & DEVADDR_FAMILY) == DEVADDR_INET4 &&
474                     !a_new->broadcast) {
475
476                         uint32_t mask = ~0;
477                         uint32_t *a = (uint32_t *) &a_new->addr;
478
479                         mask >>= a_new->mask;
480                         a_new->broadcast = *a | htonl(mask);
481                 }
482         }
483
484         if (node_old)
485                 a_old = container_of(node_old, struct device_addr, node);
486
487         if (a_new && a_old) {
488                 keep = true;
489
490                 if (a_old->flags != a_new->flags || a_old->failed)
491                         keep = false;
492
493                 if (a_old->valid_until != a_new->valid_until ||
494                                 a_old->preferred_until != a_new->preferred_until)
495                         replace = true;
496
497                 if ((a_new->flags & DEVADDR_FAMILY) == DEVADDR_INET4 &&
498                     a_new->broadcast != a_old->broadcast)
499                         keep = false;
500         }
501
502         if (node_old) {
503                 if (a_old->enabled && !keep) {
504                         if ((a_old->flags & DEVADDR_FAMILY) == DEVADDR_INET6)
505                                 v6 = true;
506
507                         unsigned int table = (v6) ? iface->ip6table : iface->ip4table;
508
509                         //This is needed for source routing to work correctly. If a device
510                         //has two connections to a network using the same subnet, adding
511                         //only the network-rule will cause packets to be routed through the
512                         //first matching network (source IP matches both masks).
513                         if (table) {
514                                 set_ip_source_policy(false, v6, IPRULE_PRIORITY_ADDR, &a_old->addr,
515                                                 (v6) ? 128 : 32, table, NULL, NULL);
516                                 set_ip_source_policy(false, v6, IPRULE_PRIORITY_NW, &a_old->addr,
517                                                 a_old->mask, table, NULL, NULL);
518                         }
519
520                         if (!(a_old->flags & DEVADDR_EXTERNAL)) {
521                                 interface_handle_subnet_route(iface, a_old, false);
522                                 system_del_address(dev, a_old);
523                         }
524                 }
525                 free(a_old->pclass);
526                 free(a_old);
527         }
528
529         if (node_new) {
530                 a_new->enabled = true;
531                 if (!keep || replace) {
532                         if (!(a_new->flags & DEVADDR_EXTERNAL)) {
533                                 if (system_add_address(dev, a_new))
534                                         a_new->failed = true;
535
536                                 if (iface->metric)
537                                         interface_handle_subnet_route(iface, a_new, true);
538                         }
539
540                         if (!keep) {
541                                 if ((a_new->flags & DEVADDR_FAMILY) == DEVADDR_INET6)
542                                         v6 = true;
543
544                                 unsigned int table = (v6) ? iface->ip6table : iface->ip4table;
545
546                                 if (table) {
547                                         set_ip_source_policy(true, v6, IPRULE_PRIORITY_ADDR, &a_new->addr,
548                                                         (v6) ? 128 : 32, table, NULL, NULL);
549                                         set_ip_source_policy(true, v6, IPRULE_PRIORITY_NW, &a_new->addr,
550                                                         a_new->mask, table, NULL, NULL);
551                                 }
552                         }
553                 }
554         }
555 }
556
557 static bool
558 enable_route(struct interface_ip_settings *ip, struct device_route *route)
559 {
560         if (ip->no_defaultroute && !route->mask)
561                 return false;
562
563         return ip->enabled;
564 }
565
566 static void
567 interface_update_proto_route(struct vlist_tree *tree,
568                              struct vlist_node *node_new,
569                              struct vlist_node *node_old)
570 {
571         struct interface_ip_settings *ip;
572         struct interface *iface;
573         struct device *dev;
574         struct device_route *route_old, *route_new;
575         bool keep = false;
576
577         ip = container_of(tree, struct interface_ip_settings, route);
578         iface = ip->iface;
579         dev = iface->l3_dev.dev;
580
581         if (!node_new || !node_old)
582                 iface->updated |= IUF_ROUTE;
583
584         route_old = container_of(node_old, struct device_route, node);
585         route_new = container_of(node_new, struct device_route, node);
586
587         if (node_old && node_new)
588                 keep = !memcmp(&route_old->nexthop, &route_new->nexthop, sizeof(route_old->nexthop)) &&
589                         (route_old->mtu == route_new->mtu) && (route_old->type == route_new->type) &&
590                         (route_old->valid_until == route_new->valid_until) && !route_old->failed;
591
592         if (node_old) {
593                 if (!(route_old->flags & DEVADDR_EXTERNAL) && route_old->enabled && !keep)
594                         system_del_route(dev, route_old);
595
596                 free(route_old);
597         }
598
599         if (node_new) {
600                 bool _enabled = enable_route(ip, route_new);
601
602                 if (!(route_new->flags & DEVADDR_EXTERNAL) && !keep && _enabled)
603                         if (system_add_route(dev, route_new))
604                                 route_new->failed = true;
605
606                 route_new->iface = iface;
607                 route_new->enabled = _enabled;
608         }
609 }
610
611 static void
612 interface_update_host_route(struct vlist_tree *tree,
613                              struct vlist_node *node_new,
614                              struct vlist_node *node_old)
615 {
616         struct interface *iface;
617         struct device *dev;
618         struct device_route *route_old, *route_new;
619
620         iface = container_of(tree, struct interface, host_routes);
621         dev = iface->l3_dev.dev;
622
623         route_old = container_of(node_old, struct device_route, node);
624         route_new = container_of(node_new, struct device_route, node);
625
626         if (node_old) {
627                 system_del_route(dev, route_old);
628                 free(route_old);
629         }
630
631         if (node_new) {
632                 if (system_add_route(dev, route_new))
633                         route_new->failed = true;
634         }
635 }
636
637 static void
638 random_ifaceid(struct in6_addr *addr)
639 {
640         static bool initialized = false;
641         struct timeval t;
642
643         if (!initialized) {
644                 long int seed = 0;
645                 gettimeofday(&t, NULL);
646                 seed = t.tv_sec ^ t.tv_usec ^ getpid();
647                 srand48(seed);
648                 initialized = true;
649         }
650         addr->s6_addr32[2] = (uint32_t)mrand48();
651         addr->s6_addr32[3] = (uint32_t)mrand48();
652 }
653
654 static void
655 eui64_ifaceid(struct interface *iface, struct in6_addr *addr)
656 {
657         /* get mac address */
658         uint8_t *macaddr = iface->l3_dev.dev->settings.macaddr;
659         uint8_t *ifaceid = addr->s6_addr + 8;
660         memcpy(ifaceid,macaddr,3);
661         memcpy(ifaceid + 5,macaddr + 3, 3);
662         ifaceid[3] = 0xff;
663         ifaceid[4] = 0xfe;
664         ifaceid[0] ^= 0x02;
665 }
666
667 static void
668 generate_ifaceid(struct interface *iface, struct in6_addr *addr)
669 {
670         /* generate new iface id */
671         switch (iface->assignment_iface_id_selection) {
672         case IFID_FIXED:
673                 /* fixed */
674                 /* copy host part from assignment_fixed_iface_id */
675                 memcpy(addr->s6_addr + 8, iface->assignment_fixed_iface_id.s6_addr + 8, 8);
676                 break;
677         case IFID_RANDOM:
678                 /* randomize last 64 bits */
679                 random_ifaceid(addr);
680                 break;
681         case IFID_EUI64:
682                 /* eui64 */
683                 eui64_ifaceid(iface, addr);
684                 break;
685         }
686 }
687
688 static void
689 interface_set_prefix_address(struct device_prefix_assignment *assignment,
690                 const struct device_prefix *prefix, struct interface *iface, bool add)
691 {
692         const struct interface *uplink = prefix->iface;
693         if (!iface->l3_dev.dev)
694                 return;
695
696         struct device *l3_downlink = iface->l3_dev.dev;
697
698         struct device_addr addr;
699         struct device_route route;
700         memset(&addr, 0, sizeof(addr));
701         memset(&route, 0, sizeof(route));
702
703         if (IN6_IS_ADDR_UNSPECIFIED(&assignment->addr)) {
704                 addr.addr.in6 = prefix->addr;
705                 addr.addr.in6.s6_addr32[1] |= htonl(assignment->assigned);
706                 generate_ifaceid(iface, &addr.addr.in6);
707                 assignment->addr = addr.addr.in6;
708         }
709         else
710                 addr.addr.in6 = assignment->addr;
711
712         addr.mask = assignment->length;
713         addr.flags = DEVADDR_INET6 | DEVADDR_OFFLINK;
714         addr.preferred_until = prefix->preferred_until;
715         addr.valid_until = prefix->valid_until;
716
717         route.flags = DEVADDR_INET6;
718         route.mask = addr.mask < 64 ? 64 : addr.mask;
719         route.addr = addr.addr;
720         clear_if_addr(&route.addr, route.mask);
721
722         if (!add && assignment->enabled) {
723                 time_t now = system_get_rtime();
724                 addr.preferred_until = now;
725                 if (!addr.valid_until || addr.valid_until - now > 7200)
726                         addr.valid_until = now + 7200;
727
728                 if (prefix->iface) {
729                         if (prefix->iface->ip6table)
730                                 set_ip_source_policy(false, true, IPRULE_PRIORITY_NW, &addr.addr,
731                                                 addr.mask, prefix->iface->ip6table, iface, NULL);
732
733                         set_ip_source_policy(false, true, IPRULE_PRIORITY_REJECT, &addr.addr,
734                                                         addr.mask, 0, iface, "unreachable");
735                 }
736
737                 system_del_route(l3_downlink, &route);
738                 system_add_address(l3_downlink, &addr);
739
740                 assignment->enabled = false;
741         } else if (add && (iface->state == IFS_UP || iface->state == IFS_SETUP) &&
742                         !system_add_address(l3_downlink, &addr)) {
743
744                 if (prefix->iface && !assignment->enabled) {
745                         set_ip_source_policy(true, true, IPRULE_PRIORITY_REJECT, &addr.addr,
746                                         addr.mask, 0, iface, "unreachable");
747
748                         if (prefix->iface->ip6table)
749                                 set_ip_source_policy(true, true, IPRULE_PRIORITY_NW, &addr.addr,
750                                                 addr.mask, prefix->iface->ip6table, iface, NULL);
751                 }
752
753                 route.metric = iface->metric;
754                 system_add_route(l3_downlink, &route);
755
756                 if (uplink && uplink->l3_dev.dev && !(l3_downlink->settings.flags & DEV_OPT_MTU6)) {
757                         int mtu = system_update_ipv6_mtu(uplink->l3_dev.dev, 0);
758                         int mtu_old = system_update_ipv6_mtu(l3_downlink, 0);
759
760                         if (mtu > 0 && mtu_old > mtu)
761                                 system_update_ipv6_mtu(l3_downlink, mtu);
762                 }
763
764                 assignment->enabled = true;
765         }
766 }
767
768 static bool interface_prefix_assign(struct list_head *list,
769                 struct device_prefix_assignment *assign)
770 {
771         int32_t current = 0, asize = (1 << (64 - assign->length)) - 1;
772         struct device_prefix_assignment *c;
773         list_for_each_entry(c, list, head) {
774                 if (assign->assigned != -1) {
775                         if (assign->assigned >= current && assign->assigned + asize < c->assigned) {
776                                 list_add_tail(&assign->head, &c->head);
777                                 return true;
778                         }
779                 } else if (assign->assigned == -1) {
780                         current = (current + asize) & (~asize);
781                         if (current + asize < c->assigned) {
782                                 assign->assigned = current;
783                                 list_add_tail(&assign->head, &c->head);
784                                 return true;
785                         }
786                 }
787                 current = (c->assigned + (1 << (64 - c->length)));
788         }
789         return false;
790 }
791
792 static void interface_update_prefix_assignments(struct device_prefix *prefix, bool setup)
793 {
794         struct device_prefix_assignment *c;
795         struct interface *iface;
796
797         // Delete all assignments
798         while (!list_empty(&prefix->assignments)) {
799                 c = list_first_entry(&prefix->assignments,
800                                 struct device_prefix_assignment, head);
801                 if ((iface = vlist_find(&interfaces, c->name, iface, node)))
802                         interface_set_prefix_address(c, prefix, iface, false);
803                 list_del(&c->head);
804                 free(c);
805         }
806
807         if (!setup)
808                 return;
809
810         // End-of-assignment sentinel
811         c = malloc(sizeof(*c) + 1);
812         c->assigned = 1 << (64 - prefix->length);
813         c->length = 64;
814         c->name[0] = 0;
815         c->addr = in6addr_any;
816         list_add(&c->head, &prefix->assignments);
817
818         // Excluded prefix
819         if (prefix->excl_length > 0) {
820                 const char name[] = "!excluded";
821                 c = malloc(sizeof(*c) + sizeof(name));
822                 c->assigned = ntohl(prefix->excl_addr.s6_addr32[1]) &
823                                 ((1 << (64 - prefix->length)) - 1);
824                 c->length = prefix->excl_length;
825                 c->addr = in6addr_any;
826                 memcpy(c->name, name, sizeof(name));
827                 list_add(&c->head, &prefix->assignments);
828         }
829
830         bool assigned_any = false;
831         struct list_head assign_later = LIST_HEAD_INIT(assign_later);
832         vlist_for_each_element(&interfaces, iface, node) {
833                 if (iface->assignment_length < 48 ||
834                                 iface->assignment_length > 64)
835                         continue;
836
837                 // Test whether there is a matching class
838                 if (!list_empty(&iface->assignment_classes)) {
839                         bool found = false;
840
841                         struct interface_assignment_class *c;
842                         list_for_each_entry(c, &iface->assignment_classes, head) {
843                                 if (!strcmp(c->name, prefix->pclass)) {
844                                         found = true;
845                                         break;
846                                 }
847                         }
848
849                         if (!found)
850                                 continue;
851                 }
852
853                 size_t namelen = strlen(iface->name) + 1;
854                 c = malloc(sizeof(*c) + namelen);
855                 c->length = iface->assignment_length;
856                 c->assigned = iface->assignment_hint;
857                 c->addr = in6addr_any;
858                 c->enabled = false;
859                 memcpy(c->name, iface->name, namelen);
860
861                 // First process all custom assignments, put all others in later-list
862                 if (c->assigned == -1 || !interface_prefix_assign(&prefix->assignments, c)) {
863                         if (c->assigned != -1) {
864                                 c->assigned = -1;
865                                 netifd_log_message(L_WARNING, "Failed to assign requested subprefix "
866                                                 "of size %hhu for %s, trying other\n", c->length, c->name);
867                         }
868
869                         struct list_head *next = &assign_later;
870                         struct device_prefix_assignment *n;
871                         list_for_each_entry(n, &assign_later, head) {
872                                 if (n->length < c->length) {
873                                         next = &n->head;
874                                         break;
875                                 }
876                         }
877                         list_add_tail(&c->head, next);
878                 }
879
880                 if (c->assigned != -1)
881                         assigned_any = true;
882         }
883
884         // Then try to assign all other + failed custom assignments
885         while (!list_empty(&assign_later)) {
886                 c = list_first_entry(&assign_later, struct device_prefix_assignment, head);
887                 list_del(&c->head);
888
889                 bool assigned = false;
890                 do {
891                         assigned = interface_prefix_assign(&prefix->assignments, c);
892                 } while (!assigned && ++c->length <= 64);
893
894                 if (!assigned) {
895                         netifd_log_message(L_WARNING, "Failed to assign subprefix "
896                                         "of size %hhu for %s\n", c->length, c->name);
897                         free(c);
898                 } else {
899                         assigned_any = true;
900                 }
901         }
902
903         list_for_each_entry(c, &prefix->assignments, head)
904                 if ((iface = vlist_find(&interfaces, c->name, iface, node)))
905                         interface_set_prefix_address(c, prefix, iface, true);
906
907         if (!assigned_any)
908                 netifd_log_message(L_WARNING, "You have delegated IPv6-prefixes but haven't assigned them "
909                                 "to any interface. Did you forget to set option ip6assign on your lan-interfaces?");
910 }
911
912
913 void interface_refresh_assignments(bool hint)
914 {
915         static bool refresh = false;
916         if (!hint && refresh) {
917                 struct device_prefix *p;
918                 list_for_each_entry(p, &prefixes, head)
919                         interface_update_prefix_assignments(p, true);
920         }
921         refresh = hint;
922 }
923
924
925 static void
926 interface_update_prefix(struct vlist_tree *tree,
927                              struct vlist_node *node_new,
928                              struct vlist_node *node_old)
929 {
930         struct device_prefix *prefix_old, *prefix_new;
931         prefix_old = container_of(node_old, struct device_prefix, node);
932         prefix_new = container_of(node_new, struct device_prefix, node);
933
934         struct interface_ip_settings *ip = container_of(tree, struct interface_ip_settings, prefix);
935         if (tree && (!node_new || !node_old))
936                 ip->iface->updated |= IUF_PREFIX;
937
938         struct device_route route;
939         memset(&route, 0, sizeof(route));
940         route.flags = DEVADDR_INET6;
941         route.metric = INT32_MAX;
942         route.mask = (node_new) ? prefix_new->length : prefix_old->length;
943         route.addr.in6 = (node_new) ? prefix_new->addr : prefix_old->addr;
944
945
946         struct device_prefix_assignment *c;
947         struct interface *iface;
948
949         if (node_old && node_new) {
950                 // Move assignments and refresh addresses to update valid times
951                 list_splice(&prefix_old->assignments, &prefix_new->assignments);
952
953                 list_for_each_entry(c, &prefix_new->assignments, head)
954                         if ((iface = vlist_find(&interfaces, c->name, iface, node)))
955                                 interface_set_prefix_address(c, prefix_new, iface, true);
956         } else if (node_new) {
957                 // Set null-route to avoid routing loops
958                 system_add_route(NULL, &route);
959
960                 if (!prefix_new->iface || !prefix_new->iface->proto_ip.no_delegation)
961                         interface_update_prefix_assignments(prefix_new, true);
962         } else if (node_old) {
963                 // Remove null-route
964                 interface_update_prefix_assignments(prefix_old, false);
965                 system_del_route(NULL, &route);
966         }
967
968         if (node_old) {
969                 if (prefix_old->head.next)
970                         list_del(&prefix_old->head);
971                 free(prefix_old);
972         }
973
974         if (node_new && (!prefix_new->iface || !prefix_new->iface->proto_ip.no_delegation))
975                 list_add(&prefix_new->head, &prefixes);
976
977 }
978
979 struct device_prefix*
980 interface_ip_add_device_prefix(struct interface *iface, struct in6_addr *addr,
981                 uint8_t length, time_t valid_until, time_t preferred_until,
982                 struct in6_addr *excl_addr, uint8_t excl_length, const char *pclass)
983 {
984         if (!pclass)
985                 pclass = (iface) ? iface->name : "local";
986
987         struct device_prefix *prefix = calloc(1, sizeof(*prefix) + strlen(pclass) + 1);
988         prefix->length = length;
989         prefix->addr = *addr;
990         prefix->preferred_until = preferred_until;
991         prefix->valid_until = valid_until;
992         prefix->iface = iface;
993         INIT_LIST_HEAD(&prefix->assignments);
994
995         if (excl_addr) {
996                 prefix->excl_addr = *excl_addr;
997                 prefix->excl_length = excl_length;
998         }
999
1000         strcpy(prefix->pclass, pclass);
1001
1002         if (iface)
1003                 vlist_add(&iface->proto_ip.prefix, &prefix->node, &prefix->addr);
1004         else
1005                 interface_update_prefix(NULL, &prefix->node, NULL);
1006
1007         return prefix;
1008 }
1009
1010 void
1011 interface_ip_set_ula_prefix(const char *prefix)
1012 {
1013         char buf[INET6_ADDRSTRLEN + 4] = {0}, *saveptr;
1014         if (prefix)
1015                 strncpy(buf, prefix, sizeof(buf) - 1);
1016         char *prefixaddr = strtok_r(buf, "/", &saveptr);
1017
1018         struct in6_addr addr;
1019         if (!prefixaddr || inet_pton(AF_INET6, prefixaddr, &addr) < 1) {
1020                 if (ula_prefix) {
1021                         interface_update_prefix(NULL, NULL, &ula_prefix->node);
1022                         ula_prefix = NULL;
1023                 }
1024                 return;
1025         }
1026
1027         int length;
1028         char *prefixlen = strtok_r(NULL, ",", &saveptr);
1029         if (!prefixlen || (length = atoi(prefixlen)) < 1 || length > 64)
1030                 return;
1031
1032         if (!ula_prefix || !IN6_ARE_ADDR_EQUAL(&addr, &ula_prefix->addr) ||
1033                         ula_prefix->length != length) {
1034                 if (ula_prefix)
1035                         interface_update_prefix(NULL, NULL, &ula_prefix->node);
1036
1037                 ula_prefix = interface_ip_add_device_prefix(NULL, &addr, length,
1038                                 0, 0, NULL, 0, NULL);
1039         }
1040 }
1041
1042 void
1043 interface_add_dns_server(struct interface_ip_settings *ip, const char *str)
1044 {
1045         struct dns_server *s;
1046
1047         s = calloc(1, sizeof(*s));
1048         if (!s)
1049                 return;
1050
1051         s->af = AF_INET;
1052         if (inet_pton(s->af, str, &s->addr.in))
1053                 goto add;
1054
1055         s->af = AF_INET6;
1056         if (inet_pton(s->af, str, &s->addr.in))
1057                 goto add;
1058
1059         free(s);
1060         return;
1061
1062 add:
1063         D(INTERFACE, "Add IPv%c DNS server: %s\n",
1064           s->af == AF_INET6 ? '6' : '4', str);
1065         vlist_simple_add(&ip->dns_servers, &s->node);
1066 }
1067
1068 void
1069 interface_add_dns_server_list(struct interface_ip_settings *ip, struct blob_attr *list)
1070 {
1071         struct blob_attr *cur;
1072         int rem;
1073
1074         blobmsg_for_each_attr(cur, list, rem) {
1075                 if (blobmsg_type(cur) != BLOBMSG_TYPE_STRING)
1076                         continue;
1077
1078                 if (!blobmsg_check_attr(cur, NULL))
1079                         continue;
1080
1081                 interface_add_dns_server(ip, blobmsg_data(cur));
1082         }
1083 }
1084
1085 static void
1086 interface_add_dns_search_domain(struct interface_ip_settings *ip, const char *str)
1087 {
1088         struct dns_search_domain *s;
1089         int len = strlen(str);
1090
1091         s = calloc(1, sizeof(*s) + len + 1);
1092         if (!s)
1093                 return;
1094
1095         D(INTERFACE, "Add DNS search domain: %s\n", str);
1096         memcpy(s->name, str, len);
1097         vlist_simple_add(&ip->dns_search, &s->node);
1098 }
1099
1100 void
1101 interface_add_dns_search_list(struct interface_ip_settings *ip, struct blob_attr *list)
1102 {
1103         struct blob_attr *cur;
1104         int rem;
1105
1106         blobmsg_for_each_attr(cur, list, rem) {
1107                 if (blobmsg_type(cur) != BLOBMSG_TYPE_STRING)
1108                         continue;
1109
1110                 if (!blobmsg_check_attr(cur, NULL))
1111                         continue;
1112
1113                 interface_add_dns_search_domain(ip, blobmsg_data(cur));
1114         }
1115 }
1116
1117 static void
1118 write_resolv_conf_entries(FILE *f, struct interface_ip_settings *ip, const char *dev)
1119 {
1120         struct dns_server *s;
1121         struct dns_search_domain *d;
1122         const char *str;
1123         char buf[INET6_ADDRSTRLEN];
1124
1125         vlist_simple_for_each_element(&ip->dns_servers, s, node) {
1126                 str = inet_ntop(s->af, &s->addr, buf, sizeof(buf));
1127                 if (!str)
1128                         continue;
1129
1130                 if (s->af == AF_INET6 && IN6_IS_ADDR_LINKLOCAL(&s->addr.in6))
1131                         fprintf(f, "nameserver %s%%%s\n", str, dev);
1132                 else
1133                         fprintf(f, "nameserver %s\n", str);
1134         }
1135
1136         vlist_simple_for_each_element(&ip->dns_search, d, node) {
1137                 fprintf(f, "search %s\n", d->name);
1138         }
1139 }
1140
1141 void
1142 interface_write_resolv_conf(void)
1143 {
1144         struct interface *iface;
1145         char *path = alloca(strlen(resolv_conf) + 5);
1146         FILE *f;
1147         uint32_t crcold, crcnew;
1148
1149         sprintf(path, "%s.tmp", resolv_conf);
1150         unlink(path);
1151         f = fopen(path, "w+");
1152         if (!f) {
1153                 D(INTERFACE, "Failed to open %s for writing\n", path);
1154                 return;
1155         }
1156
1157         vlist_for_each_element(&interfaces, iface, node) {
1158                 if (iface->state != IFS_UP)
1159                         continue;
1160
1161                 if (vlist_simple_empty(&iface->proto_ip.dns_search) &&
1162                     vlist_simple_empty(&iface->proto_ip.dns_servers) &&
1163                         vlist_simple_empty(&iface->config_ip.dns_search) &&
1164                     vlist_simple_empty(&iface->config_ip.dns_servers))
1165                         continue;
1166
1167                 fprintf(f, "# Interface %s\n", iface->name);
1168                 write_resolv_conf_entries(f, &iface->config_ip, iface->ifname);
1169                 if (!iface->proto_ip.no_dns)
1170                         write_resolv_conf_entries(f, &iface->proto_ip, iface->ifname);
1171         }
1172         fflush(f);
1173         rewind(f);
1174         crcnew = crc32_file(f);
1175         fclose(f);
1176
1177         crcold = crcnew + 1;
1178         f = fopen(resolv_conf, "r");
1179         if (f) {
1180                 crcold = crc32_file(f);
1181                 fclose(f);
1182         }
1183
1184         if (crcold == crcnew) {
1185                 unlink(path);
1186         } else if (rename(path, resolv_conf) < 0) {
1187                 D(INTERFACE, "Failed to replace %s\n", resolv_conf);
1188                 unlink(path);
1189         }
1190 }
1191
1192 void interface_ip_set_enabled(struct interface_ip_settings *ip, bool enabled)
1193 {
1194         struct device_addr *addr;
1195         struct device_route *route;
1196         struct device *dev;
1197         struct interface *iface;
1198
1199         ip->enabled = enabled;
1200         iface = ip->iface;
1201         dev = iface->l3_dev.dev;
1202         if (!dev)
1203                 return;
1204
1205         vlist_for_each_element(&ip->addr, addr, node) {
1206                 if (addr->enabled == enabled)
1207                         continue;
1208
1209                 if (enabled) {
1210                         system_add_address(dev, addr);
1211                         if (iface->metric)
1212                                 interface_handle_subnet_route(iface, addr, true);
1213                 } else {
1214                         interface_handle_subnet_route(iface, addr, false);
1215                         system_del_address(dev, addr);
1216                 }
1217                 addr->enabled = enabled;
1218         }
1219
1220         vlist_for_each_element(&ip->route, route, node) {
1221                 bool _enabled = enabled;
1222
1223                 if (!enable_route(ip, route))
1224                         _enabled = false;
1225
1226                 if (route->enabled == _enabled)
1227                         continue;
1228
1229                 if (_enabled) {
1230                         if (!(route->flags & DEVROUTE_METRIC))
1231                                 route->metric = ip->iface->metric;
1232
1233                         if (system_add_route(dev, route))
1234                                 route->failed = true;
1235                 } else
1236                         system_del_route(dev, route);
1237                 route->enabled = _enabled;
1238         }
1239
1240         struct device_prefix *c;
1241         struct device_prefix_assignment *a;
1242         list_for_each_entry(c, &prefixes, head)
1243                 list_for_each_entry(a, &c->assignments, head)
1244                         if (!strcmp(a->name, ip->iface->name))
1245                                 interface_set_prefix_address(a, c, ip->iface, enabled);
1246
1247         if (ip->iface && ip->iface->l3_dev.dev)
1248                 set_ip_source_policy(enabled, true, IPRULE_PRIORITY_REJECT + ip->iface->l3_dev.dev->ifindex,
1249                         NULL, 0, 0, ip->iface, "failed_policy");
1250 }
1251
1252 void
1253 interface_ip_update_start(struct interface_ip_settings *ip)
1254 {
1255         if (ip != &ip->iface->config_ip) {
1256                 vlist_simple_update(&ip->dns_servers);
1257                 vlist_simple_update(&ip->dns_search);
1258         }
1259         vlist_update(&ip->route);
1260         vlist_update(&ip->addr);
1261         vlist_update(&ip->prefix);
1262 }
1263
1264 void
1265 interface_ip_update_complete(struct interface_ip_settings *ip)
1266 {
1267         vlist_simple_flush(&ip->dns_servers);
1268         vlist_simple_flush(&ip->dns_search);
1269         vlist_flush(&ip->route);
1270         vlist_flush(&ip->addr);
1271         vlist_flush(&ip->prefix);
1272         interface_write_resolv_conf();
1273 }
1274
1275 void
1276 interface_ip_flush(struct interface_ip_settings *ip)
1277 {
1278         if (ip == &ip->iface->proto_ip)
1279                 vlist_flush_all(&ip->iface->host_routes);
1280         vlist_simple_flush_all(&ip->dns_servers);
1281         vlist_simple_flush_all(&ip->dns_search);
1282         vlist_flush_all(&ip->route);
1283         vlist_flush_all(&ip->addr);
1284         vlist_flush_all(&ip->prefix);
1285 }
1286
1287 static void
1288 __interface_ip_init(struct interface_ip_settings *ip, struct interface *iface)
1289 {
1290         ip->iface = iface;
1291         ip->enabled = true;
1292         vlist_simple_init(&ip->dns_search, struct dns_search_domain, node);
1293         vlist_simple_init(&ip->dns_servers, struct dns_server, node);
1294         vlist_init(&ip->route, route_cmp, interface_update_proto_route);
1295         vlist_init(&ip->addr, addr_cmp, interface_update_proto_addr);
1296         vlist_init(&ip->prefix, prefix_cmp, interface_update_prefix);
1297 }
1298
1299 void
1300 interface_ip_init(struct interface *iface)
1301 {
1302         __interface_ip_init(&iface->proto_ip, iface);
1303         __interface_ip_init(&iface->config_ip, iface);
1304         vlist_init(&iface->host_routes, route_cmp, interface_update_host_route);
1305 }
1306
1307 static void
1308 interface_ip_valid_until_handler(struct uloop_timeout *t)
1309 {
1310         time_t now = system_get_rtime();
1311         struct interface *iface;
1312         vlist_for_each_element(&interfaces, iface, node) {
1313                 if (iface->state != IFS_UP)
1314                         continue;
1315
1316                 struct device_addr *addr, *addrp;
1317                 struct device_route *route, *routep;
1318                 struct device_prefix *pref, *prefp;
1319
1320                 vlist_for_each_element_safe(&iface->proto_ip.addr, addr, node, addrp)
1321                         if (addr->valid_until && addr->valid_until < now)
1322                                 vlist_delete(&iface->proto_ip.addr, &addr->node);
1323
1324                 vlist_for_each_element_safe(&iface->proto_ip.route, route, node, routep)
1325                         if (route->valid_until && route->valid_until < now)
1326                                 vlist_delete(&iface->proto_ip.route, &route->node);
1327
1328                 vlist_for_each_element_safe(&iface->proto_ip.prefix, pref, node, prefp)
1329                         if (pref->valid_until && pref->valid_until < now)
1330                                 vlist_delete(&iface->proto_ip.prefix, &pref->node);
1331
1332         }
1333
1334         uloop_timeout_set(t, 1000);
1335 }
1336
1337 static void __init
1338 interface_ip_init_worker(void)
1339 {
1340         valid_until_timeout.cb = interface_ip_valid_until_handler;
1341         uloop_timeout_set(&valid_until_timeout, 1000);
1342 }