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