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