treewide: rework logic to retrieve IPv6 interface addresses
[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];
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         if (!nla[IFA_ADDRESS])
250                 return NL_SKIP;
251
252         addrs = realloc(addrs, sizeof(*addrs)*(ctxt->ret + 1));
253         if (!addrs)
254                 return NL_SKIP;
255
256         memset(&addrs[ctxt->ret], 0, sizeof(addrs[ctxt->ret]));
257         addrs[ctxt->ret].prefix = ifa->ifa_prefixlen;
258
259         nla_memcpy(&addrs[ctxt->ret].addr, nla[IFA_ADDRESS],
260                         sizeof(addrs[ctxt->ret].addr));
261
262         if (nla[IFA_CACHEINFO]) {
263                 struct ifa_cacheinfo *ifc = nla_data(nla[IFA_CACHEINFO]);
264
265                 addrs[ctxt->ret].preferred = ifc->ifa_prefered;
266                 addrs[ctxt->ret].valid = ifc->ifa_valid;
267         }
268
269         if (ifa->ifa_flags & IFA_F_DEPRECATED)
270                 addrs[ctxt->ret].preferred = 0;
271
272         ctxt->ret++;
273         *(ctxt->addrs) = addrs;
274
275         return NL_OK;
276 }
277
278 static int cb_finish_handler(_unused struct nl_msg *msg, void *arg)
279 {
280         struct addr_info *ctxt = (struct addr_info *)arg;
281
282         ctxt->pending = 0;
283
284         return NL_STOP;
285 }
286
287 static int cb_error_handler(_unused struct sockaddr_nl *nla, struct nlmsgerr *err,
288                 void *arg)
289 {
290         struct addr_info *ctxt = (struct addr_info *)arg;
291
292         ctxt->pending = 0;
293         ctxt->ret = err->error;
294
295         return NL_STOP;
296 }
297
298 // compare prefixes
299 static int prefixcmp(const void *va, const void *vb)
300 {
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;
305 }
306
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)
309 {
310         struct nl_msg *msg;
311         struct ifaddrmsg ifa = {
312                 .ifa_family = v6? AF_INET6: AF_INET,
313                 .ifa_prefixlen = 0,
314                 .ifa_flags = 0,
315                 .ifa_scope = 0,
316                 .ifa_index = ifindex, };
317         struct nl_cb *cb = nl_cb_alloc(NL_CB_DEFAULT);
318         struct addr_info ctxt = {
319                 .ifindex = ifindex,
320                 .af = v6? AF_INET6: AF_INET,
321                 .addrs = addrs,
322                 .ret = 0,
323                 .pending = 1,
324         };
325
326         if (!cb) {
327                 ctxt.ret = -1;
328                 goto out;
329         }
330
331         msg = nlmsg_alloc_simple(RTM_GETADDR, NLM_F_REQUEST | NLM_F_DUMP);
332
333         if (!msg) {
334                 ctxt.ret = - 1;
335                 goto out;
336         }
337
338         nlmsg_append(msg, &ifa, sizeof(ifa), 0);
339
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);
343
344         nl_send_auto_complete(rtnl_socket, msg);
345         while (ctxt.pending > 0)
346                 nl_recvmsgs(rtnl_socket, cb);
347
348         nlmsg_free(msg);
349
350         if (ctxt.ret <= 0)
351                 goto out;
352
353         time_t now = odhcpd_time();
354         struct odhcpd_ipaddr *addr = *addrs;
355
356         qsort(addr, ctxt.ret, sizeof(*addr), prefixcmp);
357
358         for (ssize_t i = 0; i < ctxt.ret; ++i) {
359                 if (addr[i].preferred < UINT32_MAX - now)
360                         addr[i].preferred += now;
361
362                 if (addr[i].valid < UINT32_MAX - now)
363                         addr[i].valid += now;
364         }
365
366 out:
367         nl_cb_put(cb);
368
369         return ctxt.ret;
370 }
371
372 static int odhcpd_get_linklocal_interface_address(int ifindex, struct in6_addr *lladdr)
373 {
374         int status = -1;
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);
378
379         if (!connect(sock, (struct sockaddr*)&addr, sizeof(addr)) &&
380                         !getsockname(sock, (struct sockaddr*)&addr, &alen)) {
381                 *lladdr = addr.sin6_addr;
382                 status = 0;
383         }
384
385         close(sock);
386
387         return status;
388 }
389
390 /*
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
396  */
397 int odhcpd_get_interface_dns_addr(const struct interface *iface, struct in6_addr *addr)
398 {
399         time_t now = odhcpd_time();
400         ssize_t m = -1;
401
402         for (size_t i = 0; i < iface->ia_addr_len; ++i) {
403                 if (iface->ia_addr[i].valid <= (uint32_t)now)
404                         continue;
405
406                 if (m < 0) {
407                         m = i;
408                         continue;
409                 }
410
411                 if (iface->ia_addr[m].preferred >= (uint32_t)now &&
412                                 iface->ia_addr[i].preferred < (uint32_t)now)
413                         continue;
414
415                 if (IN6_IS_ADDR_ULA(&iface->ia_addr[i].addr.in6)) {
416                         if (!IN6_IS_ADDR_ULA(&iface->ia_addr[m].addr.in6)) {
417                                 m = i;
418                                 continue;
419                         }
420                 } else if (IN6_IS_ADDR_ULA(&iface->ia_addr[m].addr.in6))
421                         continue;
422
423                 if (iface->ia_addr[i].preferred > iface->ia_addr[m].preferred)
424                         m = i;
425         }
426
427         if (m >= 0) {
428                 *addr = iface->ia_addr[m].addr.in6;
429                 return 0;
430         }
431
432         return odhcpd_get_linklocal_interface_address(iface->ifindex, addr);
433 }
434
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)
438 {
439         struct nl_msg *msg;
440         struct rtmsg rtm = {
441                 .rtm_family = AF_INET6,
442                 .rtm_dst_len = prefixlen,
443                 .rtm_src_len = 0,
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),
448         };
449         int ret = 0;
450
451         msg = nlmsg_alloc_simple(add ? RTM_NEWROUTE : RTM_DELROUTE,
452                                         add ? NLM_F_CREATE | NLM_F_REPLACE : 0);
453         if (!msg)
454                 return -1;
455
456         nlmsg_append(msg, &rtm, sizeof(rtm), 0);
457
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);
461
462         if (gw)
463                 nla_put(msg, RTA_GATEWAY, sizeof(*gw), gw);
464
465         ret = nl_send_auto_complete(rtnl_socket, msg);
466         nlmsg_free(msg);
467
468         if (ret < 0)
469                 return ret;
470
471         return nl_wait_for_ack(rtnl_socket);
472 }
473
474 int odhcpd_setup_proxy_neigh(const struct in6_addr *addr,
475                 const struct interface *iface, const bool add)
476 {
477         struct nl_msg *msg;
478         struct ndmsg ndm = {
479                 .ndm_family = AF_INET6,
480                 .ndm_flags = NTF_PROXY,
481                 .ndm_ifindex = iface->ifindex,
482         };
483         int ret = 0, flags = NLM_F_REQUEST;
484
485         if (add)
486                 flags |= NLM_F_REPLACE | NLM_F_CREATE;
487
488         msg = nlmsg_alloc_simple(add ? RTM_NEWNEIGH : RTM_DELNEIGH, flags);
489         if (!msg)
490                 return -1;
491
492         nlmsg_append(msg, &ndm, sizeof(ndm), 0);
493
494         nla_put(msg, NDA_DST, sizeof(*addr), addr);
495
496         ret = nl_send_auto_complete(rtnl_socket, msg);
497         nlmsg_free(msg);
498
499         if (ret < 0)
500                 return ret;
501
502         return nl_wait_for_ack(rtnl_socket);
503 }
504
505 struct interface* odhcpd_get_interface_by_index(int ifindex)
506 {
507         struct interface *iface;
508         list_for_each_entry(iface, &interfaces, head)
509                 if (iface->ifindex == ifindex)
510                         return iface;
511
512         return NULL;
513 }
514
515
516 struct interface* odhcpd_get_interface_by_name(const char *name)
517 {
518         struct interface *iface;
519         list_for_each_entry(iface, &interfaces, head)
520                 if (!strcmp(iface->ifname, name))
521                         return iface;
522
523         return NULL;
524 }
525
526
527 struct interface* odhcpd_get_master_interface(void)
528 {
529         struct interface *iface;
530         list_for_each_entry(iface, &interfaces, head)
531                 if (iface->master)
532                         return iface;
533
534         return NULL;
535 }
536
537
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)
540 {
541         struct odhcpd_event *e = container_of(u, struct odhcpd_event, uloop);
542
543         uint8_t data_buf[RELAYD_BUFFER_SIZE], cmsg_buf[128];
544         union {
545                 struct sockaddr_in6 in6;
546                 struct sockaddr_in in;
547                 struct sockaddr_ll ll;
548                 struct sockaddr_nl nl;
549         } addr;
550
551         if (u->error) {
552                 int ret = -1;
553                 socklen_t ret_len = sizeof(ret);
554                 getsockopt(u->fd, SOL_SOCKET, SO_ERROR, &ret, &ret_len);
555                 u->error = false;
556                 if (e->handle_error)
557                         e->handle_error(e, ret);
558         }
559
560         if (e->recv_msgs) {
561                 e->recv_msgs(e);
562                 return;
563         }
564
565         while (true) {
566                 struct iovec iov = {data_buf, sizeof(data_buf)};
567                 struct msghdr msg = {
568                         .msg_name = (void *) &addr,
569                         .msg_namelen = sizeof(addr),
570                         .msg_iov = &iov,
571                         .msg_iovlen = 1,
572                         .msg_control = cmsg_buf,
573                         .msg_controllen = sizeof(cmsg_buf),
574                         .msg_flags = 0
575                 };
576
577                 ssize_t len = recvmsg(u->fd, &msg, MSG_DONTWAIT);
578                 if (len < 0) {
579                         if (errno == EAGAIN)
580                                 break;
581                         else
582                                 continue;
583                 }
584
585
586                 // Extract destination interface
587                 int destiface = 0;
588                 int *hlim = NULL;
589                 void *dest = NULL;
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);
606                         }
607                 }
608
609                 // Check hoplimit if received
610                 if (hlim && *hlim != 255)
611                         continue;
612
613                 // Detect interface for packet sockets
614                 if (addr.ll.sll_family == AF_PACKET)
615                         destiface = addr.ll.sll_ifindex;
616
617                 struct interface *iface =
618                                 odhcpd_get_interface_by_index(destiface);
619
620                 if (!iface && addr.nl.nl_family != AF_NETLINK)
621                         continue;
622
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));
631
632                 syslog(LOG_DEBUG, "Received %li Bytes from %s%%%s", (long)len,
633                                 ipbuf, (iface) ? iface->ifname : "netlink");
634
635                 e->handle_dgram(&addr, data_buf, len, iface, dest);
636         }
637 }
638
639 // Register events for the multiplexer
640 int odhcpd_register(struct odhcpd_event *event)
641 {
642         event->uloop.cb = odhcpd_receive_packets;
643         return uloop_fd_add(&event->uloop, ULOOP_READ |
644                         ((event->handle_error) ? ULOOP_ERROR_CB : 0));
645 }
646
647 int odhcpd_deregister(struct odhcpd_event *event)
648 {
649         event->uloop.cb = NULL;
650         return uloop_fd_delete(&event->uloop);
651 }
652
653 void odhcpd_process(struct odhcpd_event *event)
654 {
655         odhcpd_receive_packets(&event->uloop, 0);
656 }
657
658 int odhcpd_urandom(void *data, size_t len)
659 {
660         return read(urandom_fd, data, len);
661 }
662
663
664 time_t odhcpd_time(void)
665 {
666         struct timespec ts;
667         syscall(SYS_clock_gettime, CLOCK_MONOTONIC, &ts);
668         return ts.tv_sec;
669 }
670
671
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,
682 };
683
684 ssize_t odhcpd_unhexlify(uint8_t *dst, size_t len, const char *src)
685 {
686         size_t c;
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)
692                         return -1;
693                 dst[c] = x << 4 | y;
694                 while (((int8_t)*src) < 0 ||
695                                 (*src && hexvals[(uint8_t)*src] < 0))
696                         src++;
697         }
698
699         return c;
700 }
701
702
703 void odhcpd_hexlify(char *dst, const uint8_t *src, size_t len)
704 {
705         for (size_t i = 0; i < len; ++i) {
706                 *dst++ = hexdigits[src[i] >> 4];
707                 *dst++ = hexdigits[src[i] & 0x0f];
708         }
709         *dst = 0;
710 }
711
712
713 int odhcpd_bmemcmp(const void *av, const void *bv, size_t bits)
714 {
715         const uint8_t *a = av, *b = bv;
716         size_t bytes = bits / 8;
717         bits %= 8;
718
719         int res = memcmp(a, b, bytes);
720         if (res == 0 && bits > 0)
721                 res = (a[bytes] >> (8 - bits)) - (b[bytes] >> (8 - bits));
722
723         return res;
724 }
725
726
727 void odhcpd_bmemcpy(void *av, const void *bv, size_t bits)
728 {
729         uint8_t *a = av;
730         const uint8_t *b = bv;
731
732         size_t bytes = bits / 8;
733         bits %= 8;
734         memcpy(a, b, bytes);
735
736         if (bits > 0) {
737                 uint8_t mask = (1 << (8 - bits)) - 1;
738                 a[bytes] = (a[bytes] & mask) | ((~mask) & b[bytes]);
739         }
740 }