Merge pull request #46 from stargieg/master
[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_config(const char *ifname, const char *what)
117 {
118 char buf[64];
119 const char *sysctl_pattern = "/proc/sys/net/ipv6/conf/%s/%s";
120 snprintf(buf, sizeof(buf), sysctl_pattern, ifname, what);
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 buf[len] = 0;
130 return atoi(buf);
131 }
132
133
134 // Read IPv6 MAC for interface
135 int odhcpd_get_mac(const struct interface *iface, uint8_t mac[6])
136 {
137 struct ifreq ifr;
138 memset(&ifr, 0, sizeof(ifr));
139 strncpy(ifr.ifr_name, iface->ifname, sizeof(ifr.ifr_name));
140 if (ioctl(ioctl_sock, SIOCGIFHWADDR, &ifr) < 0)
141 return -1;
142 memcpy(mac, ifr.ifr_hwaddr.sa_data, 6);
143 return 0;
144 }
145
146
147 // Forwards a packet on a specific interface
148 ssize_t odhcpd_send(int socket, struct sockaddr_in6 *dest,
149 struct iovec *iov, size_t iov_len,
150 const struct interface *iface)
151 {
152 // Construct headers
153 uint8_t cmsg_buf[CMSG_SPACE(sizeof(struct in6_pktinfo))] = {0};
154 struct msghdr msg = {
155 .msg_name = (void *) dest,
156 .msg_namelen = sizeof(*dest),
157 .msg_iov = iov,
158 .msg_iovlen = iov_len,
159 .msg_control = cmsg_buf,
160 .msg_controllen = sizeof(cmsg_buf),
161 .msg_flags = 0
162 };
163
164 // Set control data (define destination interface)
165 struct cmsghdr *chdr = CMSG_FIRSTHDR(&msg);
166 chdr->cmsg_level = IPPROTO_IPV6;
167 chdr->cmsg_type = IPV6_PKTINFO;
168 chdr->cmsg_len = CMSG_LEN(sizeof(struct in6_pktinfo));
169 struct in6_pktinfo *pktinfo = (struct in6_pktinfo*)CMSG_DATA(chdr);
170 pktinfo->ipi6_ifindex = iface->ifindex;
171
172 // Also set scope ID if link-local
173 if (IN6_IS_ADDR_LINKLOCAL(&dest->sin6_addr)
174 || IN6_IS_ADDR_MC_LINKLOCAL(&dest->sin6_addr))
175 dest->sin6_scope_id = iface->ifindex;
176
177 char ipbuf[INET6_ADDRSTRLEN];
178 inet_ntop(AF_INET6, &dest->sin6_addr, ipbuf, sizeof(ipbuf));
179
180 ssize_t sent = sendmsg(socket, &msg, MSG_DONTWAIT);
181 if (sent < 0)
182 syslog(LOG_NOTICE, "Failed to send to %s%%%s (%s)",
183 ipbuf, iface->ifname, strerror(errno));
184 else
185 syslog(LOG_DEBUG, "Sent %li bytes to %s%%%s",
186 (long)sent, ipbuf, iface->ifname);
187 return sent;
188 }
189
190
191 // Detect an IPV6-address currently assigned to the given interface
192 ssize_t odhcpd_get_interface_addresses(int ifindex,
193 struct odhcpd_ipaddr *addrs, size_t cnt)
194 {
195 struct {
196 struct nlmsghdr nhm;
197 struct ifaddrmsg ifa;
198 } req = {{sizeof(req), RTM_GETADDR, NLM_F_REQUEST | NLM_F_DUMP,
199 ++rtnl_seq, 0}, {AF_INET6, 0, 0, 0, ifindex}};
200 if (send(rtnl_socket, &req, sizeof(req), 0) < (ssize_t)sizeof(req))
201 return 0;
202
203 uint8_t buf[8192];
204 ssize_t len = 0, ret = 0;
205
206 for (struct nlmsghdr *nhm = NULL; ; nhm = NLMSG_NEXT(nhm, len)) {
207 while (len < 0 || !NLMSG_OK(nhm, (size_t)len)) {
208 len = recv(rtnl_socket, buf, sizeof(buf), 0);
209 nhm = (struct nlmsghdr*)buf;
210 if (len < 0 || !NLMSG_OK(nhm, (size_t)len)) {
211 if (errno == EINTR)
212 continue;
213 else
214 return ret;
215 }
216 }
217
218 if (nhm->nlmsg_type != RTM_NEWADDR)
219 break;
220
221 // Skip address but keep clearing socket buffer
222 if (ret >= (ssize_t)cnt)
223 continue;
224
225 struct ifaddrmsg *ifa = NLMSG_DATA(nhm);
226 if (ifa->ifa_scope != RT_SCOPE_UNIVERSE ||
227 (ifindex && ifa->ifa_index != (unsigned)ifindex))
228 continue;
229
230 struct rtattr *rta = (struct rtattr*)&ifa[1];
231 size_t alen = NLMSG_PAYLOAD(nhm, sizeof(*ifa));
232 memset(&addrs[ret], 0, sizeof(addrs[ret]));
233 addrs[ret].prefix = ifa->ifa_prefixlen;
234
235 while (RTA_OK(rta, alen)) {
236 if (rta->rta_type == IFA_ADDRESS) {
237 memcpy(&addrs[ret].addr, RTA_DATA(rta),
238 sizeof(struct in6_addr));
239 } else if (rta->rta_type == IFA_CACHEINFO) {
240 struct ifa_cacheinfo *ifc = RTA_DATA(rta);
241 addrs[ret].preferred = ifc->ifa_prefered;
242 addrs[ret].valid = ifc->ifa_valid;
243 }
244
245 rta = RTA_NEXT(rta, alen);
246 }
247
248 if (ifa->ifa_flags & IFA_F_DEPRECATED)
249 addrs[ret].preferred = 0;
250
251 ++ret;
252 }
253
254 return ret;
255 }
256
257 int odhcpd_get_preferred_interface_address(int ifindex, struct in6_addr *addr)
258 {
259 struct odhcpd_ipaddr ipaddrs[8];
260 ssize_t ip_cnt = odhcpd_get_interface_addresses(ifindex, ipaddrs, ARRAY_SIZE(ipaddrs));
261 uint32_t preferred = 0;
262 int ret = 0;
263
264 for (ssize_t i = 0; i < ip_cnt; i++) {
265 struct odhcpd_ipaddr *ipaddr = &ipaddrs[i];
266
267 if (ipaddr->preferred > preferred || !preferred) {
268 preferred = ipaddr->preferred;
269 *addr = ipaddr->addr;
270 ret = 1;
271 }
272 }
273
274 return ret;
275 }
276
277 void odhcpd_setup_route(const struct in6_addr *addr, int prefixlen,
278 const struct interface *iface, const struct in6_addr *gw,
279 int metric, bool add)
280 {
281 struct req {
282 struct nlmsghdr nh;
283 struct rtmsg rtm;
284 struct rtattr rta_dst;
285 struct in6_addr dst_addr;
286 struct rtattr rta_oif;
287 uint32_t ifindex;
288 struct rtattr rta_table;
289 uint32_t table;
290 struct rtattr rta_prio;
291 uint32_t prio;
292 struct rtattr rta_gw;
293 struct in6_addr gw;
294 } req = {
295 {sizeof(req), 0, NLM_F_REQUEST, ++rtnl_seq, 0},
296 {AF_INET6, prefixlen, 0, 0, 0, 0, 0, 0, 0},
297 {sizeof(struct rtattr) + sizeof(struct in6_addr), RTA_DST},
298 *addr,
299 {sizeof(struct rtattr) + sizeof(uint32_t), RTA_OIF},
300 iface->ifindex,
301 {sizeof(struct rtattr) + sizeof(uint32_t), RTA_TABLE},
302 RT_TABLE_MAIN,
303 {sizeof(struct rtattr) + sizeof(uint32_t), RTA_PRIORITY},
304 metric,
305 {sizeof(struct rtattr) + sizeof(struct in6_addr), RTA_GATEWAY},
306 IN6ADDR_ANY_INIT,
307 };
308
309 if (gw)
310 req.gw = *gw;
311
312 if (add) {
313 req.nh.nlmsg_type = RTM_NEWROUTE;
314 req.nh.nlmsg_flags |= (NLM_F_CREATE | NLM_F_REPLACE);
315 req.rtm.rtm_protocol = RTPROT_STATIC;
316 req.rtm.rtm_scope = (gw) ? RT_SCOPE_UNIVERSE : RT_SCOPE_LINK;
317 req.rtm.rtm_type = RTN_UNICAST;
318 } else {
319 req.nh.nlmsg_type = RTM_DELROUTE;
320 req.rtm.rtm_scope = RT_SCOPE_NOWHERE;
321 }
322
323 req.nh.nlmsg_len = (gw) ? sizeof(req) : offsetof(struct req, rta_gw);
324 send(rtnl_socket, &req, req.nh.nlmsg_len, MSG_DONTWAIT);
325 }
326
327 struct interface* odhcpd_get_interface_by_index(int ifindex)
328 {
329 struct interface *iface;
330 list_for_each_entry(iface, &interfaces, head)
331 if (iface->ifindex == ifindex)
332 return iface;
333
334 return NULL;
335 }
336
337
338 struct interface* odhcpd_get_interface_by_name(const char *name)
339 {
340 struct interface *iface;
341 list_for_each_entry(iface, &interfaces, head)
342 if (!strcmp(iface->ifname, name))
343 return iface;
344
345 return NULL;
346 }
347
348
349 struct interface* odhcpd_get_master_interface(void)
350 {
351 struct interface *iface;
352 list_for_each_entry(iface, &interfaces, head)
353 if (iface->master)
354 return iface;
355
356 return NULL;
357 }
358
359
360 // Convenience function to receive and do basic validation of packets
361 static void odhcpd_receive_packets(struct uloop_fd *u, _unused unsigned int events)
362 {
363 struct odhcpd_event *e = container_of(u, struct odhcpd_event, uloop);
364
365 uint8_t data_buf[RELAYD_BUFFER_SIZE], cmsg_buf[128];
366 union {
367 struct sockaddr_in6 in6;
368 struct sockaddr_in in;
369 struct sockaddr_ll ll;
370 struct sockaddr_nl nl;
371 } addr;
372
373 while (true) {
374 struct iovec iov = {data_buf, sizeof(data_buf)};
375 struct msghdr msg = {
376 .msg_name = (void *) &addr,
377 .msg_namelen = sizeof(addr),
378 .msg_iov = &iov,
379 .msg_iovlen = 1,
380 .msg_control = cmsg_buf,
381 .msg_controllen = sizeof(cmsg_buf),
382 .msg_flags = 0
383 };
384
385 ssize_t len = recvmsg(u->fd, &msg, MSG_DONTWAIT);
386 if (len < 0) {
387 if (errno == EAGAIN)
388 break;
389 else
390 continue;
391 }
392
393
394 // Extract destination interface
395 int destiface = 0;
396 int *hlim = NULL;
397 void *dest = NULL;
398 struct in6_pktinfo *pktinfo;
399 struct in_pktinfo *pkt4info;
400 for (struct cmsghdr *ch = CMSG_FIRSTHDR(&msg); ch != NULL; ch = CMSG_NXTHDR(&msg, ch)) {
401 if (ch->cmsg_level == IPPROTO_IPV6 &&
402 ch->cmsg_type == IPV6_PKTINFO) {
403 pktinfo = (struct in6_pktinfo*)CMSG_DATA(ch);
404 destiface = pktinfo->ipi6_ifindex;
405 dest = &pktinfo->ipi6_addr;
406 } else if (ch->cmsg_level == IPPROTO_IP &&
407 ch->cmsg_type == IP_PKTINFO) {
408 pkt4info = (struct in_pktinfo*)CMSG_DATA(ch);
409 destiface = pkt4info->ipi_ifindex;
410 dest = &pkt4info->ipi_addr;
411 } else if (ch->cmsg_level == IPPROTO_IPV6 &&
412 ch->cmsg_type == IPV6_HOPLIMIT) {
413 hlim = (int*)CMSG_DATA(ch);
414 }
415 }
416
417 // Check hoplimit if received
418 if (hlim && *hlim != 255)
419 continue;
420
421 // Detect interface for packet sockets
422 if (addr.ll.sll_family == AF_PACKET)
423 destiface = addr.ll.sll_ifindex;
424
425 struct interface *iface =
426 odhcpd_get_interface_by_index(destiface);
427
428 if (!iface && addr.nl.nl_family != AF_NETLINK)
429 continue;
430
431 char ipbuf[INET6_ADDRSTRLEN] = "kernel";
432 if (addr.ll.sll_family == AF_PACKET &&
433 len >= (ssize_t)sizeof(struct ip6_hdr))
434 inet_ntop(AF_INET6, &data_buf[8], ipbuf, sizeof(ipbuf));
435 else if (addr.in6.sin6_family == AF_INET6)
436 inet_ntop(AF_INET6, &addr.in6.sin6_addr, ipbuf, sizeof(ipbuf));
437 else if (addr.in.sin_family == AF_INET)
438 inet_ntop(AF_INET, &addr.in.sin_addr, ipbuf, sizeof(ipbuf));
439
440 syslog(LOG_DEBUG, "--");
441 syslog(LOG_DEBUG, "Received %li Bytes from %s%%%s", (long)len,
442 ipbuf, (iface) ? iface->ifname : "netlink");
443
444 e->handle_dgram(&addr, data_buf, len, iface, dest);
445 }
446 }
447
448 // Register events for the multiplexer
449 int odhcpd_register(struct odhcpd_event *event)
450 {
451 event->uloop.cb = odhcpd_receive_packets;
452 return uloop_fd_add(&event->uloop, ULOOP_READ);
453 }
454
455 void odhcpd_process(struct odhcpd_event *event)
456 {
457 odhcpd_receive_packets(&event->uloop, 0);
458 }
459
460 int odhcpd_urandom(void *data, size_t len)
461 {
462 return read(urandom_fd, data, len);
463 }
464
465
466 time_t odhcpd_time(void)
467 {
468 struct timespec ts;
469 syscall(SYS_clock_gettime, CLOCK_MONOTONIC, &ts);
470 return ts.tv_sec;
471 }
472
473
474 static const char hexdigits[] = "0123456789abcdef";
475 static const int8_t hexvals[] = {
476 -1, -1, -1, -1, -1, -1, -1, -1, -1, -2, -2, -1, -1, -2, -1, -1,
477 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
478 -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
479 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1,
480 -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
481 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
482 -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
483 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
484 };
485
486 ssize_t odhcpd_unhexlify(uint8_t *dst, size_t len, const char *src)
487 {
488 size_t c;
489 for (c = 0; c < len && src[0] && src[1]; ++c) {
490 int8_t x = (int8_t)*src++;
491 int8_t y = (int8_t)*src++;
492 if (x < 0 || (x = hexvals[x]) < 0
493 || y < 0 || (y = hexvals[y]) < 0)
494 return -1;
495 dst[c] = x << 4 | y;
496 while (((int8_t)*src) < 0 ||
497 (*src && hexvals[(uint8_t)*src] < 0))
498 src++;
499 }
500
501 return c;
502 }
503
504
505 void odhcpd_hexlify(char *dst, const uint8_t *src, size_t len)
506 {
507 for (size_t i = 0; i < len; ++i) {
508 *dst++ = hexdigits[src[i] >> 4];
509 *dst++ = hexdigits[src[i] & 0x0f];
510 }
511 *dst = 0;
512 }
513
514
515 int odhcpd_bmemcmp(const void *av, const void *bv, size_t bits)
516 {
517 const uint8_t *a = av, *b = bv;
518 size_t bytes = bits / 8;
519 bits %= 8;
520
521 int res = memcmp(a, b, bytes);
522 if (res == 0 && bits > 0)
523 res = (a[bytes] >> (8 - bits)) - (b[bytes] >> (8 - bits));
524
525 return res;
526 }
527
528
529 void odhcpd_bmemcpy(void *av, const void *bv, size_t bits)
530 {
531 uint8_t *a = av;
532 const uint8_t *b = bv;
533
534 size_t bytes = bits / 8;
535 bits %= 8;
536 memcpy(a, b, bytes);
537
538 if (bits > 0) {
539 uint8_t mask = (1 << (8 - bits)) - 1;
540 a[bytes] = (a[bytes] & mask) | ((~mask) & b[bytes]);
541 }
542 }