]> git.decadent.org.uk Git - odhcp6c.git/blob - src/dhcpv6.c
e44be4831fcaca3cfd8635a9f7d3d01ce1d54640
[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 <arpa/inet.h>
30 #include <netinet/in.h>
31
32 #include <net/if.h>
33 #include <net/ethernet.h>
34
35 #include "odhcp6c.h"
36 #include "md5.h"
37
38
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
45
46
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);
50
51 static int dhcpv6_parse_ia(void *opt, void *end);
52
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,
56                 int *ret);
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],
61                 int *ret);
62 static void dhcpv6_add_server_cand(const struct dhcpv6_server_cand *cand);
63
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);
69
70
71
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},
88 };
89
90
91 // Sockets
92 static int sock = -1;
93 static int ifindex = -1;
94 static int64_t t1 = 0, t2 = 0, t3 = 0;
95
96 // IA states
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;
102
103 // Reconfigure key
104 static uint8_t reconf_key[16];
105
106
107 int init_dhcpv6(const char *ifname, int request_pd, int sol_timeout)
108 {
109         request_prefix = request_pd;
110         dhcpv6_retx[DHCPV6_MSG_SOLICIT].max_timeo = sol_timeout;
111
112         sock = socket(AF_INET6, SOCK_DGRAM | SOCK_CLOEXEC, IPPROTO_UDP);
113         if (sock < 0)
114                 return -1;
115
116         // Detect interface
117         struct ifreq ifr;
118         strncpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name));
119         if (ioctl(sock, SIOCGIFINDEX, &ifr) < 0)
120                 return -1;
121         ifindex = ifr.ifr_ifindex;
122
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};
129
130                 if (ioctl(sock, SIOCGIFHWADDR, &ifr) >= 0)
131                         memcpy(&duid[8], ifr.ifr_hwaddr.sa_data, ETHER_ADDR_LEN);
132
133                 uint8_t zero[ETHER_ADDR_LEN] = {0, 0, 0, 0, 0, 0};
134                 struct ifreq ifs[100], *ifp, *ifend;
135                 struct ifconf ifc;
136                 ifc.ifc_req = ifs;
137                 ifc.ifc_len = sizeof(ifs);
138
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)
148                                         continue;
149
150                                 memcpy(&duid[8], ifr.ifr_hwaddr.sa_data,
151                                                 ETHER_ADDR_LEN);
152                         }
153                 }
154
155                 odhcp6c_add_state(STATE_CLIENT_ID, duid, sizeof(duid));
156         }
157
158         // Create ORO
159         uint16_t oro[] = {
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),
170 #endif
171         };
172         odhcp6c_add_state(STATE_ORO, oro, sizeof(oro));
173
174         // Configure IPv6-options
175         int val = 1;
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));
179         val = 0;
180         setsockopt(sock, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, &val, sizeof(val));
181         setsockopt(sock, SOL_SOCKET, SO_BINDTODEVICE, ifname, strlen(ifname));
182
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)
186                 return -1;
187
188         return 0;
189 }
190
191
192 void dhcpv6_set_ia_mode(enum odhcp6c_ia_mode na, enum odhcp6c_ia_mode pd)
193 {
194         na_mode = na;
195         pd_mode = pd;
196 }
197
198
199 static void dhcpv6_send(enum dhcpv6_msg type, uint8_t trid[3], uint32_t ecs)
200 {
201         // Build FQDN
202         char fqdn_buf[256];
203         gethostname(fqdn_buf, sizeof(fqdn_buf));
204         struct {
205                 uint16_t type;
206                 uint16_t len;
207                 uint8_t flags;
208                 uint8_t data[256];
209         } fqdn;
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);
214         fqdn.flags = 0;
215
216
217         // Build Client ID
218         size_t cl_id_len;
219         void *cl_id = odhcp6c_get_state(STATE_CLIENT_ID, &cl_id_len);
220
221         // Get Server ID
222         size_t srv_id_len;
223         void *srv_id = odhcp6c_get_state(STATE_SERVER_ID, &srv_id_len);
224
225         // Build IA_PDs
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),
232                 1, 0, 0
233         };
234
235
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) {
238                 uint8_t ex_len = 0;
239                 if (e[i].priority > 0)
240                         ex_len = ((e[i].priority - e[i].length - 1) / 8) + 6;
241
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,
246                         .addr = e[i].target
247                 };
248
249                 memcpy(ia_pd + ia_pd_len, &p, sizeof(p));
250                 ia_pd_len += sizeof(p);
251
252                 if (ex_len) {
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;
258
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);
262
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;
266                 }
267         }
268
269         struct dhcpv6_ia_prefix pref = {
270                 .type = htons(DHCPV6_OPT_IA_PREFIX),
271                 .len = htons(25), .prefix = request_prefix
272         };
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);
276         }
277         hdr_ia_pd.len = htons(ntohs(hdr_ia_pd.len) + ia_pd_len);
278
279         // Build IA_NAs
280         size_t ia_na_entries, ia_na_len = 0;
281         void *ia_na = NULL;
282         e = odhcp6c_get_state(STATE_IA_NA, &ia_na_entries);
283         ia_na_entries /= sizeof(*e);
284
285         struct dhcpv6_ia_hdr hdr_ia_na = {
286                 htons(DHCPV6_OPT_IA_NA),
287                 htons(sizeof(hdr_ia_na) - 4),
288                 1, 0, 0
289         };
290
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;
296                 pa[i].preferred = 0;
297                 pa[i].valid = 0;
298         }
299
300         ia_na = pa;
301         ia_na_len = sizeof(pa);
302         hdr_ia_na.len = htons(ntohs(hdr_ia_na.len) + ia_na_len);
303
304         // Reconfigure Accept
305         struct {
306                 uint16_t type;
307                 uint16_t length;
308         } reconf_accept = {htons(DHCPV6_OPT_RECONF_ACCEPT), 0};
309
310         // Request Information Refresh
311         uint16_t oro_refresh = htons(DHCPV6_OPT_INFO_REFRESH);
312
313         // Prepare Header
314         size_t oro_len;
315         void *oro = odhcp6c_get_state(STATE_ORO, &oro_len);
316         struct {
317                 uint8_t type;
318                 uint8_t trid[3];
319                 uint16_t elapsed_type;
320                 uint16_t elapsed_len;
321                 uint16_t elapsed_value;
322                 uint16_t oro_type;
323                 uint16_t oro_len;
324         } hdr = {
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),
329         };
330
331         struct iovec iov[] = {
332                 {&hdr, sizeof(hdr)},
333                 {oro, oro_len},
334                 {&oro_refresh, 0},
335                 {cl_id, cl_id_len},
336                 {srv_id, srv_id_len},
337                 {&reconf_accept, sizeof(reconf_accept)},
338                 {&fqdn, fqdn_len},
339                 {&hdr_ia_na, sizeof(hdr_ia_na)},
340                 {ia_na, ia_na_len},
341                 {&hdr_ia_pd, sizeof(hdr_ia_pd)},
342                 {ia_pd, ia_pd_len},
343         };
344
345         size_t cnt = ARRAY_SIZE(iov);
346         if (type == DHCPV6_MSG_INFO_REQ) {
347                 cnt = 5;
348                 iov[2].iov_len = sizeof(oro_refresh);
349                 hdr.oro_len = htons(oro_len + sizeof(oro_refresh));
350         } else if (!request_prefix) {
351                 cnt = 9;
352         }
353
354         // Disable IAs if not used
355         if (type != DHCPV6_MSG_SOLICIT) {
356                 iov[5].iov_len = 0;
357                 if (ia_na_len == 0)
358                         iov[7].iov_len = 0;
359                 if (ia_pd_len == 0)
360                         iov[9].iov_len = 0;
361         }
362
363         if (na_mode == IA_MODE_NONE)
364                 iov[7].iov_len = 0;
365
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};
369
370         switch (type) {
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;
380                 }
381                 break;
382         default:
383                 break;
384         }
385
386         if (sendmsg(sock, &msg, 0) < 0) {
387                 char in6_str[INET6_ADDRSTRLEN];
388
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));
392         }
393 }
394
395
396 static int64_t dhcpv6_rand_delay(int64_t time)
397 {
398         int random;
399         odhcp6c_random(&random, sizeof(random));
400         return (time * ((int64_t)random % 1000LL)) / 10000LL;
401 }
402
403
404 int dhcpv6_request(enum dhcpv6_msg type)
405 {
406         uint8_t rc = 0;
407         uint64_t timeout = UINT32_MAX;
408         struct dhcpv6_retx *retx = &dhcpv6_retx[type];
409
410         if (retx->delay) {
411                 struct timespec ts = {0, 0};
412                 ts.tv_nsec = dhcpv6_rand_delay(10 * DHCPV6_REQ_DELAY);
413                 nanosleep(&ts, NULL);
414         }
415
416         if (type == DHCPV6_MSG_UNKNOWN)
417                 timeout = t1;
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;
422
423         if (timeout == 0)
424                 return -1;
425
426         syslog(LOG_NOTICE, "Starting %s transaction (timeout %llus, max rc %d)",
427                         retx->name, (unsigned long long)timeout, retx->max_rc);
428
429         uint64_t start = odhcp6c_get_milli_time(), round_start = start, elapsed;
430
431         // Generate transaction ID
432         uint8_t trid[3] = {0, 0, 0};
433         if (type != DHCPV6_MSG_UNKNOWN)
434                 odhcp6c_random(trid, sizeof(trid));
435         ssize_t len = -1;
436         int64_t rto = 0;
437
438         do {
439                 if (rto == 0) {
440                         int64_t delay = dhcpv6_rand_delay(retx->init_timeo * 1000);
441
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);
445
446                         rto = (retx->init_timeo * 1000 + delay);
447                 }
448                 else
449                         rto = (2 * rto + dhcpv6_rand_delay(rto));
450
451                 if (retx->max_timeo && (rto >= retx->max_timeo * 1000))
452                         rto = retx->max_timeo * 1000 +
453                                 dhcpv6_rand_delay(retx->max_timeo * 1000);
454
455                 // Calculate end for this round and elapsed time
456                 uint64_t round_end = round_start + rto;
457                 elapsed = round_start - start;
458
459                 // Don't wait too long
460                 if (round_end - start > timeout * 1000)
461                         round_end = timeout * 1000 + start;
462
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);
469                         rc++;
470                 }
471
472                 // Receive rounds
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;
480
481                         // Check for pending signal
482                         if (odhcp6c_signal_process())
483                                 return -1;
484
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));
490
491                         // Receive cycle
492                         len = recvmsg(sock, &msg, 0);
493                         if (len < 0)
494                                 continue;
495
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);
501                                         break;
502                                 }
503                         }
504
505                         if (pktinfo == NULL) {
506                                 len = -1;
507                                 continue;
508                         }
509
510                         if (!dhcpv6_response_is_valid(buf, len, trid,
511                                                         type, &pktinfo->ipi6_addr)) {
512                                 len = -1;
513                                 continue;
514                         }
515
516                         uint8_t *opt = &buf[4];
517                         uint8_t *opt_end = opt + len - 4;
518
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);
523
524                         if (retx->handler_reply)
525                                 len = retx->handler_reply(type, rc, opt, opt_end);
526
527                         if (len > 0 && round_end - round_start > 1000)
528                                 round_end = 1000 + round_start;
529                 }
530
531                 // Allow
532                 if (retx->handler_finish)
533                         len = retx->handler_finish();
534         } while (len < 0 && ((elapsed / 1000 < timeout) && (!retx->max_rc || rc < retx->max_rc)));
535
536         return len;
537 }
538
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)
543 {
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
548
549         if (type == DHCPV6_MSG_SOLICIT) {
550                 if (rep->msg_type != DHCPV6_MSG_ADVERT &&
551                                 rep->msg_type != DHCPV6_MSG_REPLY)
552                         return false;
553         } else if (type == DHCPV6_MSG_UNKNOWN) {
554                 if (!accept_reconfig || rep->msg_type != DHCPV6_MSG_RECONF)
555                         return false;
556         } else if (rep->msg_type != DHCPV6_MSG_REPLY) {
557                 return false;
558         }
559
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;
565
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);
569
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) {
575                         if (server_id_len)
576                                 serverid_ok = (olen + 4U == server_id_len) && !memcmp(
577                                                 &odata[-4], server_id, server_id_len);
578                         else
579                                 serverid_ok = true;
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)
584                                 continue;
585
586                         md5_state_t md5;
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));
591
592                         for (size_t i = 0; i < sizeof(secretbytes); ++i)
593                                 secretbytes[i] ^= 0x36;
594
595                         md5_init(&md5);
596                         md5_append(&md5, secretbytes, sizeof(secretbytes));
597                         md5_append(&md5, buf, len);
598                         md5_finish(&md5, hash);
599
600                         for (size_t i = 0; i < sizeof(secretbytes); ++i) {
601                                 secretbytes[i] ^= 0x36;
602                                 secretbytes[i] ^= 0x5c;
603                         }
604
605                         md5_init(&md5);
606                         md5_append(&md5, secretbytes, sizeof(secretbytes));
607                         md5_append(&md5, hash, 16);
608                         md5_finish(&md5, hash);
609
610                         rcauth_ok = !memcmp(hash, serverhash, sizeof(hash));
611                 } else if (otype == DHCPV6_OPT_RECONF_MESSAGE && olen == 1) {
612                         rcmsg = odata[0];
613                 } else if ((otype == DHCPV6_OPT_IA_PD || otype == DHCPV6_OPT_IA_NA)) {
614                         ia_present = true;
615                         if (olen < sizeof(struct dhcpv6_ia_hdr))
616                                 options_valid = false;
617                 }
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;
622                 }
623         }
624
625         if (!options_valid)
626                 return false;
627
628         if (type == DHCPV6_MSG_INFO_REQ && ia_present)
629                 return false;
630
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))
635                         return false;
636         }
637
638         return clientid_ok && serverid_ok;
639 }
640
641
642 int dhcpv6_poll_reconfigure(void)
643 {
644         int ret = dhcpv6_request(DHCPV6_MSG_UNKNOWN);
645         if (ret != -1)
646                 ret = dhcpv6_request(ret);
647
648         return ret;
649 }
650
651
652 static int dhcpv6_handle_reconfigure(_unused enum dhcpv6_msg orig, const int rc,
653                 const void *opt, const void *end)
654 {
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))
661                         msg = odata[0];
662
663         dhcpv6_handle_reply(DHCPV6_MSG_UNKNOWN, rc, NULL, NULL);
664         return msg;
665 }
666
667
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)
671 {
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;
677         int have_pd = 0;
678
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));
685                 }
686
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]);
692
693                         switch (error) {
694                         case DHCPV6_NoPrefixAvail:
695                                 // Status code on global level
696                                 if (pd_mode == IA_MODE_FORCE)
697                                         return -1;
698                                 cand.preference -= 2000;
699                                 break;
700
701                         case DHCPV6_NoAddrsAvail:
702                                 // Status code on global level
703                                 if (na_mode == IA_MODE_FORCE)
704                                         return -1;
705                                 break;
706
707                         default :
708                                 break;
709                         }
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];
724                                         have_pd = p->prefix;
725                                 }
726                         }
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)
732                                         have_na = true;
733                 }
734         }
735
736         if ((!have_na && na_mode == IA_MODE_FORCE) ||
737                         (!have_pd && pd_mode == IA_MODE_FORCE))
738                 return -1;
739
740         if (na_mode != IA_MODE_NONE && !have_na) {
741                 cand.has_noaddravail = true;
742                 cand.preference -= 1000;
743         }
744
745         if (pd_mode != IA_MODE_NONE) {
746                 if (have_pd)
747                         cand.preference += 2000 + (128 - have_pd);
748                 else
749                         cand.preference -= 2000;
750         }
751
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);
756         }
757
758         return (rc > 1 || (pref == 255 && cand.preference > 0)) ? 1 : -1;
759 }
760
761
762 static int dhcpv6_commit_advert(void)
763 {
764         return dhcpv6_promote_server_cand();
765 }
766
767
768 static int dhcpv6_handle_rebind_reply(enum dhcpv6_msg orig, const int rc,
769                 const void *opt, const void *end)
770 {
771         dhcpv6_handle_advert(orig, rc, opt, end);
772         if (dhcpv6_commit_advert() < 0)
773                 return -1;
774
775         return dhcpv6_handle_reply(orig, rc, opt, end);
776 }
777
778
779 static int dhcpv6_handle_reply(enum dhcpv6_msg orig, _unused const int rc,
780                 const void *opt, const void *end)
781 {
782         uint8_t *odata;
783         uint16_t otype, olen;
784         uint32_t refresh = UINT32_MAX;
785         int ret = 1;
786         bool handled_status_codes[_DHCPV6_Status_Max] = { false, };
787
788         odhcp6c_expire();
789
790         if (orig == DHCPV6_MSG_UNKNOWN) {
791                 static time_t last_update = 0;
792                 time_t now = odhcp6c_get_milli_time() / 1000;
793
794                 uint32_t elapsed = (last_update > 0) ? now - last_update : 0;
795                 last_update = now;
796
797                 t1 -= elapsed;
798                 t2 -= elapsed;
799                 t3 -= elapsed;
800
801                 if (t1 < 0)
802                         t1 = 0;
803
804                 if (t2 < 0)
805                         t2 = 0;
806
807                 if (t3 < 0)
808                         t3 = 0;
809         }
810
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);
815         }
816
817         if (opt) {
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);
825         }
826
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]);
832
833                         // Test ID
834                         if (ia_hdr->iaid != 1)
835                                 continue;
836
837                         uint16_t code = DHCPV6_Success;
838                         uint16_t stype, slen;
839                         uint8_t *sdata;
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;
846
847                                         code = ((int)sdata[0]) << 8 | ((int)sdata[1]);
848
849                                         if (code == DHCPV6_Success)
850                                                 continue;
851
852                                         dhcpv6_handle_ia_status_code(orig, ia_hdr,
853                                                 code, mdata, mlen, handled_status_codes, &ret);
854
855
856                                         if (ret > 0)
857                                                 return ret;
858                                         break;
859                                 }
860                         }
861
862                         if (code != DHCPV6_Success)
863                                 continue;
864
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]);
872
873                         dhcpv6_handle_status_code(orig, code, mdata, mlen, &ret);
874                 }
875                 else if (otype == DHCPV6_OPT_DNS_SERVERS) {
876                         if (olen % 16 == 0)
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;
882                         uint8_t *sdata;
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,
889                                                         sdata, slen);
890                                 else if (slen > 0 && stype == NTP_SRV_FQDN)
891                                         odhcp6c_add_state(STATE_SNTP_FQDN,
892                                                         sdata, slen);
893                         }
894                 } else if (otype == DHCPV6_OPT_SIP_SERVER_A) {
895                         if (olen == 16)
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 &&
905                                         r->reconf_type == 1)
906                                 memcpy(reconf_key, r->key, sizeof(r->key));
907                 } else if (otype == DHCPV6_OPT_AFTR_NAME && olen > 3) {
908                         size_t cur_len;
909                         odhcp6c_get_state(STATE_AFTR_NAME, &cur_len);
910                         if (cur_len == 0)
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);
916                 }
917         }
918
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()) {
922                         switch (orig) {
923                         case DHCPV6_MSG_RENEW:
924                                 // Send further renews if T1 is not set
925                                 if (!t1)
926                                         ret = -1;
927                                 break;
928                         case DHCPV6_MSG_REBIND:
929                                 // Send further rebinds if T1 and T2 is not set
930                                 if (!t1 && !t2)
931                                         ret = -1;
932                                 break;
933
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();
938
939                         default :
940                                 break;
941                         }
942                 }
943         }
944         else if (ret > 0)
945                 t1 = refresh;
946
947         return ret;
948 }
949
950
951 static int dhcpv6_parse_ia(void *opt, void *end)
952 {
953         struct dhcpv6_ia_hdr *ia_hdr = (struct dhcpv6_ia_hdr *)opt;
954         int parsed_ia = 0;
955         uint32_t t1, t2;
956         uint16_t otype, olen;
957         uint8_t *odata;
958
959         t1 = ntohl(ia_hdr->t1);
960         t2 = ntohl(ia_hdr->t2);
961
962         if (t1 > t2)
963                 return 0;
964
965         // Update address IA
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};
969
970                 if (otype == DHCPV6_OPT_IA_PREFIX) {
971                         struct dhcpv6_ia_prefix *prefix = (void*)&odata[-4];
972                         if (olen + 4U < sizeof(*prefix))
973                                 continue;
974
975                         entry.valid = ntohl(prefix->valid);
976                         entry.preferred = ntohl(prefix->preferred);
977
978                         if (entry.preferred > entry.valid)
979                                 continue;
980
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)
984                                 entry.t1 = entry.t2;
985
986                         entry.length = prefix->prefix;
987                         entry.target = prefix->addr;
988                         uint16_t stype, slen;
989                         uint8_t *sdata;
990
991 #ifdef EXT_PREFIX_CLASS
992                         // Find prefix class, if any
993                         dhcpv6_for_each_option(&prefix[1], odata + olen,
994                                         stype, slen, sdata)
995                                 if (stype == DHCPV6_OPT_PREFIX_CLASS && slen == 2)
996                                         entry.class = sdata[0] << 8 | sdata[1];
997 #endif
998
999                         // Parse PD-exclude
1000                         bool ok = true;
1001                         dhcpv6_for_each_option(odata + sizeof(*prefix) - 4U,
1002                                         odata + olen, stype, slen, sdata) {
1003                                 if (stype != DHCPV6_OPT_PD_EXCLUDE || slen < 2)
1004                                         continue;
1005
1006                                 uint8_t elen = sdata[0];
1007                                 if (elen > 64)
1008                                         elen = 64;
1009
1010                                 if (elen <= 32 || elen <= entry.length) {
1011                                         ok = false;
1012                                         continue;
1013                                 }
1014
1015
1016                                 uint8_t bytes = ((elen - entry.length - 1) / 8) + 1;
1017                                 if (slen <= bytes) {
1018                                         ok = false;
1019                                         continue;
1020                                 }
1021
1022                                 uint32_t exclude = 0;
1023                                 do {
1024                                         exclude = exclude << 8 | sdata[bytes];
1025                                 } while (--bytes);
1026
1027                                 exclude >>= 8 - ((elen - entry.length) % 8);
1028                                 exclude <<= 64 - elen;
1029
1030                                 // Abusing router & priority fields for exclusion
1031                                 entry.router = entry.target;
1032                                 entry.router.s6_addr32[1] |= htonl(exclude);
1033                                 entry.priority = elen;
1034                         }
1035
1036                         if (ok) {
1037                                 odhcp6c_update_entry(STATE_IA_PD, &entry);
1038                                 parsed_ia++;
1039                         }
1040
1041                         entry.priority = 0;
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))
1046                                 continue;
1047
1048                         entry.preferred = ntohl(addr->preferred);
1049                         entry.valid = ntohl(addr->valid);
1050
1051                         if (entry.preferred > entry.valid)
1052                                 continue;
1053
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;
1058
1059                         entry.length = 128;
1060                         entry.target = addr->addr;
1061
1062 #ifdef EXT_PREFIX_CLASS
1063                         uint16_t stype, slen;
1064                         uint8_t *sdata;
1065                         // Find prefix class, if any
1066                         dhcpv6_for_each_option(&addr[1], odata + olen,
1067                                         stype, slen, sdata)
1068                                 if (stype == DHCPV6_OPT_PREFIX_CLASS && slen == 2)
1069                                         entry.class = sdata[0] << 8 | sdata[1];
1070 #endif
1071
1072                         odhcp6c_update_entry(STATE_IA_NA, &entry);
1073                         parsed_ia++;
1074                 }
1075         }
1076         return parsed_ia;
1077 }
1078
1079
1080 static int dhcpv6_calc_refresh_timers(void)
1081 {
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;
1085
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++) {
1089                 if (e[i].t1 < l_t1)
1090                         l_t1 = e[i].t1;
1091
1092                 if (e[i].t2 < l_t2)
1093                         l_t2 = e[i].t2;
1094
1095                 if (e[i].valid > l_t3)
1096                         l_t3 = e[i].valid;
1097         }
1098
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++) {
1102                 if (e[i].t1 < l_t1)
1103                         l_t1 = e[i].t1;
1104
1105                 if (e[i].t2 < l_t2)
1106                         l_t2 = e[i].t2;
1107
1108                 if (e[i].valid > l_t3)
1109                         l_t3 = e[i].valid;
1110         }
1111
1112         if (ia_pd_entries || ia_na_entries) {
1113                 t1 = l_t1;
1114                 t2 = l_t2;
1115                 t3 = l_t3;
1116         }
1117
1118         return (int)(ia_pd_entries + ia_na_entries);
1119 }
1120
1121
1122 static void dhcpv6_log_status_code(const uint16_t code, const char *scope,
1123                 const void *status_msg, const int len)
1124 {
1125         uint8_t buf[len + 3];
1126
1127         memset(buf, 0, sizeof(buf));
1128         if (len) {
1129                 buf[0] = '(';
1130                 memcpy(&buf[1], status_msg, len);
1131                 buf[len + 1] = ')';
1132         }
1133
1134         syslog(LOG_WARNING, "Server returned %s status %i %s",
1135                 scope, code, buf);
1136 }
1137
1138
1139 static void dhcpv6_handle_status_code(const enum dhcpv6_msg orig,
1140                 const uint16_t code, const void *status_msg, const int len,
1141                 int *ret)
1142 {
1143         dhcpv6_log_status_code(code, "message", status_msg, len);
1144
1145         switch (code) {
1146         case DHCPV6_UnspecFail:
1147                 // Generic failure
1148                 *ret = 0;
1149                 break;
1150
1151         case DHCPV6_UseMulticast:
1152                 switch(orig) {
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;
1159                         *ret = 0;
1160                         break;
1161                 default:
1162                         break;
1163                 }
1164                 break;
1165
1166         case DHCPV6_NoAddrsAvail:
1167         case DHCPV6_NoPrefixAvail:
1168                 if (orig == DHCPV6_MSG_REQUEST)
1169                         *ret = 0; // Failure
1170                 break;
1171
1172         default:
1173                 break;
1174         }
1175 }
1176
1177
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)
1182 {
1183         dhcpv6_log_status_code(code, ia_hdr->type == DHCPV6_OPT_IA_NA ?
1184                 "IA_NA" : "IA_PD", status_msg, len);
1185
1186         switch (code) {
1187         case DHCPV6_NoBinding:
1188                 switch (orig) {
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);
1193                         break;
1194
1195                 default:
1196                         break;
1197                 }
1198                 break;
1199
1200         case DHCPV6_NoAddrsAvail:
1201         case DHCPV6_NoPrefixAvail:
1202                 switch (orig) {
1203                 case DHCPV6_MSG_REQUEST:
1204                         if (*ret != 0)
1205                                 *ret = 0;
1206                         break;
1207                 default:
1208                         break;
1209                 }
1210                 break;
1211
1212         case DHCPV6_NotOnLink:
1213                 // TODO handle not onlink in case of confirm
1214                 break;
1215
1216         default:
1217                 break;
1218         }
1219 }
1220
1221 static void dhcpv6_add_server_cand(const struct dhcpv6_server_cand *cand)
1222 {
1223         size_t cand_len, i;
1224         struct dhcpv6_server_cand *c = odhcp6c_get_state(STATE_SERVER_CAND, &cand_len);
1225
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)) {
1230                         free(c[i].ia_na);
1231                         free(c[i].ia_pd);
1232                         odhcp6c_remove_state(STATE_SERVER_CAND, i * sizeof(*c), sizeof(*c));
1233                         break;
1234                 }
1235         }
1236
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)
1240                         break;
1241         }
1242
1243         odhcp6c_insert_state(STATE_SERVER_CAND, i * sizeof(*c), cand, sizeof(*cand));
1244 }
1245
1246 int dhcpv6_promote_server_cand(void)
1247 {
1248         size_t cand_len;
1249         struct dhcpv6_server_cand *cand = odhcp6c_get_state(STATE_SERVER_CAND, &cand_len);
1250         uint16_t hdr[2];
1251         int ret = DHCPV6_STATELESS;
1252
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);
1257
1258         if (!cand)
1259                 return -1;
1260
1261         if (cand->has_noaddravail && na_mode == IA_MODE_TRY) {
1262                 na_mode = IA_MODE_NONE;
1263                 return dhcpv6_request(DHCPV6_MSG_SOLICIT);
1264         }
1265
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);
1273                 free(cand->ia_na);
1274                 if (na_mode != IA_MODE_NONE)
1275                         ret = DHCPV6_STATEFUL;
1276         }
1277         if (cand->ia_pd_len) {
1278                 odhcp6c_add_state(STATE_IA_PD, cand->ia_pd, cand->ia_pd_len);
1279                 free(cand->ia_pd);
1280                 if (request_prefix)
1281                         ret = DHCPV6_STATEFUL;
1282         }
1283
1284         odhcp6c_remove_state(STATE_SERVER_CAND, 0, sizeof(*cand));
1285
1286         return ret;
1287 }
1288
1289 void dhcpv6_clear_all_server_cand(void)
1290 {
1291         size_t cand_len, i;
1292         struct dhcpv6_server_cand *c = odhcp6c_get_state(STATE_SERVER_CAND, &cand_len);
1293
1294         // Server candidates need deep delete for IA_NA/IA_PD
1295         for (i = 0; i < cand_len / sizeof(*c); ++i) {
1296                 if (c[i].ia_na)
1297                         free(c[i].ia_na);
1298                 if (c[i].ia_pd)
1299                         free(c[i].ia_pd);
1300         }
1301         odhcp6c_clear_state(STATE_SERVER_CAND);
1302 }