odhcpd: extra syslog tracing
[project/odhcpd.git] / src / odhcpd.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 <time.h>
16 #include <errno.h>
17 #include <fcntl.h>
18 #include <stdio.h>
19 #include <resolv.h>
20 #include <getopt.h>
21 #include <stddef.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <unistd.h>
25 #include <signal.h>
26 #include <stdbool.h>
27
28 #include <arpa/inet.h>
29 #include <net/if.h>
30 #include <netinet/ip6.h>
31 #include <netpacket/packet.h>
32 #include <linux/rtnetlink.h>
33
34 #include <sys/socket.h>
35 #include <sys/ioctl.h>
36 #include <sys/epoll.h>
37 #include <sys/types.h>
38 #include <sys/wait.h>
39 #include <sys/syscall.h>
40
41 #include <libubox/uloop.h>
42 #include "odhcpd.h"
43
44
45
46 static int ioctl_sock;
47 static int rtnl_socket = -1;
48 static int rtnl_seq = 0;
49 static int urandom_fd = -1;
50
51
52 static void sighandler(_unused int signal)
53 {
54 uloop_end();
55 }
56
57 static void print_usage(const char *app)
58 {
59 printf(
60 "== %s Usage ==\n\n"
61 " -h, --help Print this help\n"
62 " -l level Specify log level 0..7 (default %d)\n",
63 app, LOG_WARNING
64 );
65 }
66
67 int main(int argc, char **argv)
68 {
69 openlog("odhcpd", LOG_PERROR | LOG_PID, LOG_DAEMON);
70 int opt;
71 int log_level = LOG_WARNING;
72 while ((opt = getopt(argc, argv, "hl:")) != -1) {
73 switch (opt) {
74 case 'h':
75 print_usage(argv[0]);
76 return 0;
77 case 'l':
78 log_level = atoi(optarg);
79 fprintf(stderr, "Log level set to %d\n", log_level);
80 break;
81 }
82 }
83 setlogmask(LOG_UPTO(log_level));
84 uloop_init();
85
86 if (getuid() != 0) {
87 syslog(LOG_ERR, "Must be run as root!");
88 return 2;
89 }
90
91 ioctl_sock = socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
92
93 if ((rtnl_socket = odhcpd_open_rtnl()) < 0) {
94 syslog(LOG_ERR, "Unable to open socket: %s", strerror(errno));
95 return 2;
96 }
97
98 if ((urandom_fd = open("/dev/urandom", O_RDONLY | O_CLOEXEC)) < 0)
99 return 4;
100
101 signal(SIGUSR1, SIG_IGN);
102 signal(SIGINT, sighandler);
103 signal(SIGTERM, sighandler);
104
105 if (init_router())
106 return 4;
107
108 if (init_dhcpv6())
109 return 4;
110
111 if (init_ndp())
112 return 4;
113
114 if (init_dhcpv4())
115 return 4;
116
117 odhcpd_run();
118 return 0;
119 }
120
121 int odhcpd_open_rtnl(void)
122 {
123 int sock = socket(AF_NETLINK, SOCK_RAW | SOCK_CLOEXEC, NETLINK_ROUTE);
124
125 // Connect to the kernel netlink interface
126 struct sockaddr_nl nl = {.nl_family = AF_NETLINK};
127 if (connect(sock, (struct sockaddr*)&nl, sizeof(nl))) {
128 syslog(LOG_ERR, "Failed to connect to kernel rtnetlink: %s",
129 strerror(errno));
130 return -1;
131 }
132
133 return sock;
134 }
135
136
137 // Read IPv6 MTU for interface
138 int odhcpd_get_interface_config(const char *ifname, const char *what)
139 {
140 char buf[64];
141 const char *sysctl_pattern = "/proc/sys/net/ipv6/conf/%s/%s";
142 snprintf(buf, sizeof(buf), sysctl_pattern, ifname, what);
143
144 int fd = open(buf, O_RDONLY);
145 ssize_t len = read(fd, buf, sizeof(buf) - 1);
146 close(fd);
147
148 if (len < 0)
149 return -1;
150
151 buf[len] = 0;
152 return atoi(buf);
153 }
154
155
156 // Read IPv6 MAC for interface
157 int odhcpd_get_mac(const struct interface *iface, uint8_t mac[6])
158 {
159 struct ifreq ifr;
160 memset(&ifr, 0, sizeof(ifr));
161 strncpy(ifr.ifr_name, iface->ifname, sizeof(ifr.ifr_name));
162 if (ioctl(ioctl_sock, SIOCGIFHWADDR, &ifr) < 0)
163 return -1;
164 memcpy(mac, ifr.ifr_hwaddr.sa_data, 6);
165 return 0;
166 }
167
168
169 // Forwards a packet on a specific interface
170 ssize_t odhcpd_send(int socket, struct sockaddr_in6 *dest,
171 struct iovec *iov, size_t iov_len,
172 const struct interface *iface)
173 {
174 // Construct headers
175 uint8_t cmsg_buf[CMSG_SPACE(sizeof(struct in6_pktinfo))] = {0};
176 struct msghdr msg = {
177 .msg_name = (void *) dest,
178 .msg_namelen = sizeof(*dest),
179 .msg_iov = iov,
180 .msg_iovlen = iov_len,
181 .msg_control = cmsg_buf,
182 .msg_controllen = sizeof(cmsg_buf),
183 .msg_flags = 0
184 };
185
186 // Set control data (define destination interface)
187 struct cmsghdr *chdr = CMSG_FIRSTHDR(&msg);
188 chdr->cmsg_level = IPPROTO_IPV6;
189 chdr->cmsg_type = IPV6_PKTINFO;
190 chdr->cmsg_len = CMSG_LEN(sizeof(struct in6_pktinfo));
191 struct in6_pktinfo *pktinfo = (struct in6_pktinfo*)CMSG_DATA(chdr);
192 pktinfo->ipi6_ifindex = iface->ifindex;
193
194 // Also set scope ID if link-local
195 if (IN6_IS_ADDR_LINKLOCAL(&dest->sin6_addr)
196 || IN6_IS_ADDR_MC_LINKLOCAL(&dest->sin6_addr))
197 dest->sin6_scope_id = iface->ifindex;
198
199 char ipbuf[INET6_ADDRSTRLEN];
200 inet_ntop(AF_INET6, &dest->sin6_addr, ipbuf, sizeof(ipbuf));
201
202 ssize_t sent = sendmsg(socket, &msg, MSG_DONTWAIT);
203 if (sent < 0)
204 syslog(LOG_NOTICE, "Failed to send to %s%%%s (%s)",
205 ipbuf, iface->ifname, strerror(errno));
206 else
207 syslog(LOG_DEBUG, "Sent %li bytes to %s%%%s",
208 (long)sent, ipbuf, iface->ifname);
209 return sent;
210 }
211
212
213 // Detect an IPV6-address currently assigned to the given interface
214 ssize_t odhcpd_get_interface_addresses(int ifindex,
215 struct odhcpd_ipaddr *addrs, size_t cnt)
216 {
217 struct {
218 struct nlmsghdr nhm;
219 struct ifaddrmsg ifa;
220 } req = {{sizeof(req), RTM_GETADDR, NLM_F_REQUEST | NLM_F_DUMP,
221 ++rtnl_seq, 0}, {AF_INET6, 0, 0, 0, ifindex}};
222 if (send(rtnl_socket, &req, sizeof(req), 0) < (ssize_t)sizeof(req)) {
223 syslog(LOG_WARNING, "Request failed to dump IPv6 addresses (%s)", strerror(errno));
224 return 0;
225 }
226
227 uint8_t buf[8192];
228 ssize_t len = 0, ret = 0;
229
230 for (struct nlmsghdr *nhm = NULL; ; nhm = NLMSG_NEXT(nhm, len)) {
231 while (len < 0 || !NLMSG_OK(nhm, (size_t)len)) {
232 len = recv(rtnl_socket, buf, sizeof(buf), 0);
233 nhm = (struct nlmsghdr*)buf;
234 if (len < 0 || !NLMSG_OK(nhm, (size_t)len)) {
235 if (errno == EINTR)
236 continue;
237
238 syslog(LOG_WARNING, "Failed to receive IPv6 address rtnetlink message (%s)", strerror(errno));
239 return ret;
240 }
241 }
242
243 if (nhm->nlmsg_type != RTM_NEWADDR) {
244 syslog(LOG_WARNING, "Unexpected rtnetlink message (%d) in response to IPv6 address dump", nhm->nlmsg_type);
245 break;
246 }
247
248 // Skip address but keep clearing socket buffer
249 if (ret >= (ssize_t)cnt)
250 continue;
251
252 struct ifaddrmsg *ifa = NLMSG_DATA(nhm);
253 if (ifa->ifa_scope != RT_SCOPE_UNIVERSE ||
254 (ifindex && ifa->ifa_index != (unsigned)ifindex))
255 continue;
256
257 struct rtattr *rta = (struct rtattr*)&ifa[1];
258 size_t alen = NLMSG_PAYLOAD(nhm, sizeof(*ifa));
259 memset(&addrs[ret], 0, sizeof(addrs[ret]));
260 addrs[ret].prefix = ifa->ifa_prefixlen;
261
262 while (RTA_OK(rta, alen)) {
263 if (rta->rta_type == IFA_ADDRESS) {
264 memcpy(&addrs[ret].addr, RTA_DATA(rta),
265 sizeof(struct in6_addr));
266 } else if (rta->rta_type == IFA_CACHEINFO) {
267 struct ifa_cacheinfo *ifc = RTA_DATA(rta);
268 addrs[ret].preferred = ifc->ifa_prefered;
269 addrs[ret].valid = ifc->ifa_valid;
270 }
271
272 rta = RTA_NEXT(rta, alen);
273 }
274
275 if (ifa->ifa_flags & IFA_F_DEPRECATED)
276 addrs[ret].preferred = 0;
277
278 ++ret;
279 }
280
281 return ret;
282 }
283
284 int odhcpd_get_linklocal_interface_address(int ifindex, struct in6_addr *lladdr)
285 {
286 int status = -1;
287 struct sockaddr_in6 addr = {AF_INET6, 0, 0, ALL_IPV6_ROUTERS, ifindex};
288 socklen_t alen = sizeof(addr);
289 int sock = socket(AF_INET6, SOCK_RAW, IPPROTO_ICMPV6);
290
291 if (!connect(sock, (struct sockaddr*)&addr, sizeof(addr)) &&
292 !getsockname(sock, (struct sockaddr*)&addr, &alen)) {
293 *lladdr = addr.sin6_addr;
294 status = 0;
295 }
296
297 close(sock);
298 return status;
299 }
300
301 void odhcpd_setup_route(const struct in6_addr *addr, int prefixlen,
302 const struct interface *iface, const struct in6_addr *gw,
303 int metric, bool add)
304 {
305 struct req {
306 struct nlmsghdr nh;
307 struct rtmsg rtm;
308 struct rtattr rta_dst;
309 struct in6_addr dst_addr;
310 struct rtattr rta_oif;
311 uint32_t ifindex;
312 struct rtattr rta_table;
313 uint32_t table;
314 struct rtattr rta_prio;
315 uint32_t prio;
316 struct rtattr rta_gw;
317 struct in6_addr gw;
318 } req = {
319 {sizeof(req), 0, NLM_F_REQUEST, ++rtnl_seq, 0},
320 {AF_INET6, prefixlen, 0, 0, 0, 0, 0, 0, 0},
321 {sizeof(struct rtattr) + sizeof(struct in6_addr), RTA_DST},
322 *addr,
323 {sizeof(struct rtattr) + sizeof(uint32_t), RTA_OIF},
324 iface->ifindex,
325 {sizeof(struct rtattr) + sizeof(uint32_t), RTA_TABLE},
326 RT_TABLE_MAIN,
327 {sizeof(struct rtattr) + sizeof(uint32_t), RTA_PRIORITY},
328 metric,
329 {sizeof(struct rtattr) + sizeof(struct in6_addr), RTA_GATEWAY},
330 IN6ADDR_ANY_INIT,
331 };
332
333 if (gw)
334 req.gw = *gw;
335
336 if (add) {
337 req.nh.nlmsg_type = RTM_NEWROUTE;
338 req.nh.nlmsg_flags |= (NLM_F_CREATE | NLM_F_REPLACE);
339 req.rtm.rtm_protocol = RTPROT_STATIC;
340 req.rtm.rtm_scope = (gw) ? RT_SCOPE_UNIVERSE : RT_SCOPE_LINK;
341 req.rtm.rtm_type = RTN_UNICAST;
342 } else {
343 req.nh.nlmsg_type = RTM_DELROUTE;
344 req.rtm.rtm_scope = RT_SCOPE_NOWHERE;
345 }
346
347 req.nh.nlmsg_len = (gw) ? sizeof(req) : offsetof(struct req, rta_gw);
348 send(rtnl_socket, &req, req.nh.nlmsg_len, MSG_DONTWAIT);
349 }
350
351 struct interface* odhcpd_get_interface_by_index(int ifindex)
352 {
353 struct interface *iface;
354 list_for_each_entry(iface, &interfaces, head)
355 if (iface->ifindex == ifindex)
356 return iface;
357
358 return NULL;
359 }
360
361
362 struct interface* odhcpd_get_interface_by_name(const char *name)
363 {
364 struct interface *iface;
365 list_for_each_entry(iface, &interfaces, head)
366 if (!strcmp(iface->ifname, name))
367 return iface;
368
369 return NULL;
370 }
371
372
373 struct interface* odhcpd_get_master_interface(void)
374 {
375 struct interface *iface;
376 list_for_each_entry(iface, &interfaces, head)
377 if (iface->master)
378 return iface;
379
380 return NULL;
381 }
382
383
384 // Convenience function to receive and do basic validation of packets
385 static void odhcpd_receive_packets(struct uloop_fd *u, _unused unsigned int events)
386 {
387 struct odhcpd_event *e = container_of(u, struct odhcpd_event, uloop);
388
389 uint8_t data_buf[RELAYD_BUFFER_SIZE], cmsg_buf[128];
390 union {
391 struct sockaddr_in6 in6;
392 struct sockaddr_in in;
393 struct sockaddr_ll ll;
394 struct sockaddr_nl nl;
395 } addr;
396
397 if (u->error) {
398 int ret = -1;
399 socklen_t ret_len = sizeof(ret);
400 getsockopt(u->fd, SOL_SOCKET, SO_ERROR, &ret, &ret_len);
401 u->error = false;
402 if (e->handle_error)
403 e->handle_error(ret);
404 }
405
406 while (true) {
407 struct iovec iov = {data_buf, sizeof(data_buf)};
408 struct msghdr msg = {
409 .msg_name = (void *) &addr,
410 .msg_namelen = sizeof(addr),
411 .msg_iov = &iov,
412 .msg_iovlen = 1,
413 .msg_control = cmsg_buf,
414 .msg_controllen = sizeof(cmsg_buf),
415 .msg_flags = 0
416 };
417
418 ssize_t len = recvmsg(u->fd, &msg, MSG_DONTWAIT);
419 if (len < 0) {
420 if (errno == EAGAIN)
421 break;
422 else
423 continue;
424 }
425
426
427 // Extract destination interface
428 int destiface = 0;
429 int *hlim = NULL;
430 void *dest = NULL;
431 struct in6_pktinfo *pktinfo;
432 struct in_pktinfo *pkt4info;
433 for (struct cmsghdr *ch = CMSG_FIRSTHDR(&msg); ch != NULL; ch = CMSG_NXTHDR(&msg, ch)) {
434 if (ch->cmsg_level == IPPROTO_IPV6 &&
435 ch->cmsg_type == IPV6_PKTINFO) {
436 pktinfo = (struct in6_pktinfo*)CMSG_DATA(ch);
437 destiface = pktinfo->ipi6_ifindex;
438 dest = &pktinfo->ipi6_addr;
439 } else if (ch->cmsg_level == IPPROTO_IP &&
440 ch->cmsg_type == IP_PKTINFO) {
441 pkt4info = (struct in_pktinfo*)CMSG_DATA(ch);
442 destiface = pkt4info->ipi_ifindex;
443 dest = &pkt4info->ipi_addr;
444 } else if (ch->cmsg_level == IPPROTO_IPV6 &&
445 ch->cmsg_type == IPV6_HOPLIMIT) {
446 hlim = (int*)CMSG_DATA(ch);
447 }
448 }
449
450 // Check hoplimit if received
451 if (hlim && *hlim != 255)
452 continue;
453
454 // Detect interface for packet sockets
455 if (addr.ll.sll_family == AF_PACKET)
456 destiface = addr.ll.sll_ifindex;
457
458 struct interface *iface =
459 odhcpd_get_interface_by_index(destiface);
460
461 if (!iface && addr.nl.nl_family != AF_NETLINK)
462 continue;
463
464 char ipbuf[INET6_ADDRSTRLEN] = "kernel";
465 if (addr.ll.sll_family == AF_PACKET &&
466 len >= (ssize_t)sizeof(struct ip6_hdr))
467 inet_ntop(AF_INET6, &data_buf[8], ipbuf, sizeof(ipbuf));
468 else if (addr.in6.sin6_family == AF_INET6)
469 inet_ntop(AF_INET6, &addr.in6.sin6_addr, ipbuf, sizeof(ipbuf));
470 else if (addr.in.sin_family == AF_INET)
471 inet_ntop(AF_INET, &addr.in.sin_addr, ipbuf, sizeof(ipbuf));
472
473 syslog(LOG_DEBUG, "Received %li Bytes from %s%%%s", (long)len,
474 ipbuf, (iface) ? iface->ifname : "netlink");
475
476 e->handle_dgram(&addr, data_buf, len, iface, dest);
477 }
478 }
479
480 // Register events for the multiplexer
481 int odhcpd_register(struct odhcpd_event *event)
482 {
483 event->uloop.cb = odhcpd_receive_packets;
484 return uloop_fd_add(&event->uloop, ULOOP_READ |
485 ((event->handle_error) ? ULOOP_ERROR_CB : 0));
486 }
487
488 void odhcpd_process(struct odhcpd_event *event)
489 {
490 odhcpd_receive_packets(&event->uloop, 0);
491 }
492
493 int odhcpd_urandom(void *data, size_t len)
494 {
495 return read(urandom_fd, data, len);
496 }
497
498
499 time_t odhcpd_time(void)
500 {
501 struct timespec ts;
502 syscall(SYS_clock_gettime, CLOCK_MONOTONIC, &ts);
503 return ts.tv_sec;
504 }
505
506
507 static const char hexdigits[] = "0123456789abcdef";
508 static const int8_t hexvals[] = {
509 -1, -1, -1, -1, -1, -1, -1, -1, -1, -2, -2, -1, -1, -2, -1, -1,
510 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
511 -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
512 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1,
513 -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
514 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
515 -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
516 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
517 };
518
519 ssize_t odhcpd_unhexlify(uint8_t *dst, size_t len, const char *src)
520 {
521 size_t c;
522 for (c = 0; c < len && src[0] && src[1]; ++c) {
523 int8_t x = (int8_t)*src++;
524 int8_t y = (int8_t)*src++;
525 if (x < 0 || (x = hexvals[x]) < 0
526 || y < 0 || (y = hexvals[y]) < 0)
527 return -1;
528 dst[c] = x << 4 | y;
529 while (((int8_t)*src) < 0 ||
530 (*src && hexvals[(uint8_t)*src] < 0))
531 src++;
532 }
533
534 return c;
535 }
536
537
538 void odhcpd_hexlify(char *dst, const uint8_t *src, size_t len)
539 {
540 for (size_t i = 0; i < len; ++i) {
541 *dst++ = hexdigits[src[i] >> 4];
542 *dst++ = hexdigits[src[i] & 0x0f];
543 }
544 *dst = 0;
545 }
546
547
548 int odhcpd_bmemcmp(const void *av, const void *bv, size_t bits)
549 {
550 const uint8_t *a = av, *b = bv;
551 size_t bytes = bits / 8;
552 bits %= 8;
553
554 int res = memcmp(a, b, bytes);
555 if (res == 0 && bits > 0)
556 res = (a[bytes] >> (8 - bits)) - (b[bytes] >> (8 - bits));
557
558 return res;
559 }
560
561
562 void odhcpd_bmemcpy(void *av, const void *bv, size_t bits)
563 {
564 uint8_t *a = av;
565 const uint8_t *b = bv;
566
567 size_t bytes = bits / 8;
568 bits %= 8;
569 memcpy(a, b, bytes);
570
571 if (bits > 0) {
572 uint8_t mask = (1 << (8 - bits)) - 1;
573 a[bytes] = (a[bytes] & mask) | ((~mask) & b[bytes]);
574 }
575 }