2 * Copyright (C) 2012-2013 Steven Barth <steven@midlink.org>
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.
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.
30 #include <arpa/inet.h>
32 #include <netinet/ip6.h>
33 #include <netpacket/packet.h>
34 #include <linux/netlink.h>
35 #include <linux/if_addr.h>
36 #include <linux/neighbour.h>
37 #include <linux/rtnetlink.h>
39 #include <sys/socket.h>
40 #include <sys/ioctl.h>
41 #include <sys/epoll.h>
42 #include <sys/types.h>
44 #include <sys/syscall.h>
46 #include <netlink/msg.h>
47 #include <netlink/socket.h>
48 #include <netlink/attr.h>
49 #include <libubox/uloop.h>
54 static int ioctl_sock;
55 static struct nl_sock *rtnl_socket = NULL;
56 static int urandom_fd = -1;
58 static void sighandler(_unused int signal)
63 static void print_usage(const char *app)
67 " -h, --help Print this help\n"
68 " -l level Specify log level 0..7 (default %d)\n",
73 int main(int argc, char **argv)
75 openlog("odhcpd", LOG_PERROR | LOG_PID, LOG_DAEMON);
78 while ((opt = getopt(argc, argv, "hl:")) != -1) {
84 config.log_level = (atoi(optarg) & LOG_PRIMASK);
85 fprintf(stderr, "Log level set to %d\n", config.log_level);
89 setlogmask(LOG_UPTO(config.log_level));
93 syslog(LOG_ERR, "Must be run as root!");
97 ioctl_sock = socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
99 if (!(rtnl_socket = odhcpd_create_nl_socket(NETLINK_ROUTE))) {
100 syslog(LOG_ERR, "Unable to open nl socket: %s", strerror(errno));
104 if ((urandom_fd = open("/dev/urandom", O_RDONLY | O_CLOEXEC)) < 0)
107 signal(SIGUSR1, SIG_IGN);
108 signal(SIGINT, sighandler);
109 signal(SIGTERM, sighandler);
127 struct nl_sock *odhcpd_create_nl_socket(int protocol)
129 struct nl_sock *nl_sock;
131 nl_sock = nl_socket_alloc();
135 if (nl_connect(nl_sock, protocol) < 0)
142 nl_socket_free(nl_sock);
148 // Read IPv6 MTU for interface
149 int odhcpd_get_interface_config(const char *ifname, const char *what)
152 const char *sysctl_pattern = "/proc/sys/net/ipv6/conf/%s/%s";
153 snprintf(buf, sizeof(buf), sysctl_pattern, ifname, what);
155 int fd = open(buf, O_RDONLY);
156 ssize_t len = read(fd, buf, sizeof(buf) - 1);
167 // Read IPv6 MAC for interface
168 int odhcpd_get_mac(const struct interface *iface, uint8_t mac[6])
171 memset(&ifr, 0, sizeof(ifr));
172 strncpy(ifr.ifr_name, iface->ifname, sizeof(ifr.ifr_name));
173 if (ioctl(ioctl_sock, SIOCGIFHWADDR, &ifr) < 0)
175 memcpy(mac, ifr.ifr_hwaddr.sa_data, 6);
180 // Forwards a packet on a specific interface
181 ssize_t odhcpd_send(int socket, struct sockaddr_in6 *dest,
182 struct iovec *iov, size_t iov_len,
183 const struct interface *iface)
186 uint8_t cmsg_buf[CMSG_SPACE(sizeof(struct in6_pktinfo))] = {0};
187 struct msghdr msg = {
188 .msg_name = (void *) dest,
189 .msg_namelen = sizeof(*dest),
191 .msg_iovlen = iov_len,
192 .msg_control = cmsg_buf,
193 .msg_controllen = sizeof(cmsg_buf),
197 // Set control data (define destination interface)
198 struct cmsghdr *chdr = CMSG_FIRSTHDR(&msg);
199 chdr->cmsg_level = IPPROTO_IPV6;
200 chdr->cmsg_type = IPV6_PKTINFO;
201 chdr->cmsg_len = CMSG_LEN(sizeof(struct in6_pktinfo));
202 struct in6_pktinfo *pktinfo = (struct in6_pktinfo*)CMSG_DATA(chdr);
203 pktinfo->ipi6_ifindex = iface->ifindex;
205 // Also set scope ID if link-local
206 if (IN6_IS_ADDR_LINKLOCAL(&dest->sin6_addr)
207 || IN6_IS_ADDR_MC_LINKLOCAL(&dest->sin6_addr))
208 dest->sin6_scope_id = iface->ifindex;
210 char ipbuf[INET6_ADDRSTRLEN];
211 inet_ntop(AF_INET6, &dest->sin6_addr, ipbuf, sizeof(ipbuf));
213 ssize_t sent = sendmsg(socket, &msg, MSG_DONTWAIT);
215 syslog(LOG_NOTICE, "Failed to send to %s%%%s (%s)",
216 ipbuf, iface->ifname, strerror(errno));
218 syslog(LOG_DEBUG, "Sent %li bytes to %s%%%s",
219 (long)sent, ipbuf, iface->ifname);
226 struct odhcpd_ipaddr **addrs;
231 static int cb_valid_handler(struct nl_msg *msg, void *arg)
233 struct addr_info *ctxt = (struct addr_info *)arg;
234 struct odhcpd_ipaddr *addrs = *(ctxt->addrs);
235 struct nlmsghdr *hdr = nlmsg_hdr(msg);
236 struct ifaddrmsg *ifa;
237 struct nlattr *nla[__IFA_MAX];
239 if (hdr->nlmsg_type != RTM_NEWADDR)
242 ifa = NLMSG_DATA(hdr);
243 if (ifa->ifa_scope != RT_SCOPE_UNIVERSE ||
244 (ctxt->af != ifa->ifa_family) ||
245 (ctxt->ifindex && ifa->ifa_index != (unsigned)ctxt->ifindex))
248 nlmsg_parse(hdr, sizeof(*ifa), nla, __IFA_MAX - 1, NULL);
249 if (!nla[IFA_ADDRESS])
252 addrs = realloc(addrs, sizeof(*addrs)*(ctxt->ret + 1));
256 memset(&addrs[ctxt->ret], 0, sizeof(addrs[ctxt->ret]));
257 addrs[ctxt->ret].prefix = ifa->ifa_prefixlen;
259 nla_memcpy(&addrs[ctxt->ret].addr, nla[IFA_ADDRESS],
260 sizeof(addrs[ctxt->ret].addr));
262 if (nla[IFA_CACHEINFO]) {
263 struct ifa_cacheinfo *ifc = nla_data(nla[IFA_CACHEINFO]);
265 addrs[ctxt->ret].preferred = ifc->ifa_prefered;
266 addrs[ctxt->ret].valid = ifc->ifa_valid;
269 if (ifa->ifa_flags & IFA_F_DEPRECATED)
270 addrs[ctxt->ret].preferred = 0;
273 *(ctxt->addrs) = addrs;
278 static int cb_finish_handler(_unused struct nl_msg *msg, void *arg)
280 struct addr_info *ctxt = (struct addr_info *)arg;
287 static int cb_error_handler(_unused struct sockaddr_nl *nla, struct nlmsgerr *err,
290 struct addr_info *ctxt = (struct addr_info *)arg;
293 ctxt->ret = err->error;
299 static int prefixcmp(const void *va, const void *vb)
301 const struct odhcpd_ipaddr *a = va, *b = vb;
302 uint32_t a_pref = IN6_IS_ADDR_ULA(&a->addr.in6) ? 1 : a->preferred;
303 uint32_t b_pref = IN6_IS_ADDR_ULA(&b->addr.in6) ? 1 : b->preferred;
304 return (a_pref < b_pref) ? 1 : (a_pref > b_pref) ? -1 : 0;
307 // Detect an IPV6-address currently assigned to the given interface
308 ssize_t odhcpd_get_interface_addresses(int ifindex, bool v6, struct odhcpd_ipaddr **addrs)
311 struct ifaddrmsg ifa = {
312 .ifa_family = v6? AF_INET6: AF_INET,
316 .ifa_index = ifindex, };
317 struct nl_cb *cb = nl_cb_alloc(NL_CB_DEFAULT);
318 struct addr_info ctxt = {
320 .af = v6? AF_INET6: AF_INET,
331 msg = nlmsg_alloc_simple(RTM_GETADDR, NLM_F_REQUEST | NLM_F_DUMP);
338 nlmsg_append(msg, &ifa, sizeof(ifa), 0);
340 nl_cb_set(cb, NL_CB_VALID, NL_CB_CUSTOM, cb_valid_handler, &ctxt);
341 nl_cb_set(cb, NL_CB_FINISH, NL_CB_CUSTOM, cb_finish_handler, &ctxt);
342 nl_cb_err(cb, NL_CB_CUSTOM, cb_error_handler, &ctxt);
344 nl_send_auto_complete(rtnl_socket, msg);
345 while (ctxt.pending > 0)
346 nl_recvmsgs(rtnl_socket, cb);
353 time_t now = odhcpd_time();
354 struct odhcpd_ipaddr *addr = *addrs;
356 qsort(addr, ctxt.ret, sizeof(*addr), prefixcmp);
358 for (ssize_t i = 0; i < ctxt.ret; ++i) {
359 if (addr[i].preferred < UINT32_MAX - now)
360 addr[i].preferred += now;
362 if (addr[i].valid < UINT32_MAX - now)
363 addr[i].valid += now;
372 static int odhcpd_get_linklocal_interface_address(int ifindex, struct in6_addr *lladdr)
375 struct sockaddr_in6 addr = {AF_INET6, 0, 0, ALL_IPV6_ROUTERS, ifindex};
376 socklen_t alen = sizeof(addr);
377 int sock = socket(AF_INET6, SOCK_RAW, IPPROTO_ICMPV6);
379 if (!connect(sock, (struct sockaddr*)&addr, sizeof(addr)) &&
380 !getsockname(sock, (struct sockaddr*)&addr, &alen)) {
381 *lladdr = addr.sin6_addr;
391 * DNS address selection criteria order :
392 * - use IPv6 address with valid lifetime if none is yet selected
393 * - use IPv6 address with a preferred lifetime if the already selected IPv6 address is deprecated
394 * - use an IPv6 ULA address if the already selected IPv6 address is not an ULA address
395 * - use the IPv6 address with the longest preferred lifetime
397 int odhcpd_get_interface_dns_addr(const struct interface *iface, struct in6_addr *addr)
399 time_t now = odhcpd_time();
402 for (size_t i = 0; i < iface->ia_addr_len; ++i) {
403 if (iface->ia_addr[i].valid <= (uint32_t)now)
411 if (iface->ia_addr[m].preferred >= (uint32_t)now &&
412 iface->ia_addr[i].preferred < (uint32_t)now)
415 if (IN6_IS_ADDR_ULA(&iface->ia_addr[i].addr.in6)) {
416 if (!IN6_IS_ADDR_ULA(&iface->ia_addr[m].addr.in6)) {
420 } else if (IN6_IS_ADDR_ULA(&iface->ia_addr[m].addr.in6))
423 if (iface->ia_addr[i].preferred > iface->ia_addr[m].preferred)
428 *addr = iface->ia_addr[m].addr.in6;
432 return odhcpd_get_linklocal_interface_address(iface->ifindex, addr);
435 int odhcpd_setup_route(const struct in6_addr *addr, const int prefixlen,
436 const struct interface *iface, const struct in6_addr *gw,
437 const uint32_t metric, const bool add)
441 .rtm_family = AF_INET6,
442 .rtm_dst_len = prefixlen,
444 .rtm_table = RT_TABLE_MAIN,
445 .rtm_protocol = (add ? RTPROT_STATIC : RTPROT_UNSPEC),
446 .rtm_scope = (add ? (gw ? RT_SCOPE_UNIVERSE : RT_SCOPE_LINK) : RT_SCOPE_NOWHERE),
447 .rtm_type = (add ? RTN_UNICAST : RTN_UNSPEC),
451 msg = nlmsg_alloc_simple(add ? RTM_NEWROUTE : RTM_DELROUTE,
452 add ? NLM_F_CREATE | NLM_F_REPLACE : 0);
456 nlmsg_append(msg, &rtm, sizeof(rtm), 0);
458 nla_put(msg, RTA_DST, sizeof(*addr), addr);
459 nla_put_u32(msg, RTA_OIF, iface->ifindex);
460 nla_put_u32(msg, RTA_PRIORITY, metric);
463 nla_put(msg, RTA_GATEWAY, sizeof(*gw), gw);
465 ret = nl_send_auto_complete(rtnl_socket, msg);
471 return nl_wait_for_ack(rtnl_socket);
474 int odhcpd_setup_proxy_neigh(const struct in6_addr *addr,
475 const struct interface *iface, const bool add)
479 .ndm_family = AF_INET6,
480 .ndm_flags = NTF_PROXY,
481 .ndm_ifindex = iface->ifindex,
483 int ret = 0, flags = NLM_F_REQUEST;
486 flags |= NLM_F_REPLACE | NLM_F_CREATE;
488 msg = nlmsg_alloc_simple(add ? RTM_NEWNEIGH : RTM_DELNEIGH, flags);
492 nlmsg_append(msg, &ndm, sizeof(ndm), 0);
494 nla_put(msg, NDA_DST, sizeof(*addr), addr);
496 ret = nl_send_auto_complete(rtnl_socket, msg);
502 return nl_wait_for_ack(rtnl_socket);
505 struct interface* odhcpd_get_interface_by_index(int ifindex)
507 struct interface *iface;
508 list_for_each_entry(iface, &interfaces, head)
509 if (iface->ifindex == ifindex)
516 struct interface* odhcpd_get_interface_by_name(const char *name)
518 struct interface *iface;
519 list_for_each_entry(iface, &interfaces, head)
520 if (!strcmp(iface->ifname, name))
527 struct interface* odhcpd_get_master_interface(void)
529 struct interface *iface;
530 list_for_each_entry(iface, &interfaces, head)
538 // Convenience function to receive and do basic validation of packets
539 static void odhcpd_receive_packets(struct uloop_fd *u, _unused unsigned int events)
541 struct odhcpd_event *e = container_of(u, struct odhcpd_event, uloop);
543 uint8_t data_buf[RELAYD_BUFFER_SIZE], cmsg_buf[128];
545 struct sockaddr_in6 in6;
546 struct sockaddr_in in;
547 struct sockaddr_ll ll;
548 struct sockaddr_nl nl;
553 socklen_t ret_len = sizeof(ret);
554 getsockopt(u->fd, SOL_SOCKET, SO_ERROR, &ret, &ret_len);
557 e->handle_error(e, ret);
566 struct iovec iov = {data_buf, sizeof(data_buf)};
567 struct msghdr msg = {
568 .msg_name = (void *) &addr,
569 .msg_namelen = sizeof(addr),
572 .msg_control = cmsg_buf,
573 .msg_controllen = sizeof(cmsg_buf),
577 ssize_t len = recvmsg(u->fd, &msg, MSG_DONTWAIT);
586 // Extract destination interface
590 struct in6_pktinfo *pktinfo;
591 struct in_pktinfo *pkt4info;
592 for (struct cmsghdr *ch = CMSG_FIRSTHDR(&msg); ch != NULL; ch = CMSG_NXTHDR(&msg, ch)) {
593 if (ch->cmsg_level == IPPROTO_IPV6 &&
594 ch->cmsg_type == IPV6_PKTINFO) {
595 pktinfo = (struct in6_pktinfo*)CMSG_DATA(ch);
596 destiface = pktinfo->ipi6_ifindex;
597 dest = &pktinfo->ipi6_addr;
598 } else if (ch->cmsg_level == IPPROTO_IP &&
599 ch->cmsg_type == IP_PKTINFO) {
600 pkt4info = (struct in_pktinfo*)CMSG_DATA(ch);
601 destiface = pkt4info->ipi_ifindex;
602 dest = &pkt4info->ipi_addr;
603 } else if (ch->cmsg_level == IPPROTO_IPV6 &&
604 ch->cmsg_type == IPV6_HOPLIMIT) {
605 hlim = (int*)CMSG_DATA(ch);
609 // Check hoplimit if received
610 if (hlim && *hlim != 255)
613 // Detect interface for packet sockets
614 if (addr.ll.sll_family == AF_PACKET)
615 destiface = addr.ll.sll_ifindex;
617 struct interface *iface =
618 odhcpd_get_interface_by_index(destiface);
620 if (!iface && addr.nl.nl_family != AF_NETLINK)
623 char ipbuf[INET6_ADDRSTRLEN] = "kernel";
624 if (addr.ll.sll_family == AF_PACKET &&
625 len >= (ssize_t)sizeof(struct ip6_hdr))
626 inet_ntop(AF_INET6, &data_buf[8], ipbuf, sizeof(ipbuf));
627 else if (addr.in6.sin6_family == AF_INET6)
628 inet_ntop(AF_INET6, &addr.in6.sin6_addr, ipbuf, sizeof(ipbuf));
629 else if (addr.in.sin_family == AF_INET)
630 inet_ntop(AF_INET, &addr.in.sin_addr, ipbuf, sizeof(ipbuf));
632 syslog(LOG_DEBUG, "Received %li Bytes from %s%%%s", (long)len,
633 ipbuf, (iface) ? iface->ifname : "netlink");
635 e->handle_dgram(&addr, data_buf, len, iface, dest);
639 // Register events for the multiplexer
640 int odhcpd_register(struct odhcpd_event *event)
642 event->uloop.cb = odhcpd_receive_packets;
643 return uloop_fd_add(&event->uloop, ULOOP_READ |
644 ((event->handle_error) ? ULOOP_ERROR_CB : 0));
647 int odhcpd_deregister(struct odhcpd_event *event)
649 event->uloop.cb = NULL;
650 return uloop_fd_delete(&event->uloop);
653 void odhcpd_process(struct odhcpd_event *event)
655 odhcpd_receive_packets(&event->uloop, 0);
658 int odhcpd_urandom(void *data, size_t len)
660 return read(urandom_fd, data, len);
664 time_t odhcpd_time(void)
667 syscall(SYS_clock_gettime, CLOCK_MONOTONIC, &ts);
672 static const char hexdigits[] = "0123456789abcdef";
673 static const int8_t hexvals[] = {
674 -1, -1, -1, -1, -1, -1, -1, -1, -1, -2, -2, -1, -1, -2, -1, -1,
675 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
676 -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
677 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1,
678 -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
679 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
680 -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
681 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
684 ssize_t odhcpd_unhexlify(uint8_t *dst, size_t len, const char *src)
687 for (c = 0; c < len && src[0] && src[1]; ++c) {
688 int8_t x = (int8_t)*src++;
689 int8_t y = (int8_t)*src++;
690 if (x < 0 || (x = hexvals[x]) < 0
691 || y < 0 || (y = hexvals[y]) < 0)
694 while (((int8_t)*src) < 0 ||
695 (*src && hexvals[(uint8_t)*src] < 0))
703 void odhcpd_hexlify(char *dst, const uint8_t *src, size_t len)
705 for (size_t i = 0; i < len; ++i) {
706 *dst++ = hexdigits[src[i] >> 4];
707 *dst++ = hexdigits[src[i] & 0x0f];
713 int odhcpd_bmemcmp(const void *av, const void *bv, size_t bits)
715 const uint8_t *a = av, *b = bv;
716 size_t bytes = bits / 8;
719 int res = memcmp(a, b, bytes);
720 if (res == 0 && bits > 0)
721 res = (a[bytes] >> (8 - bits)) - (b[bytes] >> (8 - bits));
727 void odhcpd_bmemcpy(void *av, const void *bv, size_t bits)
730 const uint8_t *b = bv;
732 size_t bytes = bits / 8;
737 uint8_t mask = (1 << (8 - bits)) - 1;
738 a[bytes] = (a[bytes] & mask) | ((~mask) & b[bytes]);