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