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