properly handle return codes
[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/rtnetlink.h>
33
34 #include <sys/socket.h>
35 #include <sys/ioctl.h>
36 #include <sys/epoll.h>
37 #include <sys/types.h>
38 #include <sys/wait.h>
39 #include <sys/syscall.h>
40
41 #include <libubox/uloop.h>
42 #include "odhcpd.h"
43
44
45
46 static int ioctl_sock;
47 static int rtnl_socket = -1;
48 static int rtnl_seq = 0;
49 static int urandom_fd = -1;
50
51
52 static void sighandler(_unused int signal)
53 {
54         uloop_end();
55 }
56
57
58 int main()
59 {
60         openlog("odhcpd", LOG_PERROR | LOG_PID, LOG_DAEMON);
61         setlogmask(LOG_UPTO(LOG_WARNING));
62         uloop_init();
63
64         if (getuid() != 0) {
65                 syslog(LOG_ERR, "Must be run as root!");
66                 return 2;
67         }
68
69         ioctl_sock = socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
70
71         if ((rtnl_socket = odhcpd_open_rtnl()) < 0) {
72                 syslog(LOG_ERR, "Unable to open socket: %s", strerror(errno));
73                 return 2;
74         }
75
76         if ((urandom_fd = open("/dev/urandom", O_RDONLY | O_CLOEXEC)) < 0)
77                 return 4;
78
79         signal(SIGUSR1, SIG_IGN);
80         signal(SIGINT, sighandler);
81         signal(SIGTERM, sighandler);
82
83         if (init_router())
84                 return 4;
85
86         if (init_dhcpv6())
87                 return 4;
88
89         if (init_ndp())
90                 return 4;
91
92         if (init_dhcpv4())
93                 return 4;
94
95         odhcpd_run();
96         return 0;
97 }
98
99 int odhcpd_open_rtnl(void)
100 {
101         int sock = socket(AF_NETLINK, SOCK_RAW | SOCK_CLOEXEC, NETLINK_ROUTE);
102
103         // Connect to the kernel netlink interface
104         struct sockaddr_nl nl = {.nl_family = AF_NETLINK};
105         if (connect(sock, (struct sockaddr*)&nl, sizeof(nl))) {
106                 syslog(LOG_ERR, "Failed to connect to kernel rtnetlink: %s",
107                                 strerror(errno));
108                 return -1;
109         }
110
111         return sock;
112 }
113
114
115 // Read IPv6 MTU for interface
116 int odhcpd_get_interface_mtu(const char *ifname)
117 {
118         char buf[64];
119         const char *sysctl_pattern = "/proc/sys/net/ipv6/conf/%s/mtu";
120         snprintf(buf, sizeof(buf), sysctl_pattern, ifname);
121
122         int fd = open(buf, O_RDONLY);
123         ssize_t len = read(fd, buf, sizeof(buf) - 1);
124         close(fd);
125
126         if (len < 0)
127                 return -1;
128
129
130         buf[len] = 0;
131         return atoi(buf);
132
133 }
134
135
136 // Read IPv6 MAC for interface
137 int odhcpd_get_mac(const struct interface *iface, uint8_t mac[6])
138 {
139         struct ifreq ifr;
140         memset(&ifr, 0, sizeof(ifr));
141         strncpy(ifr.ifr_name, iface->ifname, sizeof(ifr.ifr_name));
142         if (ioctl(ioctl_sock, SIOCGIFHWADDR, &ifr) < 0)
143                 return -1;
144         memcpy(mac, ifr.ifr_hwaddr.sa_data, 6);
145         return 0;
146 }
147
148
149 // Forwards a packet on a specific interface
150 ssize_t odhcpd_send(int socket, struct sockaddr_in6 *dest,
151                 struct iovec *iov, size_t iov_len,
152                 const struct interface *iface)
153 {
154         // Construct headers
155         uint8_t cmsg_buf[CMSG_SPACE(sizeof(struct in6_pktinfo))] = {0};
156         struct msghdr msg = {
157                 .msg_name = (void *) dest,
158                 .msg_namelen = sizeof(*dest),
159                 .msg_iov = iov,
160                 .msg_iovlen = iov_len,
161                 .msg_control = cmsg_buf,
162                 .msg_controllen = sizeof(cmsg_buf),
163                 .msg_flags = 0
164         };
165
166         // Set control data (define destination interface)
167         struct cmsghdr *chdr = CMSG_FIRSTHDR(&msg);
168         chdr->cmsg_level = IPPROTO_IPV6;
169         chdr->cmsg_type = IPV6_PKTINFO;
170         chdr->cmsg_len = CMSG_LEN(sizeof(struct in6_pktinfo));
171         struct in6_pktinfo *pktinfo = (struct in6_pktinfo*)CMSG_DATA(chdr);
172         pktinfo->ipi6_ifindex = iface->ifindex;
173
174         // Also set scope ID if link-local
175         if (IN6_IS_ADDR_LINKLOCAL(&dest->sin6_addr)
176                         || IN6_IS_ADDR_MC_LINKLOCAL(&dest->sin6_addr))
177                 dest->sin6_scope_id = iface->ifindex;
178
179         // IPV6_PKTINFO doesn't really work for IPv6-raw sockets (bug?)
180         if (dest->sin6_port == 0) {
181                 msg.msg_control = NULL;
182                 msg.msg_controllen = 0;
183         }
184
185         char ipbuf[INET6_ADDRSTRLEN];
186         inet_ntop(AF_INET6, &dest->sin6_addr, ipbuf, sizeof(ipbuf));
187
188         ssize_t sent = sendmsg(socket, &msg, MSG_DONTWAIT);
189         if (sent < 0)
190                 syslog(LOG_NOTICE, "Failed to send to %s%%%s (%s)",
191                                 ipbuf, iface->ifname, strerror(errno));
192         else
193                 syslog(LOG_DEBUG, "Sent %li bytes to %s%%%s",
194                                 (long)sent, ipbuf, iface->ifname);
195         return sent;
196 }
197
198
199 // Detect an IPV6-address currently assigned to the given interface
200 ssize_t odhcpd_get_interface_addresses(int ifindex,
201                 struct odhcpd_ipaddr *addrs, size_t cnt)
202 {
203         struct {
204                 struct nlmsghdr nhm;
205                 struct ifaddrmsg ifa;
206         } req = {{sizeof(req), RTM_GETADDR, NLM_F_REQUEST | NLM_F_DUMP,
207                         ++rtnl_seq, 0}, {AF_INET6, 0, 0, 0, ifindex}};
208         if (send(rtnl_socket, &req, sizeof(req), 0) < (ssize_t)sizeof(req))
209                 return 0;
210
211         uint8_t buf[8192];
212         ssize_t len = 0, ret = 0;
213
214         for (struct nlmsghdr *nhm = NULL; ; nhm = NLMSG_NEXT(nhm, len)) {
215                 while (len < 0 || !NLMSG_OK(nhm, (size_t)len)) {
216                         len = recv(rtnl_socket, buf, sizeof(buf), 0);
217                         nhm = (struct nlmsghdr*)buf;
218                         if (len < 0 || !NLMSG_OK(nhm, (size_t)len)) {
219                                 if (errno == EINTR)
220                                         continue;
221                                 else
222                                         return ret;
223                         }
224                 }
225
226                 if (nhm->nlmsg_type != RTM_NEWADDR)
227                         break;
228
229                 // Skip address but keep clearing socket buffer
230                 if (ret >= (ssize_t)cnt)
231                         continue;
232
233                 struct ifaddrmsg *ifa = NLMSG_DATA(nhm);
234                 if (ifa->ifa_scope != RT_SCOPE_UNIVERSE ||
235                                 (ifindex && ifa->ifa_index != (unsigned)ifindex))
236                         continue;
237
238                 struct rtattr *rta = (struct rtattr*)&ifa[1];
239                 size_t alen = NLMSG_PAYLOAD(nhm, sizeof(*ifa));
240                 memset(&addrs[ret], 0, sizeof(addrs[ret]));
241                 addrs[ret].prefix = ifa->ifa_prefixlen;
242
243                 while (RTA_OK(rta, alen)) {
244                         if (rta->rta_type == IFA_ADDRESS) {
245                                 memcpy(&addrs[ret].addr, RTA_DATA(rta),
246                                                 sizeof(struct in6_addr));
247                         } else if (rta->rta_type == IFA_CACHEINFO) {
248                                 struct ifa_cacheinfo *ifc = RTA_DATA(rta);
249                                 addrs[ret].preferred = ifc->ifa_prefered;
250                                 addrs[ret].valid = ifc->ifa_valid;
251                         }
252
253                         rta = RTA_NEXT(rta, alen);
254                 }
255
256                 if (ifa->ifa_flags & IFA_F_DEPRECATED)
257                         addrs[ret].preferred = 0;
258
259                 ++ret;
260         }
261
262         return ret;
263 }
264
265 int odhcpd_get_preferred_interface_address(int ifindex, struct in6_addr *addr)
266 {
267         struct odhcpd_ipaddr ipaddrs[8];
268         ssize_t ip_cnt = odhcpd_get_interface_addresses(ifindex, ipaddrs, ARRAY_SIZE(ipaddrs));
269         uint32_t preferred = 0;
270         int ret = 0;
271
272         for (ssize_t i = 0; i < ip_cnt; i++) {
273                 struct odhcpd_ipaddr *ipaddr = &ipaddrs[i];
274
275                 if (ipaddr->preferred > preferred || !preferred) {
276                         preferred = ipaddr->preferred;
277                         *addr = ipaddr->addr;
278                         ret = 1;
279                 }
280         }
281
282         return ret;
283 }
284
285 struct interface* odhcpd_get_interface_by_index(int ifindex)
286 {
287         struct interface *iface;
288         list_for_each_entry(iface, &interfaces, head)
289                 if (iface->ifindex == ifindex)
290                         return iface;
291
292         return NULL;
293 }
294
295
296 struct interface* odhcpd_get_interface_by_name(const char *name)
297 {
298         struct interface *iface;
299         list_for_each_entry(iface, &interfaces, head)
300                 if (!strcmp(iface->ifname, name))
301                         return iface;
302
303         return NULL;
304 }
305
306
307 struct interface* odhcpd_get_master_interface(void)
308 {
309         struct interface *iface;
310         list_for_each_entry(iface, &interfaces, head)
311                 if (iface->master)
312                         return iface;
313
314         return NULL;
315 }
316
317
318 // Convenience function to receive and do basic validation of packets
319 static void odhcpd_receive_packets(struct uloop_fd *u, _unused unsigned int events)
320 {
321         struct odhcpd_event *e = container_of(u, struct odhcpd_event, uloop);
322
323         uint8_t data_buf[RELAYD_BUFFER_SIZE], cmsg_buf[128];
324         union {
325                 struct sockaddr_in6 in6;
326                 struct sockaddr_in in;
327                 struct sockaddr_ll ll;
328                 struct sockaddr_nl nl;
329         } addr;
330
331         while (true) {
332                 struct iovec iov = {data_buf, sizeof(data_buf)};
333                 struct msghdr msg = {
334                         .msg_name = (void *) &addr,
335                         .msg_namelen = sizeof(addr),
336                         .msg_iov = &iov,
337                         .msg_iovlen = 1,
338                         .msg_control = cmsg_buf,
339                         .msg_controllen = sizeof(cmsg_buf),
340                         .msg_flags = 0
341                 };
342
343                 ssize_t len = recvmsg(u->fd, &msg, MSG_DONTWAIT);
344                 if (len < 0) {
345                         if (errno == EAGAIN)
346                                 break;
347                         else
348                                 continue;
349                 }
350
351
352                 // Extract destination interface
353                 int destiface = 0;
354                 int *hlim = NULL;
355                 void *dest = NULL;
356                 struct in6_pktinfo *pktinfo;
357                 struct in_pktinfo *pkt4info;
358                 for (struct cmsghdr *ch = CMSG_FIRSTHDR(&msg); ch != NULL; ch = CMSG_NXTHDR(&msg, ch)) {
359                         if (ch->cmsg_level == IPPROTO_IPV6 &&
360                                         ch->cmsg_type == IPV6_PKTINFO) {
361                                 pktinfo = (struct in6_pktinfo*)CMSG_DATA(ch);
362                                 destiface = pktinfo->ipi6_ifindex;
363                                 dest = &pktinfo->ipi6_addr;
364                         } else if (ch->cmsg_level == IPPROTO_IP &&
365                                         ch->cmsg_type == IP_PKTINFO) {
366                                 pkt4info = (struct in_pktinfo*)CMSG_DATA(ch);
367                                 destiface = pkt4info->ipi_ifindex;
368                                 dest = &pkt4info->ipi_addr;
369                         } else if (ch->cmsg_level == IPPROTO_IPV6 &&
370                                         ch->cmsg_type == IPV6_HOPLIMIT) {
371                                 hlim = (int*)CMSG_DATA(ch);
372                         }
373                 }
374
375                 // Check hoplimit if received
376                 if (hlim && *hlim != 255)
377                         continue;
378
379                 // Detect interface for packet sockets
380                 if (addr.ll.sll_family == AF_PACKET)
381                         destiface = addr.ll.sll_ifindex;
382
383                 struct interface *iface =
384                                 odhcpd_get_interface_by_index(destiface);
385
386                 if (!iface && addr.nl.nl_family != AF_NETLINK)
387                         continue;
388
389                 char ipbuf[INET6_ADDRSTRLEN] = "kernel";
390                 if (addr.ll.sll_family == AF_PACKET &&
391                                 len >= (ssize_t)sizeof(struct ip6_hdr))
392                         inet_ntop(AF_INET6, &data_buf[8], ipbuf, sizeof(ipbuf));
393                 else if (addr.in6.sin6_family == AF_INET6)
394                         inet_ntop(AF_INET6, &addr.in6.sin6_addr, ipbuf, sizeof(ipbuf));
395                 else if (addr.in.sin_family == AF_INET)
396                         inet_ntop(AF_INET, &addr.in.sin_addr, ipbuf, sizeof(ipbuf));
397
398                 syslog(LOG_DEBUG, "--");
399                 syslog(LOG_DEBUG, "Received %li Bytes from %s%%%s", (long)len,
400                                 ipbuf, (iface) ? iface->ifname : "netlink");
401
402                 e->handle_dgram(&addr, data_buf, len, iface, dest);
403         }
404 }
405
406 // Register events for the multiplexer
407 int odhcpd_register(struct odhcpd_event *event)
408 {
409         event->uloop.cb = odhcpd_receive_packets;
410         return uloop_fd_add(&event->uloop, ULOOP_READ);
411 }
412
413 void odhcpd_process(struct odhcpd_event *event)
414 {
415         odhcpd_receive_packets(&event->uloop, 0);
416 }
417
418 int odhcpd_urandom(void *data, size_t len)
419 {
420         return read(urandom_fd, data, len);
421 }
422
423
424 time_t odhcpd_time(void)
425 {
426         struct timespec ts;
427         syscall(SYS_clock_gettime, CLOCK_MONOTONIC, &ts);
428         return ts.tv_sec;
429 }
430
431
432 static const char hexdigits[] = "0123456789abcdef";
433 static const int8_t hexvals[] = {
434     -1, -1, -1, -1, -1, -1, -1, -1, -1, -2, -2, -1, -1, -2, -1, -1,
435     -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
436     -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
437      0,  1,  2,  3,  4,  5,  6,  7,  8,  9, -1, -1, -1, -1, -1, -1,
438     -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
439     -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
440     -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
441     -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
442 };
443
444 ssize_t odhcpd_unhexlify(uint8_t *dst, size_t len, const char *src)
445 {
446         size_t c;
447         for (c = 0; c < len && src[0] && src[1]; ++c) {
448                 int8_t x = (int8_t)*src++;
449                 int8_t y = (int8_t)*src++;
450                 if (x < 0 || (x = hexvals[x]) < 0
451                                 || y < 0 || (y = hexvals[y]) < 0)
452                         return -1;
453                 dst[c] = x << 4 | y;
454                 while (((int8_t)*src) < 0 ||
455                                 (*src && hexvals[(uint8_t)*src] < 0))
456                         src++;
457         }
458
459         return c;
460 }
461
462
463 void odhcpd_hexlify(char *dst, const uint8_t *src, size_t len)
464 {
465         for (size_t i = 0; i < len; ++i) {
466                 *dst++ = hexdigits[src[i] >> 4];
467                 *dst++ = hexdigits[src[i] & 0x0f];
468         }
469         *dst = 0;
470 }
471
472
473 int odhcpd_bmemcmp(const void *av, const void *bv, size_t bits)
474 {
475         const uint8_t *a = av, *b = bv;
476         size_t bytes = bits / 8;
477         bits %= 8;
478
479         int res = memcmp(a, b, bytes);
480         if (res == 0 && bits > 0)
481                 res = (a[bytes] >> (8 - bits)) - (b[bytes] >> (8 - bits));
482
483         return res;
484 }
485
486
487 void odhcpd_bmemcpy(void *av, const void *bv, size_t bits)
488 {
489         uint8_t *a = av;
490         const uint8_t *b = bv;
491
492         size_t bytes = bits / 8;
493         bits %= 8;
494         memcpy(a, b, bytes);
495
496         if (bits > 0) {
497                 uint8_t mask = (1 << (8 - bits)) - 1;
498                 a[bytes] = (a[bytes] & mask) | ((~mask) & b[bytes]);
499         }
500 }