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