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