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