odhcpd: decrease default log level to LOG_INFO
[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
28 #include <arpa/inet.h>
29 #include <net/if.h>
30 #include <netinet/ip6.h>
31 #include <netpacket/packet.h>
32 #include <linux/netlink.h>
33 #include <linux/rtnetlink.h>
34
35 #include <sys/socket.h>
36 #include <sys/ioctl.h>
37 #include <sys/epoll.h>
38 #include <sys/types.h>
39 #include <sys/wait.h>
40 #include <sys/syscall.h>
41
42 #include <libubox/uloop.h>
43 #include "odhcpd.h"
44
45
46
47 static int ioctl_sock;
48 static int rtnl_socket = -1;
49 static int rtnl_seq = 0;
50 static int urandom_fd = -1;
51
52
53 static void sighandler(_unused int signal)
54 {
55         uloop_end();
56 }
57
58 static void print_usage(const char *app)
59 {
60         printf(
61         "== %s Usage ==\n\n"
62         "  -h, --help   Print this help\n"
63         "  -l level     Specify log level 0..7 (default %d)\n",
64                 app, LOG_WARNING
65         );
66 }
67
68 int main(int argc, char **argv)
69 {
70         openlog("odhcpd", LOG_PERROR | LOG_PID, LOG_DAEMON);
71         int opt;
72         int log_level = LOG_INFO;
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                         log_level = atoi(optarg);
80                         fprintf(stderr, "Log level set to %d\n", log_level);
81                         break;
82                 }
83         }
84         setlogmask(LOG_UPTO(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 ((rtnl_socket = odhcpd_open_rtnl()) < 0) {
95                 syslog(LOG_ERR, "Unable to open socket: %s", strerror(errno));
96                 return 2;
97         }
98
99         if ((urandom_fd = open("/dev/urandom", O_RDONLY | O_CLOEXEC)) < 0)
100                 return 4;
101
102         signal(SIGUSR1, SIG_IGN);
103         signal(SIGINT, sighandler);
104         signal(SIGTERM, sighandler);
105
106         if (init_router())
107                 return 4;
108
109         if (init_dhcpv6())
110                 return 4;
111
112         if (init_ndp())
113                 return 4;
114
115         if (init_dhcpv4())
116                 return 4;
117
118         odhcpd_run();
119         return 0;
120 }
121
122 int odhcpd_open_rtnl(void)
123 {
124         int sock = socket(AF_NETLINK, SOCK_RAW | SOCK_CLOEXEC, NETLINK_ROUTE);
125
126         // Connect to the kernel netlink interface
127         struct sockaddr_nl nl = {.nl_family = AF_NETLINK};
128         if (connect(sock, (struct sockaddr*)&nl, sizeof(nl))) {
129                 syslog(LOG_ERR, "Failed to connect to kernel rtnetlink: %s",
130                                 strerror(errno));
131                 return -1;
132         }
133
134         return sock;
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         ssize_t len = read(fd, buf, sizeof(buf) - 1);
147         close(fd);
148
149         if (len < 0)
150                 return -1;
151
152         buf[len] = 0;
153         return atoi(buf);
154 }
155
156
157 // Read IPv6 MAC for interface
158 int odhcpd_get_mac(const struct interface *iface, uint8_t mac[6])
159 {
160         struct ifreq ifr;
161         memset(&ifr, 0, sizeof(ifr));
162         strncpy(ifr.ifr_name, iface->ifname, sizeof(ifr.ifr_name));
163         if (ioctl(ioctl_sock, SIOCGIFHWADDR, &ifr) < 0)
164                 return -1;
165         memcpy(mac, ifr.ifr_hwaddr.sa_data, 6);
166         return 0;
167 }
168
169
170 // Forwards a packet on a specific interface
171 ssize_t odhcpd_send(int socket, struct sockaddr_in6 *dest,
172                 struct iovec *iov, size_t iov_len,
173                 const struct interface *iface)
174 {
175         // Construct headers
176         uint8_t cmsg_buf[CMSG_SPACE(sizeof(struct in6_pktinfo))] = {0};
177         struct msghdr msg = {
178                 .msg_name = (void *) dest,
179                 .msg_namelen = sizeof(*dest),
180                 .msg_iov = iov,
181                 .msg_iovlen = iov_len,
182                 .msg_control = cmsg_buf,
183                 .msg_controllen = sizeof(cmsg_buf),
184                 .msg_flags = 0
185         };
186
187         // Set control data (define destination interface)
188         struct cmsghdr *chdr = CMSG_FIRSTHDR(&msg);
189         chdr->cmsg_level = IPPROTO_IPV6;
190         chdr->cmsg_type = IPV6_PKTINFO;
191         chdr->cmsg_len = CMSG_LEN(sizeof(struct in6_pktinfo));
192         struct in6_pktinfo *pktinfo = (struct in6_pktinfo*)CMSG_DATA(chdr);
193         pktinfo->ipi6_ifindex = iface->ifindex;
194
195         // Also set scope ID if link-local
196         if (IN6_IS_ADDR_LINKLOCAL(&dest->sin6_addr)
197                         || IN6_IS_ADDR_MC_LINKLOCAL(&dest->sin6_addr))
198                 dest->sin6_scope_id = iface->ifindex;
199
200         char ipbuf[INET6_ADDRSTRLEN];
201         inet_ntop(AF_INET6, &dest->sin6_addr, ipbuf, sizeof(ipbuf));
202
203         ssize_t sent = sendmsg(socket, &msg, MSG_DONTWAIT);
204         if (sent < 0)
205                 syslog(LOG_NOTICE, "Failed to send to %s%%%s (%s)",
206                                 ipbuf, iface->ifname, strerror(errno));
207         else
208                 syslog(LOG_DEBUG, "Sent %li bytes to %s%%%s",
209                                 (long)sent, ipbuf, iface->ifname);
210         return sent;
211 }
212
213
214 // Detect an IPV6-address currently assigned to the given interface
215 ssize_t odhcpd_get_interface_addresses(int ifindex,
216                 struct odhcpd_ipaddr *addrs, size_t cnt)
217 {
218         struct {
219                 struct nlmsghdr nhm;
220                 struct ifaddrmsg ifa;
221         } req = {{sizeof(req), RTM_GETADDR, NLM_F_REQUEST | NLM_F_DUMP,
222                         ++rtnl_seq, 0}, {AF_INET6, 0, 0, 0, ifindex}};
223         if (send(rtnl_socket, &req, sizeof(req), 0) < (ssize_t)sizeof(req)) {
224                 syslog(LOG_WARNING, "Request failed to dump IPv6 addresses (%s)", strerror(errno));
225                 return 0;
226         }
227
228         uint8_t buf[8192];
229         ssize_t len = 0, ret = 0;
230
231         for (struct nlmsghdr *nhm = NULL; ; nhm = NLMSG_NEXT(nhm, len)) {
232                 while (len < 0 || !NLMSG_OK(nhm, (size_t)len)) {
233                         len = recv(rtnl_socket, buf, sizeof(buf), 0);
234                         nhm = (struct nlmsghdr*)buf;
235                         if (len < 0 || !NLMSG_OK(nhm, (size_t)len)) {
236                                 if (errno == EINTR)
237                                         continue;
238
239                                 syslog(LOG_WARNING, "Failed to receive IPv6 address rtnetlink message (%s)", strerror(errno));
240                                 ret = -1;
241                                 goto out;
242                         }
243                 }
244
245                 switch (nhm->nlmsg_type) {
246                 case RTM_NEWADDR: {
247                         // Skip address but keep clearing socket buffer
248                         if (ret >= (ssize_t)cnt)
249                                 continue;
250
251                         struct ifaddrmsg *ifa = NLMSG_DATA(nhm);
252                         if (ifa->ifa_scope != RT_SCOPE_UNIVERSE ||
253                                         (ifindex && ifa->ifa_index != (unsigned)ifindex))
254                                 continue;
255
256                         struct rtattr *rta = (struct rtattr*)&ifa[1];
257                         size_t alen = NLMSG_PAYLOAD(nhm, sizeof(*ifa));
258                         memset(&addrs[ret], 0, sizeof(addrs[ret]));
259                         addrs[ret].prefix = ifa->ifa_prefixlen;
260
261                         while (RTA_OK(rta, alen)) {
262                                 if (rta->rta_type == IFA_ADDRESS) {
263                                         memcpy(&addrs[ret].addr, RTA_DATA(rta),
264                                                         sizeof(struct in6_addr));
265                                 } else if (rta->rta_type == IFA_CACHEINFO) {
266                                         struct ifa_cacheinfo *ifc = RTA_DATA(rta);
267                                         addrs[ret].preferred = ifc->ifa_prefered;
268                                         addrs[ret].valid = ifc->ifa_valid;
269                                 }
270
271                                 rta = RTA_NEXT(rta, alen);
272                         }
273
274                         if (ifa->ifa_flags & IFA_F_DEPRECATED)
275                                 addrs[ret].preferred = 0;
276
277                         ++ret;
278                         break;
279                 }
280                 case NLMSG_DONE:
281                         goto out;
282                 default:
283                         syslog(LOG_WARNING, "Unexpected rtnetlink message (%d) in response to IPv6 address dump", nhm->nlmsg_type);
284                         ret = -1;
285                         goto out;
286                 }
287
288         }
289 out:
290         return ret;
291 }
292
293 int odhcpd_get_linklocal_interface_address(int ifindex, struct in6_addr *lladdr)
294 {
295                 int status = -1;
296                 struct sockaddr_in6 addr = {AF_INET6, 0, 0, ALL_IPV6_ROUTERS, ifindex};
297                 socklen_t alen = sizeof(addr);
298                 int sock = socket(AF_INET6, SOCK_RAW, IPPROTO_ICMPV6);
299
300                 if (!connect(sock, (struct sockaddr*)&addr, sizeof(addr)) &&
301                                 !getsockname(sock, (struct sockaddr*)&addr, &alen)) {
302                         *lladdr = addr.sin6_addr;
303                         status = 0;
304                 }
305
306                 close(sock);
307                 return status;
308 }
309
310 void odhcpd_setup_route(const struct in6_addr *addr, int prefixlen,
311                 const struct interface *iface, const struct in6_addr *gw,
312                 int metric, bool add)
313 {
314         struct req {
315                 struct nlmsghdr nh;
316                 struct rtmsg rtm;
317                 struct rtattr rta_dst;
318                 struct in6_addr dst_addr;
319                 struct rtattr rta_oif;
320                 uint32_t ifindex;
321                 struct rtattr rta_table;
322                 uint32_t table;
323                 struct rtattr rta_prio;
324                 uint32_t prio;
325                 struct rtattr rta_gw;
326                 struct in6_addr gw;
327         } req = {
328                 {sizeof(req), 0, NLM_F_REQUEST, ++rtnl_seq, 0},
329                 {AF_INET6, prefixlen, 0, 0, 0, 0, 0, 0, 0},
330                 {sizeof(struct rtattr) + sizeof(struct in6_addr), RTA_DST},
331                 *addr,
332                 {sizeof(struct rtattr) + sizeof(uint32_t), RTA_OIF},
333                 iface->ifindex,
334                 {sizeof(struct rtattr) + sizeof(uint32_t), RTA_TABLE},
335                 RT_TABLE_MAIN,
336                 {sizeof(struct rtattr) + sizeof(uint32_t), RTA_PRIORITY},
337                 metric,
338                 {sizeof(struct rtattr) + sizeof(struct in6_addr), RTA_GATEWAY},
339                 IN6ADDR_ANY_INIT,
340         };
341
342         if (gw)
343                 req.gw = *gw;
344
345         if (add) {
346                 req.nh.nlmsg_type = RTM_NEWROUTE;
347                 req.nh.nlmsg_flags |= (NLM_F_CREATE | NLM_F_REPLACE);
348                 req.rtm.rtm_protocol = RTPROT_STATIC;
349                 req.rtm.rtm_scope = (gw) ? RT_SCOPE_UNIVERSE : RT_SCOPE_LINK;
350                 req.rtm.rtm_type = RTN_UNICAST;
351         } else {
352                 req.nh.nlmsg_type = RTM_DELROUTE;
353                 req.rtm.rtm_scope = RT_SCOPE_NOWHERE;
354         }
355
356         req.nh.nlmsg_len = (gw) ? sizeof(req) : offsetof(struct req, rta_gw);
357         send(rtnl_socket, &req, req.nh.nlmsg_len, MSG_DONTWAIT);
358 }
359
360 struct interface* odhcpd_get_interface_by_index(int ifindex)
361 {
362         struct interface *iface;
363         list_for_each_entry(iface, &interfaces, head)
364                 if (iface->ifindex == ifindex)
365                         return iface;
366
367         return NULL;
368 }
369
370
371 struct interface* odhcpd_get_interface_by_name(const char *name)
372 {
373         struct interface *iface;
374         list_for_each_entry(iface, &interfaces, head)
375                 if (!strcmp(iface->ifname, name))
376                         return iface;
377
378         return NULL;
379 }
380
381
382 struct interface* odhcpd_get_master_interface(void)
383 {
384         struct interface *iface;
385         list_for_each_entry(iface, &interfaces, head)
386                 if (iface->master)
387                         return iface;
388
389         return NULL;
390 }
391
392
393 // Convenience function to receive and do basic validation of packets
394 static void odhcpd_receive_packets(struct uloop_fd *u, _unused unsigned int events)
395 {
396         struct odhcpd_event *e = container_of(u, struct odhcpd_event, uloop);
397
398         uint8_t data_buf[RELAYD_BUFFER_SIZE], cmsg_buf[128];
399         union {
400                 struct sockaddr_in6 in6;
401                 struct sockaddr_in in;
402                 struct sockaddr_ll ll;
403                 struct sockaddr_nl nl;
404         } addr;
405
406         if (u->error) {
407                 int ret = -1;
408                 socklen_t ret_len = sizeof(ret);
409                 getsockopt(u->fd, SOL_SOCKET, SO_ERROR, &ret, &ret_len);
410                 u->error = false;
411                 if (e->handle_error)
412                         e->handle_error(ret);
413         }
414
415         while (true) {
416                 struct iovec iov = {data_buf, sizeof(data_buf)};
417                 struct msghdr msg = {
418                         .msg_name = (void *) &addr,
419                         .msg_namelen = sizeof(addr),
420                         .msg_iov = &iov,
421                         .msg_iovlen = 1,
422                         .msg_control = cmsg_buf,
423                         .msg_controllen = sizeof(cmsg_buf),
424                         .msg_flags = 0
425                 };
426
427                 ssize_t len = recvmsg(u->fd, &msg, MSG_DONTWAIT);
428                 if (len < 0) {
429                         if (errno == EAGAIN)
430                                 break;
431                         else
432                                 continue;
433                 }
434
435
436                 // Extract destination interface
437                 int destiface = 0;
438                 int *hlim = NULL;
439                 void *dest = NULL;
440                 struct in6_pktinfo *pktinfo;
441                 struct in_pktinfo *pkt4info;
442                 for (struct cmsghdr *ch = CMSG_FIRSTHDR(&msg); ch != NULL; ch = CMSG_NXTHDR(&msg, ch)) {
443                         if (ch->cmsg_level == IPPROTO_IPV6 &&
444                                         ch->cmsg_type == IPV6_PKTINFO) {
445                                 pktinfo = (struct in6_pktinfo*)CMSG_DATA(ch);
446                                 destiface = pktinfo->ipi6_ifindex;
447                                 dest = &pktinfo->ipi6_addr;
448                         } else if (ch->cmsg_level == IPPROTO_IP &&
449                                         ch->cmsg_type == IP_PKTINFO) {
450                                 pkt4info = (struct in_pktinfo*)CMSG_DATA(ch);
451                                 destiface = pkt4info->ipi_ifindex;
452                                 dest = &pkt4info->ipi_addr;
453                         } else if (ch->cmsg_level == IPPROTO_IPV6 &&
454                                         ch->cmsg_type == IPV6_HOPLIMIT) {
455                                 hlim = (int*)CMSG_DATA(ch);
456                         }
457                 }
458
459                 // Check hoplimit if received
460                 if (hlim && *hlim != 255)
461                         continue;
462
463                 // Detect interface for packet sockets
464                 if (addr.ll.sll_family == AF_PACKET)
465                         destiface = addr.ll.sll_ifindex;
466
467                 struct interface *iface =
468                                 odhcpd_get_interface_by_index(destiface);
469
470                 if (!iface && addr.nl.nl_family != AF_NETLINK)
471                         continue;
472
473                 char ipbuf[INET6_ADDRSTRLEN] = "kernel";
474                 if (addr.ll.sll_family == AF_PACKET &&
475                                 len >= (ssize_t)sizeof(struct ip6_hdr))
476                         inet_ntop(AF_INET6, &data_buf[8], ipbuf, sizeof(ipbuf));
477                 else if (addr.in6.sin6_family == AF_INET6)
478                         inet_ntop(AF_INET6, &addr.in6.sin6_addr, ipbuf, sizeof(ipbuf));
479                 else if (addr.in.sin_family == AF_INET)
480                         inet_ntop(AF_INET, &addr.in.sin_addr, ipbuf, sizeof(ipbuf));
481
482                 syslog(LOG_DEBUG, "Received %li Bytes from %s%%%s", (long)len,
483                                 ipbuf, (iface) ? iface->ifname : "netlink");
484
485                 e->handle_dgram(&addr, data_buf, len, iface, dest);
486         }
487 }
488
489 // Register events for the multiplexer
490 int odhcpd_register(struct odhcpd_event *event)
491 {
492         event->uloop.cb = odhcpd_receive_packets;
493         return uloop_fd_add(&event->uloop, ULOOP_READ |
494                         ((event->handle_error) ? ULOOP_ERROR_CB : 0));
495 }
496
497 void odhcpd_process(struct odhcpd_event *event)
498 {
499         odhcpd_receive_packets(&event->uloop, 0);
500 }
501
502 int odhcpd_urandom(void *data, size_t len)
503 {
504         return read(urandom_fd, data, len);
505 }
506
507
508 time_t odhcpd_time(void)
509 {
510         struct timespec ts;
511         syscall(SYS_clock_gettime, CLOCK_MONOTONIC, &ts);
512         return ts.tv_sec;
513 }
514
515
516 static const char hexdigits[] = "0123456789abcdef";
517 static const int8_t hexvals[] = {
518     -1, -1, -1, -1, -1, -1, -1, -1, -1, -2, -2, -1, -1, -2, -1, -1,
519     -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
520     -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
521      0,  1,  2,  3,  4,  5,  6,  7,  8,  9, -1, -1, -1, -1, -1, -1,
522     -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
523     -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
524     -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
525     -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
526 };
527
528 ssize_t odhcpd_unhexlify(uint8_t *dst, size_t len, const char *src)
529 {
530         size_t c;
531         for (c = 0; c < len && src[0] && src[1]; ++c) {
532                 int8_t x = (int8_t)*src++;
533                 int8_t y = (int8_t)*src++;
534                 if (x < 0 || (x = hexvals[x]) < 0
535                                 || y < 0 || (y = hexvals[y]) < 0)
536                         return -1;
537                 dst[c] = x << 4 | y;
538                 while (((int8_t)*src) < 0 ||
539                                 (*src && hexvals[(uint8_t)*src] < 0))
540                         src++;
541         }
542
543         return c;
544 }
545
546
547 void odhcpd_hexlify(char *dst, const uint8_t *src, size_t len)
548 {
549         for (size_t i = 0; i < len; ++i) {
550                 *dst++ = hexdigits[src[i] >> 4];
551                 *dst++ = hexdigits[src[i] & 0x0f];
552         }
553         *dst = 0;
554 }
555
556
557 int odhcpd_bmemcmp(const void *av, const void *bv, size_t bits)
558 {
559         const uint8_t *a = av, *b = bv;
560         size_t bytes = bits / 8;
561         bits %= 8;
562
563         int res = memcmp(a, b, bytes);
564         if (res == 0 && bits > 0)
565                 res = (a[bytes] >> (8 - bits)) - (b[bytes] >> (8 - bits));
566
567         return res;
568 }
569
570
571 void odhcpd_bmemcpy(void *av, const void *bv, size_t bits)
572 {
573         uint8_t *a = av;
574         const uint8_t *b = bv;
575
576         size_t bytes = bits / 8;
577         bits %= 8;
578         memcpy(a, b, bytes);
579
580         if (bits > 0) {
581                 uint8_t mask = (1 << (8 - bits)) - 1;
582                 a[bytes] = (a[bytes] & mask) | ((~mask) & b[bytes]);
583         }
584 }