Fix DHCPv4 static leases (thanks arnd)
[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         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                         send_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 = send_router_advert;
116                         send_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 // Event handler for incoming ICMPv6 packets
172 static void handle_icmpv6(void *addr, void *data, size_t len,
173                 struct interface *iface)
174 {
175         struct icmp6_hdr *hdr = data;
176
177         if (!router_icmpv6_valid(addr, data, len))
178                 return;
179
180         if ((iface->ra == RELAYD_SERVER && !iface->master)) { // Server mode
181                 if (hdr->icmp6_type == ND_ROUTER_SOLICIT)
182                         send_router_advert(&iface->timer_rs);
183         } else if (iface->ra == RELAYD_RELAY) { // Relay mode
184                 if (hdr->icmp6_type == ND_ROUTER_ADVERT && iface->master)
185                         forward_router_advertisement(data, len);
186                 else if (hdr->icmp6_type == ND_ROUTER_SOLICIT && !iface->master)
187                         forward_router_solicitation(odhcpd_get_master_interface());
188         }
189 }
190
191
192 // Detect whether a default route exists, also find the source prefixes
193 static bool parse_routes(struct odhcpd_ipaddr *n, ssize_t len)
194 {
195         rewind(fp_route);
196
197         char line[512], ifname[16];
198         bool found_default = false;
199         struct odhcpd_ipaddr p = {IN6ADDR_ANY_INIT, 0, 0, false, 0, 0, 0};
200         while (fgets(line, sizeof(line), fp_route)) {
201                 uint32_t rflags;
202                 if (sscanf(line, "00000000000000000000000000000000 00 "
203                                 "%*s %*s %*s %*s %*s %*s %*s %15s", ifname) &&
204                                 strcmp(ifname, "lo")) {
205                         found_default = true;
206                 } else if (sscanf(line, "%8" SCNx32 "%8" SCNx32 "%*8" SCNx32 "%*8" SCNx32 " %hhx %*s "
207                                 "%*s 00000000000000000000000000000000 %*s %*s %*s %" SCNx32 " lo",
208                                 &p.addr.s6_addr32[0], &p.addr.s6_addr32[1], &p.prefix, &rflags) &&
209                                 p.prefix > 0 && (rflags & RTF_NONEXTHOP) && (rflags & RTF_REJECT)) {
210                         // Find source prefixes by scanning through unreachable-routes
211                         p.addr.s6_addr32[0] = htonl(p.addr.s6_addr32[0]);
212                         p.addr.s6_addr32[1] = htonl(p.addr.s6_addr32[1]);
213
214                         for (ssize_t i = 0; i < len; ++i) {
215                                 if (n[i].prefix <= 64 && n[i].prefix >= p.prefix &&
216                                                 !odhcpd_bmemcmp(&p.addr, &n[i].addr, p.prefix)) {
217                                         n[i].dprefix = p.prefix;
218                                         break;
219                                 }
220                         }
221
222                 }
223         }
224
225         return found_default;
226 }
227
228
229 // Router Advert server mode
230 static void send_router_advert(struct uloop_timeout *event)
231 {
232         struct interface *iface =
233                         container_of(event, struct interface, timer_rs);
234
235         int mtu = odhcpd_get_interface_mtu(iface->ifname);
236         if (mtu < 0)
237                 mtu = 1500;
238
239         struct {
240                 struct nd_router_advert h;
241                 struct icmpv6_opt lladdr;
242                 struct nd_opt_mtu mtu;
243                 struct nd_opt_prefix_info prefix[RELAYD_MAX_PREFIXES];
244         } adv = {
245                 .h = {{.icmp6_type = ND_ROUTER_ADVERT, .icmp6_code = 0}, 0, 0},
246                 .lladdr = {ND_OPT_SOURCE_LINKADDR, 1, {0}},
247                 .mtu = {ND_OPT_MTU, 1, 0, htonl(mtu)},
248         };
249
250         if (iface->dhcpv6)
251                 adv.h.nd_ra_flags_reserved = ND_RA_FLAG_OTHER;
252
253         if (iface->managed >= RELAYD_MANAGED_MFLAG)
254                 adv.h.nd_ra_flags_reserved |= ND_RA_FLAG_MANAGED;
255
256         if (iface->route_preference < 0)
257                 adv.h.nd_ra_flags_reserved |= ND_RA_PREF_LOW;
258         else if (iface->route_preference > 0)
259                 adv.h.nd_ra_flags_reserved |= ND_RA_PREF_HIGH;
260         odhcpd_get_mac(iface, adv.lladdr.data);
261
262         // If not currently shutting down
263         struct odhcpd_ipaddr addrs[RELAYD_MAX_PREFIXES];
264         ssize_t ipcnt = 0;
265         uint64_t maxpreferred = 0;
266
267         // If not shutdown
268         if (event->cb) {
269                 ipcnt = odhcpd_get_interface_addresses(iface->ifindex,
270                                 addrs, ARRAY_SIZE(addrs));
271
272                 // Check default route
273                 if (parse_routes(addrs, ipcnt) || iface->default_router > 1)
274                         adv.h.nd_ra_router_lifetime =
275                                         htons(3 * MaxRtrAdvInterval);
276         }
277
278         // Construct Prefix Information options
279         bool have_public = false;
280         size_t cnt = 0;
281
282         struct in6_addr dns_pref = IN6ADDR_ANY_INIT, *dns_addr = &dns_pref;
283         uint32_t dns_time = 0;
284         size_t dns_cnt = 1;
285
286         for (ssize_t i = 0; i < ipcnt; ++i) {
287                 struct odhcpd_ipaddr *addr = &addrs[i];
288                 if (addr->prefix > 96 || addr->has_class)
289                         continue; // Address not suitable
290
291                 if (addr->preferred > MaxPreferredTime)
292                         addr->preferred = MaxPreferredTime;
293
294                 if (addr->valid > MaxValidTime)
295                         addr->valid = MaxValidTime;
296
297                 struct nd_opt_prefix_info *p = NULL;
298                 for (size_t i = 0; i < cnt; ++i) {
299                         if (addr->prefix == adv.prefix[i].nd_opt_pi_prefix_len &&
300                                         !odhcpd_bmemcmp(&adv.prefix[i].nd_opt_pi_prefix,
301                                         &addr->addr, addr->prefix))
302                                 p = &adv.prefix[i];
303                 }
304
305                 if (!p) {
306                         if (cnt >= ARRAY_SIZE(adv.prefix))
307                                 break;
308
309                         p = &adv.prefix[cnt++];
310                 }
311
312                 if ((addr->addr.s6_addr[0] & 0xfe) != 0xfc && addr->preferred > 0) {
313                         have_public = true;
314
315                         if (maxpreferred < 1000 * addr->preferred)
316                                 maxpreferred = 1000 * addr->preferred;
317                 }
318
319                 odhcpd_bmemcpy(&p->nd_opt_pi_prefix, &addr->addr, addr->prefix);
320                 p->nd_opt_pi_type = ND_OPT_PREFIX_INFORMATION;
321                 p->nd_opt_pi_len = 4;
322                 p->nd_opt_pi_prefix_len = (addr->prefix < 64) ? 64 : addr->prefix;
323                 p->nd_opt_pi_flags_reserved = 0;
324                 if (!iface->ra_not_onlink)
325                         p->nd_opt_pi_flags_reserved |= ND_OPT_PI_FLAG_ONLINK;
326                 if (iface->managed < RELAYD_MANAGED_NO_AFLAG && addr->prefix <= 64)
327                         p->nd_opt_pi_flags_reserved |= ND_OPT_PI_FLAG_AUTO;
328                 p->nd_opt_pi_valid_time = htonl(addr->valid);
329                 p->nd_opt_pi_preferred_time = htonl(addr->preferred);
330
331                 if (addr->preferred > dns_time) {
332                         dns_time = addr->preferred;
333                         dns_pref = addr->addr;
334                 }
335         }
336
337         if (!have_public && !iface->default_router && adv.h.nd_ra_router_lifetime) {
338                 syslog(LOG_WARNING, "A default route is present but there is no public prefix "
339                                 "on %s thus we don't announce a default route!", iface->ifname);
340                 adv.h.nd_ra_router_lifetime = 0;
341         }
342
343         // DNS Recursive DNS
344         if (iface->dns_cnt > 0) {
345                 dns_addr = iface->dns;
346                 dns_cnt = iface->dns_cnt;
347                 dns_time = 2 * MaxRtrAdvInterval;
348         }
349
350         if (!dns_addr || IN6_IS_ADDR_UNSPECIFIED(dns_addr))
351                 dns_cnt = 0;
352
353         struct {
354                 uint8_t type;
355                 uint8_t len;
356                 uint8_t pad;
357                 uint8_t pad2;
358                 uint32_t lifetime;
359         } dns = {ND_OPT_RECURSIVE_DNS, (1 + (2 * dns_cnt)), 0, 0, htonl(dns_time)};
360
361
362
363         // DNS Search options
364         uint8_t search_buf[256], *search_domain = iface->search;
365         size_t search_len = iface->search_len, search_padded = 0;
366
367         if (!search_domain && !res_init() && _res.dnsrch[0] && _res.dnsrch[0][0]) {
368                 int len = dn_comp(_res.dnsrch[0], search_buf,
369                                 sizeof(search_buf), NULL, NULL);
370                 if (len > 0) {
371                         search_domain = search_buf;
372                         search_len = len;
373                 }
374         }
375
376         if (search_len > 0)
377                 search_padded = ((search_len + 7) & (~7)) + 8;
378
379         struct {
380                 uint8_t type;
381                 uint8_t len;
382                 uint8_t pad;
383                 uint8_t pad2;
384                 uint32_t lifetime;
385                 uint8_t name[];
386         } *search = alloca(sizeof(*search) + search_padded);
387
388         if (!search) {
389                 syslog(LOG_ERR, "Alloca failed for dns search on interface %s", iface->ifname);
390                 return;
391         }
392         search->type = ND_OPT_DNS_SEARCH;
393         search->len = search_len ? ((sizeof(*search) + search_padded) / 8) : 0;
394         search->pad = 0;
395         search->pad2 = 0;
396         search->lifetime = htonl(2 * MaxRtrAdvInterval);;
397         memcpy(search->name, search_domain, search_len);
398         memset(&search->name[search_len], 0, search_padded - search_len);
399
400
401         size_t routes_cnt = 0;
402         struct {
403                 uint8_t type;
404                 uint8_t len;
405                 uint8_t prefix;
406                 uint8_t flags;
407                 uint32_t lifetime;
408                 uint32_t addr[4];
409         } routes[RELAYD_MAX_PREFIXES];
410
411         for (ssize_t i = 0; i < ipcnt; ++i) {
412                 struct odhcpd_ipaddr *addr = &addrs[i];
413                 if (addr->dprefix > 64 || addr->dprefix == 0) {
414                         continue; // Address not suitable
415                 } else if (addr->dprefix > 32) {
416                         addr->addr.s6_addr32[1] &= htonl(~((1U << (64 - addr->dprefix)) - 1));
417                 } else if (addr->dprefix <= 32) {
418                         addr->addr.s6_addr32[0] &= htonl(~((1U << (32 - addr->dprefix)) - 1));
419                         addr->addr.s6_addr32[1] = 0;
420                 }
421
422                 routes[routes_cnt].type = ND_OPT_ROUTE_INFO;
423                 routes[routes_cnt].len = sizeof(*routes) / 8;
424                 routes[routes_cnt].prefix = addr->dprefix;
425                 routes[routes_cnt].flags = 0;
426                 if (iface->route_preference < 0)
427                         routes[routes_cnt].flags |= ND_RA_PREF_LOW;
428                 else if (iface->route_preference > 0)
429                         routes[routes_cnt].flags |= ND_RA_PREF_HIGH;
430                 routes[routes_cnt].lifetime = htonl(addr->valid);
431                 routes[routes_cnt].addr[0] = addr->addr.s6_addr32[0];
432                 routes[routes_cnt].addr[1] = addr->addr.s6_addr32[1];
433                 routes[routes_cnt].addr[2] = 0;
434                 routes[routes_cnt].addr[3] = 0;
435
436                 ++routes_cnt;
437         }
438
439
440         struct iovec iov[] = {{&adv, (uint8_t*)&adv.prefix[cnt] - (uint8_t*)&adv},
441                         {&routes, routes_cnt * sizeof(*routes)},
442                         {&dns, (dns_cnt) ? sizeof(dns) : 0},
443                         {dns_addr, dns_cnt * sizeof(*dns_addr)},
444                         {search, search->len * 8}};
445         struct sockaddr_in6 all_nodes = {AF_INET6, 0, 0, ALL_IPV6_NODES, 0};
446         odhcpd_send(router_event.uloop.fd,
447                         &all_nodes, iov, ARRAY_SIZE(iov), iface);
448
449         // Rearm timer if not shut down
450         if (event->cb) {
451                 uint32_t maxinterval = MaxRtrAdvInterval * 1000;
452                 uint32_t mininterval = MinRtrAdvInterval * 1000;
453
454                 if (maxpreferred > 0 && maxinterval > maxpreferred / 2) {
455                         maxinterval = maxpreferred / 2;
456                         if (maxinterval < 4000)
457                                 maxinterval = 4000;
458
459                         if (maxinterval >= 9000)
460                                 mininterval = maxinterval / 3;
461                         else
462                                 mininterval = (maxinterval * 3) / 4;
463                 }
464
465                 int msecs;
466                 odhcpd_urandom(&msecs, sizeof(msecs));
467                 msecs = (labs(msecs) % (maxinterval - mininterval)) + mininterval;
468                 uloop_timeout_set(&iface->timer_rs, msecs);
469         }
470 }
471
472
473 // Forward router solicitation
474 static void forward_router_solicitation(const struct interface *iface)
475 {
476         if (!iface)
477                 return;
478
479         struct icmp6_hdr rs = {ND_ROUTER_SOLICIT, 0, 0, {{0}}};
480         struct iovec iov = {&rs, sizeof(rs)};
481         struct sockaddr_in6 all_routers =
482                 {AF_INET6, 0, 0, ALL_IPV6_ROUTERS, iface->ifindex};
483
484         syslog(LOG_NOTICE, "Sending RS to %s", iface->ifname);
485         odhcpd_send(router_event.uloop.fd, &all_routers, &iov, 1, iface);
486 }
487
488
489 // Handler for incoming router solicitations on slave interfaces
490 static void forward_router_advertisement(uint8_t *data, size_t len)
491 {
492         struct nd_router_advert *adv = (struct nd_router_advert *)data;
493
494         // Rewrite options
495         uint8_t *end = data + len;
496         uint8_t *mac_ptr = NULL;
497         struct in6_addr *dns_ptr = NULL;
498         size_t dns_count = 0;
499
500         struct icmpv6_opt *opt;
501         icmpv6_for_each_option(opt, &adv[1], end) {
502                 if (opt->type == ND_OPT_SOURCE_LINKADDR) {
503                         // Store address of source MAC-address
504                         mac_ptr = opt->data;
505                 } else if (opt->type == ND_OPT_RECURSIVE_DNS && opt->len > 1) {
506                         // Check if we have to rewrite DNS
507                         dns_ptr = (struct in6_addr*)&opt->data[6];
508                         dns_count = (opt->len - 1) / 2;
509                 }
510         }
511
512         syslog(LOG_NOTICE, "Got a RA");
513
514         // Indicate a proxy, however we don't follow the rest of RFC 4389 yet
515         adv->nd_ra_flags_reserved |= ND_RA_FLAG_PROXY;
516
517         // Forward advertisement to all slave interfaces
518         struct sockaddr_in6 all_nodes = {AF_INET6, 0, 0, ALL_IPV6_NODES, 0};
519         struct iovec iov = {data, len};
520
521         struct odhcpd_ipaddr addr;
522         struct interface *iface;
523         list_for_each_entry(iface, &interfaces, head) {
524                 if (iface->ra != RELAYD_RELAY || iface->master)
525                         continue;
526
527                 // Fixup source hardware address option
528                 if (mac_ptr)
529                         odhcpd_get_mac(iface, mac_ptr);
530
531                 // If we have to rewrite DNS entries
532                 if (iface->always_rewrite_dns && dns_ptr && dns_count > 0) {
533                         const struct in6_addr *rewrite = iface->dns;
534                         size_t rewrite_cnt = iface->dns_cnt;
535
536                         if (rewrite_cnt == 0) {
537                                 if (odhcpd_get_interface_addresses(iface->ifindex, &addr, 1) < 1)
538                                         continue; // Unable to comply
539
540                                 rewrite = &addr.addr;
541                                 rewrite_cnt = 1;
542                         }
543
544                         // Copy over any other addresses
545                         for (size_t i = 0; i < dns_count; ++i) {
546                                 size_t j = (i < rewrite_cnt) ? i : rewrite_cnt - 1;
547                                 dns_ptr[i] = rewrite[j];
548                         }
549                 }
550
551                 odhcpd_send(router_event.uloop.fd, &all_nodes, &iov, 1, iface);
552         }
553 }