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],
62 static void dhcpv6_add_server_cand(const struct dhcpv6_server_cand *cand);
64 static reply_handler dhcpv6_handle_reply;
65 static reply_handler dhcpv6_handle_advert;
66 static reply_handler dhcpv6_handle_rebind_reply;
67 static reply_handler dhcpv6_handle_reconfigure;
68 static int dhcpv6_commit_advert(void);
72 // RFC 3315 - 5.5 Timeout and Delay values
73 static struct dhcpv6_retx dhcpv6_retx[_DHCPV6_MSG_MAX] = {
74 [DHCPV6_MSG_UNKNOWN] = {false, 1, 120, 0, "<POLL>",
75 dhcpv6_handle_reconfigure, NULL},
76 [DHCPV6_MSG_SOLICIT] = {true, 1, 3600, 0, "SOLICIT",
77 dhcpv6_handle_advert, dhcpv6_commit_advert},
78 [DHCPV6_MSG_REQUEST] = {true, 1, 30, 10, "REQUEST",
79 dhcpv6_handle_reply, NULL},
80 [DHCPV6_MSG_RENEW] = {false, 10, 600, 0, "RENEW",
81 dhcpv6_handle_reply, NULL},
82 [DHCPV6_MSG_REBIND] = {false, 10, 600, 0, "REBIND",
83 dhcpv6_handle_rebind_reply, NULL},
84 [DHCPV6_MSG_RELEASE] = {false, 1, 0, 5, "RELEASE", NULL, NULL},
85 [DHCPV6_MSG_DECLINE] = {false, 1, 0, 5, "DECLINE", NULL, NULL},
86 [DHCPV6_MSG_INFO_REQ] = {true, 1, 120, 0, "INFOREQ",
87 dhcpv6_handle_reply, NULL},
93 static int ifindex = -1;
94 static int64_t t1 = 0, t2 = 0, t3 = 0;
97 static int request_prefix = -1;
98 static enum odhcp6c_ia_mode na_mode = IA_MODE_NONE, pd_mode = IA_MODE_NONE;
99 static bool accept_reconfig = false;
100 // Server unicast address
101 static struct in6_addr server_addr = IN6ADDR_ANY_INIT;
104 static uint8_t reconf_key[16];
107 int init_dhcpv6(const char *ifname, int request_pd, int sol_timeout)
109 request_prefix = request_pd;
110 dhcpv6_retx[DHCPV6_MSG_SOLICIT].max_timeo = sol_timeout;
112 sock = socket(AF_INET6, SOCK_DGRAM | SOCK_CLOEXEC, IPPROTO_UDP);
118 strncpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name));
119 if (ioctl(sock, SIOCGIFINDEX, &ifr) < 0)
121 ifindex = ifr.ifr_ifindex;
123 // Create client DUID
124 size_t client_id_len;
125 odhcp6c_get_state(STATE_CLIENT_ID, &client_id_len);
126 if (client_id_len == 0) {
127 uint8_t duid[14] = {0, DHCPV6_OPT_CLIENTID, 0, 10, 0,
128 DHCPV6_DUID_LLADDR, 0, 1};
130 if (ioctl(sock, SIOCGIFHWADDR, &ifr) >= 0)
131 memcpy(&duid[8], ifr.ifr_hwaddr.sa_data, ETHER_ADDR_LEN);
133 uint8_t zero[ETHER_ADDR_LEN] = {0, 0, 0, 0, 0, 0};
134 struct ifreq ifs[100], *ifp, *ifend;
137 ifc.ifc_len = sizeof(ifs);
139 if (!memcmp(&duid[8], zero, ETHER_ADDR_LEN) &&
140 ioctl(sock, SIOCGIFCONF, &ifc) >= 0) {
141 // If our interface doesn't have an address...
142 ifend = ifs + (ifc.ifc_len / sizeof(struct ifreq));
143 for (ifp = ifc.ifc_req; ifp < ifend &&
144 !memcmp(&duid[8], zero, ETHER_ADDR_LEN); ifp++) {
145 memcpy(ifr.ifr_name, ifp->ifr_name,
146 sizeof(ifr.ifr_name));
147 if (ioctl(sock, SIOCGIFHWADDR, &ifr) < 0)
150 memcpy(&duid[8], ifr.ifr_hwaddr.sa_data,
155 odhcp6c_add_state(STATE_CLIENT_ID, duid, sizeof(duid));
160 htons(DHCPV6_OPT_SIP_SERVER_D),
161 htons(DHCPV6_OPT_SIP_SERVER_A),
162 htons(DHCPV6_OPT_DNS_SERVERS),
163 htons(DHCPV6_OPT_DNS_DOMAIN),
164 htons(DHCPV6_OPT_UNICAST),
165 htons(DHCPV6_OPT_NTP_SERVER),
166 htons(DHCPV6_OPT_AFTR_NAME),
167 htons(DHCPV6_OPT_PD_EXCLUDE),
168 #ifdef EXT_PREFIX_CLASS
169 htons(DHCPV6_OPT_PREFIX_CLASS),
172 odhcp6c_add_state(STATE_ORO, oro, sizeof(oro));
174 // Configure IPv6-options
176 setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &val, sizeof(val));
177 setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val));
178 setsockopt(sock, IPPROTO_IPV6, IPV6_RECVPKTINFO, &val, sizeof(val));
180 setsockopt(sock, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, &val, sizeof(val));
181 setsockopt(sock, SOL_SOCKET, SO_BINDTODEVICE, ifname, strlen(ifname));
183 struct sockaddr_in6 client_addr = { .sin6_family = AF_INET6,
184 .sin6_port = htons(DHCPV6_CLIENT_PORT), .sin6_flowinfo = 0 };
185 if (bind(sock, (struct sockaddr*)&client_addr, sizeof(client_addr)) < 0)
192 void dhcpv6_set_ia_mode(enum odhcp6c_ia_mode na, enum odhcp6c_ia_mode pd)
199 static void dhcpv6_send(enum dhcpv6_msg type, uint8_t trid[3], uint32_t ecs)
203 gethostname(fqdn_buf, sizeof(fqdn_buf));
210 size_t fqdn_len = 5 + dn_comp(fqdn_buf, fqdn.data,
211 sizeof(fqdn.data), NULL, NULL);
212 fqdn.type = htons(DHCPV6_OPT_FQDN);
213 fqdn.len = htons(fqdn_len - 4);
219 void *cl_id = odhcp6c_get_state(STATE_CLIENT_ID, &cl_id_len);
223 void *srv_id = odhcp6c_get_state(STATE_SERVER_ID, &srv_id_len);
226 size_t ia_pd_entries, ia_pd_len = 0;
227 struct odhcp6c_entry *e = odhcp6c_get_state(STATE_IA_PD, &ia_pd_entries);
228 ia_pd_entries /= sizeof(*e);
229 struct dhcpv6_ia_hdr hdr_ia_pd = {
230 htons(DHCPV6_OPT_IA_PD),
231 htons(sizeof(hdr_ia_pd) - 4),
236 uint8_t *ia_pd = alloca(ia_pd_entries * (sizeof(struct dhcpv6_ia_prefix) + 10));
237 for (size_t i = 0; i < ia_pd_entries; ++i) {
239 if (e[i].priority > 0)
240 ex_len = ((e[i].priority - e[i].length - 1) / 8) + 6;
242 struct dhcpv6_ia_prefix p = {
243 .type = htons(DHCPV6_OPT_IA_PREFIX),
244 .len = htons(sizeof(p) - 4U + ex_len),
245 .prefix = e[i].length,
249 memcpy(ia_pd + ia_pd_len, &p, sizeof(p));
250 ia_pd_len += sizeof(p);
253 ia_pd[ia_pd_len++] = 0;
254 ia_pd[ia_pd_len++] = DHCPV6_OPT_PD_EXCLUDE;
255 ia_pd[ia_pd_len++] = 0;
256 ia_pd[ia_pd_len++] = ex_len - 4;
257 ia_pd[ia_pd_len++] = e[i].priority;
259 uint32_t excl = ntohl(e[i].router.s6_addr32[1]);
260 excl >>= (64 - e[i].priority);
261 excl <<= 8 - ((e[i].priority - e[i].length) % 8);
263 for (size_t i = ex_len - 5; i > 0; --i, excl >>= 8)
264 ia_pd[ia_pd_len + i] = excl & 0xff;
265 ia_pd_len += ex_len - 5;
269 struct dhcpv6_ia_prefix pref = {
270 .type = htons(DHCPV6_OPT_IA_PREFIX),
271 .len = htons(25), .prefix = request_prefix
273 if (request_prefix > 0 && ia_pd_len == 0 && type == DHCPV6_MSG_SOLICIT) {
274 ia_pd = (uint8_t*)&pref;
275 ia_pd_len = sizeof(pref);
277 hdr_ia_pd.len = htons(ntohs(hdr_ia_pd.len) + ia_pd_len);
280 size_t ia_na_entries, ia_na_len = 0;
282 e = odhcp6c_get_state(STATE_IA_NA, &ia_na_entries);
283 ia_na_entries /= sizeof(*e);
285 struct dhcpv6_ia_hdr hdr_ia_na = {
286 htons(DHCPV6_OPT_IA_NA),
287 htons(sizeof(hdr_ia_na) - 4),
291 struct dhcpv6_ia_addr pa[ia_na_entries];
292 for (size_t i = 0; i < ia_na_entries; ++i) {
293 pa[i].type = htons(DHCPV6_OPT_IA_ADDR);
294 pa[i].len = htons(sizeof(pa[i]) - 4U);
295 pa[i].addr = e[i].target;
301 ia_na_len = sizeof(pa);
302 hdr_ia_na.len = htons(ntohs(hdr_ia_na.len) + ia_na_len);
304 // Reconfigure Accept
308 } reconf_accept = {htons(DHCPV6_OPT_RECONF_ACCEPT), 0};
310 // Request Information Refresh
311 uint16_t oro_refresh = htons(DHCPV6_OPT_INFO_REFRESH);
315 void *oro = odhcp6c_get_state(STATE_ORO, &oro_len);
319 uint16_t elapsed_type;
320 uint16_t elapsed_len;
321 uint16_t elapsed_value;
325 type, {trid[0], trid[1], trid[2]},
326 htons(DHCPV6_OPT_ELAPSED), htons(2),
327 htons((ecs > 0xffff) ? 0xffff : ecs),
328 htons(DHCPV6_OPT_ORO), htons(oro_len),
331 struct iovec iov[] = {
336 {srv_id, srv_id_len},
337 {&reconf_accept, sizeof(reconf_accept)},
339 {&hdr_ia_na, sizeof(hdr_ia_na)},
341 {&hdr_ia_pd, sizeof(hdr_ia_pd)},
345 size_t cnt = ARRAY_SIZE(iov);
346 if (type == DHCPV6_MSG_INFO_REQ) {
348 iov[2].iov_len = sizeof(oro_refresh);
349 hdr.oro_len = htons(oro_len + sizeof(oro_refresh));
350 } else if (!request_prefix) {
354 // Disable IAs if not used
355 if (type != DHCPV6_MSG_SOLICIT) {
363 if (na_mode == IA_MODE_NONE)
366 struct sockaddr_in6 srv = {AF_INET6, htons(DHCPV6_SERVER_PORT),
367 0, ALL_DHCPV6_RELAYS, ifindex};
368 struct msghdr msg = {&srv, sizeof(srv), iov, cnt, NULL, 0, 0};
371 case DHCPV6_MSG_REQUEST:
372 case DHCPV6_MSG_RENEW:
373 case DHCPV6_MSG_RELEASE:
374 case DHCPV6_MSG_DECLINE:
375 if (!IN6_IS_ADDR_UNSPECIFIED(&server_addr) &&
376 odhcp6c_addr_in_scope(&server_addr)) {
377 srv.sin6_addr = server_addr;
378 if (!IN6_IS_ADDR_LINKLOCAL(&server_addr))
379 srv.sin6_scope_id = 0;
386 if (sendmsg(sock, &msg, 0) < 0) {
387 char in6_str[INET6_ADDRSTRLEN];
389 syslog(LOG_ERR, "Failed to send DHCPV6 message to %s (%s)",
390 inet_ntop(AF_INET6, (const void *)&srv.sin6_addr,
391 in6_str, sizeof(in6_str)), strerror(errno));
396 static int64_t dhcpv6_rand_delay(int64_t time)
399 odhcp6c_random(&random, sizeof(random));
400 return (time * ((int64_t)random % 1000LL)) / 10000LL;
404 int dhcpv6_request(enum dhcpv6_msg type)
407 uint64_t timeout = UINT32_MAX;
408 struct dhcpv6_retx *retx = &dhcpv6_retx[type];
411 struct timespec ts = {0, 0};
412 ts.tv_nsec = dhcpv6_rand_delay(10 * DHCPV6_REQ_DELAY);
413 nanosleep(&ts, NULL);
416 if (type == DHCPV6_MSG_UNKNOWN)
418 else if (type == DHCPV6_MSG_RENEW)
419 timeout = (t2 > t1) ? t2 - t1 : 0;
420 else if (type == DHCPV6_MSG_REBIND)
421 timeout = (t3 > t2) ? t3 - t2 : 0;
426 syslog(LOG_NOTICE, "Starting %s transaction (timeout %llus, max rc %d)",
427 retx->name, (unsigned long long)timeout, retx->max_rc);
429 uint64_t start = odhcp6c_get_milli_time(), round_start = start, elapsed;
431 // Generate transaction ID
432 uint8_t trid[3] = {0, 0, 0};
433 if (type != DHCPV6_MSG_UNKNOWN)
434 odhcp6c_random(trid, sizeof(trid));
440 int64_t delay = dhcpv6_rand_delay(retx->init_timeo * 1000);
442 // First RT MUST be strictly greater than IRT for solicit messages (RFC3313 17.1.2)
443 while (type == DHCPV6_MSG_SOLICIT && delay <= 0)
444 delay = dhcpv6_rand_delay(retx->init_timeo * 1000);
446 rto = (retx->init_timeo * 1000 + delay);
449 rto = (2 * rto + dhcpv6_rand_delay(rto));
451 if (retx->max_timeo && (rto >= retx->max_timeo * 1000))
452 rto = retx->max_timeo * 1000 +
453 dhcpv6_rand_delay(retx->max_timeo * 1000);
455 // Calculate end for this round and elapsed time
456 uint64_t round_end = round_start + rto;
457 elapsed = round_start - start;
459 // Don't wait too long
460 if (round_end - start > timeout * 1000)
461 round_end = timeout * 1000 + start;
463 // Built and send package
464 if (type != DHCPV6_MSG_UNKNOWN) {
465 if (type != DHCPV6_MSG_SOLICIT)
466 syslog(LOG_NOTICE, "Send %s message (elapsed %llums, rc %d)",
467 retx->name, (unsigned long long)elapsed, rc);
468 dhcpv6_send(type, trid, elapsed / 10);
473 for (; len < 0 && (round_start < round_end);
474 round_start = odhcp6c_get_milli_time()) {
475 uint8_t buf[1536], cmsg_buf[CMSG_SPACE(sizeof(struct in6_pktinfo))];
476 struct iovec iov = {buf, sizeof(buf)};
477 struct msghdr msg = {NULL, 0, &iov, 1,
478 cmsg_buf, sizeof(cmsg_buf), 0};
479 struct in6_pktinfo *pktinfo = NULL;
481 // Check for pending signal
482 if (odhcp6c_signal_process())
485 // Set timeout for receiving
486 uint64_t t = round_end - round_start;
487 struct timeval timeout = {t / 1000, (t % 1000) * 1000};
488 setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO,
489 &timeout, sizeof(timeout));
492 len = recvmsg(sock, &msg, 0);
496 for (struct cmsghdr *ch = CMSG_FIRSTHDR(&msg); ch != NULL;
497 ch = CMSG_NXTHDR(&msg, ch)) {
498 if (ch->cmsg_level == SOL_IPV6 &&
499 ch->cmsg_type == IPV6_PKTINFO) {
500 pktinfo = (struct in6_pktinfo *)CMSG_DATA(ch);
505 if (pktinfo == NULL) {
510 if (!dhcpv6_response_is_valid(buf, len, trid,
511 type, &pktinfo->ipi6_addr)) {
516 uint8_t *opt = &buf[4];
517 uint8_t *opt_end = opt + len - 4;
519 round_start = odhcp6c_get_milli_time();
520 elapsed = round_start - start;
521 syslog(LOG_NOTICE, "Got a valid reply after "
522 "%llums", (unsigned long long)elapsed);
524 if (retx->handler_reply)
525 len = retx->handler_reply(type, rc, opt, opt_end);
527 if (len > 0 && round_end - round_start > 1000)
528 round_end = 1000 + round_start;
532 if (retx->handler_finish)
533 len = retx->handler_finish();
534 } while (len < 0 && ((elapsed / 1000 < timeout) && (!retx->max_rc || rc < retx->max_rc)));
539 // Message validation checks according to RFC3315 chapter 15
540 static bool dhcpv6_response_is_valid(const void *buf, ssize_t len,
541 const uint8_t transaction[3], enum dhcpv6_msg type,
542 const struct in6_addr *daddr)
544 const struct dhcpv6_header *rep = buf;
545 if (len < (ssize_t)sizeof(*rep) || memcmp(rep->tr_id,
546 transaction, sizeof(rep->tr_id)))
547 return false; // Invalid reply
549 if (type == DHCPV6_MSG_SOLICIT) {
550 if (rep->msg_type != DHCPV6_MSG_ADVERT &&
551 rep->msg_type != DHCPV6_MSG_REPLY)
553 } else if (type == DHCPV6_MSG_UNKNOWN) {
554 if (!accept_reconfig || rep->msg_type != DHCPV6_MSG_RECONF)
556 } else if (rep->msg_type != DHCPV6_MSG_REPLY) {
560 uint8_t *end = ((uint8_t*)buf) + len, *odata,
561 rcmsg = DHCPV6_MSG_UNKNOWN;
562 uint16_t otype, olen;
563 bool clientid_ok = false, serverid_ok = false, rcauth_ok = false,
564 ia_present = false, options_valid = true;
566 size_t client_id_len, server_id_len;
567 void *client_id = odhcp6c_get_state(STATE_CLIENT_ID, &client_id_len);
568 void *server_id = odhcp6c_get_state(STATE_SERVER_ID, &server_id_len);
570 dhcpv6_for_each_option(&rep[1], end, otype, olen, odata) {
571 if (otype == DHCPV6_OPT_CLIENTID) {
572 clientid_ok = (olen + 4U == client_id_len) && !memcmp(
573 &odata[-4], client_id, client_id_len);
574 } else if (otype == DHCPV6_OPT_SERVERID) {
576 serverid_ok = (olen + 4U == server_id_len) && !memcmp(
577 &odata[-4], server_id, server_id_len);
580 } else if (otype == DHCPV6_OPT_AUTH && olen == -4 +
581 sizeof(struct dhcpv6_auth_reconfigure)) {
582 struct dhcpv6_auth_reconfigure *r = (void*)&odata[-4];
583 if (r->protocol != 3 || r->algorithm != 1 || r->reconf_type != 2)
587 uint8_t serverhash[16], secretbytes[16], hash[16];
588 memcpy(serverhash, r->key, sizeof(serverhash));
589 memset(r->key, 0, sizeof(r->key));
590 memcpy(secretbytes, reconf_key, sizeof(secretbytes));
592 for (size_t i = 0; i < sizeof(secretbytes); ++i)
593 secretbytes[i] ^= 0x36;
596 md5_append(&md5, secretbytes, sizeof(secretbytes));
597 md5_append(&md5, buf, len);
598 md5_finish(&md5, hash);
600 for (size_t i = 0; i < sizeof(secretbytes); ++i) {
601 secretbytes[i] ^= 0x36;
602 secretbytes[i] ^= 0x5c;
606 md5_append(&md5, secretbytes, sizeof(secretbytes));
607 md5_append(&md5, hash, 16);
608 md5_finish(&md5, hash);
610 rcauth_ok = !memcmp(hash, serverhash, sizeof(hash));
611 } else if (otype == DHCPV6_OPT_RECONF_MESSAGE && olen == 1) {
613 } else if ((otype == DHCPV6_OPT_IA_PD || otype == DHCPV6_OPT_IA_NA)) {
615 if (olen < sizeof(struct dhcpv6_ia_hdr))
616 options_valid = false;
618 else if ((otype == DHCPV6_OPT_IA_ADDR) || (otype == DHCPV6_OPT_IA_PREFIX) ||
619 (otype == DHCPV6_OPT_PD_EXCLUDE)) {
620 // Options are not allowed on global level
621 options_valid = false;
628 if (type == DHCPV6_MSG_INFO_REQ && ia_present)
631 if (rep->msg_type == DHCPV6_MSG_RECONF) {
632 if ((rcmsg != DHCPV6_MSG_RENEW && rcmsg != DHCPV6_MSG_INFO_REQ) ||
633 (rcmsg == DHCPV6_MSG_INFO_REQ && ia_present) ||
634 !rcauth_ok || IN6_IS_ADDR_MULTICAST(daddr))
638 return clientid_ok && serverid_ok;
642 int dhcpv6_poll_reconfigure(void)
644 int ret = dhcpv6_request(DHCPV6_MSG_UNKNOWN);
646 ret = dhcpv6_request(ret);
652 static int dhcpv6_handle_reconfigure(_unused enum dhcpv6_msg orig, const int rc,
653 const void *opt, const void *end)
655 uint16_t otype, olen;
656 uint8_t *odata, msg = DHCPV6_MSG_RENEW;
657 dhcpv6_for_each_option(opt, end, otype, olen, odata)
658 if (otype == DHCPV6_OPT_RECONF_MESSAGE && olen == 1 && (
659 odata[0] == DHCPV6_MSG_RENEW ||
660 odata[0] == DHCPV6_MSG_INFO_REQ))
663 dhcpv6_handle_reply(DHCPV6_MSG_UNKNOWN, rc, NULL, NULL);
668 // Collect all advertised servers
669 static int dhcpv6_handle_advert(enum dhcpv6_msg orig, const int rc,
670 const void *opt, const void *end)
672 uint16_t olen, otype;
673 uint8_t *odata, pref = 0;
674 struct dhcpv6_server_cand cand = {false, false, 0, 0, {0},
675 IN6ADDR_ANY_INIT, NULL, NULL, 0, 0};
676 bool have_na = false;
679 dhcpv6_for_each_option(opt, end, otype, olen, odata) {
680 if (orig == DHCPV6_MSG_SOLICIT &&
681 (otype == DHCPV6_OPT_IA_PD || otype == DHCPV6_OPT_IA_NA) &&
682 olen > sizeof(struct dhcpv6_ia_hdr)) {
683 struct dhcpv6_ia_hdr *ia_hdr = (void*)(&odata[-4]);
684 dhcpv6_parse_ia(ia_hdr, odata + olen + sizeof(*ia_hdr));
687 if (otype == DHCPV6_OPT_SERVERID && olen <= 130) {
688 memcpy(cand.duid, odata, olen);
689 cand.duid_len = olen;
690 } else if (otype == DHCPV6_OPT_STATUS && olen >= 2) {
691 int error = ((int)odata[0] << 8 | (int)odata[1]);
694 case DHCPV6_NoPrefixAvail:
695 // Status code on global level
696 if (pd_mode == IA_MODE_FORCE)
698 cand.preference -= 2000;
701 case DHCPV6_NoAddrsAvail:
702 // Status code on global level
703 if (na_mode == IA_MODE_FORCE)
710 } else if (otype == DHCPV6_OPT_PREF && olen >= 1 &&
711 cand.preference >= 0) {
712 cand.preference = pref = odata[0];
713 } else if (otype == DHCPV6_OPT_UNICAST && olen == sizeof(cand.server_addr)) {
714 cand.server_addr = *(struct in6_addr *)odata;
715 } else if (otype == DHCPV6_OPT_RECONF_ACCEPT) {
716 cand.wants_reconfigure = true;
717 } else if (otype == DHCPV6_OPT_IA_PD && request_prefix) {
718 struct dhcpv6_ia_hdr *h = (struct dhcpv6_ia_hdr*)&odata[-4];
719 uint8_t *oend = odata + olen, *d;
720 dhcpv6_for_each_option(&h[1], oend, otype, olen, d) {
721 if (otype == DHCPV6_OPT_IA_PREFIX && (olen + 4) >=
722 (uint16_t)sizeof(struct dhcpv6_ia_prefix)) {
723 struct dhcpv6_ia_prefix *p = (struct dhcpv6_ia_prefix*)&d[-4];
727 } else if (otype == DHCPV6_OPT_IA_NA) {
728 struct dhcpv6_ia_hdr *h = (struct dhcpv6_ia_hdr*)&odata[-4];
729 uint8_t *oend = odata + olen, *d;
730 dhcpv6_for_each_option(&h[1], oend, otype, olen, d)
731 if (otype == DHCPV6_OPT_IA_ADDR)
736 if ((!have_na && na_mode == IA_MODE_FORCE) ||
737 (!have_pd && pd_mode == IA_MODE_FORCE))
740 if (na_mode != IA_MODE_NONE && !have_na) {
741 cand.has_noaddravail = true;
742 cand.preference -= 1000;
745 if (pd_mode != IA_MODE_NONE) {
747 cand.preference += 2000 + (128 - have_pd);
749 cand.preference -= 2000;
752 if (cand.duid_len > 0) {
753 cand.ia_na = odhcp6c_move_state(STATE_IA_NA, &cand.ia_na_len);
754 cand.ia_pd = odhcp6c_move_state(STATE_IA_PD, &cand.ia_pd_len);
755 dhcpv6_add_server_cand(&cand);
758 return (rc > 1 || (pref == 255 && cand.preference > 0)) ? 1 : -1;
762 static int dhcpv6_commit_advert(void)
764 return dhcpv6_promote_server_cand();
768 static int dhcpv6_handle_rebind_reply(enum dhcpv6_msg orig, const int rc,
769 const void *opt, const void *end)
771 dhcpv6_handle_advert(orig, rc, opt, end);
772 if (dhcpv6_commit_advert() < 0)
775 return dhcpv6_handle_reply(orig, rc, opt, end);
779 static int dhcpv6_handle_reply(enum dhcpv6_msg orig, _unused const int rc,
780 const void *opt, const void *end)
783 uint16_t otype, olen;
784 uint32_t refresh = UINT32_MAX;
786 bool handled_status_codes[_DHCPV6_Status_Max] = { false, };
790 if (orig == DHCPV6_MSG_UNKNOWN) {
791 static time_t last_update = 0;
792 time_t now = odhcp6c_get_milli_time() / 1000;
794 uint32_t elapsed = (last_update > 0) ? now - last_update : 0;
811 if (orig == DHCPV6_MSG_REQUEST && !odhcp6c_is_bound()) {
812 // Delete NA and PD we have in the state from the Advert
813 odhcp6c_clear_state(STATE_IA_NA);
814 odhcp6c_clear_state(STATE_IA_PD);
818 odhcp6c_clear_state(STATE_DNS);
819 odhcp6c_clear_state(STATE_SEARCH);
820 odhcp6c_clear_state(STATE_SNTP_IP);
821 odhcp6c_clear_state(STATE_SNTP_FQDN);
822 odhcp6c_clear_state(STATE_SIP_IP);
823 odhcp6c_clear_state(STATE_SIP_FQDN);
824 odhcp6c_clear_state(STATE_AFTR_NAME);
827 // Parse and find all matching IAs
828 dhcpv6_for_each_option(opt, end, otype, olen, odata) {
829 if ((otype == DHCPV6_OPT_IA_PD || otype == DHCPV6_OPT_IA_NA)
830 && olen > sizeof(struct dhcpv6_ia_hdr)) {
831 struct dhcpv6_ia_hdr *ia_hdr = (void*)(&odata[-4]);
834 if (ia_hdr->iaid != 1)
837 uint16_t code = DHCPV6_Success;
838 uint16_t stype, slen;
840 // Get and handle status code
841 dhcpv6_for_each_option(&ia_hdr[1], odata + olen,
842 stype, slen, sdata) {
843 if (stype == DHCPV6_OPT_STATUS && slen >= 2) {
844 uint8_t *mdata = (slen > 2) ? &sdata[2] : NULL;
845 uint16_t mlen = (slen > 2) ? slen - 2 : 0;
847 code = ((int)sdata[0]) << 8 | ((int)sdata[1]);
849 if (code == DHCPV6_Success)
852 dhcpv6_handle_ia_status_code(orig, ia_hdr,
853 code, mdata, mlen, handled_status_codes, &ret);
862 if (code != DHCPV6_Success)
865 dhcpv6_parse_ia(ia_hdr, odata + olen + sizeof(*ia_hdr));
866 } else if (otype == DHCPV6_OPT_UNICAST && olen == sizeof(server_addr)) {
867 server_addr = *(struct in6_addr *)odata;
868 } else if (otype == DHCPV6_OPT_STATUS && olen >= 2) {
869 uint8_t *mdata = (olen > 2) ? &odata[2] : NULL;
870 uint16_t mlen = (olen > 2) ? olen - 2 : 0;
871 uint16_t code = ((int)odata[0]) << 8 | ((int)odata[1]);
873 dhcpv6_handle_status_code(orig, code, mdata, mlen, &ret);
875 else if (otype == DHCPV6_OPT_DNS_SERVERS) {
877 odhcp6c_add_state(STATE_DNS, odata, olen);
878 } else if (otype == DHCPV6_OPT_DNS_DOMAIN) {
879 odhcp6c_add_state(STATE_SEARCH, odata, olen);
880 } else if (otype == DHCPV6_OPT_NTP_SERVER) {
881 uint16_t stype, slen;
883 // Test status and bail if error
884 dhcpv6_for_each_option(odata, odata + olen,
885 stype, slen, sdata) {
886 if (slen == 16 && (stype == NTP_MC_ADDR ||
887 stype == NTP_SRV_ADDR))
888 odhcp6c_add_state(STATE_SNTP_IP,
890 else if (slen > 0 && stype == NTP_SRV_FQDN)
891 odhcp6c_add_state(STATE_SNTP_FQDN,
894 } else if (otype == DHCPV6_OPT_SIP_SERVER_A) {
896 odhcp6c_add_state(STATE_SIP_IP, odata, olen);
897 } else if (otype == DHCPV6_OPT_SIP_SERVER_D) {
898 odhcp6c_add_state(STATE_SIP_FQDN, odata, olen);
899 } else if (otype == DHCPV6_OPT_INFO_REFRESH && olen >= 4) {
900 refresh = ntohl(*((uint32_t*)odata));
901 } else if (otype == DHCPV6_OPT_AUTH && olen == -4 +
902 sizeof(struct dhcpv6_auth_reconfigure)) {
903 struct dhcpv6_auth_reconfigure *r = (void*)&odata[-4];
904 if (r->protocol == 3 && r->algorithm == 1 &&
906 memcpy(reconf_key, r->key, sizeof(r->key));
907 } else if (otype == DHCPV6_OPT_AFTR_NAME && olen > 3) {
909 odhcp6c_get_state(STATE_AFTR_NAME, &cur_len);
911 odhcp6c_add_state(STATE_AFTR_NAME, odata, olen);
912 } else if (otype != DHCPV6_OPT_CLIENTID &&
913 otype != DHCPV6_OPT_SERVERID) {
914 odhcp6c_add_state(STATE_CUSTOM_OPTS,
915 &odata[-4], olen + 4);
919 if (orig != DHCPV6_MSG_INFO_REQ) {
920 // Update refresh timers if no fatal status code was received
921 if ((ret > 0) && dhcpv6_calc_refresh_timers()) {
923 case DHCPV6_MSG_RENEW:
924 // Send further renews if T1 is not set
928 case DHCPV6_MSG_REBIND:
929 // Send further rebinds if T1 and T2 is not set
934 case DHCPV6_MSG_REQUEST:
935 // All server candidates can be cleared if not yet bound
936 if (!odhcp6c_is_bound())
937 dhcpv6_clear_all_server_cand();
951 static int dhcpv6_parse_ia(void *opt, void *end)
953 struct dhcpv6_ia_hdr *ia_hdr = (struct dhcpv6_ia_hdr *)opt;
956 uint16_t otype, olen;
959 t1 = ntohl(ia_hdr->t1);
960 t2 = ntohl(ia_hdr->t2);
966 dhcpv6_for_each_option(&ia_hdr[1], end, otype, olen, odata) {
967 struct odhcp6c_entry entry = {IN6ADDR_ANY_INIT, 0, 0,
968 IN6ADDR_ANY_INIT, 0, 0, 0, 0, 0};
970 if (otype == DHCPV6_OPT_IA_PREFIX) {
971 struct dhcpv6_ia_prefix *prefix = (void*)&odata[-4];
972 if (olen + 4U < sizeof(*prefix))
975 entry.valid = ntohl(prefix->valid);
976 entry.preferred = ntohl(prefix->preferred);
978 if (entry.preferred > entry.valid)
981 entry.t1 = (t1 ? t1 : (entry.preferred != UINT32_MAX ? 0.5 * entry.preferred : UINT32_MAX));
982 entry.t2 = (t2 ? t2 : (entry.preferred != UINT32_MAX ? 0.8 * entry.preferred : UINT32_MAX));
983 if (entry.t1 > entry.t2)
986 entry.length = prefix->prefix;
987 entry.target = prefix->addr;
988 uint16_t stype, slen;
991 #ifdef EXT_PREFIX_CLASS
992 // Find prefix class, if any
993 dhcpv6_for_each_option(&prefix[1], odata + olen,
995 if (stype == DHCPV6_OPT_PREFIX_CLASS && slen == 2)
996 entry.class = sdata[0] << 8 | sdata[1];
1001 dhcpv6_for_each_option(odata + sizeof(*prefix) - 4U,
1002 odata + olen, stype, slen, sdata) {
1003 if (stype != DHCPV6_OPT_PD_EXCLUDE || slen < 2)
1006 uint8_t elen = sdata[0];
1010 if (elen <= 32 || elen <= entry.length) {
1016 uint8_t bytes = ((elen - entry.length - 1) / 8) + 1;
1017 if (slen <= bytes) {
1022 uint32_t exclude = 0;
1024 exclude = exclude << 8 | sdata[bytes];
1027 exclude >>= 8 - ((elen - entry.length) % 8);
1028 exclude <<= 64 - elen;
1030 // Abusing router & priority fields for exclusion
1031 entry.router = entry.target;
1032 entry.router.s6_addr32[1] |= htonl(exclude);
1033 entry.priority = elen;
1037 odhcp6c_update_entry(STATE_IA_PD, &entry);
1042 memset(&entry.router, 0, sizeof(entry.router));
1043 } else if (otype == DHCPV6_OPT_IA_ADDR) {
1044 struct dhcpv6_ia_addr *addr = (void*)&odata[-4];
1045 if (olen + 4U < sizeof(*addr))
1048 entry.preferred = ntohl(addr->preferred);
1049 entry.valid = ntohl(addr->valid);
1051 if (entry.preferred > entry.valid)
1054 entry.t1 = (t1 ? t1 : (entry.preferred != UINT32_MAX ? 0.5 * entry.preferred : UINT32_MAX));
1055 entry.t2 = (t2 ? t2 : (entry.preferred != UINT32_MAX ? 0.8 * entry.preferred : UINT32_MAX));
1056 if (entry.t1 > entry.t2)
1057 entry.t1 = entry.t2;
1060 entry.target = addr->addr;
1062 #ifdef EXT_PREFIX_CLASS
1063 uint16_t stype, slen;
1065 // Find prefix class, if any
1066 dhcpv6_for_each_option(&addr[1], odata + olen,
1068 if (stype == DHCPV6_OPT_PREFIX_CLASS && slen == 2)
1069 entry.class = sdata[0] << 8 | sdata[1];
1072 odhcp6c_update_entry(STATE_IA_NA, &entry);
1080 static int dhcpv6_calc_refresh_timers(void)
1082 struct odhcp6c_entry *e;
1083 size_t ia_na_entries, ia_pd_entries, i;
1084 int64_t l_t1 = UINT32_MAX, l_t2 = UINT32_MAX, l_t3 = 0;
1086 e = odhcp6c_get_state(STATE_IA_NA, &ia_na_entries);
1087 ia_na_entries /= sizeof(*e);
1088 for (i = 0; i < ia_na_entries; i++) {
1095 if (e[i].valid > l_t3)
1099 e = odhcp6c_get_state(STATE_IA_PD, &ia_pd_entries);
1100 ia_pd_entries /= sizeof(*e);
1101 for (i = 0; i < ia_pd_entries; i++) {
1108 if (e[i].valid > l_t3)
1112 if (ia_pd_entries || ia_na_entries) {
1118 return (int)(ia_pd_entries + ia_na_entries);
1122 static void dhcpv6_log_status_code(const uint16_t code, const char *scope,
1123 const void *status_msg, const int len)
1125 uint8_t buf[len + 3];
1127 memset(buf, 0, sizeof(buf));
1130 memcpy(&buf[1], status_msg, len);
1134 syslog(LOG_WARNING, "Server returned %s status %i %s",
1139 static void dhcpv6_handle_status_code(const enum dhcpv6_msg orig,
1140 const uint16_t code, const void *status_msg, const int len,
1143 dhcpv6_log_status_code(code, "message", status_msg, len);
1146 case DHCPV6_UnspecFail:
1151 case DHCPV6_UseMulticast:
1153 case DHCPV6_MSG_REQUEST:
1154 case DHCPV6_MSG_RENEW:
1155 case DHCPV6_MSG_RELEASE:
1156 case DHCPV6_MSG_DECLINE:
1157 // Message needs to be retransmitted according to RFC3315 chapter 18.1.8
1158 server_addr = in6addr_any;
1166 case DHCPV6_NoAddrsAvail:
1167 case DHCPV6_NoPrefixAvail:
1168 if (orig == DHCPV6_MSG_REQUEST)
1169 *ret = 0; // Failure
1178 static void dhcpv6_handle_ia_status_code(const enum dhcpv6_msg orig,
1179 const struct dhcpv6_ia_hdr *ia_hdr, const uint16_t code,
1180 const void *status_msg, const int len,
1181 bool handled_status_codes[_DHCPV6_Status_Max], int *ret)
1183 dhcpv6_log_status_code(code, ia_hdr->type == DHCPV6_OPT_IA_NA ?
1184 "IA_NA" : "IA_PD", status_msg, len);
1187 case DHCPV6_NoBinding:
1189 case DHCPV6_MSG_RENEW:
1190 case DHCPV6_MSG_REBIND:
1191 if ((*ret > 0) && !handled_status_codes[code])
1192 *ret = dhcpv6_request(DHCPV6_MSG_REQUEST);
1200 case DHCPV6_NoAddrsAvail:
1201 case DHCPV6_NoPrefixAvail:
1203 case DHCPV6_MSG_REQUEST:
1212 case DHCPV6_NotOnLink:
1213 // TODO handle not onlink in case of confirm
1221 static void dhcpv6_add_server_cand(const struct dhcpv6_server_cand *cand)
1224 struct dhcpv6_server_cand *c = odhcp6c_get_state(STATE_SERVER_CAND, &cand_len);
1226 // Remove identical duid server candidate
1227 for (i = 0; i < cand_len / sizeof(*c); ++i) {
1228 if (cand->duid_len == c[i].duid_len &&
1229 !memcmp(cand->duid, c[i].duid, cand->duid_len)) {
1232 odhcp6c_remove_state(STATE_SERVER_CAND, i * sizeof(*c), sizeof(*c));
1237 for (i = 0, c = odhcp6c_get_state(STATE_SERVER_CAND, &cand_len);
1238 i < cand_len / sizeof(*c); ++i) {
1239 if (c[i].preference < cand->preference)
1243 odhcp6c_insert_state(STATE_SERVER_CAND, i * sizeof(*c), cand, sizeof(*cand));
1246 int dhcpv6_promote_server_cand(void)
1249 struct dhcpv6_server_cand *cand = odhcp6c_get_state(STATE_SERVER_CAND, &cand_len);
1251 int ret = DHCPV6_STATELESS;
1253 // Clear lingering candidate state info
1254 odhcp6c_clear_state(STATE_SERVER_ID);
1255 odhcp6c_clear_state(STATE_IA_NA);
1256 odhcp6c_clear_state(STATE_IA_PD);
1261 if (cand->has_noaddravail && na_mode == IA_MODE_TRY) {
1262 na_mode = IA_MODE_NONE;
1263 return dhcpv6_request(DHCPV6_MSG_SOLICIT);
1266 hdr[0] = htons(DHCPV6_OPT_SERVERID);
1267 hdr[1] = htons(cand->duid_len);
1268 odhcp6c_add_state(STATE_SERVER_ID, hdr, sizeof(hdr));
1269 odhcp6c_add_state(STATE_SERVER_ID, cand->duid, cand->duid_len);
1270 accept_reconfig = cand->wants_reconfigure;
1271 if (cand->ia_na_len) {
1272 odhcp6c_add_state(STATE_IA_NA, cand->ia_na, cand->ia_na_len);
1274 if (na_mode != IA_MODE_NONE)
1275 ret = DHCPV6_STATEFUL;
1277 if (cand->ia_pd_len) {
1278 odhcp6c_add_state(STATE_IA_PD, cand->ia_pd, cand->ia_pd_len);
1281 ret = DHCPV6_STATEFUL;
1284 odhcp6c_remove_state(STATE_SERVER_CAND, 0, sizeof(*cand));
1289 void dhcpv6_clear_all_server_cand(void)
1292 struct dhcpv6_server_cand *c = odhcp6c_get_state(STATE_SERVER_CAND, &cand_len);
1294 // Server candidates need deep delete for IA_NA/IA_PD
1295 for (i = 0; i < cand_len / sizeof(*c); ++i) {
1301 odhcp6c_clear_state(STATE_SERVER_CAND);