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