Fix prefix class logic
[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);
34 static void send_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         struct ipv6_mreq all_nodes = {ALL_IPV6_NODES, iface->ifindex};
92         struct ipv6_mreq all_routers = {ALL_IPV6_ROUTERS, iface->ifindex};
93
94         uloop_timeout_cancel(&iface->timer_rs);
95         iface->timer_rs.cb = NULL;
96
97         setsockopt(router_event.uloop.fd, IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP,
98                         &all_nodes, sizeof(all_nodes));
99         setsockopt(router_event.uloop.fd, IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP,
100                         &all_routers, sizeof(all_routers));
101
102         if (!enable) {
103                 if (iface->ra)
104                         send_router_advert(&iface->timer_rs);
105         } else {
106                 void *mreq = &all_routers;
107
108                 if (iface->ra == RELAYD_RELAY && iface->master) {
109                         mreq = &all_nodes;
110                         forward_router_solicitation(iface);
111                 } else if (iface->ra == RELAYD_SERVER && !iface->master) {
112                         iface->timer_rs.cb = send_router_advert;
113                         send_router_advert(&iface->timer_rs);
114                 }
115
116                 if (iface->ra == RELAYD_RELAY || (iface->ra == RELAYD_SERVER && !iface->master))
117                         setsockopt(router_event.uloop.fd, IPPROTO_IPV6,
118                                         IPV6_ADD_MEMBERSHIP, mreq, sizeof(all_nodes));
119         }
120         return 0;
121 }
122
123
124 // Signal handler to resend all RDs
125 static void sigusr1_refresh(_unused int signal)
126 {
127         struct interface *iface;
128         list_for_each_entry(iface, &interfaces, head)
129                 if (iface->ra == RELAYD_SERVER && !iface->master)
130                         uloop_timeout_set(&iface->timer_rs, 1000);
131 }
132
133
134 // Event handler for incoming ICMPv6 packets
135 static void handle_icmpv6(_unused void *addr, void *data, size_t len,
136                 struct interface *iface)
137 {
138         struct icmp6_hdr *hdr = data;
139         if ((iface->ra == RELAYD_SERVER && !iface->master)) { // Server mode
140                 if (hdr->icmp6_type == ND_ROUTER_SOLICIT)
141                         send_router_advert(&iface->timer_rs);
142         } else if (iface->ra == RELAYD_RELAY) { // Relay mode
143                 if (hdr->icmp6_type == ND_ROUTER_ADVERT && iface->master)
144                         forward_router_advertisement(data, len);
145                 else if (hdr->icmp6_type == ND_ROUTER_SOLICIT && !iface->master)
146                         forward_router_solicitation(odhcpd_get_master_interface());
147         }
148 }
149
150
151 static bool match_route(const struct odhcpd_ipaddr *n, const struct in6_addr *addr)
152 {
153         if (n->prefix <= 32)
154                 return ntohl(n->addr.s6_addr32[0]) >> (32 - n->prefix) ==
155                                 ntohl(addr->s6_addr32[0]) >> (32 - n->prefix);
156
157         if (n->addr.s6_addr32[0] != addr->s6_addr32[0])
158                 return false;
159
160         return ntohl(n->addr.s6_addr32[1]) >> (64 - n->prefix) ==
161                         ntohl(addr->s6_addr32[1]) >> (64 - n->prefix);
162 }
163
164
165 // Detect whether a default route exists, also find the source prefixes
166 static bool parse_routes(struct odhcpd_ipaddr *n, ssize_t len)
167 {
168         rewind(fp_route);
169
170         char line[512], ifname[16];
171         bool found_default = false;
172         struct odhcpd_ipaddr p = {IN6ADDR_ANY_INIT, 0, false, 0, 0, 0};
173         while (fgets(line, sizeof(line), fp_route)) {
174                 uint32_t rflags;
175                 if (sscanf(line, "00000000000000000000000000000000 00 "
176                                 "%*s %*s %*s %*s %*s %*s %*s %15s", ifname) &&
177                                 strcmp(ifname, "lo")) {
178                         found_default = true;
179                 } else if (sscanf(line, "%8" SCNx32 "%8" SCNx32 "%*8" SCNx32 "%*8" SCNx32 " %hhx %*s "
180                                 "%*s 00000000000000000000000000000000 %*s %*s %*s %" SCNx32 " lo",
181                                 &p.addr.s6_addr32[0], &p.addr.s6_addr32[1], &p.prefix, &rflags) &&
182                                 p.prefix > 0 && (rflags & RTF_NONEXTHOP) && (rflags & RTF_REJECT)) {
183                         // Find source prefixes by scanning through unreachable-routes
184                         p.addr.s6_addr32[0] = htonl(p.addr.s6_addr32[0]);
185                         p.addr.s6_addr32[1] = htonl(p.addr.s6_addr32[1]);
186
187                         for (ssize_t i = 0; i < len; ++i) {
188                                 if (n[i].prefix <= 64 && n[i].prefix >= p.prefix &&
189                                                 match_route(&p, &n[i].addr)) {
190                                         n[i].prefix = p.prefix;
191                                         break;
192                                 }
193                         }
194
195                 }
196         }
197
198         return found_default;
199 }
200
201
202 // Router Advert server mode
203 static void send_router_advert(struct uloop_timeout *event)
204 {
205         struct interface *iface =
206                         container_of(event, struct interface, timer_rs);
207
208         int mtu = odhcpd_get_interface_mtu(iface->ifname);
209         if (mtu < 0)
210                 mtu = 1500;
211
212         struct {
213                 struct nd_router_advert h;
214                 struct icmpv6_opt lladdr;
215                 struct nd_opt_mtu mtu;
216                 struct nd_opt_prefix_info prefix[RELAYD_MAX_PREFIXES];
217         } adv = {
218                 .h = {{.icmp6_type = ND_ROUTER_ADVERT, .icmp6_code = 0}, 0, 0},
219                 .lladdr = {ND_OPT_SOURCE_LINKADDR, 1, {0}},
220                 .mtu = {ND_OPT_MTU, 1, 0, htonl(mtu)},
221         };
222         adv.h.nd_ra_flags_reserved = ND_RA_FLAG_OTHER;
223         if (iface->managed >= RELAYD_MANAGED_MFLAG)
224                 adv.h.nd_ra_flags_reserved |= ND_RA_FLAG_MANAGED;
225
226         if (iface->route_preference < 0)
227                 adv.h.nd_ra_flags_reserved |= ND_RA_PREF_LOW;
228         else if (iface->route_preference > 0)
229                 adv.h.nd_ra_flags_reserved |= ND_RA_PREF_HIGH;
230         odhcpd_get_mac(iface, adv.lladdr.data);
231
232         // If not currently shutting down
233         struct odhcpd_ipaddr addrs[RELAYD_MAX_PREFIXES];
234         ssize_t ipcnt = 0;
235
236         // If not shutdown
237         if (event->cb) {
238                 ipcnt = odhcpd_get_interface_addresses(iface->ifindex,
239                                 addrs, ARRAY_SIZE(addrs));
240
241                 // Check default route
242                 if (parse_routes(addrs, ipcnt) || iface->default_router > 1)
243                         adv.h.nd_ra_router_lifetime =
244                                         htons(3 * MaxRtrAdvInterval);
245         }
246
247         // Construct Prefix Information options
248         bool have_public = false;
249         size_t cnt = 0;
250
251         struct in6_addr *dns_addr = NULL;
252         uint32_t dns_time = 0;
253         size_t dns_cnt = 1;
254
255         for (ssize_t i = 0; i < ipcnt; ++i) {
256                 struct odhcpd_ipaddr *addr = &addrs[i];
257                 if (addr->prefix > 64 || addr->has_class)
258                         continue; // Address not suitable
259
260                 if (addr->preferred > MaxPreferredTime)
261                         addr->preferred = MaxPreferredTime;
262
263                 if (addr->valid > MaxValidTime)
264                         addr->valid = MaxValidTime;
265
266                 struct nd_opt_prefix_info *p = NULL;
267                 for (size_t i = 0; i < cnt; ++i) {
268                         if (!memcmp(&adv.prefix[i].nd_opt_pi_prefix,
269                                         &addr->addr, 8))
270                                 p = &adv.prefix[i];
271                 }
272
273                 if (!p) {
274                         if (cnt >= ARRAY_SIZE(adv.prefix))
275                                 break;
276
277                         p = &adv.prefix[cnt++];
278                 }
279
280                 if ((addr->addr.s6_addr[0] & 0xfe) != 0xfc && addr->preferred > 0)
281                         have_public = true;
282
283                 memcpy(&p->nd_opt_pi_prefix, &addr->addr, 8);
284                 p->nd_opt_pi_type = ND_OPT_PREFIX_INFORMATION;
285                 p->nd_opt_pi_len = 4;
286                 p->nd_opt_pi_prefix_len = 64;
287                 p->nd_opt_pi_flags_reserved = 0;
288                 if (!iface->ra_not_onlink)
289                         p->nd_opt_pi_flags_reserved |= ND_OPT_PI_FLAG_ONLINK;
290                 if (iface->managed < RELAYD_MANAGED_NO_AFLAG)
291                         p->nd_opt_pi_flags_reserved |= ND_OPT_PI_FLAG_AUTO;
292                 p->nd_opt_pi_valid_time = htonl(addr->valid);
293                 p->nd_opt_pi_preferred_time = htonl(addr->preferred);
294
295                 if (addr->preferred > dns_time) {
296                         dns_time = addr->preferred;
297                         dns_addr = &addr->addr;
298                 }
299         }
300
301         if (!have_public && !iface->default_router && adv.h.nd_ra_router_lifetime) {
302                 syslog(LOG_WARNING, "A default route is present but there is no public prefix "
303                                 "on %s thus we don't announce a default route!", iface->ifname);
304                 adv.h.nd_ra_router_lifetime = 0;
305         }
306
307         if (have_public && iface->deprecate_ula_if_public_avail)
308                 for (size_t i = 0; i < cnt; ++i)
309                         if ((adv.prefix[i].nd_opt_pi_prefix.s6_addr[0] & 0xfe) == 0xfc)
310                                 adv.prefix[i].nd_opt_pi_preferred_time = 0;
311
312         // DNS Recursive DNS
313         if (iface->dns_cnt > 0) {
314                 dns_addr = iface->dns;
315                 dns_cnt = iface->dns_cnt;
316                 dns_time = 2 * MaxRtrAdvInterval;
317         }
318
319         if (!dns_addr)
320                 dns_cnt = 0;
321
322         struct {
323                 uint8_t type;
324                 uint8_t len;
325                 uint8_t pad;
326                 uint8_t pad2;
327                 uint32_t lifetime;
328         } dns = {ND_OPT_RECURSIVE_DNS, (1 + (2 * dns_cnt)), 0, 0, htonl(dns_time)};
329
330
331
332         // DNS Search options
333         uint8_t search_buf[256], *search_domain = iface->search;
334         size_t search_len = iface->search_len, search_padded = 0;
335
336         if (!search_domain && !res_init() && _res.dnsrch[0] && _res.dnsrch[0][0]) {
337                 int len = dn_comp(_res.dnsrch[0], search_buf,
338                                 sizeof(search_buf), NULL, NULL);
339                 if (len > 0) {
340                         search_domain = search_buf;
341                         search_len = len;
342                 }
343         }
344
345         if (search_len > 0)
346                 search_padded = ((search_len + 7) & (~7)) + 8;
347
348         struct {
349                 uint8_t type;
350                 uint8_t len;
351                 uint8_t pad;
352                 uint8_t pad2;
353                 uint32_t lifetime;
354                 uint8_t name[];
355         } *search = alloca(sizeof(*search) + search_padded);
356         search->type = ND_OPT_DNS_SEARCH;
357         search->len = search_len ? ((sizeof(*search) + search_padded) / 8) : 0;
358         search->pad = 0;
359         search->pad2 = 0;
360         search->lifetime = htonl(2 * MaxRtrAdvInterval);;
361         memcpy(search->name, search_domain, search_len);
362         memset(&search->name[search_len], 0, search_padded - search_len);
363
364
365         size_t routes_cnt = 0;
366         struct {
367                 uint8_t type;
368                 uint8_t len;
369                 uint8_t prefix;
370                 uint8_t flags;
371                 uint32_t lifetime;
372                 uint32_t addr[4];
373         } routes[RELAYD_MAX_PREFIXES];
374
375         for (ssize_t i = 0; i < ipcnt; ++i) {
376                 struct odhcpd_ipaddr *addr = &addrs[i];
377                 if (addr->prefix > 64 || addr->prefix == 0) {
378                         continue; // Address not suitable
379                 } else if (addr->prefix > 32) {
380                         addr->addr.s6_addr32[1] &= htonl(~((1U << (64 - addr->prefix)) - 1));
381                 } else if (addr->prefix <= 32) {
382                         addr->addr.s6_addr32[0] &= htonl(~((1U << (32 - addr->prefix)) - 1));
383                         addr->addr.s6_addr32[1] = 0;
384                 }
385
386                 routes[routes_cnt].type = ND_OPT_ROUTE_INFO;
387                 routes[routes_cnt].len = sizeof(*routes) / 8;
388                 routes[routes_cnt].prefix = addr->prefix;
389                 routes[routes_cnt].flags = 0;
390                 if (iface->route_preference < 0)
391                         routes[routes_cnt].flags |= ND_RA_PREF_LOW;
392                 else if (iface->route_preference > 0)
393                         routes[routes_cnt].flags |= ND_RA_PREF_HIGH;
394                 routes[routes_cnt].lifetime = htonl(addr->valid);
395                 routes[routes_cnt].addr[0] = addr->addr.s6_addr32[0];
396                 routes[routes_cnt].addr[1] = addr->addr.s6_addr32[1];
397                 routes[routes_cnt].addr[2] = addr->addr.s6_addr32[2];
398                 routes[routes_cnt].addr[3] = addr->addr.s6_addr32[3];
399
400                 ++routes_cnt;
401         }
402
403
404         struct iovec iov[] = {{&adv, (uint8_t*)&adv.prefix[cnt] - (uint8_t*)&adv},
405                         {&routes, routes_cnt * sizeof(*routes)},
406                         {&dns, (dns_cnt) ? sizeof(dns) : 0},
407                         {dns_addr, dns_cnt * sizeof(*dns_addr)},
408                         {search, search->len * 8}};
409         struct sockaddr_in6 all_nodes = {AF_INET6, 0, 0, ALL_IPV6_NODES, 0};
410         odhcpd_send(router_event.uloop.fd,
411                         &all_nodes, iov, ARRAY_SIZE(iov), iface);
412
413         // Rearm timer
414         int msecs;
415         odhcpd_urandom(&msecs, sizeof(msecs));
416         msecs = (labs(msecs) % (1000 * (MaxRtrAdvInterval
417                         - MinRtrAdvInterval))) + (MinRtrAdvInterval * 1000);
418         uloop_timeout_set(&iface->timer_rs, msecs);
419 }
420
421
422 // Forward router solicitation
423 static void forward_router_solicitation(const struct interface *iface)
424 {
425         if (!iface)
426                 return;
427
428         struct icmp6_hdr rs = {ND_ROUTER_SOLICIT, 0, 0, {{0}}};
429         struct iovec iov = {&rs, sizeof(rs)};
430         struct sockaddr_in6 all_routers =
431                 {AF_INET6, 0, 0, ALL_IPV6_ROUTERS, iface->ifindex};
432
433         syslog(LOG_NOTICE, "Sending RS to %s", iface->ifname);
434         odhcpd_send(router_event.uloop.fd, &all_routers, &iov, 1, iface);
435 }
436
437
438 // Handler for incoming router solicitations on slave interfaces
439 static void forward_router_advertisement(uint8_t *data, size_t len)
440 {
441         struct nd_router_advert *adv = (struct nd_router_advert *)data;
442
443         // Rewrite options
444         uint8_t *end = data + len;
445         uint8_t *mac_ptr = NULL;
446         struct in6_addr *dns_ptr = NULL;
447         size_t dns_count = 0;
448
449         struct icmpv6_opt *opt;
450         icmpv6_for_each_option(opt, &adv[1], end) {
451                 if (opt->type == ND_OPT_SOURCE_LINKADDR) {
452                         // Store address of source MAC-address
453                         mac_ptr = opt->data;
454                 } else if (opt->type == ND_OPT_RECURSIVE_DNS && opt->len > 1) {
455                         // Check if we have to rewrite DNS
456                         dns_ptr = (struct in6_addr*)&opt->data[6];
457                         dns_count = (opt->len - 1) / 2;
458                 }
459         }
460
461         syslog(LOG_NOTICE, "Got a RA");
462
463         // Indicate a proxy, however we don't follow the rest of RFC 4389 yet
464         adv->nd_ra_flags_reserved |= ND_RA_FLAG_PROXY;
465
466         // Forward advertisement to all slave interfaces
467         struct sockaddr_in6 all_nodes = {AF_INET6, 0, 0, ALL_IPV6_NODES, 0};
468         struct iovec iov = {data, len};
469
470         struct odhcpd_ipaddr addr;
471         struct interface *iface;
472         list_for_each_entry(iface, &interfaces, head) {
473                 if (iface->ra != RELAYD_RELAY || iface->master)
474                         continue;
475
476                 // Fixup source hardware address option
477                 if (mac_ptr)
478                         odhcpd_get_mac(iface, mac_ptr);
479
480                 // If we have to rewrite DNS entries
481                 if (iface->always_rewrite_dns && dns_ptr && dns_count > 0) {
482                         const struct in6_addr *rewrite = iface->dns;
483                         size_t rewrite_cnt = iface->dns_cnt;
484
485                         if (rewrite_cnt == 0) {
486                                 if (odhcpd_get_interface_addresses(iface->ifindex, &addr, 1) < 1)
487                                         continue; // Unable to comply
488
489                                 rewrite = &addr.addr;
490                                 rewrite_cnt = 1;
491                         }
492
493                         // Copy over any other addresses
494                         for (size_t i = 0; i < dns_count; ++i) {
495                                 size_t j = (i < rewrite_cnt) ? i : rewrite_cnt - 1;
496                                 dns_ptr[i] = rewrite[j];
497                         }
498                 }
499
500                 odhcpd_send(router_event.uloop.fd, &all_nodes, &iov, 1, iface);
501         }
502 }