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.
27 #include <sys/ioctl.h>
28 #include <sys/socket.h>
29 #include <arpa/inet.h>
30 #include <netinet/in.h>
33 #include <net/ethernet.h>
39 #define ALL_DHCPV6_RELAYS {{{0xff, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
40 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x02}}}
41 #define DHCPV6_CLIENT_PORT 546
42 #define DHCPV6_SERVER_PORT 547
43 #define DHCPV6_DUID_LLADDR 3
44 #define DHCPV6_REQ_DELAY 1
47 static bool dhcpv6_response_is_valid(const void *buf, ssize_t len,
48 const uint8_t transaction[3], enum dhcpv6_msg type,
49 const struct in6_addr *daddr);
51 static int dhcpv6_parse_ia(void *opt, void *end);
53 static int dhcpv6_calc_refresh_timers(void);
54 static void dhcpv6_handle_status_code(_unused const enum dhcpv6_msg orig,
55 const uint16_t code, const void *status_msg, const int len,
57 static void dhcpv6_handle_ia_status_code(const enum dhcpv6_msg orig,
58 const struct dhcpv6_ia_hdr *ia_hdr, const uint16_t code,
59 const void *status_msg, const int len,
60 bool handled_status_codes[_DHCPV6_Status_Max],
63 static reply_handler dhcpv6_handle_reply;
64 static reply_handler dhcpv6_handle_advert;
65 static reply_handler dhcpv6_handle_rebind_reply;
66 static reply_handler dhcpv6_handle_reconfigure;
67 static int dhcpv6_commit_advert(void);
71 // RFC 3315 - 5.5 Timeout and Delay values
72 static struct dhcpv6_retx dhcpv6_retx[_DHCPV6_MSG_MAX] = {
73 [DHCPV6_MSG_UNKNOWN] = {false, 1, 120, 0, "<POLL>",
74 dhcpv6_handle_reconfigure, NULL},
75 [DHCPV6_MSG_SOLICIT] = {true, 1, 3600, 0, "SOLICIT",
76 dhcpv6_handle_advert, dhcpv6_commit_advert},
77 [DHCPV6_MSG_REQUEST] = {true, 1, 30, 10, "REQUEST",
78 dhcpv6_handle_reply, NULL},
79 [DHCPV6_MSG_RENEW] = {false, 10, 600, 0, "RENEW",
80 dhcpv6_handle_reply, NULL},
81 [DHCPV6_MSG_REBIND] = {false, 10, 600, 0, "REBIND",
82 dhcpv6_handle_rebind_reply, NULL},
83 [DHCPV6_MSG_RELEASE] = {false, 1, 0, 5, "RELEASE", NULL, NULL},
84 [DHCPV6_MSG_DECLINE] = {false, 1, 0, 5, "DECLINE", NULL, NULL},
85 [DHCPV6_MSG_INFO_REQ] = {true, 1, 120, 0, "INFOREQ",
86 dhcpv6_handle_reply, NULL},
92 static int ifindex = -1;
93 static int64_t t1 = 0, t2 = 0, t3 = 0;
96 static int request_prefix = -1;
97 static enum odhcp6c_ia_mode na_mode = IA_MODE_NONE, pd_mode = IA_MODE_NONE;
98 static bool accept_reconfig = false;
99 // Server unicast address
100 static struct in6_addr server_addr = IN6ADDR_ANY_INIT;
103 static uint8_t reconf_key[16];
106 int init_dhcpv6(const char *ifname, int request_pd, int sol_timeout)
108 request_prefix = request_pd;
109 dhcpv6_retx[DHCPV6_MSG_SOLICIT].max_timeo = sol_timeout;
111 sock = socket(AF_INET6, SOCK_DGRAM | SOCK_CLOEXEC, IPPROTO_UDP);
117 strncpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name));
118 if (ioctl(sock, SIOCGIFINDEX, &ifr) < 0)
120 ifindex = ifr.ifr_ifindex;
122 // Create client DUID
123 size_t client_id_len;
124 odhcp6c_get_state(STATE_CLIENT_ID, &client_id_len);
125 if (client_id_len == 0) {
126 uint8_t duid[14] = {0, DHCPV6_OPT_CLIENTID, 0, 10, 0,
127 DHCPV6_DUID_LLADDR, 0, 1};
129 if (ioctl(sock, SIOCGIFHWADDR, &ifr) >= 0)
130 memcpy(&duid[8], ifr.ifr_hwaddr.sa_data, ETHER_ADDR_LEN);
132 uint8_t zero[ETHER_ADDR_LEN] = {0, 0, 0, 0, 0, 0};
133 struct ifreq ifs[100], *ifp, *ifend;
136 ifc.ifc_len = sizeof(ifs);
138 if (!memcmp(&duid[8], zero, ETHER_ADDR_LEN) &&
139 ioctl(sock, SIOCGIFCONF, &ifc) >= 0) {
140 // If our interface doesn't have an address...
141 ifend = ifs + (ifc.ifc_len / sizeof(struct ifreq));
142 for (ifp = ifc.ifc_req; ifp < ifend &&
143 !memcmp(&duid[8], zero, ETHER_ADDR_LEN); ifp++) {
144 memcpy(ifr.ifr_name, ifp->ifr_name,
145 sizeof(ifr.ifr_name));
146 if (ioctl(sock, SIOCGIFHWADDR, &ifr) < 0)
149 memcpy(&duid[8], ifr.ifr_hwaddr.sa_data,
154 odhcp6c_add_state(STATE_CLIENT_ID, duid, sizeof(duid));
159 htons(DHCPV6_OPT_SIP_SERVER_D),
160 htons(DHCPV6_OPT_SIP_SERVER_A),
161 htons(DHCPV6_OPT_DNS_SERVERS),
162 htons(DHCPV6_OPT_DNS_DOMAIN),
163 htons(DHCPV6_OPT_UNICAST),
164 htons(DHCPV6_OPT_NTP_SERVER),
165 htons(DHCPV6_OPT_AFTR_NAME),
166 htons(DHCPV6_OPT_PD_EXCLUDE),
167 #ifdef EXT_PREFIX_CLASS
168 htons(DHCPV6_OPT_PREFIX_CLASS),
171 odhcp6c_add_state(STATE_ORO, oro, sizeof(oro));
173 // Configure IPv6-options
175 setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &val, sizeof(val));
176 setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val));
177 setsockopt(sock, IPPROTO_IPV6, IPV6_RECVPKTINFO, &val, sizeof(val));
179 setsockopt(sock, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, &val, sizeof(val));
180 setsockopt(sock, SOL_SOCKET, SO_BINDTODEVICE, ifname, strlen(ifname));
182 struct sockaddr_in6 client_addr = { .sin6_family = AF_INET6,
183 .sin6_port = htons(DHCPV6_CLIENT_PORT), .sin6_flowinfo = 0 };
184 if (bind(sock, (struct sockaddr*)&client_addr, sizeof(client_addr)) < 0)
191 void dhcpv6_set_ia_mode(enum odhcp6c_ia_mode na, enum odhcp6c_ia_mode pd)
198 static void dhcpv6_send(enum dhcpv6_msg type, uint8_t trid[3], uint32_t ecs)
202 gethostname(fqdn_buf, sizeof(fqdn_buf));
209 size_t fqdn_len = 5 + dn_comp(fqdn_buf, fqdn.data,
210 sizeof(fqdn.data), NULL, NULL);
211 fqdn.type = htons(DHCPV6_OPT_FQDN);
212 fqdn.len = htons(fqdn_len - 4);
218 void *cl_id = odhcp6c_get_state(STATE_CLIENT_ID, &cl_id_len);
222 void *srv_id = odhcp6c_get_state(STATE_SERVER_ID, &srv_id_len);
225 size_t ia_pd_entries, ia_pd_len = 0;
226 struct odhcp6c_entry *e = odhcp6c_get_state(STATE_IA_PD, &ia_pd_entries);
227 ia_pd_entries /= sizeof(*e);
228 struct dhcpv6_ia_hdr hdr_ia_pd = {
229 htons(DHCPV6_OPT_IA_PD),
230 htons(sizeof(hdr_ia_pd) - 4),
235 uint8_t *ia_pd = alloca(ia_pd_entries * (sizeof(struct dhcpv6_ia_prefix) + 10));
236 for (size_t i = 0; i < ia_pd_entries; ++i) {
238 if (e[i].priority > 0)
239 ex_len = ((e[i].priority - e[i].length - 1) / 8) + 6;
241 struct dhcpv6_ia_prefix p = {
242 .type = htons(DHCPV6_OPT_IA_PREFIX),
243 .len = htons(sizeof(p) - 4U + ex_len),
244 .prefix = e[i].length,
248 memcpy(ia_pd + ia_pd_len, &p, sizeof(p));
249 ia_pd_len += sizeof(p);
252 ia_pd[ia_pd_len++] = 0;
253 ia_pd[ia_pd_len++] = DHCPV6_OPT_PD_EXCLUDE;
254 ia_pd[ia_pd_len++] = 0;
255 ia_pd[ia_pd_len++] = ex_len - 4;
256 ia_pd[ia_pd_len++] = e[i].priority;
258 uint32_t excl = ntohl(e[i].router.s6_addr32[1]);
259 excl >>= (64 - e[i].priority);
260 excl <<= 8 - ((e[i].priority - e[i].length) % 8);
262 for (size_t i = ex_len - 5; i > 0; --i, excl >>= 8)
263 ia_pd[ia_pd_len + i] = excl & 0xff;
264 ia_pd_len += ex_len - 5;
268 struct dhcpv6_ia_prefix pref = {
269 .type = htons(DHCPV6_OPT_IA_PREFIX),
270 .len = htons(25), .prefix = request_prefix
272 if (request_prefix > 0 && ia_pd_len == 0 && type == DHCPV6_MSG_SOLICIT) {
273 ia_pd = (uint8_t*)&pref;
274 ia_pd_len = sizeof(pref);
276 hdr_ia_pd.len = htons(ntohs(hdr_ia_pd.len) + ia_pd_len);
279 size_t ia_na_entries, ia_na_len = 0;
281 e = odhcp6c_get_state(STATE_IA_NA, &ia_na_entries);
282 ia_na_entries /= sizeof(*e);
284 struct dhcpv6_ia_hdr hdr_ia_na = {
285 htons(DHCPV6_OPT_IA_NA),
286 htons(sizeof(hdr_ia_na) - 4),
290 struct dhcpv6_ia_addr pa[ia_na_entries];
291 for (size_t i = 0; i < ia_na_entries; ++i) {
292 pa[i].type = htons(DHCPV6_OPT_IA_ADDR);
293 pa[i].len = htons(sizeof(pa[i]) - 4U);
294 pa[i].addr = e[i].target;
300 ia_na_len = sizeof(pa);
301 hdr_ia_na.len = htons(ntohs(hdr_ia_na.len) + ia_na_len);
303 // Reconfigure Accept
307 } reconf_accept = {htons(DHCPV6_OPT_RECONF_ACCEPT), 0};
309 // Request Information Refresh
310 uint16_t oro_refresh = htons(DHCPV6_OPT_INFO_REFRESH);
314 void *oro = odhcp6c_get_state(STATE_ORO, &oro_len);
318 uint16_t elapsed_type;
319 uint16_t elapsed_len;
320 uint16_t elapsed_value;
324 type, {trid[0], trid[1], trid[2]},
325 htons(DHCPV6_OPT_ELAPSED), htons(2),
326 htons((ecs > 0xffff) ? 0xffff : ecs),
327 htons(DHCPV6_OPT_ORO), htons(oro_len),
330 struct iovec iov[] = {
335 {srv_id, srv_id_len},
336 {&reconf_accept, sizeof(reconf_accept)},
338 {&hdr_ia_na, sizeof(hdr_ia_na)},
340 {&hdr_ia_pd, sizeof(hdr_ia_pd)},
344 size_t cnt = ARRAY_SIZE(iov);
345 if (type == DHCPV6_MSG_INFO_REQ) {
347 iov[2].iov_len = sizeof(oro_refresh);
348 hdr.oro_len = htons(oro_len + sizeof(oro_refresh));
349 } else if (!request_prefix) {
353 // Disable IAs if not used
354 if (type != DHCPV6_MSG_SOLICIT) {
362 if (na_mode == IA_MODE_NONE)
365 struct sockaddr_in6 srv = {AF_INET6, htons(DHCPV6_SERVER_PORT),
366 0, ALL_DHCPV6_RELAYS, ifindex};
367 struct msghdr msg = {&srv, sizeof(srv), iov, cnt, NULL, 0, 0};
370 case DHCPV6_MSG_REQUEST:
371 case DHCPV6_MSG_RENEW:
372 case DHCPV6_MSG_RELEASE:
373 case DHCPV6_MSG_DECLINE:
374 if (!IN6_IS_ADDR_UNSPECIFIED(&server_addr) &&
375 odhcp6c_addr_in_scope(&server_addr)) {
376 srv.sin6_addr = server_addr;
377 if (!IN6_IS_ADDR_LINKLOCAL(&server_addr))
378 srv.sin6_scope_id = 0;
385 if (sendmsg(sock, &msg, 0) < 0) {
386 char in6_str[INET6_ADDRSTRLEN];
388 syslog(LOG_ERR, "Failed to send DHCPV6 message to %s (%s)",
389 inet_ntop(AF_INET6, (const void *)&srv.sin6_addr,
390 in6_str, sizeof(in6_str)), strerror(errno));
395 static int64_t dhcpv6_rand_delay(int64_t time)
398 odhcp6c_random(&random, sizeof(random));
399 return (time * ((int64_t)random % 1000LL)) / 10000LL;
403 int dhcpv6_request(enum dhcpv6_msg type)
406 uint64_t timeout = UINT32_MAX;
407 struct dhcpv6_retx *retx = &dhcpv6_retx[type];
410 struct timespec ts = {0, 0};
411 ts.tv_nsec = dhcpv6_rand_delay(10 * DHCPV6_REQ_DELAY);
412 nanosleep(&ts, NULL);
415 if (type == DHCPV6_MSG_UNKNOWN)
417 else if (type == DHCPV6_MSG_RENEW)
418 timeout = (t2 > t1) ? t2 - t1 : 0;
419 else if (type == DHCPV6_MSG_REBIND)
420 timeout = (t3 > t2) ? t3 - t2 : 0;
425 syslog(LOG_NOTICE, "Starting %s transaction (timeout %llus, max rc %d)",
426 retx->name, (unsigned long long)timeout, retx->max_rc);
428 uint64_t start = odhcp6c_get_milli_time(), round_start = start, elapsed;
430 // Generate transaction ID
431 uint8_t trid[3] = {0, 0, 0};
432 if (type != DHCPV6_MSG_UNKNOWN)
433 odhcp6c_random(trid, sizeof(trid));
439 int64_t delay = dhcpv6_rand_delay(retx->init_timeo * 1000);
441 // First RT MUST be strictly greater than IRT for solicit messages (RFC3313 17.1.2)
442 while (type == DHCPV6_MSG_SOLICIT && delay <= 0)
443 delay = dhcpv6_rand_delay(retx->init_timeo * 1000);
445 rto = (retx->init_timeo * 1000 + delay);
448 rto = (2 * rto + dhcpv6_rand_delay(rto));
450 if (retx->max_timeo && (rto >= retx->max_timeo * 1000))
451 rto = retx->max_timeo * 1000 +
452 dhcpv6_rand_delay(retx->max_timeo * 1000);
454 // Calculate end for this round and elapsed time
455 uint64_t round_end = round_start + rto;
456 elapsed = round_start - start;
458 // Don't wait too long
459 if (round_end - start > timeout * 1000)
460 round_end = timeout * 1000 + start;
462 // Built and send package
463 if (type != DHCPV6_MSG_UNKNOWN) {
464 if (type != DHCPV6_MSG_SOLICIT)
465 syslog(LOG_NOTICE, "Send %s message (elapsed %llums, rc %d)",
466 retx->name, (unsigned long long)elapsed, rc);
467 dhcpv6_send(type, trid, elapsed / 10);
472 for (; len < 0 && (round_start < round_end);
473 round_start = odhcp6c_get_milli_time()) {
474 uint8_t buf[1536], cmsg_buf[CMSG_SPACE(sizeof(struct in6_pktinfo))];
475 struct iovec iov = {buf, sizeof(buf)};
476 struct msghdr msg = {NULL, 0, &iov, 1,
477 cmsg_buf, sizeof(cmsg_buf), 0};
478 struct in6_pktinfo *pktinfo = NULL;
480 // Check for pending signal
481 if (odhcp6c_signal_process())
484 // Set timeout for receiving
485 uint64_t t = round_end - round_start;
486 struct timeval timeout = {t / 1000, (t % 1000) * 1000};
487 setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO,
488 &timeout, sizeof(timeout));
491 len = recvmsg(sock, &msg, 0);
495 for (struct cmsghdr *ch = CMSG_FIRSTHDR(&msg); ch != NULL;
496 ch = CMSG_NXTHDR(&msg, ch)) {
497 if (ch->cmsg_level == SOL_IPV6 &&
498 ch->cmsg_type == IPV6_PKTINFO) {
499 pktinfo = (struct in6_pktinfo *)CMSG_DATA(ch);
504 if (pktinfo == NULL) {
509 if (!dhcpv6_response_is_valid(buf, len, trid,
510 type, &pktinfo->ipi6_addr)) {
515 uint8_t *opt = &buf[4];
516 uint8_t *opt_end = opt + len - 4;
518 round_start = odhcp6c_get_milli_time();
519 elapsed = round_start - start;
520 syslog(LOG_NOTICE, "Got a valid reply after "
521 "%llums", (unsigned long long)elapsed);
523 if (retx->handler_reply)
524 len = retx->handler_reply(type, rc, opt, opt_end);
526 if (len > 0 && round_end - round_start > 1000)
527 round_end = 1000 + round_start;
531 if (retx->handler_finish)
532 len = retx->handler_finish();
533 } while (len < 0 && ((elapsed / 1000 < timeout) && (!retx->max_rc || rc < retx->max_rc)));
538 // Message validation checks according to RFC3315 chapter 15
539 static bool dhcpv6_response_is_valid(const void *buf, ssize_t len,
540 const uint8_t transaction[3], enum dhcpv6_msg type,
541 const struct in6_addr *daddr)
543 const struct dhcpv6_header *rep = buf;
544 if (len < (ssize_t)sizeof(*rep) || memcmp(rep->tr_id,
545 transaction, sizeof(rep->tr_id)))
546 return false; // Invalid reply
548 if (type == DHCPV6_MSG_SOLICIT) {
549 if (rep->msg_type != DHCPV6_MSG_ADVERT &&
550 rep->msg_type != DHCPV6_MSG_REPLY)
552 } else if (type == DHCPV6_MSG_UNKNOWN) {
553 if (!accept_reconfig || rep->msg_type != DHCPV6_MSG_RECONF)
555 } else if (rep->msg_type != DHCPV6_MSG_REPLY) {
559 uint8_t *end = ((uint8_t*)buf) + len, *odata,
560 rcmsg = DHCPV6_MSG_UNKNOWN;
561 uint16_t otype, olen;
562 bool clientid_ok = false, serverid_ok = false, rcauth_ok = false,
563 ia_present = false, options_valid = true;
565 size_t client_id_len, server_id_len;
566 void *client_id = odhcp6c_get_state(STATE_CLIENT_ID, &client_id_len);
567 void *server_id = odhcp6c_get_state(STATE_SERVER_ID, &server_id_len);
569 dhcpv6_for_each_option(&rep[1], end, otype, olen, odata) {
570 if (otype == DHCPV6_OPT_CLIENTID) {
571 clientid_ok = (olen + 4U == client_id_len) && !memcmp(
572 &odata[-4], client_id, client_id_len);
573 } else if (otype == DHCPV6_OPT_SERVERID) {
575 serverid_ok = (olen + 4U == server_id_len) && !memcmp(
576 &odata[-4], server_id, server_id_len);
579 } else if (otype == DHCPV6_OPT_AUTH && olen == -4 +
580 sizeof(struct dhcpv6_auth_reconfigure)) {
581 struct dhcpv6_auth_reconfigure *r = (void*)&odata[-4];
582 if (r->protocol != 3 || r->algorithm != 1 || r->reconf_type != 2)
586 uint8_t serverhash[16], secretbytes[16], hash[16];
587 memcpy(serverhash, r->key, sizeof(serverhash));
588 memset(r->key, 0, sizeof(r->key));
589 memcpy(secretbytes, reconf_key, sizeof(secretbytes));
591 for (size_t i = 0; i < sizeof(secretbytes); ++i)
592 secretbytes[i] ^= 0x36;
595 md5_append(&md5, secretbytes, sizeof(secretbytes));
596 md5_append(&md5, buf, len);
597 md5_finish(&md5, hash);
599 for (size_t i = 0; i < sizeof(secretbytes); ++i) {
600 secretbytes[i] ^= 0x36;
601 secretbytes[i] ^= 0x5c;
605 md5_append(&md5, secretbytes, sizeof(secretbytes));
606 md5_append(&md5, hash, 16);
607 md5_finish(&md5, hash);
609 rcauth_ok = !memcmp(hash, serverhash, sizeof(hash));
610 } else if (otype == DHCPV6_OPT_RECONF_MESSAGE && olen == 1) {
612 } else if ((otype == DHCPV6_OPT_IA_PD || otype == DHCPV6_OPT_IA_NA)) {
614 if (olen < sizeof(struct dhcpv6_ia_hdr))
615 options_valid = false;
617 else if ((otype == DHCPV6_OPT_IA_ADDR) || (otype == DHCPV6_OPT_IA_PREFIX) ||
618 (otype == DHCPV6_OPT_PD_EXCLUDE)) {
619 // Options are not allowed on global level
620 options_valid = false;
627 if (type == DHCPV6_MSG_INFO_REQ && ia_present)
630 if (rep->msg_type == DHCPV6_MSG_RECONF) {
631 if ((rcmsg != DHCPV6_MSG_RENEW && rcmsg != DHCPV6_MSG_INFO_REQ) ||
632 (rcmsg == DHCPV6_MSG_INFO_REQ && ia_present) ||
633 !rcauth_ok || IN6_IS_ADDR_MULTICAST(daddr))
637 return clientid_ok && serverid_ok;
641 int dhcpv6_poll_reconfigure(void)
643 int ret = dhcpv6_request(DHCPV6_MSG_UNKNOWN);
645 ret = dhcpv6_request(ret);
651 static int dhcpv6_handle_reconfigure(_unused enum dhcpv6_msg orig, const int rc,
652 const void *opt, const void *end)
654 uint16_t otype, olen;
655 uint8_t *odata, msg = DHCPV6_MSG_RENEW;
656 dhcpv6_for_each_option(opt, end, otype, olen, odata)
657 if (otype == DHCPV6_OPT_RECONF_MESSAGE && olen == 1 && (
658 odata[0] == DHCPV6_MSG_RENEW ||
659 odata[0] == DHCPV6_MSG_INFO_REQ))
662 dhcpv6_handle_reply(DHCPV6_MSG_UNKNOWN, rc, NULL, NULL);
667 // Collect all advertised servers
668 static int dhcpv6_handle_advert(enum dhcpv6_msg orig, const int rc,
669 const void *opt, const void *end)
671 uint16_t olen, otype;
672 uint8_t *odata, pref = 0;
673 struct dhcpv6_server_cand cand = {false, false, 0, 0, {0},
674 IN6ADDR_ANY_INIT, NULL, NULL, 0, 0};
675 bool have_na = false;
678 dhcpv6_for_each_option(opt, end, otype, olen, odata) {
679 if (orig == DHCPV6_MSG_SOLICIT &&
680 (otype == DHCPV6_OPT_IA_PD || otype == DHCPV6_OPT_IA_NA) &&
681 olen > sizeof(struct dhcpv6_ia_hdr)) {
682 struct dhcpv6_ia_hdr *ia_hdr = (void*)(&odata[-4]);
683 dhcpv6_parse_ia(ia_hdr, odata + olen + sizeof(*ia_hdr));
686 if (otype == DHCPV6_OPT_SERVERID && olen <= 130) {
687 memcpy(cand.duid, odata, olen);
688 cand.duid_len = olen;
689 } else if (otype == DHCPV6_OPT_STATUS && olen >= 2) {
690 int error = ((int)odata[0] << 8 | (int)odata[1]);
693 case DHCPV6_NoPrefixAvail:
694 // Status code on global level
695 if (pd_mode == IA_MODE_FORCE)
697 cand.preference -= 2000;
700 case DHCPV6_NoAddrsAvail:
701 // Status code on global level
702 if (na_mode == IA_MODE_FORCE)
709 } else if (otype == DHCPV6_OPT_PREF && olen >= 1 &&
710 cand.preference >= 0) {
711 cand.preference = pref = odata[0];
712 } else if (otype == DHCPV6_OPT_UNICAST && olen == sizeof(cand.server_addr)) {
713 cand.server_addr = *(struct in6_addr *)odata;
714 } else if (otype == DHCPV6_OPT_RECONF_ACCEPT) {
715 cand.wants_reconfigure = true;
716 } else if (otype == DHCPV6_OPT_IA_PD && request_prefix) {
717 struct dhcpv6_ia_hdr *h = (struct dhcpv6_ia_hdr*)&odata[-4];
718 uint8_t *oend = odata + olen, *d;
719 dhcpv6_for_each_option(&h[1], oend, otype, olen, d) {
720 if (otype == DHCPV6_OPT_IA_PREFIX && (olen + 4) >=
721 (uint16_t)sizeof(struct dhcpv6_ia_prefix)) {
722 struct dhcpv6_ia_prefix *p = (struct dhcpv6_ia_prefix*)&d[-4];
726 } else if (otype == DHCPV6_OPT_IA_NA) {
727 struct dhcpv6_ia_hdr *h = (struct dhcpv6_ia_hdr*)&odata[-4];
728 uint8_t *oend = odata + olen, *d;
729 dhcpv6_for_each_option(&h[1], oend, otype, olen, d)
730 if (otype == DHCPV6_OPT_IA_ADDR)
735 if ((!have_na && na_mode == IA_MODE_FORCE) ||
736 (!have_pd && pd_mode == IA_MODE_FORCE))
739 if (na_mode != IA_MODE_NONE && !have_na) {
740 cand.has_noaddravail = true;
741 cand.preference -= 1000;
744 if (pd_mode != IA_MODE_NONE) {
746 cand.preference += 2000 + (128 - have_pd);
748 cand.preference -= 2000;
751 if (cand.duid_len > 0) {
752 cand.ia_na = odhcp6c_move_state(STATE_IA_NA, &cand.ia_na_len);
753 cand.ia_pd = odhcp6c_move_state(STATE_IA_PD, &cand.ia_pd_len);
754 odhcp6c_add_state(STATE_SERVER_CAND, &cand, sizeof(cand));
757 return (rc > 1 || (pref == 255 && cand.preference > 0)) ? 1 : -1;
761 static int dhcpv6_commit_advert(void)
764 struct dhcpv6_server_cand *c = NULL, *cand =
765 odhcp6c_get_state(STATE_SERVER_CAND, &cand_len);
768 for (size_t i = 0; i < cand_len / sizeof(*c); ++i) {
769 if (cand[i].has_noaddravail)
770 retry = true; // We want to try again
772 if (!c || c->preference < cand[i].preference)
776 if (retry && na_mode == IA_MODE_TRY) {
777 // We give it a second try without the IA_NA
778 na_mode = IA_MODE_NONE;
779 return dhcpv6_request(DHCPV6_MSG_SOLICIT);
783 uint16_t hdr[2] = {htons(DHCPV6_OPT_SERVERID),
785 odhcp6c_add_state(STATE_SERVER_ID, hdr, sizeof(hdr));
786 odhcp6c_add_state(STATE_SERVER_ID, c->duid, c->duid_len);
787 accept_reconfig = c->wants_reconfigure;
788 server_addr = c->server_addr;
790 odhcp6c_add_state(STATE_IA_NA, c->ia_na, c->ia_na_len);
792 odhcp6c_add_state(STATE_IA_PD, c->ia_pd, c->ia_pd_len);
795 for (size_t i = 0; i < cand_len / sizeof(*c); ++i) {
799 odhcp6c_clear_state(STATE_SERVER_CAND);
803 else if ((request_prefix && c->ia_pd_len) || (na_mode != IA_MODE_NONE && c->ia_na_len))
804 return DHCPV6_STATEFUL;
806 return DHCPV6_STATELESS;
810 static int dhcpv6_handle_rebind_reply(enum dhcpv6_msg orig, const int rc,
811 const void *opt, const void *end)
813 dhcpv6_handle_advert(orig, rc, opt, end);
814 if (dhcpv6_commit_advert() < 0)
817 return dhcpv6_handle_reply(orig, rc, opt, end);
821 static int dhcpv6_handle_reply(enum dhcpv6_msg orig, _unused const int rc,
822 const void *opt, const void *end)
825 uint16_t otype, olen;
826 uint32_t refresh = UINT32_MAX;
828 bool handled_status_codes[_DHCPV6_Status_Max] = { false, };
832 if (orig == DHCPV6_MSG_UNKNOWN) {
833 static time_t last_update = 0;
834 time_t now = odhcp6c_get_milli_time() / 1000;
836 uint32_t elapsed = (last_update > 0) ? now - last_update : 0;
853 if (orig == DHCPV6_MSG_REQUEST && !odhcp6c_is_bound()) {
854 // Delete NA and PD we have in the state from the Advert
855 odhcp6c_clear_state(STATE_IA_NA);
856 odhcp6c_clear_state(STATE_IA_PD);
860 odhcp6c_clear_state(STATE_DNS);
861 odhcp6c_clear_state(STATE_SEARCH);
862 odhcp6c_clear_state(STATE_SNTP_IP);
863 odhcp6c_clear_state(STATE_SNTP_FQDN);
864 odhcp6c_clear_state(STATE_SIP_IP);
865 odhcp6c_clear_state(STATE_SIP_FQDN);
866 odhcp6c_clear_state(STATE_AFTR_NAME);
869 // Parse and find all matching IAs
870 dhcpv6_for_each_option(opt, end, otype, olen, odata) {
871 if ((otype == DHCPV6_OPT_IA_PD || otype == DHCPV6_OPT_IA_NA)
872 && olen > sizeof(struct dhcpv6_ia_hdr)) {
873 struct dhcpv6_ia_hdr *ia_hdr = (void*)(&odata[-4]);
876 if (ia_hdr->iaid != 1)
879 uint16_t code = DHCPV6_Success;
880 uint16_t stype, slen;
882 // Get and handle status code
883 dhcpv6_for_each_option(&ia_hdr[1], odata + olen,
884 stype, slen, sdata) {
885 if (stype == DHCPV6_OPT_STATUS && slen >= 2) {
886 uint8_t *mdata = (slen > 2) ? &sdata[2] : NULL;
887 uint16_t mlen = (slen > 2) ? slen - 2 : 0;
889 code = ((int)sdata[0]) << 8 | ((int)sdata[1]);
891 if (code == DHCPV6_Success)
894 dhcpv6_handle_ia_status_code(orig, ia_hdr,
895 code, mdata, mlen, handled_status_codes, &ret);
904 if (code != DHCPV6_Success)
907 dhcpv6_parse_ia(ia_hdr, odata + olen + sizeof(*ia_hdr));
908 } else if (otype == DHCPV6_OPT_UNICAST && olen == sizeof(server_addr)) {
909 server_addr = *(struct in6_addr *)odata;
910 } else if (otype == DHCPV6_OPT_STATUS && olen >= 2) {
911 uint8_t *mdata = (olen > 2) ? &odata[2] : NULL;
912 uint16_t mlen = (olen > 2) ? olen - 2 : 0;
913 uint16_t code = ((int)odata[0]) << 8 | ((int)odata[1]);
915 dhcpv6_handle_status_code(orig, code, mdata, mlen, &ret);
917 else if (otype == DHCPV6_OPT_DNS_SERVERS) {
919 odhcp6c_add_state(STATE_DNS, odata, olen);
920 } else if (otype == DHCPV6_OPT_DNS_DOMAIN) {
921 odhcp6c_add_state(STATE_SEARCH, odata, olen);
922 } else if (otype == DHCPV6_OPT_NTP_SERVER) {
923 uint16_t stype, slen;
925 // Test status and bail if error
926 dhcpv6_for_each_option(odata, odata + olen,
927 stype, slen, sdata) {
928 if (slen == 16 && (stype == NTP_MC_ADDR ||
929 stype == NTP_SRV_ADDR))
930 odhcp6c_add_state(STATE_SNTP_IP,
932 else if (slen > 0 && stype == NTP_SRV_FQDN)
933 odhcp6c_add_state(STATE_SNTP_FQDN,
936 } else if (otype == DHCPV6_OPT_SIP_SERVER_A) {
938 odhcp6c_add_state(STATE_SIP_IP, odata, olen);
939 } else if (otype == DHCPV6_OPT_SIP_SERVER_D) {
940 odhcp6c_add_state(STATE_SIP_FQDN, odata, olen);
941 } else if (otype == DHCPV6_OPT_INFO_REFRESH && olen >= 4) {
942 refresh = ntohl(*((uint32_t*)odata));
943 } else if (otype == DHCPV6_OPT_AUTH && olen == -4 +
944 sizeof(struct dhcpv6_auth_reconfigure)) {
945 struct dhcpv6_auth_reconfigure *r = (void*)&odata[-4];
946 if (r->protocol == 3 && r->algorithm == 1 &&
948 memcpy(reconf_key, r->key, sizeof(r->key));
949 } else if (otype == DHCPV6_OPT_AFTR_NAME && olen > 3) {
951 odhcp6c_get_state(STATE_AFTR_NAME, &cur_len);
953 odhcp6c_add_state(STATE_AFTR_NAME, odata, olen);
954 } else if (otype != DHCPV6_OPT_CLIENTID &&
955 otype != DHCPV6_OPT_SERVERID) {
956 odhcp6c_add_state(STATE_CUSTOM_OPTS,
957 &odata[-4], olen + 4);
961 if (orig != DHCPV6_MSG_INFO_REQ) {
962 // Update refresh timers if no fatal status code was received
963 if ((ret > 0) && dhcpv6_calc_refresh_timers()) {
965 case DHCPV6_MSG_RENEW:
966 // Send further renews if T1 is not set
970 case DHCPV6_MSG_REBIND:
971 // Send further rebinds if T1 and T2 is not set
988 static int dhcpv6_parse_ia(void *opt, void *end)
990 struct dhcpv6_ia_hdr *ia_hdr = (struct dhcpv6_ia_hdr *)opt;
993 uint16_t otype, olen;
996 t1 = ntohl(ia_hdr->t1);
997 t2 = ntohl(ia_hdr->t2);
1002 // Update address IA
1003 dhcpv6_for_each_option(&ia_hdr[1], end, otype, olen, odata) {
1004 struct odhcp6c_entry entry = {IN6ADDR_ANY_INIT, 0, 0,
1005 IN6ADDR_ANY_INIT, 0, 0, 0, 0, 0};
1007 if (otype == DHCPV6_OPT_IA_PREFIX) {
1008 struct dhcpv6_ia_prefix *prefix = (void*)&odata[-4];
1009 if (olen + 4U < sizeof(*prefix))
1012 entry.valid = ntohl(prefix->valid);
1013 entry.preferred = ntohl(prefix->preferred);
1015 if (entry.preferred > entry.valid)
1018 entry.t1 = (t1 ? t1 : (entry.preferred != UINT32_MAX ? 0.5 * entry.preferred : UINT32_MAX));
1019 entry.t2 = (t2 ? t2 : (entry.preferred != UINT32_MAX ? 0.8 * entry.preferred : UINT32_MAX));
1020 if (entry.t1 > entry.t2)
1021 entry.t1 = entry.t2;
1023 entry.length = prefix->prefix;
1024 entry.target = prefix->addr;
1025 uint16_t stype, slen;
1028 #ifdef EXT_PREFIX_CLASS
1029 // Find prefix class, if any
1030 dhcpv6_for_each_option(&prefix[1], odata + olen,
1032 if (stype == DHCPV6_OPT_PREFIX_CLASS && slen == 2)
1033 entry.class = sdata[0] << 8 | sdata[1];
1038 dhcpv6_for_each_option(odata + sizeof(*prefix) - 4U,
1039 odata + olen, stype, slen, sdata) {
1040 if (stype != DHCPV6_OPT_PD_EXCLUDE || slen < 2)
1043 uint8_t elen = sdata[0];
1047 if (elen <= 32 || elen <= entry.length) {
1053 uint8_t bytes = ((elen - entry.length - 1) / 8) + 1;
1054 if (slen <= bytes) {
1059 uint32_t exclude = 0;
1061 exclude = exclude << 8 | sdata[bytes];
1064 exclude >>= 8 - ((elen - entry.length) % 8);
1065 exclude <<= 64 - elen;
1067 // Abusing router & priority fields for exclusion
1068 entry.router = entry.target;
1069 entry.router.s6_addr32[1] |= htonl(exclude);
1070 entry.priority = elen;
1074 odhcp6c_update_entry(STATE_IA_PD, &entry);
1079 memset(&entry.router, 0, sizeof(entry.router));
1080 } else if (otype == DHCPV6_OPT_IA_ADDR) {
1081 struct dhcpv6_ia_addr *addr = (void*)&odata[-4];
1082 if (olen + 4U < sizeof(*addr))
1085 entry.preferred = ntohl(addr->preferred);
1086 entry.valid = ntohl(addr->valid);
1088 if (entry.preferred > entry.valid)
1091 entry.t1 = (t1 ? t1 : (entry.preferred != UINT32_MAX ? 0.5 * entry.preferred : UINT32_MAX));
1092 entry.t2 = (t2 ? t2 : (entry.preferred != UINT32_MAX ? 0.8 * entry.preferred : UINT32_MAX));
1093 if (entry.t1 > entry.t2)
1094 entry.t1 = entry.t2;
1097 entry.target = addr->addr;
1099 #ifdef EXT_PREFIX_CLASS
1100 uint16_t stype, slen;
1102 // Find prefix class, if any
1103 dhcpv6_for_each_option(&addr[1], odata + olen,
1105 if (stype == DHCPV6_OPT_PREFIX_CLASS && slen == 2)
1106 entry.class = sdata[0] << 8 | sdata[1];
1109 odhcp6c_update_entry(STATE_IA_NA, &entry);
1117 static int dhcpv6_calc_refresh_timers(void)
1119 struct odhcp6c_entry *e;
1120 size_t ia_na_entries, ia_pd_entries, i;
1121 int64_t l_t1 = UINT32_MAX, l_t2 = UINT32_MAX, l_t3 = 0;
1123 e = odhcp6c_get_state(STATE_IA_NA, &ia_na_entries);
1124 ia_na_entries /= sizeof(*e);
1125 for (i = 0; i < ia_na_entries; i++) {
1132 if (e[i].valid > l_t3)
1136 e = odhcp6c_get_state(STATE_IA_PD, &ia_pd_entries);
1137 ia_pd_entries /= sizeof(*e);
1138 for (i = 0; i < ia_pd_entries; i++) {
1145 if (e[i].valid > l_t3)
1149 if (ia_pd_entries || ia_na_entries) {
1155 return (int)(ia_pd_entries + ia_na_entries);
1159 static void dhcpv6_log_status_code(const uint16_t code, const char *scope,
1160 const void *status_msg, const int len)
1162 uint8_t buf[len + 3];
1164 memset(buf, 0, sizeof(buf));
1167 memcpy(&buf[1], status_msg, len);
1171 syslog(LOG_WARNING, "Server returned %s status %i %s",
1176 static void dhcpv6_handle_status_code(const enum dhcpv6_msg orig,
1177 const uint16_t code, const void *status_msg, const int len,
1180 dhcpv6_log_status_code(code, "message", status_msg, len);
1183 case DHCPV6_UnspecFail:
1188 case DHCPV6_UseMulticast:
1190 case DHCPV6_MSG_REQUEST:
1191 case DHCPV6_MSG_RENEW:
1192 case DHCPV6_MSG_RELEASE:
1193 case DHCPV6_MSG_DECLINE:
1194 // Message needs to be retransmitted according to RFC3315 chapter 18.1.8
1195 server_addr = in6addr_any;
1203 case DHCPV6_NoAddrsAvail:
1204 case DHCPV6_NoPrefixAvail:
1205 if (orig == DHCPV6_MSG_REQUEST)
1206 *ret = 0; // Failure
1215 static void dhcpv6_handle_ia_status_code(const enum dhcpv6_msg orig,
1216 const struct dhcpv6_ia_hdr *ia_hdr, const uint16_t code,
1217 const void *status_msg, const int len,
1218 bool handled_status_codes[_DHCPV6_Status_Max], int *ret)
1220 dhcpv6_log_status_code(code, ia_hdr->type == DHCPV6_OPT_IA_NA ?
1221 "IA_NA" : "IA_PD", status_msg, len);
1224 case DHCPV6_NoBinding:
1226 case DHCPV6_MSG_RENEW:
1227 case DHCPV6_MSG_REBIND:
1228 if ((*ret > 0) && !handled_status_codes[code])
1229 *ret = dhcpv6_request(DHCPV6_MSG_REQUEST);
1237 case DHCPV6_NoAddrsAvail:
1238 case DHCPV6_NoPrefixAvail:
1240 case DHCPV6_MSG_REQUEST:
1249 case DHCPV6_NotOnLink:
1250 // TODO handle not onlink in case of confirm