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], *nla_addr = NULL;
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);
250 switch (ifa->ifa_family) {
252 if (nla[IFA_ADDRESS])
253 nla_addr = nla[IFA_ADDRESS];
258 nla_addr = nla[IFA_LOCAL];
267 addrs = realloc(addrs, sizeof(*addrs)*(ctxt->ret + 1));
271 memset(&addrs[ctxt->ret], 0, sizeof(addrs[ctxt->ret]));
272 addrs[ctxt->ret].prefix = ifa->ifa_prefixlen;
274 nla_memcpy(&addrs[ctxt->ret].addr, nla_addr,
275 sizeof(addrs[ctxt->ret].addr));
277 if (nla[IFA_BROADCAST])
278 nla_memcpy(&addrs[ctxt->ret].broadcast, nla[IFA_BROADCAST],
279 sizeof(addrs[ctxt->ret].broadcast));
281 if (nla[IFA_CACHEINFO]) {
282 struct ifa_cacheinfo *ifc = nla_data(nla[IFA_CACHEINFO]);
284 addrs[ctxt->ret].preferred = ifc->ifa_prefered;
285 addrs[ctxt->ret].valid = ifc->ifa_valid;
288 if (ifa->ifa_flags & IFA_F_DEPRECATED)
289 addrs[ctxt->ret].preferred = 0;
292 *(ctxt->addrs) = addrs;
297 static int cb_finish_handler(_unused struct nl_msg *msg, void *arg)
299 struct addr_info *ctxt = (struct addr_info *)arg;
306 static int cb_error_handler(_unused struct sockaddr_nl *nla, struct nlmsgerr *err,
309 struct addr_info *ctxt = (struct addr_info *)arg;
312 ctxt->ret = err->error;
317 static int prefix_cmp(const void *va, const void *vb)
319 const struct odhcpd_ipaddr *a = va, *b = vb;
320 return (ntohl(a->addr.in.s_addr) < ntohl(b->addr.in.s_addr)) ? 1 :
321 (ntohl(a->addr.in.s_addr) > ntohl(b->addr.in.s_addr)) ? -1 : 0;
324 // compare IPv6 prefixes
325 static int prefix6_cmp(const void *va, const void *vb)
327 const struct odhcpd_ipaddr *a = va, *b = vb;
328 uint32_t a_pref = IN6_IS_ADDR_ULA(&a->addr.in6) ? 1 : a->preferred;
329 uint32_t b_pref = IN6_IS_ADDR_ULA(&b->addr.in6) ? 1 : b->preferred;
330 return (a_pref < b_pref) ? 1 : (a_pref > b_pref) ? -1 : 0;
333 // Detect an IPV6-address currently assigned to the given interface
334 ssize_t odhcpd_get_interface_addresses(int ifindex, bool v6, struct odhcpd_ipaddr **addrs)
337 struct ifaddrmsg ifa = {
338 .ifa_family = v6? AF_INET6: AF_INET,
342 .ifa_index = ifindex, };
343 struct nl_cb *cb = nl_cb_alloc(NL_CB_DEFAULT);
344 struct addr_info ctxt = {
346 .af = v6? AF_INET6: AF_INET,
357 msg = nlmsg_alloc_simple(RTM_GETADDR, NLM_F_REQUEST | NLM_F_DUMP);
364 nlmsg_append(msg, &ifa, sizeof(ifa), 0);
366 nl_cb_set(cb, NL_CB_VALID, NL_CB_CUSTOM, cb_valid_handler, &ctxt);
367 nl_cb_set(cb, NL_CB_FINISH, NL_CB_CUSTOM, cb_finish_handler, &ctxt);
368 nl_cb_err(cb, NL_CB_CUSTOM, cb_error_handler, &ctxt);
370 nl_send_auto_complete(rtnl_socket, msg);
371 while (ctxt.pending > 0)
372 nl_recvmsgs(rtnl_socket, cb);
379 time_t now = odhcpd_time();
380 struct odhcpd_ipaddr *addr = *addrs;
382 qsort(addr, ctxt.ret, sizeof(*addr), v6 ? prefix6_cmp : prefix_cmp);
384 for (ssize_t i = 0; i < ctxt.ret; ++i) {
385 if (addr[i].preferred < UINT32_MAX - now)
386 addr[i].preferred += now;
388 if (addr[i].valid < UINT32_MAX - now)
389 addr[i].valid += now;
398 static int odhcpd_get_linklocal_interface_address(int ifindex, struct in6_addr *lladdr)
401 struct sockaddr_in6 addr = {AF_INET6, 0, 0, ALL_IPV6_ROUTERS, ifindex};
402 socklen_t alen = sizeof(addr);
403 int sock = socket(AF_INET6, SOCK_RAW, IPPROTO_ICMPV6);
405 if (!connect(sock, (struct sockaddr*)&addr, sizeof(addr)) &&
406 !getsockname(sock, (struct sockaddr*)&addr, &alen)) {
407 *lladdr = addr.sin6_addr;
417 * DNS address selection criteria order :
418 * - use IPv6 address with valid lifetime if none is yet selected
419 * - use IPv6 address with a preferred lifetime if the already selected IPv6 address is deprecated
420 * - use an IPv6 ULA address if the already selected IPv6 address is not an ULA address
421 * - use the IPv6 address with the longest preferred lifetime
423 int odhcpd_get_interface_dns_addr(const struct interface *iface, struct in6_addr *addr)
425 time_t now = odhcpd_time();
428 for (size_t i = 0; i < iface->ia_addr_len; ++i) {
429 if (iface->ia_addr[i].valid <= (uint32_t)now)
437 if (iface->ia_addr[m].preferred >= (uint32_t)now &&
438 iface->ia_addr[i].preferred < (uint32_t)now)
441 if (IN6_IS_ADDR_ULA(&iface->ia_addr[i].addr.in6)) {
442 if (!IN6_IS_ADDR_ULA(&iface->ia_addr[m].addr.in6)) {
446 } else if (IN6_IS_ADDR_ULA(&iface->ia_addr[m].addr.in6))
449 if (iface->ia_addr[i].preferred > iface->ia_addr[m].preferred)
454 *addr = iface->ia_addr[m].addr.in6;
458 return odhcpd_get_linklocal_interface_address(iface->ifindex, addr);
461 int odhcpd_setup_route(const struct in6_addr *addr, const int prefixlen,
462 const struct interface *iface, const struct in6_addr *gw,
463 const uint32_t metric, const bool add)
467 .rtm_family = AF_INET6,
468 .rtm_dst_len = prefixlen,
470 .rtm_table = RT_TABLE_MAIN,
471 .rtm_protocol = (add ? RTPROT_STATIC : RTPROT_UNSPEC),
472 .rtm_scope = (add ? (gw ? RT_SCOPE_UNIVERSE : RT_SCOPE_LINK) : RT_SCOPE_NOWHERE),
473 .rtm_type = (add ? RTN_UNICAST : RTN_UNSPEC),
477 msg = nlmsg_alloc_simple(add ? RTM_NEWROUTE : RTM_DELROUTE,
478 add ? NLM_F_CREATE | NLM_F_REPLACE : 0);
482 nlmsg_append(msg, &rtm, sizeof(rtm), 0);
484 nla_put(msg, RTA_DST, sizeof(*addr), addr);
485 nla_put_u32(msg, RTA_OIF, iface->ifindex);
486 nla_put_u32(msg, RTA_PRIORITY, metric);
489 nla_put(msg, RTA_GATEWAY, sizeof(*gw), gw);
491 ret = nl_send_auto_complete(rtnl_socket, msg);
497 return nl_wait_for_ack(rtnl_socket);
500 int odhcpd_setup_proxy_neigh(const struct in6_addr *addr,
501 const struct interface *iface, const bool add)
505 .ndm_family = AF_INET6,
506 .ndm_flags = NTF_PROXY,
507 .ndm_ifindex = iface->ifindex,
509 int ret = 0, flags = NLM_F_REQUEST;
512 flags |= NLM_F_REPLACE | NLM_F_CREATE;
514 msg = nlmsg_alloc_simple(add ? RTM_NEWNEIGH : RTM_DELNEIGH, flags);
518 nlmsg_append(msg, &ndm, sizeof(ndm), 0);
520 nla_put(msg, NDA_DST, sizeof(*addr), addr);
522 ret = nl_send_auto_complete(rtnl_socket, msg);
528 return nl_wait_for_ack(rtnl_socket);
531 struct interface* odhcpd_get_interface_by_index(int ifindex)
533 struct interface *iface;
534 list_for_each_entry(iface, &interfaces, head)
535 if (iface->ifindex == ifindex)
542 struct interface* odhcpd_get_interface_by_name(const char *name)
544 struct interface *iface;
545 list_for_each_entry(iface, &interfaces, head)
546 if (!strcmp(iface->ifname, name))
553 struct interface* odhcpd_get_master_interface(void)
555 struct interface *iface;
556 list_for_each_entry(iface, &interfaces, head)
564 // Convenience function to receive and do basic validation of packets
565 static void odhcpd_receive_packets(struct uloop_fd *u, _unused unsigned int events)
567 struct odhcpd_event *e = container_of(u, struct odhcpd_event, uloop);
569 uint8_t data_buf[RELAYD_BUFFER_SIZE], cmsg_buf[128];
571 struct sockaddr_in6 in6;
572 struct sockaddr_in in;
573 struct sockaddr_ll ll;
574 struct sockaddr_nl nl;
579 socklen_t ret_len = sizeof(ret);
580 getsockopt(u->fd, SOL_SOCKET, SO_ERROR, &ret, &ret_len);
583 e->handle_error(e, ret);
592 struct iovec iov = {data_buf, sizeof(data_buf)};
593 struct msghdr msg = {
594 .msg_name = (void *) &addr,
595 .msg_namelen = sizeof(addr),
598 .msg_control = cmsg_buf,
599 .msg_controllen = sizeof(cmsg_buf),
603 ssize_t len = recvmsg(u->fd, &msg, MSG_DONTWAIT);
612 // Extract destination interface
616 struct in6_pktinfo *pktinfo;
617 struct in_pktinfo *pkt4info;
618 for (struct cmsghdr *ch = CMSG_FIRSTHDR(&msg); ch != NULL; ch = CMSG_NXTHDR(&msg, ch)) {
619 if (ch->cmsg_level == IPPROTO_IPV6 &&
620 ch->cmsg_type == IPV6_PKTINFO) {
621 pktinfo = (struct in6_pktinfo*)CMSG_DATA(ch);
622 destiface = pktinfo->ipi6_ifindex;
623 dest = &pktinfo->ipi6_addr;
624 } else if (ch->cmsg_level == IPPROTO_IP &&
625 ch->cmsg_type == IP_PKTINFO) {
626 pkt4info = (struct in_pktinfo*)CMSG_DATA(ch);
627 destiface = pkt4info->ipi_ifindex;
628 dest = &pkt4info->ipi_addr;
629 } else if (ch->cmsg_level == IPPROTO_IPV6 &&
630 ch->cmsg_type == IPV6_HOPLIMIT) {
631 hlim = (int*)CMSG_DATA(ch);
635 // Check hoplimit if received
636 if (hlim && *hlim != 255)
639 // Detect interface for packet sockets
640 if (addr.ll.sll_family == AF_PACKET)
641 destiface = addr.ll.sll_ifindex;
643 struct interface *iface =
644 odhcpd_get_interface_by_index(destiface);
646 if (!iface && addr.nl.nl_family != AF_NETLINK)
649 char ipbuf[INET6_ADDRSTRLEN] = "kernel";
650 if (addr.ll.sll_family == AF_PACKET &&
651 len >= (ssize_t)sizeof(struct ip6_hdr))
652 inet_ntop(AF_INET6, &data_buf[8], ipbuf, sizeof(ipbuf));
653 else if (addr.in6.sin6_family == AF_INET6)
654 inet_ntop(AF_INET6, &addr.in6.sin6_addr, ipbuf, sizeof(ipbuf));
655 else if (addr.in.sin_family == AF_INET)
656 inet_ntop(AF_INET, &addr.in.sin_addr, ipbuf, sizeof(ipbuf));
658 syslog(LOG_DEBUG, "Received %li Bytes from %s%%%s", (long)len,
659 ipbuf, (iface) ? iface->ifname : "netlink");
661 e->handle_dgram(&addr, data_buf, len, iface, dest);
665 // Register events for the multiplexer
666 int odhcpd_register(struct odhcpd_event *event)
668 event->uloop.cb = odhcpd_receive_packets;
669 return uloop_fd_add(&event->uloop, ULOOP_READ |
670 ((event->handle_error) ? ULOOP_ERROR_CB : 0));
673 int odhcpd_deregister(struct odhcpd_event *event)
675 event->uloop.cb = NULL;
676 return uloop_fd_delete(&event->uloop);
679 void odhcpd_process(struct odhcpd_event *event)
681 odhcpd_receive_packets(&event->uloop, 0);
684 int odhcpd_urandom(void *data, size_t len)
686 return read(urandom_fd, data, len);
690 time_t odhcpd_time(void)
693 syscall(SYS_clock_gettime, CLOCK_MONOTONIC, &ts);
698 static const char hexdigits[] = "0123456789abcdef";
699 static const int8_t hexvals[] = {
700 -1, -1, -1, -1, -1, -1, -1, -1, -1, -2, -2, -1, -1, -2, -1, -1,
701 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
702 -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
703 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1,
704 -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
705 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
706 -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
707 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
710 ssize_t odhcpd_unhexlify(uint8_t *dst, size_t len, const char *src)
713 for (c = 0; c < len && src[0] && src[1]; ++c) {
714 int8_t x = (int8_t)*src++;
715 int8_t y = (int8_t)*src++;
716 if (x < 0 || (x = hexvals[x]) < 0
717 || y < 0 || (y = hexvals[y]) < 0)
720 while (((int8_t)*src) < 0 ||
721 (*src && hexvals[(uint8_t)*src] < 0))
729 void odhcpd_hexlify(char *dst, const uint8_t *src, size_t len)
731 for (size_t i = 0; i < len; ++i) {
732 *dst++ = hexdigits[src[i] >> 4];
733 *dst++ = hexdigits[src[i] & 0x0f];
739 int odhcpd_bmemcmp(const void *av, const void *bv, size_t bits)
741 const uint8_t *a = av, *b = bv;
742 size_t bytes = bits / 8;
745 int res = memcmp(a, b, bytes);
746 if (res == 0 && bits > 0)
747 res = (a[bytes] >> (8 - bits)) - (b[bytes] >> (8 - bits));
753 void odhcpd_bmemcpy(void *av, const void *bv, size_t bits)
756 const uint8_t *b = bv;
758 size_t bytes = bits / 8;
763 uint8_t mask = (1 << (8 - bits)) - 1;
764 a[bytes] = (a[bytes] & mask) | ((~mask) & b[bytes]);