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