dhcpv6: fix calculation of T1 and T2
[project/odhcpd.git] / src / router.c
1 /**
2  * Copyright (C) 2012-2013 Steven Barth <steven@midlink.org>
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License v2 as published by
6  * the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11  * GNU General Public License for more details.
12  *
13  */
14
15 #include <errno.h>
16 #include <fcntl.h>
17 #include <signal.h>
18 #include <resolv.h>
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <unistd.h>
22 #include <stdbool.h>
23 #include <net/route.h>
24
25 #include "router.h"
26 #include "odhcpd.h"
27
28
29 static void forward_router_solicitation(const struct interface *iface);
30 static void forward_router_advertisement(uint8_t *data, size_t len);
31
32 static void handle_icmpv6(void *addr, void *data, size_t len,
33                 struct interface *iface, void *dest);
34 static void trigger_router_advert(struct uloop_timeout *event);
35 static void sigusr1_refresh(int signal);
36
37 static struct odhcpd_event router_event = {{.fd = -1}, handle_icmpv6};
38
39 static FILE *fp_route = NULL;
40
41
42 int init_router(void)
43 {
44         // Open ICMPv6 socket
45         int sock = socket(AF_INET6, SOCK_RAW | SOCK_CLOEXEC, IPPROTO_ICMPV6);
46         if (sock < 0 && errno != EAFNOSUPPORT) {
47                 syslog(LOG_ERR, "Failed to open RAW-socket: %s", strerror(errno));
48                 return -1;
49         }
50
51         // Let the kernel compute our checksums
52         int val = 2;
53         setsockopt(sock, IPPROTO_RAW, IPV6_CHECKSUM, &val, sizeof(val));
54
55         // This is required by RFC 4861
56         val = 255;
57         setsockopt(sock, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &val, sizeof(val));
58         setsockopt(sock, IPPROTO_IPV6, IPV6_UNICAST_HOPS, &val, sizeof(val));
59
60         // We need to know the source interface
61         val = 1;
62         setsockopt(sock, IPPROTO_IPV6, IPV6_RECVPKTINFO, &val, sizeof(val));
63         setsockopt(sock, IPPROTO_IPV6, IPV6_RECVHOPLIMIT, &val, sizeof(val));
64
65         // Don't loop back
66         val = 0;
67         setsockopt(sock, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, &val, sizeof(val));
68
69         // Filter ICMPv6 package types
70         struct icmp6_filter filt;
71         ICMP6_FILTER_SETBLOCKALL(&filt);
72         ICMP6_FILTER_SETPASS(ND_ROUTER_ADVERT, &filt);
73         ICMP6_FILTER_SETPASS(ND_ROUTER_SOLICIT, &filt);
74         setsockopt(sock, IPPROTO_ICMPV6, ICMP6_FILTER, &filt, sizeof(filt));
75
76         // Register socket
77         router_event.uloop.fd = sock;
78         odhcpd_register(&router_event);
79
80         if (!(fp_route = fopen("/proc/net/ipv6_route", "r")))
81                 syslog(LOG_ERR, "Failed to open routing table: %s",
82                                 strerror(errno));
83
84         signal(SIGUSR1, sigusr1_refresh);
85         return 0;
86 }
87
88
89 int setup_router_interface(struct interface *iface, bool enable)
90 {
91         if (!fp_route || router_event.uloop.fd < 0)
92                 return -1;
93
94         struct ipv6_mreq all_nodes = {ALL_IPV6_NODES, iface->ifindex};
95         struct ipv6_mreq all_routers = {ALL_IPV6_ROUTERS, iface->ifindex};
96
97         uloop_timeout_cancel(&iface->timer_rs);
98         iface->timer_rs.cb = NULL;
99
100         setsockopt(router_event.uloop.fd, IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP,
101                         &all_nodes, sizeof(all_nodes));
102         setsockopt(router_event.uloop.fd, IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP,
103                         &all_routers, sizeof(all_routers));
104
105         if (!enable) {
106                 if (iface->ra)
107                         trigger_router_advert(&iface->timer_rs);
108         } else {
109                 void *mreq = &all_routers;
110
111                 if (iface->ra == RELAYD_RELAY && iface->master) {
112                         mreq = &all_nodes;
113                         forward_router_solicitation(iface);
114                 } else if (iface->ra == RELAYD_SERVER && !iface->master) {
115                         iface->timer_rs.cb = trigger_router_advert;
116                         trigger_router_advert(&iface->timer_rs);
117                 }
118
119                 if (iface->ra == RELAYD_RELAY || (iface->ra == RELAYD_SERVER && !iface->master))
120                         setsockopt(router_event.uloop.fd, IPPROTO_IPV6,
121                                         IPV6_ADD_MEMBERSHIP, mreq, sizeof(all_nodes));
122         }
123         return 0;
124 }
125
126
127 // Signal handler to resend all RDs
128 static void sigusr1_refresh(_unused int signal)
129 {
130         struct interface *iface;
131         list_for_each_entry(iface, &interfaces, head)
132                 if (iface->ra == RELAYD_SERVER && !iface->master)
133                         uloop_timeout_set(&iface->timer_rs, 1000);
134 }
135
136 static bool router_icmpv6_valid(struct sockaddr_in6 *source, uint8_t *data, size_t len)
137 {
138         struct icmp6_hdr *hdr = (struct icmp6_hdr *)data;
139         struct icmpv6_opt *opt, *end = (struct icmpv6_opt*)&data[len];
140
141         /* Hoplimit is already checked in odhcpd_receive_packets */
142         if (len < sizeof(*hdr) || hdr->icmp6_code)
143                 return false;
144
145         switch (hdr->icmp6_type) {
146         case ND_ROUTER_ADVERT:
147                 if (!IN6_IS_ADDR_LINKLOCAL(&source->sin6_addr))
148                         return false;
149
150                 opt = (struct icmpv6_opt *)((struct nd_router_advert *)data + 1);
151                 break;
152
153         case ND_ROUTER_SOLICIT:
154                 opt = (struct icmpv6_opt *)((struct nd_router_solicit *)data + 1);
155                 break;
156
157         default:
158                 return false;
159         }
160
161         icmpv6_for_each_option(opt, opt, end)
162                 if (opt->type == ND_OPT_SOURCE_LINKADDR &&
163                                 IN6_IS_ADDR_UNSPECIFIED(&source->sin6_addr) &&
164                                 hdr->icmp6_type == ND_ROUTER_SOLICIT)
165                         return false;
166
167         // Check all options parsed successfully
168         return opt == end;
169 }
170
171
172 // Detect whether a default route exists, also find the source prefixes
173 static bool parse_routes(struct odhcpd_ipaddr *n, ssize_t len)
174 {
175         rewind(fp_route);
176
177         char line[512], ifname[16];
178         bool found_default = false;
179         struct odhcpd_ipaddr p = {IN6ADDR_ANY_INIT, 0, 0, false, 0, 0, 0};
180         while (fgets(line, sizeof(line), fp_route)) {
181                 uint32_t rflags;
182                 if (sscanf(line, "00000000000000000000000000000000 00 "
183                                 "%*s %*s %*s %*s %*s %*s %*s %15s", ifname) &&
184                                 strcmp(ifname, "lo")) {
185                         found_default = true;
186                 } else if (sscanf(line, "%8" SCNx32 "%8" SCNx32 "%*8" SCNx32 "%*8" SCNx32 " %hhx %*s "
187                                 "%*s 00000000000000000000000000000000 %*s %*s %*s %" SCNx32 " lo",
188                                 &p.addr.s6_addr32[0], &p.addr.s6_addr32[1], &p.prefix, &rflags) &&
189                                 p.prefix > 0 && (rflags & RTF_NONEXTHOP) && (rflags & RTF_REJECT)) {
190                         // Find source prefixes by scanning through unreachable-routes
191                         p.addr.s6_addr32[0] = htonl(p.addr.s6_addr32[0]);
192                         p.addr.s6_addr32[1] = htonl(p.addr.s6_addr32[1]);
193
194                         for (ssize_t i = 0; i < len; ++i) {
195                                 if (n[i].prefix <= 64 && n[i].prefix >= p.prefix &&
196                                                 !odhcpd_bmemcmp(&p.addr, &n[i].addr, p.prefix)) {
197                                         n[i].dprefix = p.prefix;
198                                         break;
199                                 }
200                         }
201
202                 }
203         }
204
205         return found_default;
206 }
207
208
209 // Router Advert server mode
210 static uint64_t send_router_advert(struct interface *iface, const struct in6_addr *from)
211 {
212         int mtu = odhcpd_get_interface_mtu(iface->ifname);
213         if (mtu < 0)
214                 mtu = 1500;
215
216         struct {
217                 struct nd_router_advert h;
218                 struct icmpv6_opt lladdr;
219                 struct nd_opt_mtu mtu;
220                 struct nd_opt_prefix_info prefix[RELAYD_MAX_PREFIXES];
221         } adv = {
222                 .h = {{.icmp6_type = ND_ROUTER_ADVERT, .icmp6_code = 0}, 0, 0},
223                 .lladdr = {ND_OPT_SOURCE_LINKADDR, 1, {0}},
224                 .mtu = {ND_OPT_MTU, 1, 0, htonl(mtu)},
225         };
226
227         if (iface->dhcpv6)
228                 adv.h.nd_ra_flags_reserved = ND_RA_FLAG_OTHER;
229
230         if (iface->managed >= RELAYD_MANAGED_MFLAG)
231                 adv.h.nd_ra_flags_reserved |= ND_RA_FLAG_MANAGED;
232
233         if (iface->route_preference < 0)
234                 adv.h.nd_ra_flags_reserved |= ND_RA_PREF_LOW;
235         else if (iface->route_preference > 0)
236                 adv.h.nd_ra_flags_reserved |= ND_RA_PREF_HIGH;
237         odhcpd_get_mac(iface, adv.lladdr.data);
238
239         // If not currently shutting down
240         struct odhcpd_ipaddr addrs[RELAYD_MAX_PREFIXES];
241         ssize_t ipcnt = 0;
242         uint64_t maxpreferred = 0;
243
244         // If not shutdown
245         if (iface->timer_rs.cb) {
246                 ipcnt = odhcpd_get_interface_addresses(iface->ifindex,
247                                 addrs, ARRAY_SIZE(addrs));
248
249                 // Check default route
250                 if (parse_routes(addrs, ipcnt) || iface->default_router > 1)
251                         adv.h.nd_ra_router_lifetime =
252                                         htons(3 * MaxRtrAdvInterval);
253         }
254
255         // Construct Prefix Information options
256         bool have_public = false;
257         size_t cnt = 0;
258
259         struct in6_addr dns_pref = IN6ADDR_ANY_INIT, *dns_addr = &dns_pref;
260         uint32_t dns_time = 0;
261         size_t dns_cnt = 1;
262
263         for (ssize_t i = 0; i < ipcnt; ++i) {
264                 struct odhcpd_ipaddr *addr = &addrs[i];
265                 if (addr->prefix > 96 || addr->has_class)
266                         continue; // Address not suitable
267
268                 if (addr->preferred > MaxPreferredTime)
269                         addr->preferred = MaxPreferredTime;
270
271                 if (addr->valid > MaxValidTime)
272                         addr->valid = MaxValidTime;
273
274                 struct nd_opt_prefix_info *p = NULL;
275                 for (size_t i = 0; i < cnt; ++i) {
276                         if (addr->prefix == adv.prefix[i].nd_opt_pi_prefix_len &&
277                                         !odhcpd_bmemcmp(&adv.prefix[i].nd_opt_pi_prefix,
278                                         &addr->addr, addr->prefix))
279                                 p = &adv.prefix[i];
280                 }
281
282                 if (!p) {
283                         if (cnt >= ARRAY_SIZE(adv.prefix))
284                                 break;
285
286                         p = &adv.prefix[cnt++];
287                 }
288
289                 if ((addr->addr.s6_addr[0] & 0xfe) != 0xfc && addr->preferred > 0) {
290                         have_public = true;
291
292                         if (maxpreferred < 1000 * addr->preferred)
293                                 maxpreferred = 1000 * addr->preferred;
294                 }
295
296                 odhcpd_bmemcpy(&p->nd_opt_pi_prefix, &addr->addr,
297                                 (iface->ra_advrouter) ? 128 : addr->prefix);
298                 p->nd_opt_pi_type = ND_OPT_PREFIX_INFORMATION;
299                 p->nd_opt_pi_len = 4;
300                 p->nd_opt_pi_prefix_len = (addr->prefix < 64) ? 64 : addr->prefix;
301                 p->nd_opt_pi_flags_reserved = 0;
302                 if (!iface->ra_not_onlink)
303                         p->nd_opt_pi_flags_reserved |= ND_OPT_PI_FLAG_ONLINK;
304                 if (iface->managed < RELAYD_MANAGED_NO_AFLAG && addr->prefix <= 64)
305                         p->nd_opt_pi_flags_reserved |= ND_OPT_PI_FLAG_AUTO;
306                 if (iface->ra_advrouter)
307                         p->nd_opt_pi_flags_reserved |= ND_OPT_PI_FLAG_RADDR;
308                 p->nd_opt_pi_valid_time = htonl(addr->valid);
309                 p->nd_opt_pi_preferred_time = htonl(addr->preferred);
310
311                 if (addr->preferred > dns_time) {
312                         dns_time = addr->preferred;
313                         dns_pref = addr->addr;
314                 }
315         }
316
317         if (!have_public && !iface->default_router && adv.h.nd_ra_router_lifetime) {
318                 syslog(LOG_WARNING, "A default route is present but there is no public prefix "
319                                 "on %s thus we don't announce a default route!", iface->ifname);
320                 adv.h.nd_ra_router_lifetime = 0;
321         }
322
323         // DNS Recursive DNS
324         if (iface->dns_cnt > 0) {
325                 dns_addr = iface->dns;
326                 dns_cnt = iface->dns_cnt;
327                 dns_time = 2 * MaxRtrAdvInterval;
328         }
329
330         if (!dns_addr || IN6_IS_ADDR_UNSPECIFIED(dns_addr))
331                 dns_cnt = 0;
332
333         struct {
334                 uint8_t type;
335                 uint8_t len;
336                 uint8_t pad;
337                 uint8_t pad2;
338                 uint32_t lifetime;
339         } dns = {ND_OPT_RECURSIVE_DNS, (1 + (2 * dns_cnt)), 0, 0, htonl(dns_time)};
340
341
342
343         // DNS Search options
344         uint8_t search_buf[256], *search_domain = iface->search;
345         size_t search_len = iface->search_len, search_padded = 0;
346
347         if (!search_domain && !res_init() && _res.dnsrch[0] && _res.dnsrch[0][0]) {
348                 int len = dn_comp(_res.dnsrch[0], search_buf,
349                                 sizeof(search_buf), NULL, NULL);
350                 if (len > 0) {
351                         search_domain = search_buf;
352                         search_len = len;
353                 }
354         }
355
356         if (search_len > 0)
357                 search_padded = ((search_len + 7) & (~7)) + 8;
358
359         struct {
360                 uint8_t type;
361                 uint8_t len;
362                 uint8_t pad;
363                 uint8_t pad2;
364                 uint32_t lifetime;
365                 uint8_t name[];
366         } *search = alloca(sizeof(*search) + search_padded);
367
368         search->type = ND_OPT_DNS_SEARCH;
369         search->len = search_len ? ((sizeof(*search) + search_padded) / 8) : 0;
370         search->pad = 0;
371         search->pad2 = 0;
372         search->lifetime = htonl(2 * MaxRtrAdvInterval);;
373         memcpy(search->name, search_domain, search_len);
374         memset(&search->name[search_len], 0, search_padded - search_len);
375
376
377         size_t routes_cnt = 0;
378         struct {
379                 uint8_t type;
380                 uint8_t len;
381                 uint8_t prefix;
382                 uint8_t flags;
383                 uint32_t lifetime;
384                 uint32_t addr[4];
385         } routes[RELAYD_MAX_PREFIXES];
386
387         for (ssize_t i = 0; i < ipcnt; ++i) {
388                 struct odhcpd_ipaddr *addr = &addrs[i];
389                 if (addr->dprefix > 64 || addr->dprefix == 0 ||
390                                 (addr->dprefix == 64 && addr->prefix == 64)) {
391                         continue; // Address not suitable
392                 } else if (addr->dprefix > 32) {
393                         addr->addr.s6_addr32[1] &= htonl(~((1U << (64 - addr->dprefix)) - 1));
394                 } else if (addr->dprefix <= 32) {
395                         addr->addr.s6_addr32[0] &= htonl(~((1U << (32 - addr->dprefix)) - 1));
396                         addr->addr.s6_addr32[1] = 0;
397                 }
398
399                 routes[routes_cnt].type = ND_OPT_ROUTE_INFO;
400                 routes[routes_cnt].len = sizeof(*routes) / 8;
401                 routes[routes_cnt].prefix = addr->dprefix;
402                 routes[routes_cnt].flags = 0;
403                 if (iface->route_preference < 0)
404                         routes[routes_cnt].flags |= ND_RA_PREF_LOW;
405                 else if (iface->route_preference > 0)
406                         routes[routes_cnt].flags |= ND_RA_PREF_HIGH;
407                 routes[routes_cnt].lifetime = htonl(addr->valid);
408                 routes[routes_cnt].addr[0] = addr->addr.s6_addr32[0];
409                 routes[routes_cnt].addr[1] = addr->addr.s6_addr32[1];
410                 routes[routes_cnt].addr[2] = 0;
411                 routes[routes_cnt].addr[3] = 0;
412
413                 ++routes_cnt;
414         }
415
416         // Calculate periodic transmit
417         int msecs = 0;
418         uint32_t maxival = MaxRtrAdvInterval * 1000;
419         uint32_t minival = MinRtrAdvInterval * 1000;
420
421         if (maxpreferred > 0 && maxival > maxpreferred / 2) {
422                 maxival = maxpreferred / 2;
423                 if (maxival < 4000)
424                         maxival = 4000;
425
426                 if (maxival >= 9000)
427                         minival = maxival / 3;
428                 else
429                         minival = (maxival * 3) / 4;
430         }
431
432         odhcpd_urandom(&msecs, sizeof(msecs));
433         msecs = (labs(msecs) % (maxival - minival)) + minival;
434
435         struct icmpv6_opt adv_interval = {
436                 .type = ND_OPT_RTR_ADV_INTERVAL,
437                 .len = 1,
438                 .data = {0, 0, maxival >> 24, maxival >> 16, maxival >> 8, maxival}
439         };
440
441         struct iovec iov[] = {{&adv, (uint8_t*)&adv.prefix[cnt] - (uint8_t*)&adv},
442                         {&routes, routes_cnt * sizeof(*routes)},
443                         {&dns, (dns_cnt) ? sizeof(dns) : 0},
444                         {dns_addr, dns_cnt * sizeof(*dns_addr)},
445                         {search, search->len * 8},
446                         {&adv_interval, adv_interval.len * 8}};
447         struct sockaddr_in6 dest = {AF_INET6, 0, 0, ALL_IPV6_NODES, 0};
448
449         if (from && !IN6_IS_ADDR_UNSPECIFIED(from))
450                 dest.sin6_addr = *from;
451
452         odhcpd_send(router_event.uloop.fd,
453                         &dest, iov, ARRAY_SIZE(iov), iface);
454
455         return msecs;
456 }
457
458
459 static void trigger_router_advert(struct uloop_timeout *event)
460 {
461         struct interface *iface = container_of(event, struct interface, timer_rs);
462         int msecs = send_router_advert(iface, NULL);
463
464         // Rearm timer if not shut down
465         if (event->cb)
466                 uloop_timeout_set(event, msecs);
467 }
468
469
470 // Event handler for incoming ICMPv6 packets
471 static void handle_icmpv6(void *addr, void *data, size_t len,
472                 struct interface *iface, _unused void *dest)
473 {
474         struct icmp6_hdr *hdr = data;
475         struct sockaddr_in6 *from = addr;
476
477         if (!router_icmpv6_valid(addr, data, len))
478                 return;
479
480         if ((iface->ra == RELAYD_SERVER && !iface->master)) { // Server mode
481                 if (hdr->icmp6_type == ND_ROUTER_SOLICIT)
482                         send_router_advert(iface, &from->sin6_addr);
483         } else if (iface->ra == RELAYD_RELAY) { // Relay mode
484                 if (hdr->icmp6_type == ND_ROUTER_ADVERT && iface->master)
485                         forward_router_advertisement(data, len);
486                 else if (hdr->icmp6_type == ND_ROUTER_SOLICIT && !iface->master)
487                         forward_router_solicitation(odhcpd_get_master_interface());
488         }
489 }
490
491
492 // Forward router solicitation
493 static void forward_router_solicitation(const struct interface *iface)
494 {
495         if (!iface)
496                 return;
497
498         struct icmp6_hdr rs = {ND_ROUTER_SOLICIT, 0, 0, {{0}}};
499         struct iovec iov = {&rs, sizeof(rs)};
500         struct sockaddr_in6 all_routers =
501                 {AF_INET6, 0, 0, ALL_IPV6_ROUTERS, iface->ifindex};
502
503         syslog(LOG_NOTICE, "Sending RS to %s", iface->ifname);
504         odhcpd_send(router_event.uloop.fd, &all_routers, &iov, 1, iface);
505 }
506
507
508 // Handler for incoming router solicitations on slave interfaces
509 static void forward_router_advertisement(uint8_t *data, size_t len)
510 {
511         struct nd_router_advert *adv = (struct nd_router_advert *)data;
512
513         // Rewrite options
514         uint8_t *end = data + len;
515         uint8_t *mac_ptr = NULL;
516         struct in6_addr *dns_ptr = NULL;
517         size_t dns_count = 0;
518
519         struct icmpv6_opt *opt;
520         icmpv6_for_each_option(opt, &adv[1], end) {
521                 if (opt->type == ND_OPT_SOURCE_LINKADDR) {
522                         // Store address of source MAC-address
523                         mac_ptr = opt->data;
524                 } else if (opt->type == ND_OPT_RECURSIVE_DNS && opt->len > 1) {
525                         // Check if we have to rewrite DNS
526                         dns_ptr = (struct in6_addr*)&opt->data[6];
527                         dns_count = (opt->len - 1) / 2;
528                 }
529         }
530
531         syslog(LOG_NOTICE, "Got a RA");
532
533         // Indicate a proxy, however we don't follow the rest of RFC 4389 yet
534         adv->nd_ra_flags_reserved |= ND_RA_FLAG_PROXY;
535
536         // Forward advertisement to all slave interfaces
537         struct sockaddr_in6 all_nodes = {AF_INET6, 0, 0, ALL_IPV6_NODES, 0};
538         struct iovec iov = {data, len};
539
540         struct odhcpd_ipaddr addr;
541         struct interface *iface;
542         list_for_each_entry(iface, &interfaces, head) {
543                 if (iface->ra != RELAYD_RELAY || iface->master)
544                         continue;
545
546                 // Fixup source hardware address option
547                 if (mac_ptr)
548                         odhcpd_get_mac(iface, mac_ptr);
549
550                 // If we have to rewrite DNS entries
551                 if (iface->always_rewrite_dns && dns_ptr && dns_count > 0) {
552                         const struct in6_addr *rewrite = iface->dns;
553                         size_t rewrite_cnt = iface->dns_cnt;
554
555                         if (rewrite_cnt == 0) {
556                                 if (odhcpd_get_interface_addresses(iface->ifindex, &addr, 1) < 1)
557                                         continue; // Unable to comply
558
559                                 rewrite = &addr.addr;
560                                 rewrite_cnt = 1;
561                         }
562
563                         // Copy over any other addresses
564                         for (size_t i = 0; i < dns_count; ++i) {
565                                 size_t j = (i < rewrite_cnt) ? i : rewrite_cnt - 1;
566                                 dns_ptr[i] = rewrite[j];
567                         }
568                 }
569
570                 odhcpd_send(router_event.uloop.fd, &all_nodes, &iov, 1, iface);
571         }
572 }