ndp: code cleanup
[project/odhcpd.git] / src / ndp.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 <stdio.h>
16 #include <stdlib.h>
17 #include <signal.h>
18 #include <errno.h>
19
20 #include <fcntl.h>
21 #include <unistd.h>
22 #include <arpa/inet.h>
23 #include <sys/socket.h>
24 #include <net/ethernet.h>
25 #include <netinet/ip6.h>
26 #include <netinet/icmp6.h>
27 #include <netpacket/packet.h>
28
29 #include <linux/rtnetlink.h>
30 #include <linux/filter.h>
31
32 #include <netlink/msg.h>
33 #include <netlink/socket.h>
34 #include <netlink/attr.h>
35
36 #include "dhcpv6.h"
37 #include "odhcpd.h"
38
39 struct event_socket {
40 struct odhcpd_event ev;
41 struct nl_sock *sock;
42 int sock_bufsize;
43 };
44
45 static void handle_solicit(void *addr, void *data, size_t len,
46 struct interface *iface, void *dest);
47 static void handle_rtnl_event(struct odhcpd_event *ev);
48 static int cb_rtnl_valid(struct nl_msg *msg, void *arg);
49 static void catch_rtnl_err(struct odhcpd_event *e, int error);
50
51 static int addr6_dump_rqs = 0;
52 static int ping_socket = -1;
53 static struct event_socket rtnl_event = {
54 .ev = {
55 .uloop = {.fd = - 1, },
56 .handle_dgram = NULL,
57 .handle_error = catch_rtnl_err,
58 .recv_msgs = handle_rtnl_event,
59 },
60 .sock = NULL,
61 .sock_bufsize = 133120,
62 };
63
64 // Filter ICMPv6 messages of type neighbor soliciation
65 static struct sock_filter bpf[] = {
66 BPF_STMT(BPF_LD | BPF_B | BPF_ABS, offsetof(struct ip6_hdr, ip6_nxt)),
67 BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, IPPROTO_ICMPV6, 0, 3),
68 BPF_STMT(BPF_LD | BPF_B | BPF_ABS, sizeof(struct ip6_hdr) +
69 offsetof(struct icmp6_hdr, icmp6_type)),
70 BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, ND_NEIGHBOR_SOLICIT, 0, 1),
71 BPF_STMT(BPF_RET | BPF_K, 0xffffffff),
72 BPF_STMT(BPF_RET | BPF_K, 0),
73 };
74 static const struct sock_fprog bpf_prog = {sizeof(bpf) / sizeof(*bpf), bpf};
75
76
77 // Initialize NDP-proxy
78 int init_ndp(void)
79 {
80 int val = 2;
81
82 rtnl_event.sock = odhcpd_create_nl_socket(NETLINK_ROUTE);
83 if (!rtnl_event.sock)
84 goto err;
85
86 rtnl_event.ev.uloop.fd = nl_socket_get_fd(rtnl_event.sock);
87
88 if (nl_socket_set_buffer_size(rtnl_event.sock, rtnl_event.sock_bufsize, 0))
89 goto err;
90
91 nl_socket_disable_seq_check(rtnl_event.sock);
92
93 nl_socket_modify_cb(rtnl_event.sock, NL_CB_VALID, NL_CB_CUSTOM,
94 cb_rtnl_valid, NULL);
95
96 // Receive IPv6 address, IPv6 routes and neighbor events
97 if (nl_socket_add_memberships(rtnl_event.sock, RTNLGRP_IPV6_IFADDR,
98 RTNLGRP_IPV6_ROUTE, RTNLGRP_NEIGH, 0))
99 goto err;
100
101 odhcpd_register(&rtnl_event.ev);
102
103 // Open ICMPv6 socket
104 ping_socket = socket(AF_INET6, SOCK_RAW | SOCK_CLOEXEC, IPPROTO_ICMPV6);
105 if (ping_socket < 0) {
106 syslog(LOG_ERR, "Unable to open raw socket: %s", strerror(errno));
107 return -1;
108 }
109
110 setsockopt(ping_socket, IPPROTO_RAW, IPV6_CHECKSUM, &val, sizeof(val));
111
112 // This is required by RFC 4861
113 val = 255;
114 setsockopt(ping_socket, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &val, sizeof(val));
115 setsockopt(ping_socket, IPPROTO_IPV6, IPV6_UNICAST_HOPS, &val, sizeof(val));
116
117 // Filter all packages, we only want to send
118 struct icmp6_filter filt;
119 ICMP6_FILTER_SETBLOCKALL(&filt);
120 setsockopt(ping_socket, IPPROTO_ICMPV6, ICMP6_FILTER, &filt, sizeof(filt));
121
122 return 0;
123
124 err:
125 if (rtnl_event.sock) {
126 nl_socket_free(rtnl_event.sock);
127 rtnl_event.sock = NULL;
128 rtnl_event.ev.uloop.fd = -1;
129 }
130
131 return -1;
132 }
133
134 static void dump_neigh_table(const bool proxy)
135 {
136 struct nl_msg *msg;
137 struct ndmsg ndm = {
138 .ndm_family = AF_INET6,
139 .ndm_flags = proxy ? NTF_PROXY : 0,
140 };
141
142 msg = nlmsg_alloc_simple(RTM_GETNEIGH, NLM_F_REQUEST | NLM_F_DUMP);
143 if (!msg)
144 return;
145
146 nlmsg_append(msg, &ndm, sizeof(ndm), 0);
147
148 nl_send_auto_complete(rtnl_event.sock, msg);
149
150 nlmsg_free(msg);
151 }
152
153 static void dump_addr6_table(void)
154 {
155 struct nl_msg *msg;
156 struct ifaddrmsg ifa = {
157 .ifa_family = AF_INET6,
158 };
159
160 msg = nlmsg_alloc_simple(RTM_GETADDR, NLM_F_REQUEST | NLM_F_DUMP);
161 if (!msg)
162 return;
163
164 nlmsg_append(msg, &ifa, sizeof(ifa), 0);
165
166 nl_send_auto_complete(rtnl_event.sock, msg);
167
168 nlmsg_free(msg);
169 }
170
171 void ndp_handle_addr6_dump(void)
172 {
173 if (!addr6_dump_rqs)
174 return;
175
176 dump_addr6_table();
177 addr6_dump_rqs = 0;
178 }
179
180 inline void ndp_rqs_addr6_dump(void)
181 {
182 addr6_dump_rqs++;
183 }
184
185 int setup_ndp_interface(struct interface *iface, bool enable)
186 {
187 int ret = 0, procfd;
188 bool dump_neigh = false;
189 char procbuf[64];
190
191 snprintf(procbuf, sizeof(procbuf), "/proc/sys/net/ipv6/conf/%s/proxy_ndp", iface->ifname);
192 procfd = open(procbuf, O_WRONLY);
193
194 if (procfd < 0) {
195 ret = -1;
196 goto out;
197 }
198
199 if (iface->ndp_event.uloop.fd > 0) {
200 uloop_fd_delete(&iface->ndp_event.uloop);
201 close(iface->ndp_event.uloop.fd);
202 iface->ndp_event.uloop.fd = -1;
203
204 if (!enable || iface->ndp != RELAYD_RELAY)
205 if (write(procfd, "0\n", 2) < 0) {}
206
207 dump_neigh = true;
208 }
209
210 if (enable && iface->ndp == RELAYD_RELAY) {
211 if (write(procfd, "1\n", 2) < 0) {}
212
213 int sock = socket(AF_PACKET, SOCK_DGRAM | SOCK_CLOEXEC, htons(ETH_P_IPV6));
214 if (sock < 0) {
215 syslog(LOG_ERR, "Unable to open packet socket: %s",
216 strerror(errno));
217 ret = -1;
218 goto out;
219 }
220
221 #ifdef PACKET_RECV_TYPE
222 int pktt = 1 << PACKET_MULTICAST;
223 setsockopt(sock, SOL_PACKET, PACKET_RECV_TYPE, &pktt, sizeof(pktt));
224 #endif
225
226 if (setsockopt(sock, SOL_SOCKET, SO_ATTACH_FILTER,
227 &bpf_prog, sizeof(bpf_prog))) {
228 syslog(LOG_ERR, "Failed to set BPF: %s", strerror(errno));
229 ret = -1;
230 goto out;
231 }
232
233 struct sockaddr_ll ll = {
234 .sll_family = AF_PACKET,
235 .sll_ifindex = iface->ifindex,
236 .sll_protocol = htons(ETH_P_IPV6),
237 .sll_hatype = 0,
238 .sll_pkttype = 0,
239 .sll_halen = 0,
240 .sll_addr = {0},
241 };
242 bind(sock, (struct sockaddr*)&ll, sizeof(ll));
243
244 struct packet_mreq mreq = {iface->ifindex, PACKET_MR_ALLMULTI, ETH_ALEN, {0}};
245 setsockopt(sock, SOL_PACKET, PACKET_ADD_MEMBERSHIP, &mreq, sizeof(mreq));
246
247 iface->ndp_event.uloop.fd = sock;
248 iface->ndp_event.handle_dgram = handle_solicit;
249 odhcpd_register(&iface->ndp_event);
250
251 // If we already were enabled dump is unnecessary, if not do dump
252 if (!dump_neigh)
253 dump_neigh_table(false);
254 else
255 dump_neigh = false;
256
257 ndp_rqs_addr6_dump();
258 }
259
260 if (dump_neigh)
261 dump_neigh_table(true);
262
263 out:
264 if (procfd >= 0)
265 close(procfd);
266
267 return ret;
268 }
269
270
271 // Send an ICMP-ECHO. This is less for actually pinging but for the
272 // neighbor cache to be kept up-to-date.
273 static void ping6(struct in6_addr *addr,
274 const struct interface *iface)
275 {
276 struct sockaddr_in6 dest = { .sin6_family = AF_INET6, .sin6_addr = *addr, .sin6_scope_id = iface->ifindex, };
277 struct icmp6_hdr echo = { .icmp6_type = ICMP6_ECHO_REQUEST };
278 struct iovec iov = { .iov_base = &echo, .iov_len = sizeof(echo) };
279 char ipbuf[INET6_ADDRSTRLEN];
280
281 inet_ntop(AF_INET6, addr, ipbuf, sizeof(ipbuf));
282 syslog(LOG_NOTICE, "Pinging for %s%%%s", ipbuf, iface->ifname);
283
284 odhcpd_setup_route(addr, 128, iface, NULL, 128, true);
285 odhcpd_send(ping_socket, &dest, &iov, 1, iface);
286 odhcpd_setup_route(addr, 128, iface, NULL, 128, false);
287 }
288
289 // Handle solicitations
290 static void handle_solicit(void *addr, void *data, size_t len,
291 struct interface *iface, _unused void *dest)
292 {
293 struct ip6_hdr *ip6 = data;
294 struct nd_neighbor_solicit *req = (struct nd_neighbor_solicit*)&ip6[1];
295 struct sockaddr_ll *ll = addr;
296 char ipbuf[INET6_ADDRSTRLEN];
297 uint8_t mac[6];
298
299 // Solicitation is for duplicate address detection
300 bool ns_is_dad = IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src);
301
302 // Don't process solicit messages on non relay interfaces
303 // Don't forward any non-DAD solicitation for external ifaces
304 // TODO: check if we should even forward DADs for them
305 if (iface->ndp != RELAYD_RELAY || (iface->external && !ns_is_dad))
306 return;
307
308 if (len < sizeof(*ip6) + sizeof(*req))
309 return; // Invalid reqicitation
310
311 if (IN6_IS_ADDR_LINKLOCAL(&req->nd_ns_target) ||
312 IN6_IS_ADDR_LOOPBACK(&req->nd_ns_target) ||
313 IN6_IS_ADDR_MULTICAST(&req->nd_ns_target))
314 return; // Invalid target
315
316 inet_ntop(AF_INET6, &req->nd_ns_target, ipbuf, sizeof(ipbuf));
317 syslog(LOG_DEBUG, "Got a NS for %s%%%s", ipbuf, iface->ifname);
318
319 odhcpd_get_mac(iface, mac);
320 if (!memcmp(ll->sll_addr, mac, sizeof(mac)))
321 return; // Looped back
322
323 struct interface *c;
324 list_for_each_entry(c, &interfaces, head)
325 if (iface != c && c->ndp == RELAYD_RELAY &&
326 (ns_is_dad || !c->external))
327 ping6(&req->nd_ns_target, c);
328 }
329
330 // Use rtnetlink to modify kernel routes
331 static void setup_route(struct in6_addr *addr, struct interface *iface, bool add)
332 {
333 char ipbuf[INET6_ADDRSTRLEN];
334
335 inet_ntop(AF_INET6, addr, ipbuf, sizeof(ipbuf));
336 syslog(LOG_NOTICE, "%s about %s%%%s",
337 (add) ? "Learned" : "Forgot", ipbuf, iface->ifname);
338
339 if (iface->learn_routes)
340 odhcpd_setup_route(addr, 128, iface, NULL, 1024, add);
341 }
342
343 // compare prefixes
344 static int prefixcmp(const void *va, const void *vb)
345 {
346 const struct odhcpd_ipaddr *a = va, *b = vb;
347 uint32_t a_pref = IN6_IS_ADDR_ULA(&a->addr) ? 1 : a->preferred;
348 uint32_t b_pref = IN6_IS_ADDR_ULA(&b->addr) ? 1 : b->preferred;
349 return (a_pref < b_pref) ? 1 : (a_pref > b_pref) ? -1 : 0;
350 }
351
352 // Check address update
353 static void check_addr_updates(struct interface *iface)
354 {
355 struct odhcpd_ipaddr addr[RELAYD_MAX_ADDRS] = {{IN6ADDR_ANY_INIT, 0, 0, 0, 0}};
356 time_t now = odhcpd_time();
357 ssize_t len = odhcpd_get_interface_addresses(iface->ifindex, addr, ARRAY_SIZE(addr));
358
359 if (len < 0)
360 return;
361
362 qsort(addr, len, sizeof(*addr), prefixcmp);
363
364 for (int i = 0; i < len; ++i) {
365 addr[i].addr.s6_addr32[3] = 0;
366
367 if (addr[i].preferred < UINT32_MAX - now)
368 addr[i].preferred += now;
369
370 if (addr[i].valid < UINT32_MAX - now)
371 addr[i].valid += now;
372 }
373
374 bool change = len != (ssize_t)iface->ia_addr_len;
375 for (ssize_t i = 0; !change && i < len; ++i)
376 if (!IN6_ARE_ADDR_EQUAL(&addr[i].addr, &iface->ia_addr[i].addr) ||
377 (addr[i].preferred > 0) != (iface->ia_addr[i].preferred > 0) ||
378 addr[i].valid < iface->ia_addr[i].valid ||
379 addr[i].preferred < iface->ia_addr[i].preferred)
380 change = true;
381
382 if (change)
383 dhcpv6_ia_preupdate(iface);
384
385 memcpy(iface->ia_addr, addr, len * sizeof(*addr));
386 iface->ia_addr_len = len;
387
388 if (change)
389 dhcpv6_ia_postupdate(iface, now);
390
391 if (change) {
392 syslog(LOG_INFO, "Raising SIGUSR1 due to address change on %s", iface->ifname);
393 raise(SIGUSR1);
394 }
395 }
396
397 static void setup_addr_for_relaying(struct in6_addr *addr, struct interface *iface, bool add)
398 {
399 struct interface *c;
400 char ipbuf[INET6_ADDRSTRLEN];
401
402 inet_ntop(AF_INET6, addr, ipbuf, sizeof(ipbuf));
403
404 list_for_each_entry(c, &interfaces, head) {
405 if (iface == c || (c->ndp != RELAYD_RELAY && !add))
406 continue;
407
408 add = (c->ndp == RELAYD_RELAY ? add : false);
409
410 if (odhcpd_setup_proxy_neigh(addr, c, add))
411 syslog(LOG_DEBUG, "Failed to %s proxy neighbour entry %s%%%s",
412 add ? "add" : "delete", ipbuf, iface->ifname);
413 else
414 syslog(LOG_DEBUG, "%s proxy neighbour entry %s%%%s",
415 add ? "Added" : "Deleted", ipbuf, iface->ifname);
416 }
417 }
418
419 static void setup_ping6(struct in6_addr *addr, struct interface *iface)
420 {
421 struct interface *c;
422
423 list_for_each_entry(c, &interfaces, head) {
424 if (iface == c || c->ndp != RELAYD_RELAY ||
425 c->external == true)
426 continue;
427
428 ping6(addr, c);
429 }
430 }
431
432 static struct in6_addr last_solicited;
433
434 static void handle_rtnl_event(struct odhcpd_event *e)
435 {
436 struct event_socket *ev_sock = container_of(e, struct event_socket, ev);
437
438 nl_recvmsgs_default(ev_sock->sock);
439 }
440
441
442 // Handler for neighbor cache entries from the kernel. This is our source
443 // to learn and unlearn hosts on interfaces.
444 static int cb_rtnl_valid(struct nl_msg *msg, _unused void *arg)
445 {
446 struct nlmsghdr *hdr = nlmsg_hdr(msg);
447 struct in6_addr *addr = NULL;
448 struct interface *iface = NULL;
449 bool add = false;
450 char ipbuf[INET6_ADDRSTRLEN];
451
452 switch (hdr->nlmsg_type) {
453 case RTM_NEWROUTE:
454 case RTM_DELROUTE: {
455 struct rtmsg *rtm = nlmsg_data(hdr);
456
457 if (!nlmsg_valid_hdr(hdr, sizeof(*rtm)) ||
458 rtm->rtm_family != AF_INET6)
459 return NL_SKIP;
460
461 if (rtm->rtm_dst_len == 0) {
462 syslog(LOG_INFO, "Raising SIGUSR1 due to default route change");
463 raise(SIGUSR1);
464 }
465 return NL_OK;
466 }
467
468 case RTM_NEWADDR:
469 add = true;
470 case RTM_DELADDR: {
471 struct ifaddrmsg *ifa = nlmsg_data(hdr);
472 struct nlattr *nla[__IFA_MAX];
473
474 if (!nlmsg_valid_hdr(hdr, sizeof(*ifa)) ||
475 ifa->ifa_family != AF_INET6)
476 return NL_SKIP;
477
478 iface = odhcpd_get_interface_by_index(ifa->ifa_index);
479 if (!iface)
480 return NL_SKIP;
481
482 nlmsg_parse(hdr, sizeof(*ifa), nla, __IFA_MAX - 1, NULL);
483 if (!nla[IFA_ADDRESS])
484 return NL_SKIP;
485
486 addr = nla_data(nla[IFA_ADDRESS]);
487 if (!addr || IN6_IS_ADDR_LINKLOCAL(addr) ||
488 IN6_IS_ADDR_MULTICAST(addr))
489 return NL_SKIP;
490
491 inet_ntop(AF_INET6, addr, ipbuf, sizeof(ipbuf));
492 syslog(LOG_DEBUG, "Netlink %s %s%%%s", true ? "newaddr" : "deladdr",
493 ipbuf, iface->ifname);
494
495 check_addr_updates(iface);
496
497 if (iface->ndp != RELAYD_RELAY)
498 break;
499
500 /* handle the relay logic below */
501 setup_addr_for_relaying(addr, iface, add);
502
503 if (!add)
504 dump_neigh_table(false);
505 break;
506 }
507
508 case RTM_NEWNEIGH:
509 add = true;
510 case RTM_DELNEIGH: {
511 struct ndmsg *ndm = nlmsg_data(hdr);
512 struct nlattr *nla[__NDA_MAX];
513
514 if (!nlmsg_valid_hdr(hdr, sizeof(*ndm)) ||
515 ndm->ndm_family != AF_INET6)
516 return NL_SKIP;
517
518 iface = odhcpd_get_interface_by_index(ndm->ndm_ifindex);
519 if (!iface || iface->ndp != RELAYD_RELAY)
520 return (iface ? NL_OK : NL_SKIP);
521
522 nlmsg_parse(hdr, sizeof(*ndm), nla, __NDA_MAX - 1, NULL);
523 if (!nla[NDA_DST])
524 return NL_SKIP;
525
526 addr = nla_data(nla[NDA_DST]);
527 if (!addr || IN6_IS_ADDR_LINKLOCAL(addr) ||
528 IN6_IS_ADDR_MULTICAST(addr))
529 return NL_SKIP;
530
531 inet_ntop(AF_INET6, addr, ipbuf, sizeof(ipbuf));
532 syslog(LOG_DEBUG, "Netlink %s %s%%%s", true ? "newneigh" : "delneigh",
533 ipbuf, iface->ifname);
534
535 if (ndm->ndm_flags & NTF_PROXY) {
536 /* Dump and flush proxy entries */
537 if (hdr->nlmsg_type == RTM_NEWNEIGH) {
538 odhcpd_setup_proxy_neigh(addr, iface, false);
539 setup_route(addr, iface, false);
540 dump_neigh_table(false);
541 }
542
543 return NL_OK;
544 }
545
546 if (add && !(ndm->ndm_state &
547 (NUD_REACHABLE | NUD_STALE | NUD_DELAY | NUD_PROBE |
548 NUD_PERMANENT | NUD_NOARP))) {
549 if (!IN6_ARE_ADDR_EQUAL(&last_solicited, addr)) {
550 last_solicited = *addr;
551 setup_ping6(addr, iface);
552 }
553
554 return NL_OK;
555 }
556
557 setup_addr_for_relaying(addr, iface, add);
558 setup_route(addr, iface, add);
559
560 if (!add)
561 dump_neigh_table(false);
562 break;
563 }
564
565 default:
566 return NL_SKIP;
567 }
568
569 return NL_OK;
570 }
571
572 static void catch_rtnl_err(struct odhcpd_event *e, int error)
573 {
574 struct event_socket *ev_sock = container_of(e, struct event_socket, ev);
575
576 if (error != ENOBUFS)
577 goto err;
578
579 /* Double netlink event buffer size */
580 ev_sock->sock_bufsize *= 2;
581
582 if (nl_socket_set_buffer_size(ev_sock->sock, ev_sock->sock_bufsize, 0))
583 goto err;
584
585 dump_addr6_table();
586 return;
587
588 err:
589 odhcpd_deregister(e);
590 }