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