]> git.decadent.org.uk Git - odhcp6c.git/blob - src/dhcpv6.c
Merge remote-tracking branch 'up/master' into hnet
[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
46 static bool dhcpv6_response_is_valid(const void *buf, ssize_t len,
47                 const uint8_t transaction[3], enum dhcpv6_msg type);
48
49 static uint32_t dhcpv6_parse_ia(void *opt, void *end);
50
51 static reply_handler dhcpv6_handle_reply;
52 static reply_handler dhcpv6_handle_advert;
53 static reply_handler dhcpv6_handle_rebind_reply;
54 static reply_handler dhcpv6_handle_reconfigure;
55 static int dhcpv6_commit_advert(void);
56
57
58
59 // RFC 3315 - 5.5 Timeout and Delay values
60 static struct dhcpv6_retx dhcpv6_retx[_DHCPV6_MSG_MAX] = {
61         [DHCPV6_MSG_UNKNOWN] = {false, 1, 120, "<POLL>",
62                         dhcpv6_handle_reconfigure, NULL},
63         [DHCPV6_MSG_SOLICIT] = {true, 1, 3600, "SOLICIT",
64                         dhcpv6_handle_advert, dhcpv6_commit_advert},
65         [DHCPV6_MSG_REQUEST] = {true, 30, 10, "REQUEST",
66                         dhcpv6_handle_reply, NULL},
67         [DHCPV6_MSG_RENEW] = {false, 10, 600, "RENEW",
68                         dhcpv6_handle_reply, NULL},
69         [DHCPV6_MSG_REBIND] = {false, 10, 600, "REBIND",
70                         dhcpv6_handle_rebind_reply, NULL},
71         [DHCPV6_MSG_RELEASE] = {false, 1, 600, "RELEASE", NULL, NULL},
72         [DHCPV6_MSG_DECLINE] = {false, 1, 3, "DECLINE", NULL, NULL},
73         [DHCPV6_MSG_INFO_REQ] = {true, 1, 120, "INFOREQ",
74                         dhcpv6_handle_reply, NULL},
75 };
76
77
78 // Sockets
79 static int sock = -1;
80 static int ifindex = -1;
81 static int64_t t1 = 0, t2 = 0, t3 = 0;
82
83 // IA states
84 static int request_prefix = -1;
85 static enum odhcp6c_ia_mode na_mode = IA_MODE_NONE;
86 static bool accept_reconfig = false;
87
88 // Reconfigure key
89 static uint8_t reconf_key[16];
90
91
92
93 int init_dhcpv6(const char *ifname, int request_pd)
94 {
95         request_prefix = request_pd;
96
97         sock = socket(AF_INET6, SOCK_DGRAM | SOCK_CLOEXEC, IPPROTO_UDP);
98
99         // Detect interface
100         struct ifreq ifr;
101         strncpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name));
102         if (ioctl(sock, SIOCGIFINDEX, &ifr))
103                 return -1;
104         ifindex = ifr.ifr_ifindex;
105
106         // Create client DUID
107         size_t client_id_len;
108         odhcp6c_get_state(STATE_CLIENT_ID, &client_id_len);
109         if (client_id_len == 0) {
110                 ioctl(sock, SIOCGIFHWADDR, &ifr);
111                 uint8_t duid[14] = {0, DHCPV6_OPT_CLIENTID, 0, 10, 0,
112                                 DHCPV6_DUID_LLADDR, 0, 1};
113                 memcpy(&duid[8], ifr.ifr_hwaddr.sa_data, ETHER_ADDR_LEN);
114
115                 uint8_t zero[ETHER_ADDR_LEN] = {0, 0, 0, 0, 0, 0};
116                 struct ifreq ifs[100], *ifp, *ifend;
117                 struct ifconf ifc;
118                 ifc.ifc_req = ifs;
119                 ifc.ifc_len = sizeof(ifs);
120
121                 if (!memcmp(&duid[8], zero, ETHER_ADDR_LEN) &&
122                                 ioctl(sock, SIOCGIFCONF, &ifc) >= 0) {
123                         // If our interface doesn't have an address...
124                         ifend = ifs + (ifc.ifc_len / sizeof(struct ifreq));
125                         for (ifp = ifc.ifc_req; ifp < ifend &&
126                                         !memcmp(&duid[8], zero, 6); ifp++) {
127                                 memcpy(ifr.ifr_name, ifp->ifr_name,
128                                                 sizeof(ifr.ifr_name));
129                                 ioctl(sock, SIOCGIFHWADDR, &ifr);
130                                 memcpy(&duid[8], ifr.ifr_hwaddr.sa_data,
131                                                 ETHER_ADDR_LEN);
132                         }
133                 }
134
135                 odhcp6c_add_state(STATE_CLIENT_ID, duid, sizeof(duid));
136         }
137
138         // Create ORO
139         uint16_t oro[] = {
140                         htons(DHCPV6_OPT_SIP_SERVER_D),
141                         htons(DHCPV6_OPT_SIP_SERVER_A),
142                         htons(DHCPV6_OPT_DNS_SERVERS),
143                         htons(DHCPV6_OPT_DNS_DOMAIN),
144                         htons(DHCPV6_OPT_NTP_SERVER),
145                         htons(DHCPV6_OPT_SIP_SERVER_A),
146                         htons(DHCPV6_OPT_AFTR_NAME),
147                         htons(DHCPV6_OPT_PD_EXCLUDE),
148                         htons(DHCPV6_OPT_PREFIX_CLASS),
149         };
150         odhcp6c_add_state(STATE_ORO, oro, sizeof(oro));
151
152
153         // Configure IPv6-options
154         int val = 1;
155         setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &val, sizeof(val));
156         setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val));
157         setsockopt(sock, SOL_SOCKET, SO_BINDTODEVICE, ifname, strlen(ifname));
158
159         struct sockaddr_in6 client_addr = { .sin6_family = AF_INET6,
160                 .sin6_port = htons(DHCPV6_CLIENT_PORT), .sin6_flowinfo = 0 };
161         if (bind(sock, (struct sockaddr*)&client_addr, sizeof(client_addr)))
162                 return -1;
163
164         return 0;
165 }
166
167
168 void dhcpv6_set_ia_na_mode(enum odhcp6c_ia_mode mode)
169 {
170         na_mode = mode;
171 }
172
173
174 static void dhcpv6_send(enum dhcpv6_msg type, uint8_t trid[3], uint32_t ecs)
175 {
176         // Build FQDN
177         char fqdn_buf[256];
178         gethostname(fqdn_buf, sizeof(fqdn_buf));
179         struct {
180                 uint16_t type;
181                 uint16_t len;
182                 uint8_t flags;
183                 uint8_t data[256];
184         } fqdn;
185         size_t fqdn_len = 5 + dn_comp(fqdn_buf, fqdn.data,
186                         sizeof(fqdn.data), NULL, NULL);
187         fqdn.type = htons(DHCPV6_OPT_FQDN);
188         fqdn.len = htons(fqdn_len - 4);
189         fqdn.flags = 0;
190
191
192         // Build Client ID
193         size_t cl_id_len;
194         void *cl_id = odhcp6c_get_state(STATE_CLIENT_ID, &cl_id_len);
195
196         // Get Server ID
197         size_t srv_id_len;
198         void *srv_id = odhcp6c_get_state(STATE_SERVER_ID, &srv_id_len);
199
200         // Build IA_PDs
201         size_t ia_pd_entries, ia_pd_len = 0;
202         struct odhcp6c_entry *e = odhcp6c_get_state(STATE_IA_PD, &ia_pd_entries);
203         ia_pd_entries /= sizeof(*e);
204         struct dhcpv6_ia_hdr hdr_ia_pd = {
205                 htons(DHCPV6_OPT_IA_PD),
206                 htons(sizeof(hdr_ia_pd) - 4),
207                 1, 0, 0
208         };
209
210
211         uint8_t *ia_pd = alloca(ia_pd_entries * (sizeof(struct dhcpv6_ia_prefix) + 10));
212         for (size_t i = 0; i < ia_pd_entries; ++i) {
213                 uint8_t ex_len = 0;
214                 if (e[i].priority > 0)
215                         ex_len = ((e[i].priority - e[i].length - 1) / 8) + 6;
216
217                 struct dhcpv6_ia_prefix p = {
218                         .type = htons(DHCPV6_OPT_IA_PREFIX),
219                         .len = htons(sizeof(p) - 4U + ex_len),
220                         .prefix = e[i].length,
221                         .addr = e[i].target
222                 };
223
224                 memcpy(ia_pd + ia_pd_len, &p, sizeof(p));
225                 ia_pd_len += sizeof(p);
226
227                 if (ex_len) {
228                         ia_pd[ia_pd_len++] = 0;
229                         ia_pd[ia_pd_len++] = DHCPV6_OPT_PD_EXCLUDE;
230                         ia_pd[ia_pd_len++] = 0;
231                         ia_pd[ia_pd_len++] = ex_len - 4;
232                         ia_pd[ia_pd_len++] = e[i].priority;
233
234                         uint32_t excl = ntohl(e[i].router.s6_addr32[1]);
235                         excl >>= (64 - e[i].priority);
236                         excl <<= 8 - ((e[i].priority - e[i].length) % 8);
237
238                         for (size_t i = ex_len - 5; i > 0; --i, excl >>= 8)
239                                 ia_pd[ia_pd_len + i] = excl & 0xff;
240                         ia_pd_len += ex_len - 5;
241                 }
242         }
243
244         struct dhcpv6_ia_prefix pref = {
245                 .type = htons(DHCPV6_OPT_IA_PREFIX),
246                 .len = htons(25), .prefix = request_prefix
247         };
248         if (request_prefix > 0 && ia_pd_len == 0 &&
249                         (type == DHCPV6_MSG_SOLICIT ||
250                         type == DHCPV6_MSG_REQUEST)) {
251                 ia_pd = (uint8_t*)&pref;
252                 ia_pd_len = sizeof(pref);
253         }
254         hdr_ia_pd.len = htons(ntohs(hdr_ia_pd.len) + ia_pd_len);
255
256         // Build IA_NAs
257         size_t ia_na_entries, ia_na_len = 0;
258         void *ia_na = NULL;
259         e = odhcp6c_get_state(STATE_IA_NA, &ia_na_entries);
260         ia_na_entries /= sizeof(*e);
261
262         struct dhcpv6_ia_hdr hdr_ia_na = {
263                 htons(DHCPV6_OPT_IA_NA),
264                 htons(sizeof(hdr_ia_na) - 4),
265                 1, 0, 0
266         };
267
268         struct dhcpv6_ia_addr pa[ia_na_entries];
269         for (size_t i = 0; i < ia_na_entries; ++i) {
270                 pa[i].type = htons(DHCPV6_OPT_IA_ADDR);
271                 pa[i].len = htons(sizeof(pa[i]) - 4U);
272                 pa[i].addr = e[i].target;
273                 pa[i].preferred = 0;
274                 pa[i].valid = 0;
275         }
276
277         ia_na = pa;
278         ia_na_len = sizeof(pa);
279         hdr_ia_na.len = htons(ntohs(hdr_ia_na.len) + ia_na_len);
280
281         // Reconfigure Accept
282         struct {
283                 uint16_t type;
284                 uint16_t length;
285         } reconf_accept = {htons(DHCPV6_OPT_RECONF_ACCEPT), 0};
286
287         // Request Information Refresh
288         uint16_t oro_refresh = htons(DHCPV6_OPT_INFO_REFRESH);
289
290         // Prepare Header
291         size_t oro_len;
292         void *oro = odhcp6c_get_state(STATE_ORO, &oro_len);
293         struct {
294                 uint8_t type;
295                 uint8_t trid[3];
296                 uint16_t elapsed_type;
297                 uint16_t elapsed_len;
298                 uint16_t elapsed_value;
299                 uint16_t oro_type;
300                 uint16_t oro_len;
301         } hdr = {
302                 type, {trid[0], trid[1], trid[2]},
303                 htons(DHCPV6_OPT_ELAPSED), htons(2),
304                         htons((ecs > 0xffff) ? 0xffff : ecs),
305                 htons(DHCPV6_OPT_ORO), htons(oro_len),
306         };
307
308         struct iovec iov[] = {
309                 {&hdr, sizeof(hdr)},
310                 {oro, oro_len},
311                 {&oro_refresh, 0},
312                 {cl_id, cl_id_len},
313                 {srv_id, srv_id_len},
314                 {&reconf_accept, sizeof(reconf_accept)},
315                 {&fqdn, fqdn_len},
316                 {&hdr_ia_na, sizeof(hdr_ia_na)},
317                 {ia_na, ia_na_len},
318                 {&hdr_ia_pd, sizeof(hdr_ia_pd)},
319                 {ia_pd, ia_pd_len},
320         };
321
322         size_t cnt = ARRAY_SIZE(iov);
323         if (type == DHCPV6_MSG_INFO_REQ) {
324                 cnt = 5;
325                 iov[2].iov_len = sizeof(oro_refresh);
326                 hdr.oro_len = htons(oro_len + sizeof(oro_refresh));
327         } else if (!request_prefix) {
328                 cnt = 9;
329         }
330
331         // Disable IAs if not used
332         if (type != DHCPV6_MSG_REQUEST && type != DHCPV6_MSG_SOLICIT) {
333                 iov[5].iov_len = 0;
334                 if (ia_na_len == 0)
335                         iov[7].iov_len = 0;
336                 if (ia_pd_len == 0)
337                         iov[9].iov_len = 0;
338         }
339
340         if (na_mode == IA_MODE_NONE)
341                 iov[7].iov_len = 0;
342
343         struct sockaddr_in6 srv = {AF_INET6, htons(DHCPV6_SERVER_PORT),
344                 0, ALL_DHCPV6_RELAYS, ifindex};
345         struct msghdr msg = {&srv, sizeof(srv), iov, cnt, NULL, 0, 0};
346
347         sendmsg(sock, &msg, 0);
348 }
349
350
351 static int64_t dhcpv6_rand_delay(int64_t time)
352 {
353         int random;
354         odhcp6c_random(&random, sizeof(random));
355         return (time * ((int64_t)random % 1000LL)) / 10000LL;
356 }
357
358
359 int dhcpv6_request(enum dhcpv6_msg type)
360 {
361         uint8_t buf[1536];
362         uint64_t timeout = UINT32_MAX;
363         struct dhcpv6_retx *retx = &dhcpv6_retx[type];
364
365         if (retx->delay) {
366                 struct timespec ts = {0, 0};
367                 ts.tv_nsec = dhcpv6_rand_delay(10 * DHCPV6_REQ_DELAY);
368                 nanosleep(&ts, NULL);
369         }
370
371         if (type == DHCPV6_MSG_RELEASE || type == DHCPV6_MSG_DECLINE)
372                 timeout = 3;
373         else if (type == DHCPV6_MSG_UNKNOWN)
374                 timeout = t1;
375         else if (type == DHCPV6_MSG_RENEW)
376                 timeout = (t2 > t1) ? t2 - t1 : 0;
377         else if (type == DHCPV6_MSG_REBIND)
378                 timeout = (t3 > t2) ? t3 - t2 : 0;
379
380         if (timeout == 0)
381                 return -1;
382
383         syslog(LOG_NOTICE, "Sending %s (timeout %us)", retx->name, (unsigned)timeout);
384
385         uint64_t start = odhcp6c_get_milli_time(), round_start = start, elapsed;
386
387         // Generate transaction ID
388         uint8_t trid[3] = {0, 0, 0};
389         if (type != DHCPV6_MSG_UNKNOWN)
390                 odhcp6c_random(trid, sizeof(trid));
391         ssize_t len = -1;
392         int64_t rto = 0;
393
394         do {
395                 rto = (rto == 0) ? (retx->init_timeo * 1000 +
396                                 dhcpv6_rand_delay(retx->init_timeo * 1000)) :
397                                 (2 * rto + dhcpv6_rand_delay(rto));
398
399                 if (rto >= retx->max_timeo * 1000)
400                         rto = retx->max_timeo * 1000 +
401                                 dhcpv6_rand_delay(retx->max_timeo * 1000);
402
403                 // Calculate end for this round and elapsed time
404                 uint64_t round_end = round_start + rto;
405                 elapsed = round_start - start;
406
407                 // Don't wait too long
408                 if (round_end - start > timeout * 1000)
409                         round_end = timeout * 1000 + start;
410
411                 // Built and send package
412                 if (type != DHCPV6_MSG_UNKNOWN)
413                         dhcpv6_send(type, trid, elapsed / 10);
414
415                 // Receive rounds
416                 for (; len < 0 && round_start < round_end;
417                                 round_start = odhcp6c_get_milli_time()) {
418                         // Check for pending signal
419                         if (odhcp6c_signal_process())
420                                 return -1;
421
422                         // Set timeout for receiving
423                         uint64_t t = round_end - round_start;
424                         struct timeval timeout = {t / 1000, (t % 1000) * 1000};
425                         setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO,
426                                         &timeout, sizeof(timeout));
427
428                         // Receive cycle
429                         len = recv(sock, buf, sizeof(buf), 0);
430
431                         if (!dhcpv6_response_is_valid(buf, len, trid, type))
432                                 len = -1;
433
434                         if (len > 0) {
435                                 uint8_t *opt = &buf[4];
436                                 uint8_t *opt_end = opt + len - 4;
437
438                                 round_start = odhcp6c_get_milli_time();
439                                 elapsed = round_start - start;
440                                 syslog(LOG_NOTICE, "Got a valid reply after "
441                                                 "%ums", (unsigned)elapsed);
442
443                                 if (retx->handler_reply)
444                                         len = retx->handler_reply(
445                                                         type, opt, opt_end);
446
447                                 if (round_end - round_start > 1000)
448                                         round_end = 1000 + round_start;
449                         }
450                 }
451
452                 // Allow
453                 if (retx->handler_finish)
454                         len = retx->handler_finish();
455         } while (len < 0 && elapsed / 1000 < timeout);
456
457         return len;
458 }
459
460
461 static bool dhcpv6_response_is_valid(const void *buf, ssize_t len,
462                 const uint8_t transaction[3], enum dhcpv6_msg type)
463 {
464         const struct dhcpv6_header *rep = buf;
465         if (len < (ssize_t)sizeof(*rep) || memcmp(rep->tr_id,
466                         transaction, sizeof(rep->tr_id)))
467                 return false; // Invalid reply
468
469         if (type == DHCPV6_MSG_SOLICIT) {
470                 if (rep->msg_type != DHCPV6_MSG_ADVERT &&
471                                 rep->msg_type != DHCPV6_MSG_REPLY)
472                         return false;
473         } else if (type == DHCPV6_MSG_UNKNOWN) {
474                 if (!accept_reconfig || rep->msg_type != DHCPV6_MSG_RECONF)
475                         return false;
476         } else if (rep->msg_type != DHCPV6_MSG_REPLY) {
477                 return false;
478         }
479
480         uint8_t *end = ((uint8_t*)buf) + len, *odata;
481         uint16_t otype, olen;
482         bool clientid_ok = false, serverid_ok = false, rcauth_ok = false;
483
484         size_t client_id_len, server_id_len;
485         void *client_id = odhcp6c_get_state(STATE_CLIENT_ID, &client_id_len);
486         void *server_id = odhcp6c_get_state(STATE_SERVER_ID, &server_id_len);
487
488         dhcpv6_for_each_option(&rep[1], end, otype, olen, odata) {
489                 if (otype == DHCPV6_OPT_CLIENTID) {
490                         clientid_ok = (olen + 4U == client_id_len) && !memcmp(
491                                         &odata[-4], client_id, client_id_len);
492                 } else if (otype == DHCPV6_OPT_SERVERID) {
493                         serverid_ok = (olen + 4U == server_id_len) && !memcmp(
494                                         &odata[-4], server_id, server_id_len);
495                 } else if (otype == DHCPV6_OPT_AUTH && olen == -4 +
496                                 sizeof(struct dhcpv6_auth_reconfigure)) {
497                         struct dhcpv6_auth_reconfigure *r = (void*)&odata[-4];
498                         if (r->protocol != 3 || r->algorithm != 1 || r->reconf_type != 2)
499                                 continue;
500
501                         md5_state_t md5;
502                         uint8_t serverhash[16], secretbytes[16], hash[16];
503                         memcpy(serverhash, r->key, sizeof(serverhash));
504                         memset(r->key, 0, sizeof(r->key));
505                         memcpy(secretbytes, reconf_key, sizeof(secretbytes));
506
507                         for (size_t i = 0; i < sizeof(secretbytes); ++i)
508                                 secretbytes[i] ^= 0x36;
509
510                         md5_init(&md5);
511                         md5_append(&md5, secretbytes, sizeof(secretbytes));
512                         md5_append(&md5, buf, len);
513                         md5_finish(&md5, hash);
514
515                         for (size_t i = 0; i < sizeof(secretbytes); ++i) {
516                                 secretbytes[i] ^= 0x36;
517                                 secretbytes[i] ^= 0x5c;
518                         }
519
520                         md5_init(&md5);
521                         md5_append(&md5, secretbytes, sizeof(secretbytes));
522                         md5_append(&md5, hash, 16);
523                         md5_finish(&md5, hash);
524
525                         rcauth_ok = !memcmp(hash, serverhash, sizeof(hash));
526                 }
527         }
528
529         if (rep->msg_type == DHCPV6_MSG_RECONF && !rcauth_ok)
530                 return false;
531
532         return clientid_ok && (serverid_ok || server_id_len == 0);
533 }
534
535
536 int dhcpv6_poll_reconfigure(void)
537 {
538         int ret = dhcpv6_request(DHCPV6_MSG_UNKNOWN);
539         if (ret != -1)
540                 ret = dhcpv6_request(ret);
541
542         return ret;
543 }
544
545
546 static int dhcpv6_handle_reconfigure(_unused enum dhcpv6_msg orig,
547                 const void *opt, const void *end)
548 {
549         // TODO: should verify the reconfigure message
550         uint16_t otype, olen;
551         uint8_t *odata, msg = DHCPV6_MSG_RENEW;
552         dhcpv6_for_each_option(opt, end, otype, olen, odata)
553                 if (otype == DHCPV6_OPT_RECONF_MESSAGE && olen == 1 && (
554                                 odata[0] == DHCPV6_MSG_RENEW ||
555                                 odata[0] == DHCPV6_MSG_INFO_REQ))
556                         msg = odata[0];
557
558         dhcpv6_handle_reply(DHCPV6_MSG_UNKNOWN, NULL, NULL);
559         return msg;
560 }
561
562
563 // Collect all advertised servers
564 static int dhcpv6_handle_advert(enum dhcpv6_msg orig,
565                 const void *opt, const void *end)
566 {
567         uint16_t olen, otype;
568         uint8_t *odata;
569         struct dhcpv6_server_cand cand = {false, false, 0, 0, {0}, NULL, NULL, 0, 0};
570
571         dhcpv6_for_each_option(opt, end, otype, olen, odata) {
572                 if (orig == DHCPV6_MSG_SOLICIT &&
573                                 (otype == DHCPV6_OPT_IA_PD || otype == DHCPV6_OPT_IA_NA) &&
574                                 olen > sizeof(struct dhcpv6_ia_hdr)) {
575                         struct dhcpv6_ia_hdr *ia_hdr = (void*)(&odata[-4]);
576                         dhcpv6_parse_ia(&ia_hdr[1], odata + olen);
577                 }
578
579                 if (otype == DHCPV6_OPT_SERVERID && olen <= 130) {
580                         memcpy(cand.duid, odata, olen);
581                         cand.duid_len = olen;
582                 } else if (otype == DHCPV6_OPT_STATUS && olen >= 2 && !odata[0]
583                                 && odata[1] == DHCPV6_NoAddrsAvail) {
584                         if (na_mode == IA_MODE_FORCE) {
585                                 return -1;
586                         } else {
587                                 cand.has_noaddravail = true;
588                                 cand.preference -= 1000;
589                         }
590                 } else if (otype == DHCPV6_OPT_STATUS && olen >= 2 && !odata[0]
591                                 && odata[1] == DHCPV6_NoPrefixAvail) {
592                         cand.preference -= 2000;
593                 } else if (otype == DHCPV6_OPT_PREF && olen >= 1 &&
594                                 cand.preference >= 0) {
595                         cand.preference = odata[0];
596                 } else if (otype == DHCPV6_OPT_RECONF_ACCEPT) {
597                         cand.wants_reconfigure = true;
598                 } else if (otype == DHCPV6_OPT_IA_PD && request_prefix) {
599                         struct dhcpv6_ia_hdr *h = (struct dhcpv6_ia_hdr*)&odata[-4];
600                         uint8_t *oend = odata + olen, *d;
601                         dhcpv6_for_each_option(&h[1], oend, otype, olen, d) {
602                                 if (otype == DHCPV6_OPT_IA_PREFIX)
603                                         cand.preference += 2000;
604                                 else if (otype == DHCPV6_OPT_STATUS &&
605                                                 olen >= 2 && d[0] == 0 &&
606                                                 d[1] == DHCPV6_NoPrefixAvail)
607                                         cand.preference -= 2000;
608                         }
609                 }
610         }
611
612         if (cand.duid_len > 0) {
613                 cand.ia_na = odhcp6c_move_state(STATE_IA_NA, &cand.ia_na_len);
614                 cand.ia_pd = odhcp6c_move_state(STATE_IA_PD, &cand.ia_pd_len);
615                 odhcp6c_add_state(STATE_SERVER_CAND, &cand, sizeof(cand));
616         }
617
618         if (orig == DHCPV6_MSG_SOLICIT) {
619                 odhcp6c_clear_state(STATE_IA_NA);
620                 odhcp6c_clear_state(STATE_IA_PD);
621         }
622
623         return -1;
624 }
625
626
627 static int dhcpv6_commit_advert(void)
628 {
629         size_t cand_len;
630         struct dhcpv6_server_cand *c = NULL, *cand =
631                         odhcp6c_get_state(STATE_SERVER_CAND, &cand_len);
632
633         bool retry = false;
634         for (size_t i = 0; i < cand_len / sizeof(*c); ++i) {
635                 if (cand[i].has_noaddravail)
636                         retry = true; // We want to try again
637
638                 if (!c || c->preference < cand[i].preference)
639                         c = &cand[i];
640         }
641
642         if (retry && na_mode == IA_MODE_TRY) {
643                 // We give it a second try without the IA_NA
644                 na_mode = IA_MODE_NONE;
645                 return dhcpv6_request(DHCPV6_MSG_SOLICIT);
646         }
647
648         if (c) {
649                 uint16_t hdr[2] = {htons(DHCPV6_OPT_SERVERID),
650                                 htons(c->duid_len)};
651                 odhcp6c_add_state(STATE_SERVER_ID, hdr, sizeof(hdr));
652                 odhcp6c_add_state(STATE_SERVER_ID, c->duid, c->duid_len);
653                 accept_reconfig = c->wants_reconfigure;
654                 odhcp6c_add_state(STATE_IA_NA, c->ia_na, c->ia_na_len);
655                 odhcp6c_add_state(STATE_IA_PD, c->ia_pd, c->ia_pd_len);
656         }
657
658         for (size_t i = 0; i < cand_len / sizeof(*c); ++i) {
659                 free(cand[i].ia_na);
660                 free(cand[i].ia_pd);
661         }
662         odhcp6c_clear_state(STATE_SERVER_CAND);
663
664         if (!c)
665                 return -1;
666         else if (request_prefix || na_mode != IA_MODE_NONE)
667                 return DHCPV6_STATEFUL;
668         else
669                 return DHCPV6_STATELESS;
670 }
671
672
673 static int dhcpv6_handle_rebind_reply(enum dhcpv6_msg orig,
674                 const void *opt, const void *end)
675 {
676         dhcpv6_handle_advert(orig, opt, end);
677         if (dhcpv6_commit_advert() < 0) {
678                 dhcpv6_handle_reply(DHCPV6_MSG_UNKNOWN, NULL, NULL);
679                 return -1;
680         }
681
682         return dhcpv6_handle_reply(orig, opt, end);
683 }
684
685
686 static int dhcpv6_handle_reply(enum dhcpv6_msg orig,
687                 const void *opt, const void *end)
688 {
689         uint8_t *odata;
690         uint16_t otype, olen;
691
692         odhcp6c_expire();
693
694         if (orig == DHCPV6_MSG_UNKNOWN) {
695                 static time_t last_update = 0;
696                 time_t now = odhcp6c_get_milli_time() / 1000;
697
698                 uint32_t elapsed = (last_update > 0) ? now - last_update : 0;
699                 last_update = now;
700
701                 t1 -= elapsed;
702                 t2 -= elapsed;
703                 t3 -= elapsed;
704
705                 if (t1 < 0)
706                         t1 = 0;
707
708                 if (t2 < 0)
709                         t2 = 0;
710
711                 if (t3 < 0)
712                         t3 = 0;
713         } else {
714                 t1 = t2 = t3 = UINT32_MAX;
715         }
716
717         if (orig == DHCPV6_MSG_REQUEST) {
718                 // Delete NA and PD we have in the state from the Advert
719                 odhcp6c_clear_state(STATE_IA_NA);
720                 odhcp6c_clear_state(STATE_IA_PD);
721         }
722
723         if (opt) {
724                 odhcp6c_clear_state(STATE_DNS);
725                 odhcp6c_clear_state(STATE_SEARCH);
726                 odhcp6c_clear_state(STATE_SNTP_IP);
727                 odhcp6c_clear_state(STATE_SNTP_FQDN);
728                 odhcp6c_clear_state(STATE_SIP_IP);
729                 odhcp6c_clear_state(STATE_SIP_FQDN);
730                 odhcp6c_clear_state(STATE_AFTR_NAME);
731         }
732
733         // Parse and find all matching IAs
734         dhcpv6_for_each_option(opt, end, otype, olen, odata) {
735                 if ((otype == DHCPV6_OPT_IA_PD || otype == DHCPV6_OPT_IA_NA)
736                                 && olen > sizeof(struct dhcpv6_ia_hdr)) {
737                         struct dhcpv6_ia_hdr *ia_hdr = (void*)(&odata[-4]);
738                         uint32_t l_t1 = ntohl(ia_hdr->t1);
739                         uint32_t l_t2 = ntohl(ia_hdr->t2);
740
741                         // Test ID and T1-T2 validity
742                         if (ia_hdr->iaid != 1 || l_t2 < l_t1)
743                                 continue;
744
745                         bool error = false;
746                         uint16_t stype, slen;
747                         uint8_t *sdata;
748                         // Test status and bail if error
749                         dhcpv6_for_each_option(&ia_hdr[1], odata + olen,
750                                         stype, slen, sdata)
751                                 if (stype == DHCPV6_OPT_STATUS && slen >= 2 &&
752                                                 (sdata[0] || sdata[1]))
753                                         error = true;
754
755                         if (error)
756                                 continue;
757
758                         uint32_t n = dhcpv6_parse_ia(&ia_hdr[1], odata + olen);
759
760                         if (!l_t1)
761                                 l_t1 = 300;
762
763                         if (!l_t2)
764                                 l_t2 = 600;
765
766                         if (n < t3)
767                                 t3 = n;
768
769                         // Update times
770                         if (l_t1 > 0 && t1 > l_t1)
771                                 t1 = l_t1;
772
773                         if (l_t2 > 0 && t2 > l_t2)
774                                 t2 = l_t2;
775
776                 } else if (otype == DHCPV6_OPT_DNS_SERVERS) {
777                         if (olen % 16 == 0)
778                                 odhcp6c_add_state(STATE_DNS, odata, olen);
779                 } else if (otype == DHCPV6_OPT_DNS_DOMAIN) {
780                         odhcp6c_add_state(STATE_SEARCH, odata, olen);
781                 } else if (otype == DHCPV6_OPT_NTP_SERVER) {
782                         uint16_t stype, slen;
783                         uint8_t *sdata;
784                         // Test status and bail if error
785                         dhcpv6_for_each_option(odata, odata + olen,
786                                         stype, slen, sdata) {
787                                 if (slen == 16 && (stype == NTP_MC_ADDR ||
788                                                 stype == NTP_SRV_ADDR))
789                                         odhcp6c_add_state(STATE_SNTP_IP,
790                                                         sdata, slen);
791                                 else if (slen > 0 && stype == NTP_SRV_FQDN)
792                                         odhcp6c_add_state(STATE_SNTP_FQDN,
793                                                         sdata, slen);
794                         }
795                 } else if (otype == DHCPV6_OPT_SIP_SERVER_A) {
796                         if (olen == 16)
797                                 odhcp6c_add_state(STATE_SIP_IP, odata, olen);
798                 } else if (otype == DHCPV6_OPT_SIP_SERVER_D) {
799                         odhcp6c_add_state(STATE_SIP_FQDN, odata, olen);
800                 } else if (otype == DHCPV6_OPT_INFO_REFRESH && olen >= 4) {
801                         uint32_t refresh = ntohl(*((uint32_t*)odata));
802                         if (refresh < (uint32_t)t1)
803                                 t1 = refresh;
804                 } else if (otype == DHCPV6_OPT_AUTH && olen == -4 +
805                                 sizeof(struct dhcpv6_auth_reconfigure)) {
806                         struct dhcpv6_auth_reconfigure *r = (void*)&odata[-4];
807                         if (r->protocol == 3 && r->algorithm == 1 &&
808                                         r->reconf_type == 1)
809                                 memcpy(reconf_key, r->key, sizeof(r->key));
810                 } else if (otype == DHCPV6_OPT_AFTR_NAME && olen > 3) {
811                         size_t cur_len;
812                         odhcp6c_get_state(STATE_AFTR_NAME, &cur_len);
813                         if (cur_len == 0)
814                                 odhcp6c_add_state(STATE_AFTR_NAME, odata, olen);
815                 } else if (otype != DHCPV6_OPT_CLIENTID &&
816                                 otype != DHCPV6_OPT_SERVERID) {
817                         odhcp6c_add_state(STATE_CUSTOM_OPTS,
818                                         &odata[-4], olen + 4);
819                 }
820         }
821
822         return true;
823 }
824
825
826 static uint32_t dhcpv6_parse_ia(void *opt, void *end)
827 {
828         uint32_t timeout = UINT32_MAX; // Minimum timeout
829         uint16_t otype, olen;
830         uint8_t *odata;
831
832         // Update address IA
833         dhcpv6_for_each_option(opt, end, otype, olen, odata) {
834           struct odhcp6c_entry entry = {IN6ADDR_ANY_INIT,
835                                         0, 0, IN6ADDR_ANY_INIT, 0, 0, 0};
836
837                 if (otype == DHCPV6_OPT_IA_PREFIX) {
838                         struct dhcpv6_ia_prefix *prefix = (void*)&odata[-4];
839                         if (olen + 4U < sizeof(*prefix))
840                                 continue;
841
842                         entry.valid = ntohl(prefix->valid);
843                         entry.preferred = ntohl(prefix->preferred);
844
845                         if (entry.preferred > entry.valid)
846                                 continue;
847
848                         entry.length = prefix->prefix;
849                         entry.target = prefix->addr;
850                         uint16_t stype, slen;
851                         uint8_t *sdata;
852
853                         // Find prefix class, if any
854                         dhcpv6_for_each_option(&prefix[1], odata + olen,
855                                                stype, slen, sdata)
856                           if (stype == DHCPV6_OPT_PREFIX_CLASS && slen == 2) 
857                             entry.prefix_class = ntohs(*((uint16_t*)sdata));
858
859                         // Parse PD-exclude
860                         bool ok = true;
861                         dhcpv6_for_each_option(odata + sizeof(*prefix) - 4U,
862                                         odata + olen, stype, slen, sdata) {
863                                 if (stype != DHCPV6_OPT_PD_EXCLUDE || slen < 2)
864                                         continue;
865
866                                 uint8_t elen = sdata[0];
867                                 if (elen > 64)
868                                         elen = 64;
869
870                                 if (elen <= 32 || elen <= entry.length) {
871                                         ok = false;
872                                         continue;
873                                 }
874
875
876                                 uint8_t bytes = ((elen - entry.length - 1) / 8) + 1;
877                                 if (slen <= bytes) {
878                                         ok = false;
879                                         continue;
880                                 }
881
882                                 uint32_t exclude = 0;
883                                 do {
884                                         exclude = exclude << 8 | sdata[bytes];
885                                 } while (--bytes);
886
887                                 exclude >>= 8 - ((elen - entry.length) % 8);
888                                 exclude <<= 64 - elen;
889
890                                 // Abusing router & priority fields for exclusion
891                                 entry.router = entry.target;
892                                 entry.router.s6_addr32[1] |= htonl(exclude);
893                                 entry.priority = elen;
894                         }
895
896                         if (ok)
897                                 odhcp6c_update_entry(STATE_IA_PD, &entry);
898
899                         entry.priority = 0;
900                         memset(&entry.router, 0, sizeof(entry.router));
901                 } else if (otype == DHCPV6_OPT_IA_ADDR) {
902                         struct dhcpv6_ia_addr *addr = (void*)&odata[-4];
903                         if (olen + 4U < sizeof(*addr))
904                                 continue;
905
906                         entry.preferred = ntohl(addr->preferred);
907                         entry.valid = ntohl(addr->valid);
908
909                         if (entry.preferred > entry.valid)
910                                 continue;
911
912                         entry.length = 128;
913                         entry.target = addr->addr;
914
915                         uint16_t stype, slen;
916                         uint8_t *sdata;
917                         
918                         // Find prefix class, if any
919                         dhcpv6_for_each_option(&addr[1], odata + olen,
920                                                stype, slen, sdata)
921                           if (stype == DHCPV6_OPT_PREFIX_CLASS && slen == 2) 
922                             entry.prefix_class = ntohs(*((uint16_t*)sdata));
923                         
924                         odhcp6c_update_entry(STATE_IA_NA, &entry);
925                 }
926
927                 if (entry.valid > 0 && timeout > entry.valid)
928                         timeout = entry.valid;
929         }
930
931         return timeout;
932 }