dhcpv4: rework assignment lookup
[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 #include <syslog.h>
28 #include <alloca.h>
29
30 #include <arpa/inet.h>
31 #include <net/if.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>
38
39 #include <sys/socket.h>
40 #include <sys/ioctl.h>
41 #include <sys/epoll.h>
42 #include <sys/types.h>
43 #include <sys/wait.h>
44 #include <sys/syscall.h>
45
46 #include <netlink/msg.h>
47 #include <netlink/socket.h>
48 #include <netlink/attr.h>
49 #include <libubox/uloop.h>
50 #include "odhcpd.h"
51
52
53
54 static int ioctl_sock;
55 static struct nl_sock *rtnl_socket = NULL;
56 static int urandom_fd = -1;
57
58 static void sighandler(_unused int signal)
59 {
60         uloop_end();
61 }
62
63 static void print_usage(const char *app)
64 {
65         printf(
66         "== %s Usage ==\n\n"
67         "  -h, --help   Print this help\n"
68         "  -l level     Specify log level 0..7 (default %d)\n",
69                 app, config.log_level
70         );
71 }
72
73 int main(int argc, char **argv)
74 {
75         openlog("odhcpd", LOG_PERROR | LOG_PID, LOG_DAEMON);
76         int opt;
77
78         while ((opt = getopt(argc, argv, "hl:")) != -1) {
79                 switch (opt) {
80                 case 'h':
81                         print_usage(argv[0]);
82                         return 0;
83                 case 'l':
84                         config.log_level = (atoi(optarg) & LOG_PRIMASK);
85                         fprintf(stderr, "Log level set to %d\n", config.log_level);
86                         break;
87                 }
88         }
89         setlogmask(LOG_UPTO(config.log_level));
90         uloop_init();
91
92         if (getuid() != 0) {
93                 syslog(LOG_ERR, "Must be run as root!");
94                 return 2;
95         }
96
97         ioctl_sock = socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
98
99         if (!(rtnl_socket = odhcpd_create_nl_socket(NETLINK_ROUTE))) {
100                 syslog(LOG_ERR, "Unable to open nl socket: %s", strerror(errno));
101                 return 2;
102         }
103
104         if ((urandom_fd = open("/dev/urandom", O_RDONLY | O_CLOEXEC)) < 0)
105                 return 4;
106
107         signal(SIGUSR1, SIG_IGN);
108         signal(SIGINT, sighandler);
109         signal(SIGTERM, sighandler);
110
111         if (init_router())
112                 return 4;
113
114         if (init_dhcpv6())
115                 return 4;
116
117         if (init_ndp())
118                 return 4;
119
120         if (init_dhcpv4())
121                 return 4;
122
123         odhcpd_run();
124         return 0;
125 }
126
127 struct nl_sock *odhcpd_create_nl_socket(int protocol)
128 {
129         struct nl_sock *nl_sock;
130
131         nl_sock = nl_socket_alloc();
132         if (!nl_sock)
133                 goto err;
134
135         if (nl_connect(nl_sock, protocol) < 0)
136                 goto err;
137
138         return nl_sock;
139
140 err:
141         if (nl_sock)
142                 nl_socket_free(nl_sock);
143
144         return NULL;
145 }
146
147
148 // Read IPv6 MTU for interface
149 int odhcpd_get_interface_config(const char *ifname, const char *what)
150 {
151         char buf[64];
152         const char *sysctl_pattern = "/proc/sys/net/ipv6/conf/%s/%s";
153         snprintf(buf, sizeof(buf), sysctl_pattern, ifname, what);
154
155         int fd = open(buf, O_RDONLY);
156         ssize_t len = read(fd, buf, sizeof(buf) - 1);
157         close(fd);
158
159         if (len < 0)
160                 return -1;
161
162         buf[len] = 0;
163         return atoi(buf);
164 }
165
166
167 // Read IPv6 MAC for interface
168 int odhcpd_get_mac(const struct interface *iface, uint8_t mac[6])
169 {
170         struct ifreq ifr;
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)
174                 return -1;
175         memcpy(mac, ifr.ifr_hwaddr.sa_data, 6);
176         return 0;
177 }
178
179
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)
184 {
185         // Construct headers
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),
190                 .msg_iov = iov,
191                 .msg_iovlen = iov_len,
192                 .msg_control = cmsg_buf,
193                 .msg_controllen = sizeof(cmsg_buf),
194                 .msg_flags = 0
195         };
196
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;
204
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;
209
210         char ipbuf[INET6_ADDRSTRLEN];
211         inet_ntop(AF_INET6, &dest->sin6_addr, ipbuf, sizeof(ipbuf));
212
213         ssize_t sent = sendmsg(socket, &msg, MSG_DONTWAIT);
214         if (sent < 0)
215                 syslog(LOG_NOTICE, "Failed to send to %s%%%s (%s)",
216                                 ipbuf, iface->ifname, strerror(errno));
217         else
218                 syslog(LOG_DEBUG, "Sent %li bytes to %s%%%s",
219                                 (long)sent, ipbuf, iface->ifname);
220         return sent;
221 }
222
223 struct addr_info {
224         int ifindex;
225         int af;
226         struct odhcpd_ipaddr **addrs;
227         int pending;
228         ssize_t ret;
229 };
230
231 static int cb_valid_handler(struct nl_msg *msg, void *arg)
232 {
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;
238
239         if (hdr->nlmsg_type != RTM_NEWADDR)
240                 return NL_SKIP;
241
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))
246                 return NL_SKIP;
247
248         nlmsg_parse(hdr, sizeof(*ifa), nla, __IFA_MAX - 1, NULL);
249
250         switch (ifa->ifa_family) {
251         case AF_INET6:
252                 if (nla[IFA_ADDRESS])
253                         nla_addr = nla[IFA_ADDRESS];
254                 break;
255
256         case AF_INET:
257                 if (nla[IFA_LOCAL])
258                         nla_addr = nla[IFA_LOCAL];
259                 break;
260
261         default:
262                 break;
263         }
264         if (!nla_addr)
265                 return NL_SKIP;
266
267         addrs = realloc(addrs, sizeof(*addrs)*(ctxt->ret + 1));
268         if (!addrs)
269                 return NL_SKIP;
270
271         memset(&addrs[ctxt->ret], 0, sizeof(addrs[ctxt->ret]));
272         addrs[ctxt->ret].prefix = ifa->ifa_prefixlen;
273
274         nla_memcpy(&addrs[ctxt->ret].addr, nla_addr,
275                         sizeof(addrs[ctxt->ret].addr));
276
277         if (nla[IFA_BROADCAST])
278                 nla_memcpy(&addrs[ctxt->ret].broadcast, nla[IFA_BROADCAST],
279                                 sizeof(addrs[ctxt->ret].broadcast));
280
281         if (nla[IFA_CACHEINFO]) {
282                 struct ifa_cacheinfo *ifc = nla_data(nla[IFA_CACHEINFO]);
283
284                 addrs[ctxt->ret].preferred = ifc->ifa_prefered;
285                 addrs[ctxt->ret].valid = ifc->ifa_valid;
286         }
287
288         if (ifa->ifa_flags & IFA_F_DEPRECATED)
289                 addrs[ctxt->ret].preferred = 0;
290
291         ctxt->ret++;
292         *(ctxt->addrs) = addrs;
293
294         return NL_OK;
295 }
296
297 static int cb_finish_handler(_unused struct nl_msg *msg, void *arg)
298 {
299         struct addr_info *ctxt = (struct addr_info *)arg;
300
301         ctxt->pending = 0;
302
303         return NL_STOP;
304 }
305
306 static int cb_error_handler(_unused struct sockaddr_nl *nla, struct nlmsgerr *err,
307                 void *arg)
308 {
309         struct addr_info *ctxt = (struct addr_info *)arg;
310
311         ctxt->pending = 0;
312         ctxt->ret = err->error;
313
314         return NL_STOP;
315 }
316
317 static int prefix_cmp(const void *va, const void *vb)
318 {
319         const struct odhcpd_ipaddr *a = va, *b = vb;
320         int ret = 0;
321
322         if (a->prefix == b->prefix) {
323                 ret = (ntohl(a->addr.in.s_addr) < ntohl(b->addr.in.s_addr)) ? 1 :
324                         (ntohl(a->addr.in.s_addr) > ntohl(b->addr.in.s_addr)) ? -1 : 0;
325         } else
326                 ret = a->prefix < b->prefix ? 1 : -1;
327
328         return ret;
329 }
330
331 // compare IPv6 prefixes
332 static int prefix6_cmp(const void *va, const void *vb)
333 {
334         const struct odhcpd_ipaddr *a = va, *b = vb;
335         uint32_t a_pref = IN6_IS_ADDR_ULA(&a->addr.in6) ? 1 : a->preferred;
336         uint32_t b_pref = IN6_IS_ADDR_ULA(&b->addr.in6) ? 1 : b->preferred;
337         return (a_pref < b_pref) ? 1 : (a_pref > b_pref) ? -1 : 0;
338 }
339
340 // Detect an IPV6-address currently assigned to the given interface
341 ssize_t odhcpd_get_interface_addresses(int ifindex, bool v6, struct odhcpd_ipaddr **addrs)
342 {
343         struct nl_msg *msg;
344         struct ifaddrmsg ifa = {
345                 .ifa_family = v6? AF_INET6: AF_INET,
346                 .ifa_prefixlen = 0,
347                 .ifa_flags = 0,
348                 .ifa_scope = 0,
349                 .ifa_index = ifindex, };
350         struct nl_cb *cb = nl_cb_alloc(NL_CB_DEFAULT);
351         struct addr_info ctxt = {
352                 .ifindex = ifindex,
353                 .af = v6? AF_INET6: AF_INET,
354                 .addrs = addrs,
355                 .ret = 0,
356                 .pending = 1,
357         };
358
359         if (!cb) {
360                 ctxt.ret = -1;
361                 goto out;
362         }
363
364         msg = nlmsg_alloc_simple(RTM_GETADDR, NLM_F_REQUEST | NLM_F_DUMP);
365
366         if (!msg) {
367                 ctxt.ret = - 1;
368                 goto out;
369         }
370
371         nlmsg_append(msg, &ifa, sizeof(ifa), 0);
372
373         nl_cb_set(cb, NL_CB_VALID, NL_CB_CUSTOM, cb_valid_handler, &ctxt);
374         nl_cb_set(cb, NL_CB_FINISH, NL_CB_CUSTOM, cb_finish_handler, &ctxt);
375         nl_cb_err(cb, NL_CB_CUSTOM, cb_error_handler, &ctxt);
376
377         nl_send_auto_complete(rtnl_socket, msg);
378         while (ctxt.pending > 0)
379                 nl_recvmsgs(rtnl_socket, cb);
380
381         nlmsg_free(msg);
382
383         if (ctxt.ret <= 0)
384                 goto out;
385
386         time_t now = odhcpd_time();
387         struct odhcpd_ipaddr *addr = *addrs;
388
389         qsort(addr, ctxt.ret, sizeof(*addr), v6 ? prefix6_cmp : prefix_cmp);
390
391         for (ssize_t i = 0; i < ctxt.ret; ++i) {
392                 if (addr[i].preferred < UINT32_MAX - now)
393                         addr[i].preferred += now;
394
395                 if (addr[i].valid < UINT32_MAX - now)
396                         addr[i].valid += now;
397         }
398
399 out:
400         nl_cb_put(cb);
401
402         return ctxt.ret;
403 }
404
405 static int odhcpd_get_linklocal_interface_address(int ifindex, struct in6_addr *lladdr)
406 {
407         int status = -1;
408         struct sockaddr_in6 addr = {AF_INET6, 0, 0, ALL_IPV6_ROUTERS, ifindex};
409         socklen_t alen = sizeof(addr);
410         int sock = socket(AF_INET6, SOCK_RAW, IPPROTO_ICMPV6);
411
412         if (!connect(sock, (struct sockaddr*)&addr, sizeof(addr)) &&
413                         !getsockname(sock, (struct sockaddr*)&addr, &alen)) {
414                 *lladdr = addr.sin6_addr;
415                 status = 0;
416         }
417
418         close(sock);
419
420         return status;
421 }
422
423 /*
424  * DNS address selection criteria order :
425  * - use IPv6 address with valid lifetime if none is yet selected
426  * - use IPv6 address with a preferred lifetime if the already selected IPv6 address is deprecated
427  * - use an IPv6 ULA address if the already selected IPv6 address is not an ULA address
428  * - use the IPv6 address with the longest preferred lifetime
429  */
430 int odhcpd_get_interface_dns_addr(const struct interface *iface, struct in6_addr *addr)
431 {
432         time_t now = odhcpd_time();
433         ssize_t m = -1;
434
435         for (size_t i = 0; i < iface->ia_addr_len; ++i) {
436                 if (iface->ia_addr[i].valid <= (uint32_t)now)
437                         continue;
438
439                 if (m < 0) {
440                         m = i;
441                         continue;
442                 }
443
444                 if (iface->ia_addr[m].preferred >= (uint32_t)now &&
445                                 iface->ia_addr[i].preferred < (uint32_t)now)
446                         continue;
447
448                 if (IN6_IS_ADDR_ULA(&iface->ia_addr[i].addr.in6)) {
449                         if (!IN6_IS_ADDR_ULA(&iface->ia_addr[m].addr.in6)) {
450                                 m = i;
451                                 continue;
452                         }
453                 } else if (IN6_IS_ADDR_ULA(&iface->ia_addr[m].addr.in6))
454                         continue;
455
456                 if (iface->ia_addr[i].preferred > iface->ia_addr[m].preferred)
457                         m = i;
458         }
459
460         if (m >= 0) {
461                 *addr = iface->ia_addr[m].addr.in6;
462                 return 0;
463         }
464
465         return odhcpd_get_linklocal_interface_address(iface->ifindex, addr);
466 }
467
468 int odhcpd_setup_route(const struct in6_addr *addr, const int prefixlen,
469                 const struct interface *iface, const struct in6_addr *gw,
470                 const uint32_t metric, const bool add)
471 {
472         struct nl_msg *msg;
473         struct rtmsg rtm = {
474                 .rtm_family = AF_INET6,
475                 .rtm_dst_len = prefixlen,
476                 .rtm_src_len = 0,
477                 .rtm_table = RT_TABLE_MAIN,
478                 .rtm_protocol = (add ? RTPROT_STATIC : RTPROT_UNSPEC),
479                 .rtm_scope = (add ? (gw ? RT_SCOPE_UNIVERSE : RT_SCOPE_LINK) : RT_SCOPE_NOWHERE),
480                 .rtm_type = (add ? RTN_UNICAST : RTN_UNSPEC),
481         };
482         int ret = 0;
483
484         msg = nlmsg_alloc_simple(add ? RTM_NEWROUTE : RTM_DELROUTE,
485                                         add ? NLM_F_CREATE | NLM_F_REPLACE : 0);
486         if (!msg)
487                 return -1;
488
489         nlmsg_append(msg, &rtm, sizeof(rtm), 0);
490
491         nla_put(msg, RTA_DST, sizeof(*addr), addr);
492         nla_put_u32(msg, RTA_OIF, iface->ifindex);
493         nla_put_u32(msg, RTA_PRIORITY, metric);
494
495         if (gw)
496                 nla_put(msg, RTA_GATEWAY, sizeof(*gw), gw);
497
498         ret = nl_send_auto_complete(rtnl_socket, msg);
499         nlmsg_free(msg);
500
501         if (ret < 0)
502                 return ret;
503
504         return nl_wait_for_ack(rtnl_socket);
505 }
506
507 int odhcpd_setup_proxy_neigh(const struct in6_addr *addr,
508                 const struct interface *iface, const bool add)
509 {
510         struct nl_msg *msg;
511         struct ndmsg ndm = {
512                 .ndm_family = AF_INET6,
513                 .ndm_flags = NTF_PROXY,
514                 .ndm_ifindex = iface->ifindex,
515         };
516         int ret = 0, flags = NLM_F_REQUEST;
517
518         if (add)
519                 flags |= NLM_F_REPLACE | NLM_F_CREATE;
520
521         msg = nlmsg_alloc_simple(add ? RTM_NEWNEIGH : RTM_DELNEIGH, flags);
522         if (!msg)
523                 return -1;
524
525         nlmsg_append(msg, &ndm, sizeof(ndm), 0);
526
527         nla_put(msg, NDA_DST, sizeof(*addr), addr);
528
529         ret = nl_send_auto_complete(rtnl_socket, msg);
530         nlmsg_free(msg);
531
532         if (ret < 0)
533                 return ret;
534
535         return nl_wait_for_ack(rtnl_socket);
536 }
537
538 int odhcpd_setup_addr(struct odhcpd_ipaddr *addr,
539                 const struct interface *iface, const bool v6,
540                 const bool add)
541 {
542         struct nl_msg *msg;
543         struct ifaddrmsg ifa = {
544                 .ifa_family = v6 ? AF_INET6 : AF_INET,
545                 .ifa_prefixlen = addr->prefix,
546                 .ifa_flags = 0,
547                 .ifa_scope = 0,
548                 .ifa_index = iface->ifindex, };
549         int ret = 0, flags = NLM_F_REQUEST;
550
551         if (add)
552                 flags |= NLM_F_REPLACE | NLM_F_CREATE;
553
554         msg = nlmsg_alloc_simple(add ? RTM_NEWADDR : RTM_DELADDR, 0);
555         if (!msg)
556                 return -1;
557
558         nlmsg_append(msg, &ifa, sizeof(ifa), flags);
559         nla_put(msg, IFA_LOCAL, v6 ? 16 : 4, &addr->addr);
560         if (v6) {
561                 struct ifa_cacheinfo cinfo = {  .ifa_prefered = 0xffffffffU,
562                                                 .ifa_valid = 0xffffffffU,
563                                                 .cstamp = 0,
564                                                 .tstamp = 0 };
565                 time_t now = odhcpd_time();
566
567                 if (addr->preferred) {
568                         int64_t preferred = addr->preferred - now;
569                         if (preferred < 0)
570                                 preferred = 0;
571                         else if (preferred > UINT32_MAX)
572                                 preferred = UINT32_MAX;
573
574                         cinfo.ifa_prefered = preferred;
575                 }
576
577                 if (addr->valid) {
578                         int64_t valid = addr->valid - now;
579                         if (valid <= 0) {
580                                 nlmsg_free(msg);
581                                 return -1;
582                         }
583                         else if (valid > UINT32_MAX)
584                                 valid = UINT32_MAX;
585
586                         cinfo.ifa_valid = valid;
587                 }
588
589                 nla_put(msg, IFA_CACHEINFO, sizeof(cinfo), &cinfo);
590
591                 nla_put_u32(msg, IFA_FLAGS, IFA_F_NOPREFIXROUTE);
592         } else {
593                 if (addr->broadcast.s_addr)
594                         nla_put_u32(msg, IFA_BROADCAST, addr->broadcast.s_addr);
595         }
596
597         ret = nl_send_auto_complete(rtnl_socket, msg);
598         nlmsg_free(msg);
599
600         if (ret < 0)
601                 return ret;
602
603         return nl_wait_for_ack(rtnl_socket);
604 }
605
606 struct interface* odhcpd_get_interface_by_index(int ifindex)
607 {
608         struct interface *iface;
609         list_for_each_entry(iface, &interfaces, head)
610                 if (iface->ifindex == ifindex)
611                         return iface;
612
613         return NULL;
614 }
615
616
617 struct interface* odhcpd_get_interface_by_name(const char *name)
618 {
619         struct interface *iface;
620         list_for_each_entry(iface, &interfaces, head)
621                 if (!strcmp(iface->ifname, name))
622                         return iface;
623
624         return NULL;
625 }
626
627
628 struct interface* odhcpd_get_master_interface(void)
629 {
630         struct interface *iface;
631         list_for_each_entry(iface, &interfaces, head)
632                 if (iface->master)
633                         return iface;
634
635         return NULL;
636 }
637
638
639 // Convenience function to receive and do basic validation of packets
640 static void odhcpd_receive_packets(struct uloop_fd *u, _unused unsigned int events)
641 {
642         struct odhcpd_event *e = container_of(u, struct odhcpd_event, uloop);
643
644         uint8_t data_buf[8192], cmsg_buf[128];
645         union {
646                 struct sockaddr_in6 in6;
647                 struct sockaddr_in in;
648                 struct sockaddr_ll ll;
649                 struct sockaddr_nl nl;
650         } addr;
651
652         if (u->error) {
653                 int ret = -1;
654                 socklen_t ret_len = sizeof(ret);
655                 getsockopt(u->fd, SOL_SOCKET, SO_ERROR, &ret, &ret_len);
656                 u->error = false;
657                 if (e->handle_error)
658                         e->handle_error(e, ret);
659         }
660
661         if (e->recv_msgs) {
662                 e->recv_msgs(e);
663                 return;
664         }
665
666         while (true) {
667                 struct iovec iov = {data_buf, sizeof(data_buf)};
668                 struct msghdr msg = {
669                         .msg_name = (void *) &addr,
670                         .msg_namelen = sizeof(addr),
671                         .msg_iov = &iov,
672                         .msg_iovlen = 1,
673                         .msg_control = cmsg_buf,
674                         .msg_controllen = sizeof(cmsg_buf),
675                         .msg_flags = 0
676                 };
677
678                 ssize_t len = recvmsg(u->fd, &msg, MSG_DONTWAIT);
679                 if (len < 0) {
680                         if (errno == EAGAIN)
681                                 break;
682                         else
683                                 continue;
684                 }
685
686
687                 // Extract destination interface
688                 int destiface = 0;
689                 int *hlim = NULL;
690                 void *dest = NULL;
691                 struct in6_pktinfo *pktinfo;
692                 struct in_pktinfo *pkt4info;
693                 for (struct cmsghdr *ch = CMSG_FIRSTHDR(&msg); ch != NULL; ch = CMSG_NXTHDR(&msg, ch)) {
694                         if (ch->cmsg_level == IPPROTO_IPV6 &&
695                                         ch->cmsg_type == IPV6_PKTINFO) {
696                                 pktinfo = (struct in6_pktinfo*)CMSG_DATA(ch);
697                                 destiface = pktinfo->ipi6_ifindex;
698                                 dest = &pktinfo->ipi6_addr;
699                         } else if (ch->cmsg_level == IPPROTO_IP &&
700                                         ch->cmsg_type == IP_PKTINFO) {
701                                 pkt4info = (struct in_pktinfo*)CMSG_DATA(ch);
702                                 destiface = pkt4info->ipi_ifindex;
703                                 dest = &pkt4info->ipi_addr;
704                         } else if (ch->cmsg_level == IPPROTO_IPV6 &&
705                                         ch->cmsg_type == IPV6_HOPLIMIT) {
706                                 hlim = (int*)CMSG_DATA(ch);
707                         }
708                 }
709
710                 // Check hoplimit if received
711                 if (hlim && *hlim != 255)
712                         continue;
713
714                 // Detect interface for packet sockets
715                 if (addr.ll.sll_family == AF_PACKET)
716                         destiface = addr.ll.sll_ifindex;
717
718                 struct interface *iface =
719                                 odhcpd_get_interface_by_index(destiface);
720
721                 if (!iface && addr.nl.nl_family != AF_NETLINK)
722                         continue;
723
724                 char ipbuf[INET6_ADDRSTRLEN] = "kernel";
725                 if (addr.ll.sll_family == AF_PACKET &&
726                                 len >= (ssize_t)sizeof(struct ip6_hdr))
727                         inet_ntop(AF_INET6, &data_buf[8], ipbuf, sizeof(ipbuf));
728                 else if (addr.in6.sin6_family == AF_INET6)
729                         inet_ntop(AF_INET6, &addr.in6.sin6_addr, ipbuf, sizeof(ipbuf));
730                 else if (addr.in.sin_family == AF_INET)
731                         inet_ntop(AF_INET, &addr.in.sin_addr, ipbuf, sizeof(ipbuf));
732
733                 syslog(LOG_DEBUG, "Received %li Bytes from %s%%%s", (long)len,
734                                 ipbuf, (iface) ? iface->ifname : "netlink");
735
736                 e->handle_dgram(&addr, data_buf, len, iface, dest);
737         }
738 }
739
740 // Register events for the multiplexer
741 int odhcpd_register(struct odhcpd_event *event)
742 {
743         event->uloop.cb = odhcpd_receive_packets;
744         return uloop_fd_add(&event->uloop, ULOOP_READ |
745                         ((event->handle_error) ? ULOOP_ERROR_CB : 0));
746 }
747
748 int odhcpd_deregister(struct odhcpd_event *event)
749 {
750         event->uloop.cb = NULL;
751         return uloop_fd_delete(&event->uloop);
752 }
753
754 void odhcpd_process(struct odhcpd_event *event)
755 {
756         odhcpd_receive_packets(&event->uloop, 0);
757 }
758
759 int odhcpd_urandom(void *data, size_t len)
760 {
761         return read(urandom_fd, data, len);
762 }
763
764
765 time_t odhcpd_time(void)
766 {
767         struct timespec ts;
768         syscall(SYS_clock_gettime, CLOCK_MONOTONIC, &ts);
769         return ts.tv_sec;
770 }
771
772
773 static const char hexdigits[] = "0123456789abcdef";
774 static const int8_t hexvals[] = {
775     -1, -1, -1, -1, -1, -1, -1, -1, -1, -2, -2, -1, -1, -2, -1, -1,
776     -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
777     -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
778      0,  1,  2,  3,  4,  5,  6,  7,  8,  9, -1, -1, -1, -1, -1, -1,
779     -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
780     -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
781     -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
782     -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
783 };
784
785 ssize_t odhcpd_unhexlify(uint8_t *dst, size_t len, const char *src)
786 {
787         size_t c;
788         for (c = 0; c < len && src[0] && src[1]; ++c) {
789                 int8_t x = (int8_t)*src++;
790                 int8_t y = (int8_t)*src++;
791                 if (x < 0 || (x = hexvals[x]) < 0
792                                 || y < 0 || (y = hexvals[y]) < 0)
793                         return -1;
794                 dst[c] = x << 4 | y;
795                 while (((int8_t)*src) < 0 ||
796                                 (*src && hexvals[(uint8_t)*src] < 0))
797                         src++;
798         }
799
800         return c;
801 }
802
803
804 void odhcpd_hexlify(char *dst, const uint8_t *src, size_t len)
805 {
806         for (size_t i = 0; i < len; ++i) {
807                 *dst++ = hexdigits[src[i] >> 4];
808                 *dst++ = hexdigits[src[i] & 0x0f];
809         }
810         *dst = 0;
811 }
812
813
814 int odhcpd_bmemcmp(const void *av, const void *bv, size_t bits)
815 {
816         const uint8_t *a = av, *b = bv;
817         size_t bytes = bits / 8;
818         bits %= 8;
819
820         int res = memcmp(a, b, bytes);
821         if (res == 0 && bits > 0)
822                 res = (a[bytes] >> (8 - bits)) - (b[bytes] >> (8 - bits));
823
824         return res;
825 }
826
827
828 void odhcpd_bmemcpy(void *av, const void *bv, size_t bits)
829 {
830         uint8_t *a = av;
831         const uint8_t *b = bv;
832
833         size_t bytes = bits / 8;
834         bits %= 8;
835         memcpy(a, b, bytes);
836
837         if (bits > 0) {
838                 uint8_t mask = (1 << (8 - bits)) - 1;
839                 a[bytes] = (a[bytes] & mask) | ((~mask) & b[bytes]);
840         }
841 }
842
843
844 int odhcpd_netmask2bitlen(bool inet6, void *mask)
845 {
846         int bits;
847         struct in_addr *v4;
848         struct in6_addr *v6;
849
850         if (inet6)
851                 for (bits = 0, v6 = mask;
852                      bits < 128 && (v6->s6_addr[bits / 8] << (bits % 8)) & 128;
853                      bits++);
854         else
855                 for (bits = 0, v4 = mask;
856                      bits < 32 && (ntohl(v4->s_addr) << bits) & 0x80000000;
857                      bits++);
858
859         return bits;
860 }
861
862 bool odhcpd_bitlen2netmask(bool inet6, unsigned int bits, void *mask)
863 {
864         uint8_t b;
865         struct in_addr *v4;
866         struct in6_addr *v6;
867
868         if (inet6)
869         {
870                 if (bits > 128)
871                         return false;
872
873                 v6 = mask;
874
875                 for (unsigned int i = 0; i < sizeof(v6->s6_addr); i++)
876                 {
877                         b = (bits > 8) ? 8 : bits;
878                         v6->s6_addr[i] = (uint8_t)(0xFF << (8 - b));
879                         bits -= b;
880                 }
881         }
882         else
883         {
884                 if (bits > 32)
885                         return false;
886
887                 v4 = mask;
888                 v4->s_addr = bits ? htonl(~((1 << (32 - bits)) - 1)) : 0;
889         }
890
891         return true;
892 }