]> git.decadent.org.uk Git - odhcp6c.git/blob - src/dhcpv6.c
Revert to old behaviour regarding information requests
[odhcp6c.git] / src / dhcpv6.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 <fcntl.h>
17 #include <errno.h>
18 #include <stdlib.h>
19 #include <signal.h>
20 #include <limits.h>
21 #include <resolv.h>
22 #include <string.h>
23 #include <unistd.h>
24 #include <syslog.h>
25 #include <stdbool.h>
26 #include <sys/time.h>
27 #include <sys/ioctl.h>
28 #include <sys/socket.h>
29 #include <netinet/in.h>
30
31 #include <net/if.h>
32 #include <net/ethernet.h>
33
34 #include "odhcp6c.h"
35 #include "md5.h"
36
37
38 #define ALL_DHCPV6_RELAYS {{{0xff, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
39                 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x02}}}
40 #define DHCPV6_CLIENT_PORT 546
41 #define DHCPV6_SERVER_PORT 547
42 #define DHCPV6_DUID_LLADDR 3
43 #define DHCPV6_REQ_DELAY 1
44
45 #define DHCPV6_SOL_MAX_RT_MIN 60
46 #define DHCPV6_SOL_MAX_RT_MAX 86400
47 #define DHCPV6_INF_MAX_RT_MIN 60
48 #define DHCPV6_INF_MAX_RT_MAX 86400
49
50 static bool dhcpv6_response_is_valid(const void *buf, ssize_t len,
51                 const uint8_t transaction[3], enum dhcpv6_msg type,
52                 const struct in6_addr *daddr);
53
54 static int dhcpv6_parse_ia(void *opt, void *end);
55
56 static int dhcpv6_calc_refresh_timers(void);
57 static void dhcpv6_handle_status_code(_unused const enum dhcpv6_msg orig,
58                 const uint16_t code, const void *status_msg, const int len,
59                 int *ret);
60 static void dhcpv6_handle_ia_status_code(const enum dhcpv6_msg orig,
61                 const struct dhcpv6_ia_hdr *ia_hdr, const uint16_t code,
62                 const void *status_msg, const int len,
63                 bool handled_status_codes[_DHCPV6_Status_Max],
64                 int *ret);
65 static void dhcpv6_add_server_cand(const struct dhcpv6_server_cand *cand);
66 static void dhcpv6_clear_all_server_cand(void);
67
68 static reply_handler dhcpv6_handle_reply;
69 static reply_handler dhcpv6_handle_advert;
70 static reply_handler dhcpv6_handle_rebind_reply;
71 static reply_handler dhcpv6_handle_reconfigure;
72 static int dhcpv6_commit_advert(void);
73
74
75
76 // RFC 3315 - 5.5 Timeout and Delay values
77 static struct dhcpv6_retx dhcpv6_retx[_DHCPV6_MSG_MAX] = {
78         [DHCPV6_MSG_UNKNOWN] = {false, 1, 120, 0, "<POLL>",
79                         dhcpv6_handle_reconfigure, NULL},
80         [DHCPV6_MSG_SOLICIT] = {true, 1, DHCPV6_SOL_MAX_RT, 0, "SOLICIT",
81                         dhcpv6_handle_advert, dhcpv6_commit_advert},
82         [DHCPV6_MSG_REQUEST] = {true, 1, DHCPV6_REQ_MAX_RT, 10, "REQUEST",
83                         dhcpv6_handle_reply, NULL},
84         [DHCPV6_MSG_RENEW] = {false, 10, DHCPV6_REN_MAX_RT, 0, "RENEW",
85                         dhcpv6_handle_reply, NULL},
86         [DHCPV6_MSG_REBIND] = {false, 10, DHCPV6_REB_MAX_RT, 0, "REBIND",
87                         dhcpv6_handle_rebind_reply, NULL},
88         [DHCPV6_MSG_RELEASE] = {false, 1, 0, 5, "RELEASE", NULL, NULL},
89         [DHCPV6_MSG_DECLINE] = {false, 1, 0, 5, "DECLINE", NULL, NULL},
90         [DHCPV6_MSG_INFO_REQ] = {true, 1, DHCPV6_INF_MAX_RT, 0, "INFOREQ",
91                         dhcpv6_handle_reply, NULL},
92 };
93
94
95 // Sockets
96 static int sock = -1;
97 static int ifindex = -1;
98 static int64_t t1 = 0, t2 = 0, t3 = 0;
99
100 // IA states
101 static int request_prefix = -1;
102 static enum odhcp6c_ia_mode na_mode = IA_MODE_NONE, pd_mode = IA_MODE_NONE;
103 static bool accept_reconfig = false;
104
105 // Reconfigure key
106 static uint8_t reconf_key[16];
107
108
109 int init_dhcpv6(const char *ifname, int request_pd, int sol_timeout)
110 {
111         request_prefix = request_pd;
112         dhcpv6_retx[DHCPV6_MSG_SOLICIT].max_timeo = sol_timeout;
113
114         sock = socket(AF_INET6, SOCK_DGRAM | SOCK_CLOEXEC, IPPROTO_UDP);
115         if (sock < 0)
116                 return -1;
117
118         // Detect interface
119         struct ifreq ifr;
120         strncpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name));
121         if (ioctl(sock, SIOCGIFINDEX, &ifr) < 0)
122                 return -1;
123         ifindex = ifr.ifr_ifindex;
124
125         // Create client DUID
126         size_t client_id_len;
127         odhcp6c_get_state(STATE_CLIENT_ID, &client_id_len);
128         if (client_id_len == 0) {
129                 uint8_t duid[14] = {0, DHCPV6_OPT_CLIENTID, 0, 10, 0,
130                                 DHCPV6_DUID_LLADDR, 0, 1};
131
132                 if (ioctl(sock, SIOCGIFHWADDR, &ifr) >= 0)
133                         memcpy(&duid[8], ifr.ifr_hwaddr.sa_data, ETHER_ADDR_LEN);
134
135                 uint8_t zero[ETHER_ADDR_LEN] = {0, 0, 0, 0, 0, 0};
136                 struct ifreq ifs[100], *ifp, *ifend;
137                 struct ifconf ifc;
138                 ifc.ifc_req = ifs;
139                 ifc.ifc_len = sizeof(ifs);
140
141                 if (!memcmp(&duid[8], zero, ETHER_ADDR_LEN) &&
142                                 ioctl(sock, SIOCGIFCONF, &ifc) >= 0) {
143                         // If our interface doesn't have an address...
144                         ifend = ifs + (ifc.ifc_len / sizeof(struct ifreq));
145                         for (ifp = ifc.ifc_req; ifp < ifend &&
146                                         !memcmp(&duid[8], zero, ETHER_ADDR_LEN); ifp++) {
147                                 memcpy(ifr.ifr_name, ifp->ifr_name,
148                                                 sizeof(ifr.ifr_name));
149                                 if (ioctl(sock, SIOCGIFHWADDR, &ifr) < 0)
150                                         continue;
151
152                                 memcpy(&duid[8], ifr.ifr_hwaddr.sa_data,
153                                                 ETHER_ADDR_LEN);
154                         }
155                 }
156
157                 odhcp6c_add_state(STATE_CLIENT_ID, duid, sizeof(duid));
158         }
159
160         // Create ORO
161         uint16_t oro[] = {
162                         htons(DHCPV6_OPT_SIP_SERVER_D),
163                         htons(DHCPV6_OPT_SIP_SERVER_A),
164                         htons(DHCPV6_OPT_DNS_SERVERS),
165                         htons(DHCPV6_OPT_DNS_DOMAIN),
166                         htons(DHCPV6_OPT_NTP_SERVER),
167                         htons(DHCPV6_OPT_AFTR_NAME),
168                         htons(DHCPV6_OPT_PD_EXCLUDE),
169                         htons(DHCPV6_OPT_SOL_MAX_RT),
170                         htons(DHCPV6_OPT_INF_MAX_RT),
171 #ifdef EXT_PREFIX_CLASS
172                         htons(DHCPV6_OPT_PREFIX_CLASS),
173 #endif
174         };
175         odhcp6c_add_state(STATE_ORO, oro, sizeof(oro));
176
177         // Configure IPv6-options
178         int val = 1;
179         setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &val, sizeof(val));
180         setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val));
181         setsockopt(sock, IPPROTO_IPV6, IPV6_RECVPKTINFO, &val, sizeof(val));
182         val = 0;
183         setsockopt(sock, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, &val, sizeof(val));
184         setsockopt(sock, SOL_SOCKET, SO_BINDTODEVICE, ifname, strlen(ifname));
185
186         struct sockaddr_in6 client_addr = { .sin6_family = AF_INET6,
187                 .sin6_port = htons(DHCPV6_CLIENT_PORT), .sin6_flowinfo = 0 };
188         if (bind(sock, (struct sockaddr*)&client_addr, sizeof(client_addr)) < 0)
189                 return -1;
190
191         return 0;
192 }
193
194
195 void dhcpv6_set_ia_mode(enum odhcp6c_ia_mode na, enum odhcp6c_ia_mode pd)
196 {
197         na_mode = na;
198         pd_mode = pd;
199 }
200
201
202 static void dhcpv6_send(enum dhcpv6_msg type, uint8_t trid[3], uint32_t ecs)
203 {
204         // Build FQDN
205         char fqdn_buf[256];
206         gethostname(fqdn_buf, sizeof(fqdn_buf));
207         struct {
208                 uint16_t type;
209                 uint16_t len;
210                 uint8_t flags;
211                 uint8_t data[256];
212         } fqdn;
213         size_t fqdn_len = 5 + dn_comp(fqdn_buf, fqdn.data,
214                         sizeof(fqdn.data), NULL, NULL);
215         fqdn.type = htons(DHCPV6_OPT_FQDN);
216         fqdn.len = htons(fqdn_len - 4);
217         fqdn.flags = 0;
218
219
220         // Build Client ID
221         size_t cl_id_len;
222         void *cl_id = odhcp6c_get_state(STATE_CLIENT_ID, &cl_id_len);
223
224         // Get Server ID
225         size_t srv_id_len;
226         void *srv_id = odhcp6c_get_state(STATE_SERVER_ID, &srv_id_len);
227
228         // Build IA_PDs
229         size_t ia_pd_entries, ia_pd_len = 0;
230         struct odhcp6c_entry *e = odhcp6c_get_state(STATE_IA_PD, &ia_pd_entries);
231         ia_pd_entries /= sizeof(*e);
232         struct dhcpv6_ia_hdr hdr_ia_pd = {
233                 htons(DHCPV6_OPT_IA_PD),
234                 htons(sizeof(hdr_ia_pd) - 4),
235                 1, 0, 0
236         };
237
238
239         uint8_t *ia_pd = alloca(ia_pd_entries * (sizeof(struct dhcpv6_ia_prefix) + 10));
240         for (size_t i = 0; i < ia_pd_entries; ++i) {
241                 uint8_t ex_len = 0;
242                 if (e[i].priority > 0)
243                         ex_len = ((e[i].priority - e[i].length - 1) / 8) + 6;
244
245                 struct dhcpv6_ia_prefix p = {
246                         .type = htons(DHCPV6_OPT_IA_PREFIX),
247                         .len = htons(sizeof(p) - 4U + ex_len),
248                         .prefix = e[i].length,
249                         .addr = e[i].target
250                 };
251
252                 memcpy(ia_pd + ia_pd_len, &p, sizeof(p));
253                 ia_pd_len += sizeof(p);
254
255                 if (ex_len) {
256                         ia_pd[ia_pd_len++] = 0;
257                         ia_pd[ia_pd_len++] = DHCPV6_OPT_PD_EXCLUDE;
258                         ia_pd[ia_pd_len++] = 0;
259                         ia_pd[ia_pd_len++] = ex_len - 4;
260                         ia_pd[ia_pd_len++] = e[i].priority;
261
262                         uint32_t excl = ntohl(e[i].router.s6_addr32[1]);
263                         excl >>= (64 - e[i].priority);
264                         excl <<= 8 - ((e[i].priority - e[i].length) % 8);
265
266                         for (size_t i = ex_len - 5; i > 0; --i, excl >>= 8)
267                                 ia_pd[ia_pd_len + i] = excl & 0xff;
268                         ia_pd_len += ex_len - 5;
269                 }
270         }
271
272         struct dhcpv6_ia_prefix pref = {
273                 .type = htons(DHCPV6_OPT_IA_PREFIX),
274                 .len = htons(25), .prefix = request_prefix
275         };
276         if (request_prefix > 0 && ia_pd_len == 0 && type == DHCPV6_MSG_SOLICIT) {
277                 ia_pd = (uint8_t*)&pref;
278                 ia_pd_len = sizeof(pref);
279         }
280         hdr_ia_pd.len = htons(ntohs(hdr_ia_pd.len) + ia_pd_len);
281
282         // Build IA_NAs
283         size_t ia_na_entries, ia_na_len = 0;
284         void *ia_na = NULL;
285         e = odhcp6c_get_state(STATE_IA_NA, &ia_na_entries);
286         ia_na_entries /= sizeof(*e);
287
288         struct dhcpv6_ia_hdr hdr_ia_na = {
289                 htons(DHCPV6_OPT_IA_NA),
290                 htons(sizeof(hdr_ia_na) - 4),
291                 1, 0, 0
292         };
293
294         struct dhcpv6_ia_addr pa[ia_na_entries];
295         for (size_t i = 0; i < ia_na_entries; ++i) {
296                 pa[i].type = htons(DHCPV6_OPT_IA_ADDR);
297                 pa[i].len = htons(sizeof(pa[i]) - 4U);
298                 pa[i].addr = e[i].target;
299                 pa[i].preferred = 0;
300                 pa[i].valid = 0;
301         }
302
303         ia_na = pa;
304         ia_na_len = sizeof(pa);
305         hdr_ia_na.len = htons(ntohs(hdr_ia_na.len) + ia_na_len);
306
307         // Reconfigure Accept
308         struct {
309                 uint16_t type;
310                 uint16_t length;
311         } reconf_accept = {htons(DHCPV6_OPT_RECONF_ACCEPT), 0};
312
313         // Request Information Refresh
314         uint16_t oro_refresh = htons(DHCPV6_OPT_INFO_REFRESH);
315
316         // Prepare Header
317         size_t oro_len;
318         void *oro = odhcp6c_get_state(STATE_ORO, &oro_len);
319         struct {
320                 uint8_t type;
321                 uint8_t trid[3];
322                 uint16_t elapsed_type;
323                 uint16_t elapsed_len;
324                 uint16_t elapsed_value;
325                 uint16_t oro_type;
326                 uint16_t oro_len;
327         } hdr = {
328                 type, {trid[0], trid[1], trid[2]},
329                 htons(DHCPV6_OPT_ELAPSED), htons(2),
330                         htons((ecs > 0xffff) ? 0xffff : ecs),
331                 htons(DHCPV6_OPT_ORO), htons(oro_len),
332         };
333
334         struct iovec iov[] = {
335                 {&hdr, sizeof(hdr)},
336                 {oro, oro_len},
337                 {&oro_refresh, 0},
338                 {cl_id, cl_id_len},
339                 {srv_id, srv_id_len},
340                 {&reconf_accept, sizeof(reconf_accept)},
341                 {&fqdn, fqdn_len},
342                 {&hdr_ia_na, sizeof(hdr_ia_na)},
343                 {ia_na, ia_na_len},
344                 {&hdr_ia_pd, sizeof(hdr_ia_pd)},
345                 {ia_pd, ia_pd_len},
346         };
347
348         size_t cnt = ARRAY_SIZE(iov);
349         if (type == DHCPV6_MSG_INFO_REQ) {
350                 cnt = 5;
351                 iov[2].iov_len = sizeof(oro_refresh);
352                 hdr.oro_len = htons(oro_len + sizeof(oro_refresh));
353         } else if (!request_prefix) {
354                 cnt = 9;
355         }
356
357         // Disable IAs if not used
358         if (type != DHCPV6_MSG_SOLICIT) {
359                 iov[5].iov_len = 0;
360                 if (ia_na_len == 0)
361                         iov[7].iov_len = 0;
362                 if (ia_pd_len == 0)
363                         iov[9].iov_len = 0;
364         }
365
366         if (na_mode == IA_MODE_NONE)
367                 iov[7].iov_len = 0;
368
369         struct sockaddr_in6 srv = {AF_INET6, htons(DHCPV6_SERVER_PORT),
370                 0, ALL_DHCPV6_RELAYS, ifindex};
371         struct msghdr msg = {&srv, sizeof(srv), iov, cnt, NULL, 0, 0};
372
373         sendmsg(sock, &msg, 0);
374 }
375
376
377 static int64_t dhcpv6_rand_delay(int64_t time)
378 {
379         int random;
380         odhcp6c_random(&random, sizeof(random));
381         return (time * ((int64_t)random % 1000LL)) / 10000LL;
382 }
383
384
385 int dhcpv6_request(enum dhcpv6_msg type)
386 {
387         uint8_t rc = 0;
388         uint64_t timeout = UINT32_MAX;
389         struct dhcpv6_retx *retx = &dhcpv6_retx[type];
390
391         if (retx->delay) {
392                 struct timespec ts = {0, 0};
393                 ts.tv_nsec = dhcpv6_rand_delay(10 * DHCPV6_REQ_DELAY);
394                 nanosleep(&ts, NULL);
395         }
396
397         if (type == DHCPV6_MSG_UNKNOWN)
398                 timeout = t1;
399         else if (type == DHCPV6_MSG_RENEW)
400                 timeout = (t2 > t1) ? t2 - t1 : 0;
401         else if (type == DHCPV6_MSG_REBIND)
402                 timeout = (t3 > t2) ? t3 - t2 : 0;
403
404         if (timeout == 0)
405                 return -1;
406
407         syslog(LOG_NOTICE, "Starting %s transaction (timeout %llus, max rc %d)",
408                         retx->name, (unsigned long long)timeout, retx->max_rc);
409
410         uint64_t start = odhcp6c_get_milli_time(), round_start = start, elapsed;
411
412         // Generate transaction ID
413         uint8_t trid[3] = {0, 0, 0};
414         if (type != DHCPV6_MSG_UNKNOWN)
415                 odhcp6c_random(trid, sizeof(trid));
416         ssize_t len = -1;
417         int64_t rto = 0;
418
419         do {
420                 if (rto == 0) {
421                         int64_t delay = dhcpv6_rand_delay(retx->init_timeo * 1000);
422
423                         // First RT MUST be strictly greater than IRT for solicit messages (RFC3313 17.1.2)
424                         while (type == DHCPV6_MSG_SOLICIT && delay <= 0)
425                                 delay = dhcpv6_rand_delay(retx->init_timeo * 1000);
426
427                         rto = (retx->init_timeo * 1000 + delay);
428                 }
429                 else
430                         rto = (2 * rto + dhcpv6_rand_delay(rto));
431
432                 if (retx->max_timeo && (rto >= retx->max_timeo * 1000))
433                         rto = retx->max_timeo * 1000 +
434                                 dhcpv6_rand_delay(retx->max_timeo * 1000);
435
436                 // Calculate end for this round and elapsed time
437                 uint64_t round_end = round_start + rto;
438                 elapsed = round_start - start;
439
440                 // Don't wait too long
441                 if (round_end - start > timeout * 1000)
442                         round_end = timeout * 1000 + start;
443
444                 // Built and send package
445                 if (type != DHCPV6_MSG_UNKNOWN) {
446                         if (type != DHCPV6_MSG_SOLICIT)
447                                 syslog(LOG_NOTICE, "Send %s message (elapsed %llums, rc %d)",
448                                                 retx->name, (unsigned long long)elapsed, rc);
449                         dhcpv6_send(type, trid, elapsed / 10);
450                         rc++;
451                 }
452
453                 // Receive rounds
454                 for (; len < 0 && (round_start < round_end);
455                                 round_start = odhcp6c_get_milli_time()) {
456                         uint8_t buf[1536], cmsg_buf[CMSG_SPACE(sizeof(struct in6_pktinfo))];
457                         struct iovec iov = {buf, sizeof(buf)};
458                         struct msghdr msg = {NULL, 0, &iov, 1,
459                                         cmsg_buf, sizeof(cmsg_buf), 0};
460                         struct in6_pktinfo *pktinfo = NULL;
461
462                         // Check for pending signal
463                         if (odhcp6c_signal_process())
464                                 return -1;
465
466                         // Set timeout for receiving
467                         uint64_t t = round_end - round_start;
468                         struct timeval timeout = {t / 1000, (t % 1000) * 1000};
469                         setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO,
470                                         &timeout, sizeof(timeout));
471
472                         // Receive cycle
473                         len = recvmsg(sock, &msg, 0);
474                         if (len < 0)
475                                 continue;
476
477                         for (struct cmsghdr *ch = CMSG_FIRSTHDR(&msg); ch != NULL;
478                                 ch = CMSG_NXTHDR(&msg, ch)) {
479                                 if (ch->cmsg_level == SOL_IPV6 &&
480                                         ch->cmsg_type == IPV6_PKTINFO) {
481                                         pktinfo = (struct in6_pktinfo *)CMSG_DATA(ch);
482                                         break;
483                                 }
484                         }
485
486                         if (pktinfo == NULL) {
487                                 len = -1;
488                                 continue;
489                         }
490
491                         if (!dhcpv6_response_is_valid(buf, len, trid,
492                                                         type, &pktinfo->ipi6_addr)) {
493                                 len = -1;
494                                 continue;
495                         }
496
497                         uint8_t *opt = &buf[4];
498                         uint8_t *opt_end = opt + len - 4;
499
500                         round_start = odhcp6c_get_milli_time();
501                         elapsed = round_start - start;
502                         syslog(LOG_NOTICE, "Got a valid reply after "
503                                         "%llums", (unsigned long long)elapsed);
504
505                         if (retx->handler_reply)
506                                 len = retx->handler_reply(type, rc, opt, opt_end);
507
508                         if (len > 0 && round_end - round_start > 1000)
509                                 round_end = 1000 + round_start;
510                 }
511
512                 // Allow
513                 if (retx->handler_finish)
514                         len = retx->handler_finish();
515         } while (len < 0 && ((elapsed / 1000 < timeout) && (!retx->max_rc || rc < retx->max_rc)));
516
517         return len;
518 }
519
520 // Message validation checks according to RFC3315 chapter 15
521 static bool dhcpv6_response_is_valid(const void *buf, ssize_t len,
522                 const uint8_t transaction[3], enum dhcpv6_msg type,
523                 const struct in6_addr *daddr)
524 {
525         const struct dhcpv6_header *rep = buf;
526         if (len < (ssize_t)sizeof(*rep) || memcmp(rep->tr_id,
527                         transaction, sizeof(rep->tr_id)))
528                 return false; // Invalid reply
529
530         if (type == DHCPV6_MSG_SOLICIT) {
531                 if (rep->msg_type != DHCPV6_MSG_ADVERT &&
532                                 rep->msg_type != DHCPV6_MSG_REPLY)
533                         return false;
534         } else if (type == DHCPV6_MSG_UNKNOWN) {
535                 if (!accept_reconfig || rep->msg_type != DHCPV6_MSG_RECONF)
536                         return false;
537         } else if (rep->msg_type != DHCPV6_MSG_REPLY) {
538                 return false;
539         }
540
541         uint8_t *end = ((uint8_t*)buf) + len, *odata = NULL,
542                 rcmsg = DHCPV6_MSG_UNKNOWN;
543         uint16_t otype, olen = UINT16_MAX;
544         bool clientid_ok = false, serverid_ok = false, rcauth_ok = false,
545                 ia_present = false, options_valid = true;
546
547         size_t client_id_len, server_id_len;
548         void *client_id = odhcp6c_get_state(STATE_CLIENT_ID, &client_id_len);
549         void *server_id = odhcp6c_get_state(STATE_SERVER_ID, &server_id_len);
550
551         dhcpv6_for_each_option(&rep[1], end, otype, olen, odata) {
552                 if (otype == DHCPV6_OPT_CLIENTID) {
553                         clientid_ok = (olen + 4U == client_id_len) && !memcmp(
554                                         &odata[-4], client_id, client_id_len);
555                 } else if (otype == DHCPV6_OPT_SERVERID) {
556                         if (server_id_len)
557                                 serverid_ok = (olen + 4U == server_id_len) && !memcmp(
558                                                 &odata[-4], server_id, server_id_len);
559                         else
560                                 serverid_ok = true;
561                 } else if (otype == DHCPV6_OPT_AUTH && olen == -4 +
562                                 sizeof(struct dhcpv6_auth_reconfigure)) {
563                         struct dhcpv6_auth_reconfigure *r = (void*)&odata[-4];
564                         if (r->protocol != 3 || r->algorithm != 1 || r->reconf_type != 2)
565                                 continue;
566
567                         md5_state_t md5;
568                         uint8_t serverhash[16], secretbytes[16], hash[16];
569                         memcpy(serverhash, r->key, sizeof(serverhash));
570                         memset(r->key, 0, sizeof(r->key));
571                         memcpy(secretbytes, reconf_key, sizeof(secretbytes));
572
573                         for (size_t i = 0; i < sizeof(secretbytes); ++i)
574                                 secretbytes[i] ^= 0x36;
575
576                         md5_init(&md5);
577                         md5_append(&md5, secretbytes, sizeof(secretbytes));
578                         md5_append(&md5, buf, len);
579                         md5_finish(&md5, hash);
580
581                         for (size_t i = 0; i < sizeof(secretbytes); ++i) {
582                                 secretbytes[i] ^= 0x36;
583                                 secretbytes[i] ^= 0x5c;
584                         }
585
586                         md5_init(&md5);
587                         md5_append(&md5, secretbytes, sizeof(secretbytes));
588                         md5_append(&md5, hash, 16);
589                         md5_finish(&md5, hash);
590
591                         rcauth_ok = !memcmp(hash, serverhash, sizeof(hash));
592                 } else if (otype == DHCPV6_OPT_RECONF_MESSAGE && olen == 1) {
593                         rcmsg = odata[0];
594                 } else if ((otype == DHCPV6_OPT_IA_PD || otype == DHCPV6_OPT_IA_NA)) {
595                         ia_present = true;
596                         if (olen < sizeof(struct dhcpv6_ia_hdr))
597                                 options_valid = false;
598                 }
599                 else if ((otype == DHCPV6_OPT_IA_ADDR) || (otype == DHCPV6_OPT_IA_PREFIX) ||
600                                 (otype == DHCPV6_OPT_PD_EXCLUDE)) {
601                         // Options are not allowed on global level
602                         options_valid = false;
603                 }
604         }
605
606         if (!options_valid || ((odata + olen) > end))
607                 return false;
608
609         if (type == DHCPV6_MSG_INFO_REQ && ia_present)
610                 return false;
611
612         if (rep->msg_type == DHCPV6_MSG_RECONF) {
613                 if ((rcmsg != DHCPV6_MSG_RENEW && rcmsg != DHCPV6_MSG_INFO_REQ) ||
614                         (rcmsg == DHCPV6_MSG_INFO_REQ && ia_present) ||
615                         !rcauth_ok || IN6_IS_ADDR_MULTICAST(daddr))
616                         return false;
617         }
618
619         return clientid_ok && serverid_ok;
620 }
621
622
623 int dhcpv6_poll_reconfigure(void)
624 {
625         int ret = dhcpv6_request(DHCPV6_MSG_UNKNOWN);
626         if (ret != -1)
627                 ret = dhcpv6_request(ret);
628
629         return ret;
630 }
631
632
633 static int dhcpv6_handle_reconfigure(_unused enum dhcpv6_msg orig, const int rc,
634                 const void *opt, const void *end)
635 {
636         uint16_t otype, olen;
637         uint8_t *odata, msg = DHCPV6_MSG_RENEW;
638         dhcpv6_for_each_option(opt, end, otype, olen, odata)
639                 if (otype == DHCPV6_OPT_RECONF_MESSAGE && olen == 1 && (
640                                 odata[0] == DHCPV6_MSG_RENEW ||
641                                 odata[0] == DHCPV6_MSG_INFO_REQ))
642                         msg = odata[0];
643
644         dhcpv6_handle_reply(DHCPV6_MSG_UNKNOWN, rc, NULL, NULL);
645         return msg;
646 }
647
648
649 // Collect all advertised servers
650 static int dhcpv6_handle_advert(enum dhcpv6_msg orig, const int rc,
651                 const void *opt, const void *end)
652 {
653         uint16_t olen, otype;
654         uint8_t *odata, pref = 0;
655         struct dhcpv6_server_cand cand = {false, false, 0, 0, {0},
656                                         DHCPV6_SOL_MAX_RT,
657                                         DHCPV6_INF_MAX_RT, NULL, NULL, 0, 0};
658         bool have_na = false;
659         int have_pd = 0;
660
661         dhcpv6_for_each_option(opt, end, otype, olen, odata) {
662                 if (orig == DHCPV6_MSG_SOLICIT &&
663                                 (otype == DHCPV6_OPT_IA_PD || otype == DHCPV6_OPT_IA_NA) &&
664                                 olen > sizeof(struct dhcpv6_ia_hdr)) {
665                         struct dhcpv6_ia_hdr *ia_hdr = (void*)(&odata[-4]);
666                         dhcpv6_parse_ia(ia_hdr, odata + olen + sizeof(*ia_hdr));
667                 }
668
669                 if (otype == DHCPV6_OPT_SERVERID && olen <= 130) {
670                         memcpy(cand.duid, odata, olen);
671                         cand.duid_len = olen;
672                 } else if (otype == DHCPV6_OPT_STATUS && olen >= 2) {
673                         int error = ((int)odata[0] << 8 | (int)odata[1]);
674
675                         switch (error) {
676                         case DHCPV6_NoPrefixAvail:
677                                 // Status code on global level
678                                 cand.preference -= 2000;
679                                 break;
680
681                         default :
682                                 break;
683                         }
684                 } else if (otype == DHCPV6_OPT_PREF && olen >= 1 &&
685                                 cand.preference >= 0) {
686                         cand.preference = pref = odata[0];
687                 } else if (otype == DHCPV6_OPT_RECONF_ACCEPT) {
688                         cand.wants_reconfigure = true;
689                 } else if (otype == DHCPV6_OPT_SOL_MAX_RT && olen == 4) {
690                         uint32_t sol_max_rt = ntohl(*((uint32_t *)odata));
691                         if (sol_max_rt >= DHCPV6_SOL_MAX_RT_MIN && 
692                                         sol_max_rt <= DHCPV6_SOL_MAX_RT_MAX)
693                                 cand.sol_max_rt = sol_max_rt;
694                 } else if (otype == DHCPV6_OPT_INF_MAX_RT && olen == 4) {
695                         uint32_t inf_max_rt = ntohl(*((uint32_t *)odata));
696                         if (inf_max_rt >= DHCPV6_INF_MAX_RT_MIN && 
697                                         inf_max_rt <= DHCPV6_INF_MAX_RT_MAX)
698                                 cand.inf_max_rt = inf_max_rt;
699                 } else if (otype == DHCPV6_OPT_IA_PD && request_prefix) {
700                         struct dhcpv6_ia_hdr *h = (struct dhcpv6_ia_hdr*)&odata[-4];
701                         uint8_t *oend = odata + olen, *d;
702                         dhcpv6_for_each_option(&h[1], oend, otype, olen, d) {
703                                 if (otype == DHCPV6_OPT_IA_PREFIX && (olen + 4) >=
704                                                 (uint16_t)sizeof(struct dhcpv6_ia_prefix)) {
705                                         struct dhcpv6_ia_prefix *p = (struct dhcpv6_ia_prefix*)&d[-4];
706                                         have_pd = p->prefix;
707                                 }
708                         }
709                 } else if (otype == DHCPV6_OPT_IA_NA) {
710                         struct dhcpv6_ia_hdr *h = (struct dhcpv6_ia_hdr*)&odata[-4];
711                         uint8_t *oend = odata + olen, *d;
712                         dhcpv6_for_each_option(&h[1], oend, otype, olen, d)
713                                 if (otype == DHCPV6_OPT_IA_ADDR)
714                                         have_na = true;
715                 }
716         }
717
718         if ((!have_na && na_mode == IA_MODE_FORCE) ||
719                         (!have_pd && pd_mode == IA_MODE_FORCE)) {
720                 /* 
721                  * RFC7083 states to process the SOL_MAX_RT and 
722                  * INF_MAX_RT options even if the DHCPv6 server
723                  * did not propose any IA_NA and/or IA_PD
724                  */
725                 dhcpv6_retx[DHCPV6_MSG_SOLICIT].max_timeo = cand.sol_max_rt;
726                 dhcpv6_retx[DHCPV6_MSG_INFO_REQ].max_timeo = cand.inf_max_rt;
727                 return -1;
728         }
729
730         if (na_mode != IA_MODE_NONE && !have_na) {
731                 cand.has_noaddravail = true;
732                 cand.preference -= 1000;
733         }
734
735         if (pd_mode != IA_MODE_NONE) {
736                 if (have_pd)
737                         cand.preference += 2000 + (128 - have_pd);
738                 else
739                         cand.preference -= 2000;
740         }
741
742         if (cand.duid_len > 0) {
743                 cand.ia_na = odhcp6c_move_state(STATE_IA_NA, &cand.ia_na_len);
744                 cand.ia_pd = odhcp6c_move_state(STATE_IA_PD, &cand.ia_pd_len);
745                 dhcpv6_add_server_cand(&cand);
746         }
747
748         return (rc > 1 || (pref == 255 && cand.preference > 0)) ? 1 : -1;
749 }
750
751
752 static int dhcpv6_commit_advert(void)
753 {
754         return dhcpv6_promote_server_cand();
755 }
756
757
758 static int dhcpv6_handle_rebind_reply(enum dhcpv6_msg orig, const int rc,
759                 const void *opt, const void *end)
760 {
761         dhcpv6_handle_advert(orig, rc, opt, end);
762         if (dhcpv6_commit_advert() < 0)
763                 return -1;
764
765         return dhcpv6_handle_reply(orig, rc, opt, end);
766 }
767
768
769 static int dhcpv6_handle_reply(enum dhcpv6_msg orig, _unused const int rc,
770                 const void *opt, const void *end)
771 {
772         uint8_t *odata;
773         uint16_t otype, olen;
774         uint32_t refresh = UINT32_MAX;
775         int ret = 1;
776         bool handled_status_codes[_DHCPV6_Status_Max] = { false, };
777
778         odhcp6c_expire();
779
780         if (orig == DHCPV6_MSG_UNKNOWN) {
781                 static time_t last_update = 0;
782                 time_t now = odhcp6c_get_milli_time() / 1000;
783
784                 uint32_t elapsed = (last_update > 0) ? now - last_update : 0;
785                 last_update = now;
786
787                 t1 -= elapsed;
788                 t2 -= elapsed;
789                 t3 -= elapsed;
790
791                 if (t1 < 0)
792                         t1 = 0;
793
794                 if (t2 < 0)
795                         t2 = 0;
796
797                 if (t3 < 0)
798                         t3 = 0;
799         }
800
801         if (orig == DHCPV6_MSG_REQUEST && !odhcp6c_is_bound()) {
802                 // Delete NA and PD we have in the state from the Advert
803                 odhcp6c_clear_state(STATE_IA_NA);
804                 odhcp6c_clear_state(STATE_IA_PD);
805         }
806
807         if (opt) {
808                 odhcp6c_clear_state(STATE_DNS);
809                 odhcp6c_clear_state(STATE_SEARCH);
810                 odhcp6c_clear_state(STATE_SNTP_IP);
811                 odhcp6c_clear_state(STATE_SNTP_FQDN);
812                 odhcp6c_clear_state(STATE_SIP_IP);
813                 odhcp6c_clear_state(STATE_SIP_FQDN);
814                 odhcp6c_clear_state(STATE_AFTR_NAME);
815         }
816
817         // Parse and find all matching IAs
818         dhcpv6_for_each_option(opt, end, otype, olen, odata) {
819                 if ((otype == DHCPV6_OPT_IA_PD || otype == DHCPV6_OPT_IA_NA)
820                                 && olen > sizeof(struct dhcpv6_ia_hdr)) {
821                         struct dhcpv6_ia_hdr *ia_hdr = (void*)(&odata[-4]);
822
823                         // Test ID
824                         if (ia_hdr->iaid != 1)
825                                 continue;
826
827                         uint16_t code = DHCPV6_Success;
828                         uint16_t stype, slen;
829                         uint8_t *sdata;
830                         // Get and handle status code
831                         dhcpv6_for_each_option(&ia_hdr[1], odata + olen,
832                                         stype, slen, sdata) {
833                                 if (stype == DHCPV6_OPT_STATUS && slen >= 2) {
834                                         uint8_t *mdata = (slen > 2) ? &sdata[2] : NULL;
835                                         uint16_t mlen = (slen > 2) ? slen - 2 : 0;
836
837                                         code = ((int)sdata[0]) << 8 | ((int)sdata[1]);
838
839                                         if (code == DHCPV6_Success)
840                                                 continue;
841
842                                         dhcpv6_handle_ia_status_code(orig, ia_hdr,
843                                                 code, mdata, mlen, handled_status_codes, &ret);
844
845
846                                         if (ret > 0)
847                                                 return ret;
848                                         break;
849                                 }
850                         }
851
852                         if (code != DHCPV6_Success)
853                                 continue;
854
855                         dhcpv6_parse_ia(ia_hdr, odata + olen + sizeof(*ia_hdr));
856                 } else if (otype == DHCPV6_OPT_STATUS && olen >= 2) {
857                         uint8_t *mdata = (olen > 2) ? &odata[2] : NULL;
858                         uint16_t mlen = (olen > 2) ? olen - 2 : 0;
859                         uint16_t code = ((int)odata[0]) << 8 | ((int)odata[1]);
860
861                         dhcpv6_handle_status_code(orig, code, mdata, mlen, &ret);
862                 }
863                 else if (otype == DHCPV6_OPT_DNS_SERVERS) {
864                         if (olen % 16 == 0)
865                                 odhcp6c_add_state(STATE_DNS, odata, olen);
866                 } else if (otype == DHCPV6_OPT_DNS_DOMAIN) {
867                         odhcp6c_add_state(STATE_SEARCH, odata, olen);
868                 } else if (otype == DHCPV6_OPT_NTP_SERVER) {
869                         uint16_t stype, slen;
870                         uint8_t *sdata;
871                         // Test status and bail if error
872                         dhcpv6_for_each_option(odata, odata + olen,
873                                         stype, slen, sdata) {
874                                 if (slen == 16 && (stype == NTP_MC_ADDR ||
875                                                 stype == NTP_SRV_ADDR))
876                                         odhcp6c_add_state(STATE_SNTP_IP,
877                                                         sdata, slen);
878                                 else if (slen > 0 && stype == NTP_SRV_FQDN)
879                                         odhcp6c_add_state(STATE_SNTP_FQDN,
880                                                         sdata, slen);
881                         }
882                 } else if (otype == DHCPV6_OPT_SIP_SERVER_A) {
883                         if (olen == 16)
884                                 odhcp6c_add_state(STATE_SIP_IP, odata, olen);
885                 } else if (otype == DHCPV6_OPT_SIP_SERVER_D) {
886                         odhcp6c_add_state(STATE_SIP_FQDN, odata, olen);
887                 } else if (otype == DHCPV6_OPT_INFO_REFRESH && olen >= 4) {
888                         refresh = ntohl(*((uint32_t*)odata));
889                 } else if (otype == DHCPV6_OPT_AUTH && olen == -4 +
890                                 sizeof(struct dhcpv6_auth_reconfigure)) {
891                         struct dhcpv6_auth_reconfigure *r = (void*)&odata[-4];
892                         if (r->protocol == 3 && r->algorithm == 1 &&
893                                         r->reconf_type == 1)
894                                 memcpy(reconf_key, r->key, sizeof(r->key));
895                 } else if (otype == DHCPV6_OPT_AFTR_NAME && olen > 3) {
896                         size_t cur_len;
897                         odhcp6c_get_state(STATE_AFTR_NAME, &cur_len);
898                         if (cur_len == 0)
899                                 odhcp6c_add_state(STATE_AFTR_NAME, odata, olen);
900                 } else if (otype == DHCPV6_OPT_SOL_MAX_RT && olen == 4) {
901                         uint32_t sol_max_rt = ntohl(*((uint32_t *)odata));
902                         if (sol_max_rt >= DHCPV6_SOL_MAX_RT_MIN && 
903                                         sol_max_rt <= DHCPV6_SOL_MAX_RT_MAX)
904                                 dhcpv6_retx[DHCPV6_MSG_SOLICIT].max_timeo = sol_max_rt;
905                 } else if (otype == DHCPV6_OPT_INF_MAX_RT && olen == 4) {
906                         uint32_t inf_max_rt = ntohl(*((uint32_t *)odata));
907                         if (inf_max_rt >= DHCPV6_INF_MAX_RT_MIN && 
908                                         inf_max_rt <= DHCPV6_INF_MAX_RT_MAX)
909                                 dhcpv6_retx[DHCPV6_MSG_INFO_REQ].max_timeo = inf_max_rt;
910                 }else if (otype != DHCPV6_OPT_CLIENTID &&
911                                 otype != DHCPV6_OPT_SERVERID) {
912                         odhcp6c_add_state(STATE_CUSTOM_OPTS,
913                                         &odata[-4], olen + 4);
914                 }
915         }
916
917         if (orig != DHCPV6_MSG_INFO_REQ) {
918                 // Update refresh timers if no fatal status code was received
919                 if ((ret > 0) && dhcpv6_calc_refresh_timers()) {
920                         switch (orig) {
921                         case DHCPV6_MSG_RENEW:
922                                 // Send further renews if T1 is not set
923                                 if (!t1)
924                                         ret = -1;
925                                 break;
926                         case DHCPV6_MSG_REBIND:
927                                 // Send further rebinds if T1 and T2 is not set
928                                 if (!t1 && !t2)
929                                         ret = -1;
930                                 break;
931
932                         case DHCPV6_MSG_REQUEST:
933                                 // All server candidates can be cleared if not yet bound
934                                 if (!odhcp6c_is_bound())
935                                         dhcpv6_clear_all_server_cand();
936
937                         default :
938                                 break;
939                         }
940                 }
941         }
942         else if (ret > 0) {
943                 // All server candidates can be cleared if not yet bound
944                 if (!odhcp6c_is_bound())
945                         dhcpv6_clear_all_server_cand();
946
947                 t1 = refresh;
948         }
949
950         return ret;
951 }
952
953
954 static int dhcpv6_parse_ia(void *opt, void *end)
955 {
956         struct dhcpv6_ia_hdr *ia_hdr = (struct dhcpv6_ia_hdr *)opt;
957         int parsed_ia = 0;
958         uint32_t t1, t2;
959         uint16_t otype, olen;
960         uint8_t *odata;
961
962         t1 = ntohl(ia_hdr->t1);
963         t2 = ntohl(ia_hdr->t2);
964
965         if (t1 > t2)
966                 return 0;
967
968         // Update address IA
969         dhcpv6_for_each_option(&ia_hdr[1], end, otype, olen, odata) {
970                 struct odhcp6c_entry entry = {IN6ADDR_ANY_INIT, 0, 0,
971                                 IN6ADDR_ANY_INIT, 0, 0, 0, 0, 0};
972
973                 if (otype == DHCPV6_OPT_IA_PREFIX) {
974                         struct dhcpv6_ia_prefix *prefix = (void*)&odata[-4];
975                         if (olen + 4U < sizeof(*prefix))
976                                 continue;
977
978                         entry.valid = ntohl(prefix->valid);
979                         entry.preferred = ntohl(prefix->preferred);
980
981                         if (entry.preferred > entry.valid)
982                                 continue;
983
984                         entry.t1 = (t1 ? t1 : (entry.preferred != UINT32_MAX ? 0.5 * entry.preferred : UINT32_MAX));
985                         entry.t2 = (t2 ? t2 : (entry.preferred != UINT32_MAX ? 0.8 * entry.preferred : UINT32_MAX));
986                         if (entry.t1 > entry.t2)
987                                 entry.t1 = entry.t2;
988
989                         entry.length = prefix->prefix;
990                         entry.target = prefix->addr;
991                         uint16_t stype, slen;
992                         uint8_t *sdata;
993
994 #ifdef EXT_PREFIX_CLASS
995                         // Find prefix class, if any
996                         dhcpv6_for_each_option(&prefix[1], odata + olen,
997                                         stype, slen, sdata)
998                                 if (stype == DHCPV6_OPT_PREFIX_CLASS && slen == 2)
999                                         entry.class = sdata[0] << 8 | sdata[1];
1000 #endif
1001
1002                         // Parse PD-exclude
1003                         bool ok = true;
1004                         dhcpv6_for_each_option(odata + sizeof(*prefix) - 4U,
1005                                         odata + olen, stype, slen, sdata) {
1006                                 if (stype != DHCPV6_OPT_PD_EXCLUDE || slen < 2)
1007                                         continue;
1008
1009                                 uint8_t elen = sdata[0];
1010                                 if (elen > 64)
1011                                         elen = 64;
1012
1013                                 if (elen <= 32 || elen <= entry.length) {
1014                                         ok = false;
1015                                         continue;
1016                                 }
1017
1018
1019                                 uint8_t bytes = ((elen - entry.length - 1) / 8) + 1;
1020                                 if (slen <= bytes) {
1021                                         ok = false;
1022                                         continue;
1023                                 }
1024
1025                                 uint32_t exclude = 0;
1026                                 do {
1027                                         exclude = exclude << 8 | sdata[bytes];
1028                                 } while (--bytes);
1029
1030                                 exclude >>= 8 - ((elen - entry.length) % 8);
1031                                 exclude <<= 64 - elen;
1032
1033                                 // Abusing router & priority fields for exclusion
1034                                 entry.router = entry.target;
1035                                 entry.router.s6_addr32[1] |= htonl(exclude);
1036                                 entry.priority = elen;
1037                         }
1038
1039                         if (ok) {
1040                                 odhcp6c_update_entry(STATE_IA_PD, &entry);
1041                                 parsed_ia++;
1042                         }
1043
1044                         entry.priority = 0;
1045                         memset(&entry.router, 0, sizeof(entry.router));
1046                 } else if (otype == DHCPV6_OPT_IA_ADDR) {
1047                         struct dhcpv6_ia_addr *addr = (void*)&odata[-4];
1048                         if (olen + 4U < sizeof(*addr))
1049                                 continue;
1050
1051                         entry.preferred = ntohl(addr->preferred);
1052                         entry.valid = ntohl(addr->valid);
1053
1054                         if (entry.preferred > entry.valid)
1055                                 continue;
1056
1057                         entry.t1 = (t1 ? t1 : (entry.preferred != UINT32_MAX ? 0.5 * entry.preferred : UINT32_MAX));
1058                         entry.t2 = (t2 ? t2 : (entry.preferred != UINT32_MAX ? 0.8 * entry.preferred : UINT32_MAX));
1059                         if (entry.t1 > entry.t2)
1060                                 entry.t1 = entry.t2;
1061
1062                         entry.length = 128;
1063                         entry.target = addr->addr;
1064
1065 #ifdef EXT_PREFIX_CLASS
1066                         uint16_t stype, slen;
1067                         uint8_t *sdata;
1068                         // Find prefix class, if any
1069                         dhcpv6_for_each_option(&addr[1], odata + olen,
1070                                         stype, slen, sdata)
1071                                 if (stype == DHCPV6_OPT_PREFIX_CLASS && slen == 2)
1072                                         entry.class = sdata[0] << 8 | sdata[1];
1073 #endif
1074
1075                         odhcp6c_update_entry(STATE_IA_NA, &entry);
1076                         parsed_ia++;
1077                 }
1078         }
1079         return parsed_ia;
1080 }
1081
1082
1083 static int dhcpv6_calc_refresh_timers(void)
1084 {
1085         struct odhcp6c_entry *e;
1086         size_t ia_na_entries, ia_pd_entries, i;
1087         int64_t l_t1 = UINT32_MAX, l_t2 = UINT32_MAX, l_t3 = 0;
1088
1089         e = odhcp6c_get_state(STATE_IA_NA, &ia_na_entries);
1090         ia_na_entries /= sizeof(*e);
1091         for (i = 0; i < ia_na_entries; i++) {
1092                 if (e[i].t1 < l_t1)
1093                         l_t1 = e[i].t1;
1094
1095                 if (e[i].t2 < l_t2)
1096                         l_t2 = e[i].t2;
1097
1098                 if (e[i].valid > l_t3)
1099                         l_t3 = e[i].valid;
1100         }
1101
1102         e = odhcp6c_get_state(STATE_IA_PD, &ia_pd_entries);
1103         ia_pd_entries /= sizeof(*e);
1104         for (i = 0; i < ia_pd_entries; i++) {
1105                 if (e[i].t1 < l_t1)
1106                         l_t1 = e[i].t1;
1107
1108                 if (e[i].t2 < l_t2)
1109                         l_t2 = e[i].t2;
1110
1111                 if (e[i].valid > l_t3)
1112                         l_t3 = e[i].valid;
1113         }
1114
1115         if (ia_pd_entries || ia_na_entries) {
1116                 t1 = l_t1;
1117                 t2 = l_t2;
1118                 t3 = l_t3;
1119         } else {
1120                 t1 = 600;
1121         }
1122
1123         return (int)(ia_pd_entries + ia_na_entries);
1124 }
1125
1126
1127 static void dhcpv6_log_status_code(const uint16_t code, const char *scope,
1128                 const void *status_msg, const int len)
1129 {
1130         uint8_t buf[len + 3];
1131
1132         memset(buf, 0, sizeof(buf));
1133         if (len) {
1134                 buf[0] = '(';
1135                 memcpy(&buf[1], status_msg, len);
1136                 buf[len + 1] = ')';
1137         }
1138
1139         syslog(LOG_WARNING, "Server returned %s status %i %s",
1140                 scope, code, buf);
1141 }
1142
1143
1144 static void dhcpv6_handle_status_code(const enum dhcpv6_msg orig,
1145                 const uint16_t code, const void *status_msg, const int len,
1146                 int *ret)
1147 {
1148         dhcpv6_log_status_code(code, "message", status_msg, len);
1149
1150         switch (code) {
1151         case DHCPV6_UnspecFail:
1152                 // Generic failure
1153                 *ret = 0;
1154                 break;
1155
1156         case DHCPV6_UseMulticast:
1157                 // TODO handle multicast status code
1158                 break;
1159
1160         case DHCPV6_NoAddrsAvail:
1161         case DHCPV6_NoPrefixAvail:
1162                 if (orig == DHCPV6_MSG_REQUEST)
1163                         *ret = 0; // Failure
1164                 break;
1165
1166         default:
1167                 break;
1168         }
1169 }
1170
1171
1172 static void dhcpv6_handle_ia_status_code(const enum dhcpv6_msg orig,
1173                 const struct dhcpv6_ia_hdr *ia_hdr, const uint16_t code,
1174                 const void *status_msg, const int len,
1175                 bool handled_status_codes[_DHCPV6_Status_Max], int *ret)
1176 {
1177         dhcpv6_log_status_code(code, ia_hdr->type == DHCPV6_OPT_IA_NA ?
1178                 "IA_NA" : "IA_PD", status_msg, len);
1179
1180         switch (code) {
1181         case DHCPV6_NoBinding:
1182                 switch (orig) {
1183                 case DHCPV6_MSG_RENEW:
1184                 case DHCPV6_MSG_REBIND:
1185                         if ((*ret > 0) && !handled_status_codes[code])
1186                                 *ret = dhcpv6_request(DHCPV6_MSG_REQUEST);
1187                         break;
1188
1189                 default:
1190                         break;
1191                 }
1192                 break;
1193
1194         case DHCPV6_NoAddrsAvail:
1195         case DHCPV6_NoPrefixAvail:
1196                 switch (orig) {
1197                 case DHCPV6_MSG_REQUEST:
1198                         if (*ret != 0)
1199                                 *ret = 0;
1200                         break;
1201                 default:
1202                         break;
1203                 }
1204                 break;
1205
1206         case DHCPV6_NotOnLink:
1207                 // TODO handle not onlink in case of confirm
1208                 break;
1209
1210         default:
1211                 break;
1212         }
1213 }
1214
1215 static void dhcpv6_add_server_cand(const struct dhcpv6_server_cand *cand)
1216 {
1217         size_t cand_len, i;
1218         struct dhcpv6_server_cand *c = odhcp6c_get_state(STATE_SERVER_CAND, &cand_len);
1219
1220         // Remove identical duid server candidate
1221         for (i = 0; i < cand_len / sizeof(*c); ++i) {
1222                 if (cand->duid_len == c[i].duid_len &&
1223                                 !memcmp(cand->duid, c[i].duid, cand->duid_len)) {
1224                         free(c[i].ia_na);
1225                         free(c[i].ia_pd);
1226                         odhcp6c_remove_state(STATE_SERVER_CAND, i * sizeof(*c), sizeof(*c));
1227                         break;
1228                 }
1229         }
1230
1231         for (i = 0, c = odhcp6c_get_state(STATE_SERVER_CAND, &cand_len);
1232                 i < cand_len / sizeof(*c); ++i) {
1233                 if (c[i].preference < cand->preference)
1234                         break;
1235         }
1236
1237         odhcp6c_insert_state(STATE_SERVER_CAND, i * sizeof(*c), cand, sizeof(*cand));
1238 }
1239
1240 static void dhcpv6_clear_all_server_cand(void)
1241 {
1242         size_t cand_len, i;
1243         struct dhcpv6_server_cand *c = odhcp6c_get_state(STATE_SERVER_CAND, &cand_len);
1244
1245         // Server candidates need deep delete for IA_NA/IA_PD
1246         for (i = 0; i < cand_len / sizeof(*c); ++i) {
1247                 free(c[i].ia_na);
1248                 free(c[i].ia_pd);
1249         }
1250         odhcp6c_clear_state(STATE_SERVER_CAND);
1251 }
1252
1253 int dhcpv6_promote_server_cand(void)
1254 {
1255         size_t cand_len;
1256         struct dhcpv6_server_cand *cand = odhcp6c_get_state(STATE_SERVER_CAND, &cand_len);
1257         uint16_t hdr[2];
1258         int ret = (na_mode == IA_MODE_NONE && pd_mode == IA_MODE_NONE) ?
1259                         DHCPV6_STATELESS : DHCPV6_STATEFUL;
1260
1261         // Clear lingering candidate state info
1262         odhcp6c_clear_state(STATE_SERVER_ID);
1263         odhcp6c_clear_state(STATE_IA_NA);
1264         odhcp6c_clear_state(STATE_IA_PD);
1265
1266         if (!cand_len)
1267                 return -1;
1268
1269         if (cand->has_noaddravail && na_mode == IA_MODE_TRY) {
1270                 na_mode = IA_MODE_NONE;
1271
1272                 dhcpv6_retx[DHCPV6_MSG_SOLICIT].max_timeo = cand->sol_max_rt;
1273                 dhcpv6_retx[DHCPV6_MSG_INFO_REQ].max_timeo = cand->inf_max_rt;
1274
1275                 return dhcpv6_request(DHCPV6_MSG_SOLICIT);
1276         }
1277
1278         hdr[0] = htons(DHCPV6_OPT_SERVERID);
1279         hdr[1] = htons(cand->duid_len);
1280         odhcp6c_add_state(STATE_SERVER_ID, hdr, sizeof(hdr));
1281         odhcp6c_add_state(STATE_SERVER_ID, cand->duid, cand->duid_len);
1282         accept_reconfig = cand->wants_reconfigure;
1283         if (cand->ia_na_len) {
1284                 odhcp6c_add_state(STATE_IA_NA, cand->ia_na, cand->ia_na_len);
1285                 free(cand->ia_na);
1286                 if (na_mode != IA_MODE_NONE)
1287                         ret = DHCPV6_STATEFUL;
1288         }
1289         if (cand->ia_pd_len) {
1290                 odhcp6c_add_state(STATE_IA_PD, cand->ia_pd, cand->ia_pd_len);
1291                 free(cand->ia_pd);
1292                 if (request_prefix)
1293                         ret = DHCPV6_STATEFUL;
1294         }
1295
1296         dhcpv6_retx[DHCPV6_MSG_SOLICIT].max_timeo = cand->sol_max_rt;
1297         dhcpv6_retx[DHCPV6_MSG_INFO_REQ].max_timeo = cand->inf_max_rt;
1298         
1299         odhcp6c_remove_state(STATE_SERVER_CAND, 0, sizeof(*cand));
1300
1301         return ret;
1302 }