ra: align ifindex resolving
[project/odhcp6c.git] / src / ra.c
1 /**
2 * Copyright (C) 2012-2014 Steven Barth <steven@midlink.org>
3 * Copyright (C) 2017-2018 Hans Dedecker <dedeckeh@gmail.com>
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License v2 as published by
7 * the Free Software Foundation.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 */
15
16 #include <errno.h>
17 #include <fcntl.h>
18 #include <stdio.h>
19 #include <signal.h>
20 #include <string.h>
21 #include <stddef.h>
22 #include <stdbool.h>
23 #include <syslog.h>
24 #include <unistd.h>
25 #include <resolv.h>
26 #include <alloca.h>
27
28 #include <net/if.h>
29 #include <arpa/inet.h>
30 #include <sys/ioctl.h>
31 #include <sys/socket.h>
32 #include <sys/types.h>
33 #include <netinet/in.h>
34 #include <netinet/icmp6.h>
35
36 #include <linux/rtnetlink.h>
37
38 #ifndef SOL_NETLINK
39 #define SOL_NETLINK 270
40 #endif
41
42 #ifndef NETLINK_ADD_MEMBERSHIP
43 #define NETLINK_ADD_MEMBERSHIP 1
44 #endif
45
46 #ifndef IFF_LOWER_UP
47 #define IFF_LOWER_UP 0x10000
48 #endif
49
50 #include "odhcp6c.h"
51 #include "ra.h"
52
53 static bool nocarrier = false;
54
55 static int sock = -1, rtnl = -1;
56 static int if_index = 0;
57 static char if_name[IF_NAMESIZE] = {0};
58 static volatile int rs_attempt = 0;
59 static struct in6_addr lladdr = IN6ADDR_ANY_INIT;
60 static unsigned int ra_options = 0;
61 static unsigned int ra_holdoff_interval = 0;
62 static int ra_hoplimit = 0;
63 static int ra_mtu = 0;
64 static int ra_reachable = 0;
65 static int ra_retransmit = 0;
66
67 struct {
68 struct icmp6_hdr hdr;
69 struct icmpv6_opt lladdr;
70 } rs = {
71 .hdr = {ND_ROUTER_SOLICIT, 0, 0, {{0}}},
72 .lladdr = {ND_OPT_SOURCE_LINKADDR, 1, {0}},
73 };
74
75 static void ra_send_rs(int signal __attribute__((unused)));
76
77 int ra_init(const char *ifname, const struct in6_addr *ifid,
78 unsigned int options, unsigned int holdoff_interval)
79 {
80 struct ifreq ifr;
81
82 ra_options = options;
83 ra_holdoff_interval = holdoff_interval;
84
85 const pid_t ourpid = getpid();
86 sock = socket(AF_INET6, SOCK_RAW | SOCK_CLOEXEC, IPPROTO_ICMPV6);
87 if (sock < 0)
88 goto failure;
89
90 memset(&ifr, 0, sizeof(ifr));
91 strncpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name) - 1);
92 if (ioctl(sock, SIOCGIFINDEX, &ifr) < 0)
93 goto failure;
94
95 if_index = ifr.ifr_ifindex;
96 lladdr = *ifid;
97
98 rtnl = socket(AF_NETLINK, SOCK_DGRAM | SOCK_CLOEXEC, NETLINK_ROUTE);
99 if (rtnl < 0)
100 goto failure;
101
102 struct sockaddr_nl rtnl_kernel = { .nl_family = AF_NETLINK };
103 if (connect(rtnl, (const struct sockaddr*)&rtnl_kernel, sizeof(rtnl_kernel)) < 0)
104 goto failure;
105
106 int val = RTNLGRP_LINK;
107 if (setsockopt(rtnl, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP, &val, sizeof(val)) < 0)
108 goto failure;
109
110 if (fcntl(rtnl, F_SETOWN, ourpid) < 0)
111 goto failure;
112
113 if (fcntl(rtnl, F_SETFL, fcntl(sock, F_GETFL) | O_ASYNC) < 0)
114 goto failure;
115
116 struct {
117 struct nlmsghdr hdr;
118 struct ifinfomsg ifi;
119 } req = {
120 .hdr = {sizeof(req), RTM_GETLINK, NLM_F_REQUEST, 1, 0},
121 .ifi = {.ifi_index = if_index}
122 };
123 if (send(rtnl, &req, sizeof(req), 0) < 0)
124 goto failure;
125
126 ra_link_up();
127
128 // Filter ICMPv6 package types
129 struct icmp6_filter filt;
130 ICMP6_FILTER_SETBLOCKALL(&filt);
131 ICMP6_FILTER_SETPASS(ND_ROUTER_ADVERT, &filt);
132 if (setsockopt(sock, IPPROTO_ICMPV6, ICMP6_FILTER, &filt, sizeof(filt)) < 0)
133 goto failure;
134
135 // Bind to all-nodes
136 struct ipv6_mreq an = {ALL_IPV6_NODES, if_index};
137 if (setsockopt(sock, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, &an, sizeof(an)) < 0)
138 goto failure;
139
140 // Let the kernel compute our checksums
141 val = 2;
142 if (setsockopt(sock, IPPROTO_RAW, IPV6_CHECKSUM, &val, sizeof(val)) < 0)
143 goto failure;
144
145 // This is required by RFC 4861
146 val = 255;
147 if (setsockopt(sock, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &val, sizeof(val)) < 0)
148 goto failure;
149
150 // Receive multicast hops
151 val = 1;
152 if (setsockopt(sock, IPPROTO_IPV6, IPV6_RECVHOPLIMIT, &val, sizeof(val)) < 0)
153 goto failure;
154
155 // Bind to one device
156 if (setsockopt(sock, SOL_SOCKET, SO_BINDTODEVICE, ifname, strlen(ifname)) < 0)
157 goto failure;
158
159 // Add async-mode
160 if (fcntl(sock, F_SETOWN, ourpid) < 0)
161 goto failure;
162
163 val = fcntl(sock, F_GETFL);
164 if (val < 0)
165 goto failure;
166
167 if (fcntl(sock, F_SETFL, val | O_ASYNC) < 0)
168 goto failure;
169
170 // Send RS
171 signal(SIGALRM, ra_send_rs);
172 ra_send_rs(SIGALRM);
173
174 return 0;
175
176 failure:
177 if (sock >= 0)
178 close(sock);
179
180 if (rtnl >= 0)
181 close(rtnl);
182
183 return -1;
184 }
185
186 static void ra_send_rs(int signal __attribute__((unused)))
187 {
188 const struct sockaddr_in6 dest = {AF_INET6, 0, 0, ALL_IPV6_ROUTERS, if_index};
189 const struct icmpv6_opt llnull = {ND_OPT_SOURCE_LINKADDR, 1, {0}};
190 size_t len;
191
192 if ((rs_attempt % 2 == 0) && memcmp(&rs.lladdr, &llnull, sizeof(llnull)))
193 len = sizeof(rs);
194 else
195 len = sizeof(struct icmp6_hdr);
196
197 if (sendto(sock, &rs, len, MSG_DONTWAIT, (struct sockaddr*)&dest, sizeof(dest)) < 0)
198 syslog(LOG_ERR, "Failed to send RS (%s)", strerror(errno));
199
200 if (++rs_attempt <= 3)
201 alarm(4);
202 }
203
204 static int16_t pref_to_priority(uint8_t flags)
205 {
206 flags = (flags >> 3) & 0x03;
207
208 return (flags == 0x0) ? 512 : (flags == 0x1) ? 384 :
209 (flags == 0x3) ? 640 : -1;
210 }
211
212 bool ra_link_up(void)
213 {
214 static bool firstcall = true;
215 struct {
216 struct nlmsghdr hdr;
217 struct ifinfomsg msg;
218 uint8_t pad[4000];
219 } resp;
220 bool ret = false;
221 ssize_t read;
222
223 do {
224 read = recv(rtnl, &resp, sizeof(resp), MSG_DONTWAIT);
225
226 if (read < 0 || !NLMSG_OK(&resp.hdr, (size_t)read) ||
227 resp.hdr.nlmsg_type != RTM_NEWLINK ||
228 resp.msg.ifi_index != if_index)
229 continue;
230
231 ssize_t alen = NLMSG_PAYLOAD(&resp.hdr, sizeof(resp.msg));
232 for (struct rtattr *rta = (struct rtattr*)(resp.pad);
233 RTA_OK(rta, alen); rta = RTA_NEXT(rta, alen)) {
234 if (rta->rta_type == IFLA_ADDRESS &&
235 RTA_PAYLOAD(rta) >= sizeof(rs.lladdr.data))
236 memcpy(rs.lladdr.data, RTA_DATA(rta), sizeof(rs.lladdr.data));
237 }
238
239 bool hascarrier = resp.msg.ifi_flags & IFF_LOWER_UP;
240 if (!firstcall && nocarrier != !hascarrier)
241 ret = true;
242
243 nocarrier = !hascarrier;
244 firstcall = false;
245 } while (read > 0);
246
247 if (ret) {
248 syslog(LOG_NOTICE, "carrier => %i event on %s", (int)!nocarrier, if_name);
249
250 rs_attempt = 0;
251 ra_send_rs(SIGALRM);
252 }
253
254 return ret;
255 }
256
257 static bool ra_icmpv6_valid(struct sockaddr_in6 *source, int hlim, uint8_t *data, size_t len)
258 {
259 struct icmp6_hdr *hdr = (struct icmp6_hdr*)data;
260 struct icmpv6_opt *opt, *end = (struct icmpv6_opt*)&data[len];
261
262 if (hlim != 255 || len < sizeof(*hdr) || hdr->icmp6_code)
263 return false;
264
265 switch (hdr->icmp6_type) {
266 case ND_ROUTER_ADVERT:
267 if (!IN6_IS_ADDR_LINKLOCAL(&source->sin6_addr))
268 return false;
269
270 opt = (struct icmpv6_opt*)((struct nd_router_advert*)data + 1);
271 break;
272
273 default:
274 return false;
275 }
276
277 icmpv6_for_each_option(opt, opt, end)
278 ;
279
280 return opt == end;
281 }
282
283 static bool ra_set_hoplimit(int val)
284 {
285 if (val > 0 && val != ra_hoplimit) {
286 ra_hoplimit = val;
287 return true;
288 }
289
290 return false;
291 }
292
293 static bool ra_set_mtu(int val)
294 {
295 if (val >= 1280 && val <= 65535 && ra_mtu != val) {
296 ra_mtu = val;
297 return true;
298 }
299
300 return false;
301 }
302
303 static bool ra_set_reachable(int val)
304 {
305 if (val > 0 && val <= 3600000 && ra_reachable != val) {
306 ra_reachable = val;
307 return true;
308 }
309
310 return false;
311 }
312
313 static bool ra_set_retransmit(int val)
314 {
315 if (val > 0 && val <= 60000 && ra_retransmit != val) {
316 ra_retransmit = val;
317 return true;
318 }
319
320 return false;
321 }
322
323 int ra_get_hoplimit(void)
324 {
325 return ra_hoplimit;
326 }
327
328 int ra_get_mtu(void)
329 {
330 return ra_mtu;
331 }
332
333 int ra_get_reachable(void)
334 {
335 return ra_reachable;
336 }
337
338 int ra_get_retransmit(void)
339 {
340 return ra_retransmit;
341 }
342
343 bool ra_process(void)
344 {
345 bool found = false;
346 bool changed = false;
347 uint8_t buf[1500] _aligned(4);
348 union {
349 struct cmsghdr hdr;
350 uint8_t buf[CMSG_SPACE(sizeof(int))];
351 } cmsg_buf;
352 struct nd_router_advert *adv = (struct nd_router_advert*)buf;
353 struct odhcp6c_entry *entry = alloca(sizeof(*entry) + 256);
354 const struct in6_addr any = IN6ADDR_ANY_INIT;
355
356 memset(entry, 0, sizeof(*entry));
357
358 if (IN6_IS_ADDR_UNSPECIFIED(&lladdr)) {
359 struct sockaddr_in6 addr = {AF_INET6, 0, 0, ALL_IPV6_ROUTERS, if_index};
360 socklen_t alen = sizeof(addr);
361 int sock = socket(AF_INET6, SOCK_RAW, IPPROTO_ICMPV6);
362
363 if (sock >= 0) {
364 if (!connect(sock, (struct sockaddr*)&addr, sizeof(addr)) &&
365 !getsockname(sock, (struct sockaddr*)&addr, &alen))
366 lladdr = addr.sin6_addr;
367
368 close(sock);
369 }
370 }
371
372 while (true) {
373 struct sockaddr_in6 from;
374 struct iovec iov = {buf, sizeof(buf)};
375 struct msghdr msg = {
376 .msg_name = (void *) &from,
377 .msg_namelen = sizeof(from),
378 .msg_iov = &iov,
379 .msg_iovlen = 1,
380 .msg_control = cmsg_buf.buf,
381 .msg_controllen = sizeof(cmsg_buf),
382 .msg_flags = 0
383 };
384 struct icmpv6_opt *opt;
385 uint32_t router_valid;
386 int hlim = 0;
387
388 ssize_t len = recvmsg(sock, &msg, MSG_DONTWAIT);
389 if (len <= 0)
390 break;
391
392 if (IN6_IS_ADDR_UNSPECIFIED(&lladdr))
393 continue;
394
395 for (struct cmsghdr *ch = CMSG_FIRSTHDR(&msg); ch != NULL;
396 ch = CMSG_NXTHDR(&msg, ch))
397 if (ch->cmsg_level == IPPROTO_IPV6 &&
398 ch->cmsg_type == IPV6_HOPLIMIT)
399 memcpy(&hlim, CMSG_DATA(ch), sizeof(hlim));
400
401 if (!ra_icmpv6_valid(&from, hlim, buf, len))
402 continue;
403
404 if (!found) {
405 odhcp6c_expire();
406 found = true;
407 }
408
409 router_valid = ntohs(adv->nd_ra_router_lifetime);
410
411 /* RFC4861 ยง6.3.7
412 * Once the host sends a Router Solicitation, and receives a valid
413 * Router Advertisement with a non-zero Router Lifetime, the host MUST
414 * desist from sending additional solicitations on that interface
415 * Moreover, a host SHOULD send at least one solicitation in the case
416 * where an advertisement is received prior to having sent a solicitation.
417 */
418 if (rs_attempt > 0 && router_valid > 0) {
419 alarm(0);
420 rs_attempt = 0;
421 }
422
423 // Parse default route
424 entry->target = any;
425 entry->length = 0;
426 entry->router = from.sin6_addr;
427 entry->priority = pref_to_priority(adv->nd_ra_flags_reserved);
428 if (entry->priority < 0)
429 entry->priority = pref_to_priority(0);
430
431 entry->valid = router_valid;
432 entry->preferred = entry->valid;
433 changed |= odhcp6c_update_entry(STATE_RA_ROUTE, entry,
434 0, ra_holdoff_interval);
435
436 // Parse hoplimit
437 changed |= ra_set_hoplimit(adv->nd_ra_curhoplimit);
438
439 // Parse ND parameters
440 changed |= ra_set_reachable(ntohl(adv->nd_ra_reachable));
441 changed |= ra_set_retransmit(ntohl(adv->nd_ra_retransmit));
442
443 // Evaluate options
444 icmpv6_for_each_option(opt, &adv[1], &buf[len]) {
445 if (opt->type == ND_OPT_MTU) {
446 uint32_t *mtu = (uint32_t*)&opt->data[2];
447 changed |= ra_set_mtu(ntohl(*mtu));
448 } else if (opt->type == ND_OPT_ROUTE_INFORMATION && opt->len <= 3) {
449 struct icmpv6_opt_route_info *ri = (struct icmpv6_opt_route_info *)opt;
450
451 if (ri->prefix_len > 128) {
452 continue;
453 } else if (ri->prefix_len > 64) {
454 if (ri->len < 2)
455 continue;
456 } else if (ri->prefix_len > 0) {
457 if (ri->len < 1)
458 continue;
459 }
460
461 entry->router = from.sin6_addr;
462 entry->target = any;
463 entry->priority = pref_to_priority(ri->flags);
464 entry->length = ri->prefix_len;
465 entry->valid = ntohl(ri->lifetime);
466 memcpy(&entry->target, ri->prefix, (ri->len - 1) * 8);
467
468 if (IN6_IS_ADDR_LINKLOCAL(&entry->target)
469 || IN6_IS_ADDR_LOOPBACK(&entry->target)
470 || IN6_IS_ADDR_MULTICAST(&entry->target))
471 continue;
472
473 if (entry->priority > 0)
474 changed |= odhcp6c_update_entry(STATE_RA_ROUTE, entry,
475 0, ra_holdoff_interval);
476 } else if (opt->type == ND_OPT_PREFIX_INFORMATION && opt->len == 4) {
477 struct nd_opt_prefix_info *pinfo = (struct nd_opt_prefix_info*)opt;
478 entry->router = any;
479 entry->target = pinfo->nd_opt_pi_prefix;
480 entry->priority = 256;
481 entry->length = pinfo->nd_opt_pi_prefix_len;
482 entry->valid = ntohl(pinfo->nd_opt_pi_valid_time);
483 entry->preferred = ntohl(pinfo->nd_opt_pi_preferred_time);
484
485 if (entry->length > 128 || IN6_IS_ADDR_LINKLOCAL(&entry->target)
486 || IN6_IS_ADDR_LOOPBACK(&entry->target)
487 || IN6_IS_ADDR_MULTICAST(&entry->target)
488 || entry->valid < entry->preferred)
489 continue;
490
491 if (pinfo->nd_opt_pi_flags_reserved & ND_OPT_PI_FLAG_ONLINK)
492 changed |= odhcp6c_update_entry(STATE_RA_ROUTE, entry,
493 7200, ra_holdoff_interval);
494
495 if (!(pinfo->nd_opt_pi_flags_reserved & ND_OPT_PI_FLAG_AUTO) ||
496 pinfo->nd_opt_pi_prefix_len != 64)
497 continue;
498
499 entry->target.s6_addr32[2] = lladdr.s6_addr32[2];
500 entry->target.s6_addr32[3] = lladdr.s6_addr32[3];
501
502 changed |= odhcp6c_update_entry(STATE_RA_PREFIX, entry,
503 7200, ra_holdoff_interval);
504 } else if (opt->type == ND_OPT_RECURSIVE_DNS && opt->len > 2) {
505 entry->router = from.sin6_addr;
506 entry->priority = 0;
507 entry->length = 128;
508 uint32_t *valid = (uint32_t*)&opt->data[2];
509 entry->valid = ntohl(*valid);
510 entry->preferred = 0;
511
512 for (ssize_t i = 0; i < (opt->len - 1) / 2; ++i) {
513 memcpy(&entry->target, &opt->data[6 + i * sizeof(entry->target)],
514 sizeof(entry->target));
515 changed |= odhcp6c_update_entry(STATE_RA_DNS, entry,
516 0, ra_holdoff_interval);
517 }
518 } else if (opt->type == ND_OPT_DNSSL && opt->len > 1) {
519 uint32_t *valid = (uint32_t*)&opt->data[2];
520 uint8_t *buf = &opt->data[6];
521 uint8_t *end = &buf[(opt->len - 1) * 8];
522
523 entry->router = from.sin6_addr;
524 entry->valid = ntohl(*valid);
525
526 while (buf < end) {
527 int len = dn_expand(buf, end, buf, (char*)entry->auxtarget, 256);
528 if (len < 1)
529 break;
530
531 buf = &buf[len];
532 entry->auxlen = strlen((char*)entry->auxtarget);
533
534 if (entry->auxlen == 0)
535 continue;
536
537 changed |= odhcp6c_update_entry(STATE_RA_SEARCH, entry,
538 0, ra_holdoff_interval);
539 entry->auxlen = 0;
540 }
541 }
542 }
543
544 if (ra_options & RA_RDNSS_DEFAULT_LIFETIME) {
545 int states[2] = {STATE_RA_DNS, STATE_RA_SEARCH};
546
547 for (size_t i = 0; i < 2; ++i) {
548 size_t ra_dns_len;
549 uint8_t *start = odhcp6c_get_state(states[i], &ra_dns_len);
550
551 for (struct odhcp6c_entry *c = (struct odhcp6c_entry*)start;
552 (uint8_t*)c < &start[ra_dns_len] &&
553 (uint8_t*)odhcp6c_next_entry(c) <= &start[ra_dns_len];
554 c = odhcp6c_next_entry(c)) {
555 if (IN6_ARE_ADDR_EQUAL(&c->router, &from.sin6_addr) &&
556 c->valid > router_valid)
557 c->valid = router_valid;
558 }
559 }
560 }
561 }
562
563 if (found)
564 odhcp6c_expire();
565
566 return found && changed;
567 }