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