dhcpv4: add in_addr dhcpv4_mask and in_addr dhcpv4_addr to struct interface
[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, 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_config(iface->ifname, "mtu");
213         int hlim = odhcpd_get_interface_config(iface->ifname, "hop_limit");
214
215         if (mtu < 1280)
216                 mtu = 1280;
217
218         struct {
219                 struct nd_router_advert h;
220                 struct icmpv6_opt lladdr;
221                 struct nd_opt_mtu mtu;
222                 struct nd_opt_prefix_info prefix[RELAYD_MAX_PREFIXES];
223         } adv = {
224                 .h = {{.icmp6_type = ND_ROUTER_ADVERT, .icmp6_code = 0}, 0, 0},
225                 .lladdr = {ND_OPT_SOURCE_LINKADDR, 1, {0}},
226                 .mtu = {ND_OPT_MTU, 1, 0, htonl(mtu)},
227         };
228
229         if (hlim > 0)
230                 adv.h.nd_ra_curhoplimit = hlim;
231
232         if (iface->dhcpv6)
233                 adv.h.nd_ra_flags_reserved = ND_RA_FLAG_OTHER;
234
235         if (iface->managed >= RELAYD_MANAGED_MFLAG)
236                 adv.h.nd_ra_flags_reserved |= ND_RA_FLAG_MANAGED;
237
238         if (iface->route_preference < 0)
239                 adv.h.nd_ra_flags_reserved |= ND_RA_PREF_LOW;
240         else if (iface->route_preference > 0)
241                 adv.h.nd_ra_flags_reserved |= ND_RA_PREF_HIGH;
242         odhcpd_get_mac(iface, adv.lladdr.data);
243
244         // If not currently shutting down
245         struct odhcpd_ipaddr addrs[RELAYD_MAX_PREFIXES];
246         ssize_t ipcnt = 0;
247         uint64_t maxpreferred = 0;
248
249         // If not shutdown
250         if (iface->timer_rs.cb) {
251                 ipcnt = odhcpd_get_interface_addresses(iface->ifindex,
252                                 addrs, ARRAY_SIZE(addrs));
253
254                 // Check default route
255                 if (parse_routes(addrs, ipcnt) || iface->default_router > 1)
256                         adv.h.nd_ra_router_lifetime =
257                                         htons(3 * MaxRtrAdvInterval);
258         }
259
260         // Construct Prefix Information options
261         bool have_public = false;
262         size_t cnt = 0;
263
264         struct in6_addr dns_pref = IN6ADDR_ANY_INIT, *dns_addr = &dns_pref;
265         uint32_t dns_time = 0;
266         size_t dns_cnt = 1;
267
268         for (ssize_t i = 0; i < ipcnt; ++i) {
269                 struct odhcpd_ipaddr *addr = &addrs[i];
270                 if (addr->prefix > 96)
271                         continue; // Address not suitable
272
273                 if (addr->preferred > MaxPreferredTime)
274                         addr->preferred = MaxPreferredTime;
275
276                 if (addr->valid > MaxValidTime)
277                         addr->valid = MaxValidTime;
278
279                 struct nd_opt_prefix_info *p = NULL;
280                 for (size_t i = 0; i < cnt; ++i) {
281                         if (addr->prefix == adv.prefix[i].nd_opt_pi_prefix_len &&
282                                         !odhcpd_bmemcmp(&adv.prefix[i].nd_opt_pi_prefix,
283                                         &addr->addr, addr->prefix))
284                                 p = &adv.prefix[i];
285                 }
286
287                 if (!p) {
288                         if (cnt >= ARRAY_SIZE(adv.prefix))
289                                 break;
290
291                         p = &adv.prefix[cnt++];
292                 }
293
294                 if ((addr->addr.s6_addr[0] & 0xfe) != 0xfc && addr->preferred > 0) {
295                         have_public = true;
296
297                         if (maxpreferred < 1000 * addr->preferred)
298                                 maxpreferred = 1000 * addr->preferred;
299                 }
300
301                 odhcpd_bmemcpy(&p->nd_opt_pi_prefix, &addr->addr,
302                                 (iface->ra_advrouter) ? 128 : addr->prefix);
303                 p->nd_opt_pi_type = ND_OPT_PREFIX_INFORMATION;
304                 p->nd_opt_pi_len = 4;
305                 p->nd_opt_pi_prefix_len = (addr->prefix < 64) ? 64 : addr->prefix;
306                 p->nd_opt_pi_flags_reserved = 0;
307                 if (!iface->ra_not_onlink)
308                         p->nd_opt_pi_flags_reserved |= ND_OPT_PI_FLAG_ONLINK;
309                 if (iface->managed < RELAYD_MANAGED_NO_AFLAG && addr->prefix <= 64)
310                         p->nd_opt_pi_flags_reserved |= ND_OPT_PI_FLAG_AUTO;
311                 if (iface->ra_advrouter)
312                         p->nd_opt_pi_flags_reserved |= ND_OPT_PI_FLAG_RADDR;
313                 p->nd_opt_pi_valid_time = htonl(addr->valid);
314                 p->nd_opt_pi_preferred_time = htonl(addr->preferred);
315
316                 if (addr->preferred > dns_time) {
317                         dns_time = addr->preferred;
318                         dns_pref = addr->addr;
319                 }
320         }
321
322         if (!have_public && !iface->default_router && adv.h.nd_ra_router_lifetime) {
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                 dns_time = 2 * MaxRtrAdvInterval;
333         }
334
335         if (!dns_addr || IN6_IS_ADDR_UNSPECIFIED(dns_addr))
336                 dns_cnt = 0;
337
338         struct {
339                 uint8_t type;
340                 uint8_t len;
341                 uint8_t pad;
342                 uint8_t pad2;
343                 uint32_t lifetime;
344         } dns = {ND_OPT_RECURSIVE_DNS, (1 + (2 * dns_cnt)), 0, 0, htonl(dns_time)};
345
346
347
348         // DNS Search options
349         uint8_t search_buf[256], *search_domain = iface->search;
350         size_t search_len = iface->search_len, search_padded = 0;
351
352         if (!search_domain && !res_init() && _res.dnsrch[0] && _res.dnsrch[0][0]) {
353                 int len = dn_comp(_res.dnsrch[0], search_buf,
354                                 sizeof(search_buf), NULL, NULL);
355                 if (len > 0) {
356                         search_domain = search_buf;
357                         search_len = len;
358                 }
359         }
360
361         if (search_len > 0)
362                 search_padded = ((search_len + 7) & (~7)) + 8;
363
364         struct {
365                 uint8_t type;
366                 uint8_t len;
367                 uint8_t pad;
368                 uint8_t pad2;
369                 uint32_t lifetime;
370                 uint8_t name[];
371         } *search = alloca(sizeof(*search) + search_padded);
372
373         search->type = ND_OPT_DNS_SEARCH;
374         search->len = search_len ? ((sizeof(*search) + search_padded) / 8) : 0;
375         search->pad = 0;
376         search->pad2 = 0;
377         search->lifetime = htonl(2 * MaxRtrAdvInterval);;
378         memcpy(search->name, search_domain, search_len);
379         memset(&search->name[search_len], 0, search_padded - search_len);
380
381
382         size_t routes_cnt = 0;
383         struct {
384                 uint8_t type;
385                 uint8_t len;
386                 uint8_t prefix;
387                 uint8_t flags;
388                 uint32_t lifetime;
389                 uint32_t addr[4];
390         } routes[RELAYD_MAX_PREFIXES];
391
392         for (ssize_t i = 0; i < ipcnt; ++i) {
393                 struct odhcpd_ipaddr *addr = &addrs[i];
394                 if (addr->dprefix > 64 || addr->dprefix == 0 ||
395                                 (addr->dprefix == 64 && addr->prefix == 64)) {
396                         continue; // Address not suitable
397                 } else if (addr->dprefix > 32) {
398                         addr->addr.s6_addr32[1] &= htonl(~((1U << (64 - addr->dprefix)) - 1));
399                 } else if (addr->dprefix <= 32) {
400                         addr->addr.s6_addr32[0] &= htonl(~((1U << (32 - addr->dprefix)) - 1));
401                         addr->addr.s6_addr32[1] = 0;
402                 }
403
404                 routes[routes_cnt].type = ND_OPT_ROUTE_INFO;
405                 routes[routes_cnt].len = sizeof(*routes) / 8;
406                 routes[routes_cnt].prefix = addr->dprefix;
407                 routes[routes_cnt].flags = 0;
408                 if (iface->route_preference < 0)
409                         routes[routes_cnt].flags |= ND_RA_PREF_LOW;
410                 else if (iface->route_preference > 0)
411                         routes[routes_cnt].flags |= ND_RA_PREF_HIGH;
412                 routes[routes_cnt].lifetime = htonl(addr->valid);
413                 routes[routes_cnt].addr[0] = addr->addr.s6_addr32[0];
414                 routes[routes_cnt].addr[1] = addr->addr.s6_addr32[1];
415                 routes[routes_cnt].addr[2] = 0;
416                 routes[routes_cnt].addr[3] = 0;
417
418                 ++routes_cnt;
419         }
420
421         // Calculate periodic transmit
422         int msecs = 0;
423         uint32_t maxival = MaxRtrAdvInterval * 1000;
424         uint32_t minival = MinRtrAdvInterval * 1000;
425
426         if (maxpreferred > 0 && maxival > maxpreferred / 2) {
427                 maxival = maxpreferred / 2;
428                 if (maxival < 4000)
429                         maxival = 4000;
430
431                 if (maxival >= 9000)
432                         minival = maxival / 3;
433                 else
434                         minival = (maxival * 3) / 4;
435         }
436
437         odhcpd_urandom(&msecs, sizeof(msecs));
438         msecs = (labs(msecs) % (maxival - minival)) + minival;
439
440         struct icmpv6_opt adv_interval = {
441                 .type = ND_OPT_RTR_ADV_INTERVAL,
442                 .len = 1,
443                 .data = {0, 0, maxival >> 24, maxival >> 16, maxival >> 8, maxival}
444         };
445
446         struct iovec iov[] = {{&adv, (uint8_t*)&adv.prefix[cnt] - (uint8_t*)&adv},
447                         {&routes, routes_cnt * sizeof(*routes)},
448                         {&dns, (dns_cnt) ? sizeof(dns) : 0},
449                         {dns_addr, dns_cnt * sizeof(*dns_addr)},
450                         {search, search->len * 8},
451                         {&adv_interval, adv_interval.len * 8}};
452         struct sockaddr_in6 dest = {AF_INET6, 0, 0, ALL_IPV6_NODES, 0};
453
454         if (from && !IN6_IS_ADDR_UNSPECIFIED(from))
455                 dest.sin6_addr = *from;
456
457         odhcpd_send(router_event.uloop.fd,
458                         &dest, iov, ARRAY_SIZE(iov), iface);
459
460         return msecs;
461 }
462
463
464 static void trigger_router_advert(struct uloop_timeout *event)
465 {
466         struct interface *iface = container_of(event, struct interface, timer_rs);
467         int msecs = send_router_advert(iface, NULL);
468
469         // Rearm timer if not shut down
470         if (event->cb)
471                 uloop_timeout_set(event, msecs);
472 }
473
474
475 // Event handler for incoming ICMPv6 packets
476 static void handle_icmpv6(void *addr, void *data, size_t len,
477                 struct interface *iface, _unused void *dest)
478 {
479         struct icmp6_hdr *hdr = data;
480         struct sockaddr_in6 *from = addr;
481
482         if (!router_icmpv6_valid(addr, data, len))
483                 return;
484
485         if ((iface->ra == RELAYD_SERVER && !iface->master)) { // Server mode
486                 if (hdr->icmp6_type == ND_ROUTER_SOLICIT)
487                         send_router_advert(iface, &from->sin6_addr);
488         } else if (iface->ra == RELAYD_RELAY) { // Relay mode
489                 if (hdr->icmp6_type == ND_ROUTER_ADVERT && iface->master)
490                         forward_router_advertisement(data, len);
491                 else if (hdr->icmp6_type == ND_ROUTER_SOLICIT && !iface->master)
492                         forward_router_solicitation(odhcpd_get_master_interface());
493         }
494 }
495
496
497 // Forward router solicitation
498 static void forward_router_solicitation(const struct interface *iface)
499 {
500         if (!iface)
501                 return;
502
503         struct icmp6_hdr rs = {ND_ROUTER_SOLICIT, 0, 0, {{0}}};
504         struct iovec iov = {&rs, sizeof(rs)};
505         struct sockaddr_in6 all_routers =
506                 {AF_INET6, 0, 0, ALL_IPV6_ROUTERS, iface->ifindex};
507
508         syslog(LOG_NOTICE, "Sending RS to %s", iface->ifname);
509         odhcpd_send(router_event.uloop.fd, &all_routers, &iov, 1, iface);
510 }
511
512
513 // Handler for incoming router solicitations on slave interfaces
514 static void forward_router_advertisement(uint8_t *data, size_t len)
515 {
516         struct nd_router_advert *adv = (struct nd_router_advert *)data;
517
518         // Rewrite options
519         uint8_t *end = data + len;
520         uint8_t *mac_ptr = NULL;
521         struct in6_addr *dns_ptr = NULL;
522         size_t dns_count = 0;
523
524         struct icmpv6_opt *opt;
525         icmpv6_for_each_option(opt, &adv[1], end) {
526                 if (opt->type == ND_OPT_SOURCE_LINKADDR) {
527                         // Store address of source MAC-address
528                         mac_ptr = opt->data;
529                 } else if (opt->type == ND_OPT_RECURSIVE_DNS && opt->len > 1) {
530                         // Check if we have to rewrite DNS
531                         dns_ptr = (struct in6_addr*)&opt->data[6];
532                         dns_count = (opt->len - 1) / 2;
533                 }
534         }
535
536         syslog(LOG_NOTICE, "Got a RA");
537
538         // Indicate a proxy, however we don't follow the rest of RFC 4389 yet
539         adv->nd_ra_flags_reserved |= ND_RA_FLAG_PROXY;
540
541         // Forward advertisement to all slave interfaces
542         struct sockaddr_in6 all_nodes = {AF_INET6, 0, 0, ALL_IPV6_NODES, 0};
543         struct iovec iov = {data, len};
544
545         struct interface *iface;
546         list_for_each_entry(iface, &interfaces, head) {
547                 if (iface->ra != RELAYD_RELAY || iface->master)
548                         continue;
549
550                 // Fixup source hardware address option
551                 if (mac_ptr)
552                         odhcpd_get_mac(iface, mac_ptr);
553
554                 // If we have to rewrite DNS entries
555                 if (iface->always_rewrite_dns && dns_ptr && dns_count > 0) {
556                         const struct in6_addr *rewrite = iface->dns;
557                         struct in6_addr addr;
558                         size_t rewrite_cnt = iface->dns_cnt;
559
560                         if (rewrite_cnt == 0) {
561                                 if (odhcpd_get_preferred_interface_address(iface->ifindex, &addr) < 1)
562                                         continue; // Unable to comply
563
564                                 rewrite = &addr;
565                                 rewrite_cnt = 1;
566                         }
567
568                         // Copy over any other addresses
569                         for (size_t i = 0; i < dns_count; ++i) {
570                                 size_t j = (i < rewrite_cnt) ? i : rewrite_cnt - 1;
571                                 dns_ptr[i] = rewrite[j];
572                         }
573                 }
574
575                 odhcpd_send(router_event.uloop.fd, &all_nodes, &iov, 1, iface);
576         }
577 }