4cb4878e46563ac125db6e24ca000500209ad8cc
[oweals/odhcp6c.git] / src / dhcpv6.c
1 /**
2  * Copyright (C) 2012-2014 Steven Barth <steven@midlink.org>
3  * Copyright (C) 2017-2018 Hans Dedecker <dedeckeh@gmail.com>
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License v2 as published by
7  * the Free Software Foundation.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  */
15
16 #include <time.h>
17 #include <fcntl.h>
18 #include <errno.h>
19 #include <inttypes.h>
20 #include <stdlib.h>
21 #include <signal.h>
22 #include <limits.h>
23 #include <resolv.h>
24 #include <string.h>
25 #include <unistd.h>
26 #include <syslog.h>
27 #include <stdbool.h>
28 #include <ctype.h>
29 #include <sys/time.h>
30 #include <sys/ioctl.h>
31 #include <sys/socket.h>
32 #include <arpa/inet.h>
33 #include <netinet/in.h>
34
35 #include <net/if.h>
36 #include <net/ethernet.h>
37
38 #include "odhcp6c.h"
39 #ifdef USE_LIBUBOX
40 #include <libubox/md5.h>
41 #else
42 #include "md5.h"
43 #endif
44
45
46 #define ALL_DHCPV6_RELAYS {{{0xff, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
47                 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x02}}}
48 #define DHCPV6_CLIENT_PORT 546
49 #define DHCPV6_SERVER_PORT 547
50 #define DHCPV6_DUID_LLADDR 3
51 #define DHCPV6_REQ_DELAY 1
52
53 #define DHCPV6_SOL_MAX_RT_MIN 60
54 #define DHCPV6_SOL_MAX_RT_MAX 86400
55 #define DHCPV6_INF_MAX_RT_MIN 60
56 #define DHCPV6_INF_MAX_RT_MAX 86400
57
58 static bool dhcpv6_response_is_valid(const void *buf, ssize_t len,
59                 const uint8_t transaction[3], enum dhcpv6_msg type,
60                 const struct in6_addr *daddr);
61
62 static unsigned int dhcpv6_parse_ia(void *opt, void *end);
63
64 static int dhcpv6_calc_refresh_timers(void);
65 static void dhcpv6_handle_status_code(_unused const enum dhcpv6_msg orig,
66                 const uint16_t code, const void *status_msg, const int len,
67                 int *ret);
68 static void dhcpv6_handle_ia_status_code(const enum dhcpv6_msg orig,
69                 const struct dhcpv6_ia_hdr *ia_hdr, const uint16_t code,
70                 const void *status_msg, const int len,
71                 bool handled_status_codes[_DHCPV6_Status_Max],
72                 int *ret);
73 static void dhcpv6_add_server_cand(const struct dhcpv6_server_cand *cand);
74 static void dhcpv6_clear_all_server_cand(void);
75
76 static reply_handler dhcpv6_handle_reply;
77 static reply_handler dhcpv6_handle_advert;
78 static reply_handler dhcpv6_handle_rebind_reply;
79 static reply_handler dhcpv6_handle_reconfigure;
80 static int dhcpv6_commit_advert(void);
81
82 // RFC 3315 - 5.5 Timeout and Delay values
83 static struct dhcpv6_retx dhcpv6_retx[_DHCPV6_MSG_MAX] = {
84         [DHCPV6_MSG_UNKNOWN] = {false, 1, 120, 0, "<POLL>",
85                         dhcpv6_handle_reconfigure, NULL},
86         [DHCPV6_MSG_SOLICIT] = {true, 1, DHCPV6_SOL_MAX_RT, 0, "SOLICIT",
87                         dhcpv6_handle_advert, dhcpv6_commit_advert},
88         [DHCPV6_MSG_REQUEST] = {true, 1, DHCPV6_REQ_MAX_RT, 10, "REQUEST",
89                         dhcpv6_handle_reply, NULL},
90         [DHCPV6_MSG_RENEW] = {false, 10, DHCPV6_REN_MAX_RT, 0, "RENEW",
91                         dhcpv6_handle_reply, NULL},
92         [DHCPV6_MSG_REBIND] = {false, 10, DHCPV6_REB_MAX_RT, 0, "REBIND",
93                         dhcpv6_handle_rebind_reply, NULL},
94         [DHCPV6_MSG_RELEASE] = {false, 1, 0, 5, "RELEASE", NULL, NULL},
95         [DHCPV6_MSG_DECLINE] = {false, 1, 0, 5, "DECLINE", NULL, NULL},
96         [DHCPV6_MSG_INFO_REQ] = {true, 1, DHCPV6_INF_MAX_RT, 0, "INFOREQ",
97                         dhcpv6_handle_reply, NULL},
98 };
99
100 // Sockets
101 static int sock = -1;
102 static int ifindex = -1;
103 static int64_t t1 = 0, t2 = 0, t3 = 0;
104
105 // IA states
106 static enum odhcp6c_ia_mode na_mode = IA_MODE_NONE, pd_mode = IA_MODE_NONE;
107 static bool accept_reconfig = false;
108 // Server unicast address
109 static struct in6_addr server_addr = IN6ADDR_ANY_INIT;
110
111 // Reconfigure key
112 static uint8_t reconf_key[16];
113
114 // client options
115 static unsigned int client_options = 0;
116
117 static uint32_t ntohl_unaligned(const uint8_t *data)
118 {
119         uint32_t buf;
120
121         memcpy(&buf, data, sizeof(buf));
122         return ntohl(buf);
123 }
124
125 int init_dhcpv6(const char *ifname, unsigned int options, int sol_timeout)
126 {
127         client_options = options;
128         dhcpv6_retx[DHCPV6_MSG_SOLICIT].max_timeo = sol_timeout;
129
130         sock = socket(AF_INET6, SOCK_DGRAM | SOCK_CLOEXEC, IPPROTO_UDP);
131         if (sock < 0)
132                 goto failure;
133
134         // Detect interface
135         struct ifreq ifr;
136         memset(&ifr, 0, sizeof(ifr));
137         strncpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name) - 1);
138         if (ioctl(sock, SIOCGIFINDEX, &ifr) < 0)
139                 goto failure;
140
141         ifindex = ifr.ifr_ifindex;
142
143         // Create client DUID
144         size_t client_id_len;
145         odhcp6c_get_state(STATE_CLIENT_ID, &client_id_len);
146         if (client_id_len == 0) {
147                 uint8_t duid[14] = {0, DHCPV6_OPT_CLIENTID, 0, 10, 0,
148                                 DHCPV6_DUID_LLADDR, 0, 1};
149
150                 if (ioctl(sock, SIOCGIFHWADDR, &ifr) >= 0)
151                         memcpy(&duid[8], ifr.ifr_hwaddr.sa_data, ETHER_ADDR_LEN);
152
153                 uint8_t zero[ETHER_ADDR_LEN] = {0, 0, 0, 0, 0, 0};
154                 struct ifreq ifs[100], *ifp, *ifend;
155                 struct ifconf ifc;
156                 ifc.ifc_req = ifs;
157                 ifc.ifc_len = sizeof(ifs);
158
159                 if (!memcmp(&duid[8], zero, ETHER_ADDR_LEN) &&
160                                 ioctl(sock, SIOCGIFCONF, &ifc) >= 0) {
161                         // If our interface doesn't have an address...
162                         ifend = ifs + (ifc.ifc_len / sizeof(struct ifreq));
163                         for (ifp = ifc.ifc_req; ifp < ifend &&
164                                         !memcmp(&duid[8], zero, ETHER_ADDR_LEN); ifp++) {
165                                 memcpy(ifr.ifr_name, ifp->ifr_name,
166                                                 sizeof(ifr.ifr_name));
167                                 if (ioctl(sock, SIOCGIFHWADDR, &ifr) < 0)
168                                         continue;
169
170                                 memcpy(&duid[8], ifr.ifr_hwaddr.sa_data,
171                                                 ETHER_ADDR_LEN);
172                         }
173                 }
174
175                 odhcp6c_add_state(STATE_CLIENT_ID, duid, sizeof(duid));
176         }
177
178         // Create ORO
179         if (!(client_options & DHCPV6_STRICT_OPTIONS)) {
180                 uint16_t oro[] = {
181                         htons(DHCPV6_OPT_SIP_SERVER_D),
182                         htons(DHCPV6_OPT_SIP_SERVER_A),
183                         htons(DHCPV6_OPT_DNS_SERVERS),
184                         htons(DHCPV6_OPT_DNS_DOMAIN),
185                         htons(DHCPV6_OPT_SNTP_SERVERS),
186                         htons(DHCPV6_OPT_NTP_SERVER),
187                         htons(DHCPV6_OPT_AFTR_NAME),
188                         htons(DHCPV6_OPT_PD_EXCLUDE),
189                         htons(DHCPV6_OPT_SOL_MAX_RT),
190                         htons(DHCPV6_OPT_INF_MAX_RT),
191 #ifdef EXT_CER_ID
192                         htons(DHCPV6_OPT_CER_ID),
193 #endif
194                         htons(DHCPV6_OPT_S46_CONT_MAPE),
195                         htons(DHCPV6_OPT_S46_CONT_MAPT),
196                         htons(DHCPV6_OPT_S46_CONT_LW),
197                 };
198                 odhcp6c_add_state(STATE_ORO, oro, sizeof(oro));
199         }
200         // Required oro
201         uint16_t req_oro[] = {
202                 htons(DHCPV6_OPT_INF_MAX_RT),
203                 htons(DHCPV6_OPT_SOL_MAX_RT),
204                 htons(DHCPV6_OPT_INFO_REFRESH),
205         };
206         odhcp6c_add_state(STATE_ORO, req_oro, sizeof(req_oro));
207
208         // Configure IPv6-options
209         int val = 1;
210         if (setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &val, sizeof(val)) < 0)
211                 goto failure;
212
213         if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val)) < 0)
214                 goto failure;
215
216         if (setsockopt(sock, IPPROTO_IPV6, IPV6_RECVPKTINFO, &val, sizeof(val)) < 0)
217                 goto failure;
218
219         if (setsockopt(sock, SOL_SOCKET, SO_BINDTODEVICE, ifname, strlen(ifname)) < 0)
220                 goto failure;
221
222         struct sockaddr_in6 client_addr = { .sin6_family = AF_INET6,
223                 .sin6_port = htons(DHCPV6_CLIENT_PORT), .sin6_flowinfo = 0 };
224
225         if (bind(sock, (struct sockaddr*)&client_addr, sizeof(client_addr)) < 0)
226                 goto failure;
227
228         return 0;
229
230 failure:
231         if (sock >= 0)
232                 close(sock);
233
234         return -1;
235 }
236
237 enum {
238         IOV_HDR=0,
239         IOV_ORO,
240         IOV_CL_ID,
241         IOV_SRV_ID,
242         IOV_OPTS,
243         IOV_RECONF_ACCEPT,
244         IOV_FQDN,
245         IOV_HDR_IA_NA,
246         IOV_IA_NA,
247         IOV_IA_PD,
248         IOV_TOTAL
249 };
250
251 int dhcpv6_set_ia_mode(enum odhcp6c_ia_mode na, enum odhcp6c_ia_mode pd)
252 {
253         int mode = DHCPV6_UNKNOWN;
254
255         na_mode = na;
256         pd_mode = pd;
257
258         if (na_mode == IA_MODE_NONE && pd_mode == IA_MODE_NONE)
259                 mode = DHCPV6_STATELESS;
260         else if (na_mode == IA_MODE_FORCE || pd_mode == IA_MODE_FORCE)
261                 mode = DHCPV6_STATEFUL;
262
263         return mode;
264 }
265
266 static void dhcpv6_send(enum dhcpv6_msg type, uint8_t trid[3], uint32_t ecs)
267 {
268         // Build FQDN
269         char fqdn_buf[256];
270         gethostname(fqdn_buf, sizeof(fqdn_buf));
271         struct {
272                 uint16_t type;
273                 uint16_t len;
274                 uint8_t flags;
275                 uint8_t data[256];
276         } fqdn;
277         size_t fqdn_len = 5 + dn_comp(fqdn_buf, fqdn.data,
278                         sizeof(fqdn.data), NULL, NULL);
279         fqdn.type = htons(DHCPV6_OPT_FQDN);
280         fqdn.len = htons(fqdn_len - 4);
281         fqdn.flags = 0;
282
283         // Build Client ID
284         size_t cl_id_len;
285         void *cl_id = odhcp6c_get_state(STATE_CLIENT_ID, &cl_id_len);
286
287         // Get Server ID
288         size_t srv_id_len;
289         void *srv_id = odhcp6c_get_state(STATE_SERVER_ID, &srv_id_len);
290
291         // Build IA_PDs
292         size_t ia_pd_entries = 0, ia_pd_len = 0;
293         uint8_t *ia_pd;
294
295         if (type == DHCPV6_MSG_SOLICIT) {
296                 odhcp6c_clear_state(STATE_IA_PD);
297                 size_t n_prefixes;
298                 struct odhcp6c_request_prefix *request_prefixes = odhcp6c_get_state(STATE_IA_PD_INIT, &n_prefixes);
299                 n_prefixes /= sizeof(struct odhcp6c_request_prefix);
300
301                 ia_pd = alloca(n_prefixes * (sizeof(struct dhcpv6_ia_hdr) + sizeof(struct dhcpv6_ia_prefix)));
302
303                 for (size_t i = 0; i < n_prefixes; i++) {
304                         struct dhcpv6_ia_hdr hdr_ia_pd = {
305                                 htons(DHCPV6_OPT_IA_PD),
306                                 htons(sizeof(hdr_ia_pd) - 4 +
307                                       sizeof(struct dhcpv6_ia_prefix) * !!request_prefixes[i].length),
308                                 request_prefixes[i].iaid, 0, 0
309                         };
310                         struct dhcpv6_ia_prefix pref = {
311                                 .type = htons(DHCPV6_OPT_IA_PREFIX),
312                                 .len = htons(sizeof(pref) - 4),
313                                 .prefix = request_prefixes[i].length
314                         };
315                         memcpy(ia_pd + ia_pd_len, &hdr_ia_pd, sizeof(hdr_ia_pd));
316                         ia_pd_len += sizeof(hdr_ia_pd);
317                         if (request_prefixes[i].length) {
318                                 memcpy(ia_pd + ia_pd_len, &pref, sizeof(pref));
319                                 ia_pd_len += sizeof(pref);
320                         }
321                 }
322         } else {
323                 struct odhcp6c_entry *e = odhcp6c_get_state(STATE_IA_PD, &ia_pd_entries);
324                 ia_pd_entries /= sizeof(*e);
325
326                 // we're too lazy to count our distinct IAIDs,
327                 // so just allocate maximally needed space
328                 ia_pd = alloca(ia_pd_entries * (sizeof(struct dhcpv6_ia_prefix) + 10 +
329                                         sizeof(struct dhcpv6_ia_hdr)));
330
331                 for (size_t i = 0; i < ia_pd_entries; ++i) {
332                         uint32_t iaid = e[i].iaid;
333
334                         // check if this is an unprocessed IAID and skip if not.
335                         int new_iaid = 1;
336                         for (int j = i-1; j >= 0; j--) {
337                                 if (e[j].iaid == iaid) {
338                                         new_iaid = 0;
339                                         break;
340                                 }
341                         }
342
343                         if (!new_iaid)
344                                 continue;
345
346                         // construct header
347                         struct dhcpv6_ia_hdr hdr_ia_pd = {
348                                 htons(DHCPV6_OPT_IA_PD),
349                                 htons(sizeof(hdr_ia_pd) - 4),
350                                 iaid, 0, 0
351                         };
352
353                         memcpy(ia_pd + ia_pd_len, &hdr_ia_pd, sizeof(hdr_ia_pd));
354                         struct dhcpv6_ia_hdr *hdr = (struct dhcpv6_ia_hdr *) (ia_pd + ia_pd_len);
355                         ia_pd_len += sizeof(hdr_ia_pd);
356
357                         for (size_t j = i; j < ia_pd_entries; j++) {
358                                 if (e[j].iaid != iaid)
359                                         continue;
360
361                                 uint8_t ex_len = 0;
362                                 if (e[j].priority > 0)
363                                         ex_len = ((e[j].priority - e[j].length - 1) / 8) + 6;
364
365                                 struct dhcpv6_ia_prefix p = {
366                                         .type = htons(DHCPV6_OPT_IA_PREFIX),
367                                         .len = htons(sizeof(p) - 4U + ex_len),
368                                         .prefix = e[j].length,
369                                         .addr = e[j].target
370                                 };
371
372                                 if (type == DHCPV6_MSG_REQUEST) {
373                                         p.preferred = htonl(e[j].preferred);
374                                         p.valid = htonl(e[j].valid);
375                                 }
376
377                                 memcpy(ia_pd + ia_pd_len, &p, sizeof(p));
378                                 ia_pd_len += sizeof(p);
379
380                                 if (ex_len) {
381                                         ia_pd[ia_pd_len++] = 0;
382                                         ia_pd[ia_pd_len++] = DHCPV6_OPT_PD_EXCLUDE;
383                                         ia_pd[ia_pd_len++] = 0;
384                                         ia_pd[ia_pd_len++] = ex_len - 4;
385                                         ia_pd[ia_pd_len++] = e[j].priority;
386
387                                         uint32_t excl = ntohl(e[j].router.s6_addr32[1]);
388                                         excl >>= (64 - e[j].priority);
389                                         excl <<= 8 - ((e[j].priority - e[j].length) % 8);
390
391                                         for (size_t i = ex_len - 5; i > 0; --i, excl >>= 8)
392                                                 ia_pd[ia_pd_len + i] = excl & 0xff;
393                                         ia_pd_len += ex_len - 5;
394                                 }
395
396                                 hdr->len = htons(ntohs(hdr->len) + ntohs(p.len) + 4U);
397                         }
398                 }
399         }
400
401         // Build IA_NAs
402         size_t ia_na_entries, ia_na_len = 0;
403         void *ia_na = NULL;
404         struct odhcp6c_entry *e = odhcp6c_get_state(STATE_IA_NA, &ia_na_entries);
405         ia_na_entries /= sizeof(*e);
406
407         struct dhcpv6_ia_hdr hdr_ia_na = {
408                 htons(DHCPV6_OPT_IA_NA),
409                 htons(sizeof(hdr_ia_na) - 4),
410                 htonl(1), 0, 0
411         };
412
413         struct dhcpv6_ia_addr pa[ia_na_entries];
414         for (size_t i = 0; i < ia_na_entries; ++i) {
415                 pa[i].type = htons(DHCPV6_OPT_IA_ADDR);
416                 pa[i].len = htons(sizeof(pa[i]) - 4U);
417                 pa[i].addr = e[i].target;
418
419                 if (type == DHCPV6_MSG_REQUEST) {
420                         pa[i].preferred = htonl(e[i].preferred);
421                         pa[i].valid = htonl(e[i].valid);
422                 } else {
423                         pa[i].preferred = 0;
424                         pa[i].valid = 0;
425                 }
426         }
427
428         ia_na = pa;
429         ia_na_len = sizeof(pa);
430         hdr_ia_na.len = htons(ntohs(hdr_ia_na.len) + ia_na_len);
431
432         // Reconfigure Accept
433         struct {
434                 uint16_t type;
435                 uint16_t length;
436         } reconf_accept = {htons(DHCPV6_OPT_RECONF_ACCEPT), 0};
437
438         // Option list
439         size_t opts_len;
440         void *opts = odhcp6c_get_state(STATE_OPTS, &opts_len);
441
442         // Option Request List
443         size_t oro_entries, oro_len = 0;
444         uint16_t *oro, *s_oro = odhcp6c_get_state(STATE_ORO, &oro_entries);
445
446         oro_entries /= sizeof(*s_oro);
447         oro = alloca(oro_entries * sizeof(*oro));
448
449         for (size_t i = 0; i < oro_entries; i++) {
450                 struct odhcp6c_opt *opt = odhcp6c_find_opt(htons(s_oro[i]));
451
452                 if (opt) {
453                         if (!(opt->flags & OPT_ORO))
454                                 continue;
455
456                         if ((opt->flags & OPT_ORO_SOLICIT) && type != DHCPV6_MSG_SOLICIT)
457                                 continue;
458
459                         if ((opt->flags & OPT_ORO_STATELESS) && type != DHCPV6_MSG_INFO_REQ)
460                                 continue;
461
462                         if ((opt->flags & OPT_ORO_STATEFUL) && type == DHCPV6_MSG_INFO_REQ)
463                                 continue;
464                 }
465
466                 oro[oro_len++] = s_oro[i];
467         }
468         oro_len *= sizeof(*oro);
469
470         // Prepare Header
471         struct {
472                 uint8_t type;
473                 uint8_t trid[3];
474                 uint16_t elapsed_type;
475                 uint16_t elapsed_len;
476                 uint16_t elapsed_value;
477                 uint16_t oro_type;
478                 uint16_t oro_len;
479         } hdr = {
480                 type, {trid[0], trid[1], trid[2]},
481                 htons(DHCPV6_OPT_ELAPSED), htons(2),
482                         htons((ecs > 0xffff) ? 0xffff : ecs),
483                 htons(DHCPV6_OPT_ORO), htons(oro_len),
484         };
485
486         struct iovec iov[IOV_TOTAL] = {
487                 [IOV_HDR] = {&hdr, sizeof(hdr)},
488                 [IOV_ORO] = {oro, oro_len},
489                 [IOV_CL_ID] = {cl_id, cl_id_len},
490                 [IOV_SRV_ID] = {srv_id, srv_id_len},
491                 [IOV_OPTS] = { opts, opts_len },
492                 [IOV_RECONF_ACCEPT] = {&reconf_accept, sizeof(reconf_accept)},
493                 [IOV_FQDN] = {&fqdn, fqdn_len},
494                 [IOV_HDR_IA_NA] = {&hdr_ia_na, sizeof(hdr_ia_na)},
495                 [IOV_IA_NA] = {ia_na, ia_na_len},
496                 [IOV_IA_PD] = {ia_pd, ia_pd_len},
497         };
498
499         size_t cnt = IOV_TOTAL;
500         if (type == DHCPV6_MSG_INFO_REQ)
501                 cnt = 8;
502
503         // Disable IAs if not used
504         if (type != DHCPV6_MSG_SOLICIT && ia_na_len == 0)
505                 iov[IOV_HDR_IA_NA].iov_len = 0;
506
507         if (na_mode == IA_MODE_NONE)
508                 iov[IOV_HDR_IA_NA].iov_len = 0;
509
510         if ((type != DHCPV6_MSG_SOLICIT && type != DHCPV6_MSG_REQUEST) ||
511                         !(client_options & DHCPV6_ACCEPT_RECONFIGURE))
512                 iov[IOV_RECONF_ACCEPT].iov_len = 0;
513
514         if (!(client_options & DHCPV6_CLIENT_FQDN))
515                 iov[IOV_FQDN].iov_len = 0;
516
517         struct sockaddr_in6 srv = {AF_INET6, htons(DHCPV6_SERVER_PORT),
518                 0, ALL_DHCPV6_RELAYS, ifindex};
519         struct msghdr msg = {.msg_name = &srv, .msg_namelen = sizeof(srv),
520                         .msg_iov = iov, .msg_iovlen = cnt};
521
522         switch (type) {
523         case DHCPV6_MSG_REQUEST:
524         case DHCPV6_MSG_RENEW:
525         case DHCPV6_MSG_RELEASE:
526         case DHCPV6_MSG_DECLINE:
527                 if (!IN6_IS_ADDR_UNSPECIFIED(&server_addr) &&
528                         odhcp6c_addr_in_scope(&server_addr)) {
529                         srv.sin6_addr = server_addr;
530                         if (!IN6_IS_ADDR_LINKLOCAL(&server_addr))
531                                 srv.sin6_scope_id = 0;
532                 }
533                 break;
534         default:
535                 break;
536         }
537
538         if (sendmsg(sock, &msg, 0) < 0) {
539                 char in6_str[INET6_ADDRSTRLEN];
540
541                 syslog(LOG_ERR, "Failed to send DHCPV6 message to %s (%s)",
542                         inet_ntop(AF_INET6, (const void *)&srv.sin6_addr,
543                                 in6_str, sizeof(in6_str)), strerror(errno));
544         }
545 }
546
547 static int64_t dhcpv6_rand_delay(int64_t time)
548 {
549         int random;
550         odhcp6c_random(&random, sizeof(random));
551
552         return (time * ((int64_t)random % 1000LL)) / 10000LL;
553 }
554
555 int dhcpv6_request(enum dhcpv6_msg type)
556 {
557         uint8_t rc = 0;
558         uint64_t timeout = UINT32_MAX;
559         struct dhcpv6_retx *retx = &dhcpv6_retx[type];
560
561         if (retx->delay) {
562                 struct timespec ts = {0, 0};
563                 ts.tv_nsec = (dhcpv6_rand_delay((10000 * DHCPV6_REQ_DELAY) / 2) + (1000 * DHCPV6_REQ_DELAY) / 2) * 1000000;
564
565                 while (nanosleep(&ts, &ts) < 0 && errno == EINTR);
566         }
567
568         if (type == DHCPV6_MSG_UNKNOWN)
569                 timeout = t1;
570         else if (type == DHCPV6_MSG_RENEW)
571                 timeout = (t2 > t1) ? t2 - t1 : ((t1 == UINT32_MAX) ? UINT32_MAX : 0);
572         else if (type == DHCPV6_MSG_REBIND)
573                 timeout = (t3 > t2) ? t3 - t2 : ((t2 == UINT32_MAX) ? UINT32_MAX : 0);
574
575         if (timeout == 0)
576                 return -1;
577
578         syslog(LOG_NOTICE, "Starting %s transaction (timeout %"PRIu64"s, max rc %d)",
579                         retx->name, timeout, retx->max_rc);
580
581         uint64_t start = odhcp6c_get_milli_time(), round_start = start, elapsed;
582
583         // Generate transaction ID
584         uint8_t trid[3] = {0, 0, 0};
585         if (type != DHCPV6_MSG_UNKNOWN)
586                 odhcp6c_random(trid, sizeof(trid));
587
588         ssize_t len = -1;
589         int64_t rto = 0;
590
591         do {
592                 if (rto == 0) {
593                         int64_t delay = dhcpv6_rand_delay(retx->init_timeo * 1000);
594
595                         // First RT MUST be strictly greater than IRT for solicit messages (RFC3313 17.1.2)
596                         while (type == DHCPV6_MSG_SOLICIT && delay <= 0)
597                                 delay = dhcpv6_rand_delay(retx->init_timeo * 1000);
598
599                         rto = (retx->init_timeo * 1000 + delay);
600                 } else
601                         rto = (2 * rto + dhcpv6_rand_delay(rto));
602
603                 if (retx->max_timeo && (rto >= retx->max_timeo * 1000))
604                         rto = retx->max_timeo * 1000 +
605                                 dhcpv6_rand_delay(retx->max_timeo * 1000);
606
607                 // Calculate end for this round and elapsed time
608                 uint64_t round_end = round_start + rto;
609                 elapsed = round_start - start;
610
611                 // Don't wait too long if timeout differs from infinite
612                 if ((timeout != UINT32_MAX) && (round_end - start > timeout * 1000))
613                         round_end = timeout * 1000 + start;
614
615                 // Built and send package
616                 switch (type) {
617                 case DHCPV6_MSG_UNKNOWN:
618                         break;
619                 default:
620                         syslog(LOG_NOTICE, "Send %s message (elapsed %"PRIu64"ms, rc %d)",
621                                         retx->name, elapsed, rc);
622                         // Fall through
623                 case DHCPV6_MSG_SOLICIT:
624                 case DHCPV6_MSG_INFO_REQ:
625                         dhcpv6_send(type, trid, elapsed / 10);
626                         rc++;
627                 }
628
629                 // Receive rounds
630                 for (; len < 0 && (round_start < round_end);
631                                 round_start = odhcp6c_get_milli_time()) {
632                         uint8_t buf[1536];
633                         union {
634                                 struct cmsghdr hdr;
635                                 uint8_t buf[CMSG_SPACE(sizeof(struct in6_pktinfo))];
636                         } cmsg_buf;
637                         struct iovec iov = {buf, sizeof(buf)};
638                         struct sockaddr_in6 addr;
639                         struct msghdr msg = {.msg_name = &addr, .msg_namelen = sizeof(addr),
640                                         .msg_iov = &iov, .msg_iovlen = 1, .msg_control = cmsg_buf.buf,
641                                         .msg_controllen = sizeof(cmsg_buf)};
642                         struct in6_pktinfo *pktinfo = NULL;
643
644                         // Check for pending signal
645                         if (odhcp6c_signal_process())
646                                 return -1;
647
648                         // Set timeout for receiving
649                         uint64_t t = round_end - round_start;
650                         struct timeval tv = {t / 1000, (t % 1000) * 1000};
651                         if (setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO,
652                                         &tv, sizeof(tv)) < 0)
653                                 syslog(LOG_ERR, "setsockopt SO_RCVTIMEO failed (%s)",
654                                                 strerror(errno));
655
656                         // Receive cycle
657                         len = recvmsg(sock, &msg, 0);
658                         if (len < 0)
659                                 continue;
660
661                         for (struct cmsghdr *ch = CMSG_FIRSTHDR(&msg); ch != NULL;
662                                 ch = CMSG_NXTHDR(&msg, ch)) {
663                                 if (ch->cmsg_level == SOL_IPV6 &&
664                                         ch->cmsg_type == IPV6_PKTINFO) {
665                                         pktinfo = (struct in6_pktinfo *)CMSG_DATA(ch);
666                                         break;
667                                 }
668                         }
669
670                         if (pktinfo == NULL) {
671                                 len = -1;
672                                 continue;
673                         }
674
675                         if (!dhcpv6_response_is_valid(buf, len, trid,
676                                                         type, &pktinfo->ipi6_addr)) {
677                                 len = -1;
678                                 continue;
679                         }
680
681                         uint8_t *opt = &buf[4];
682                         uint8_t *opt_end = opt + len - 4;
683
684                         round_start = odhcp6c_get_milli_time();
685                         elapsed = round_start - start;
686                         syslog(LOG_NOTICE, "Got a valid reply after %"PRIu64"ms",
687                                         elapsed);
688
689                         if (retx->handler_reply)
690                                 len = retx->handler_reply(type, rc, opt, opt_end, &addr);
691
692                         if (len > 0 && round_end - round_start > 1000)
693                                 round_end = 1000 + round_start;
694                 }
695
696                 // Allow
697                 if (retx->handler_finish)
698                         len = retx->handler_finish();
699         } while (len < 0 && ((timeout == UINT32_MAX) || (elapsed / 1000 < timeout)) &&
700                         (!retx->max_rc || rc < retx->max_rc));
701         return len;
702 }
703
704 // Message validation checks according to RFC3315 chapter 15
705 static bool dhcpv6_response_is_valid(const void *buf, ssize_t len,
706                 const uint8_t transaction[3], enum dhcpv6_msg type,
707                 const struct in6_addr *daddr)
708 {
709         const struct dhcpv6_header *rep = buf;
710         if (len < (ssize_t)sizeof(*rep) || memcmp(rep->tr_id,
711                         transaction, sizeof(rep->tr_id)))
712                 return false; // Invalid reply
713
714         if (type == DHCPV6_MSG_SOLICIT) {
715                 if (rep->msg_type != DHCPV6_MSG_ADVERT &&
716                                 rep->msg_type != DHCPV6_MSG_REPLY)
717                         return false;
718
719         } else if (type == DHCPV6_MSG_UNKNOWN) {
720                 if (!accept_reconfig || rep->msg_type != DHCPV6_MSG_RECONF)
721                         return false;
722
723         } else if (rep->msg_type != DHCPV6_MSG_REPLY)
724                 return false;
725
726         uint8_t *end = ((uint8_t*)buf) + len, *odata = NULL,
727                 rcmsg = DHCPV6_MSG_UNKNOWN;
728         uint16_t otype, olen = UINT16_MAX;
729         bool clientid_ok = false, serverid_ok = false, rcauth_ok = false,
730                 ia_present = false, options_valid = true;
731
732         size_t client_id_len, server_id_len;
733         void *client_id = odhcp6c_get_state(STATE_CLIENT_ID, &client_id_len);
734         void *server_id = odhcp6c_get_state(STATE_SERVER_ID, &server_id_len);
735
736         dhcpv6_for_each_option(&rep[1], end, otype, olen, odata) {
737                 if (otype == DHCPV6_OPT_CLIENTID) {
738                         clientid_ok = (olen + 4U == client_id_len) && !memcmp(
739                                         &odata[-4], client_id, client_id_len);
740                 } else if (otype == DHCPV6_OPT_SERVERID) {
741                         if (server_id_len)
742                                 serverid_ok = (olen + 4U == server_id_len) && !memcmp(
743                                                 &odata[-4], server_id, server_id_len);
744                         else
745                                 serverid_ok = true;
746                 } else if (otype == DHCPV6_OPT_AUTH && olen == -4 +
747                                 sizeof(struct dhcpv6_auth_reconfigure)) {
748                         struct dhcpv6_auth_reconfigure *r = (void*)&odata[-4];
749                         if (r->protocol != 3 || r->algorithm != 1 || r->reconf_type != 2)
750                                 continue;
751
752                         md5_ctx_t md5;
753                         uint8_t serverhash[16], secretbytes[64];
754                         uint32_t hash[4];
755                         memcpy(serverhash, r->key, sizeof(serverhash));
756                         memset(r->key, 0, sizeof(r->key));
757
758                         memset(secretbytes, 0, sizeof(secretbytes));
759                         memcpy(secretbytes, reconf_key, sizeof(reconf_key));
760
761                         for (size_t i = 0; i < sizeof(secretbytes); ++i)
762                                 secretbytes[i] ^= 0x36;
763
764                         md5_begin(&md5);
765                         md5_hash(secretbytes, sizeof(secretbytes), &md5);
766                         md5_hash(buf, len, &md5);
767                         md5_end(hash, &md5);
768
769                         for (size_t i = 0; i < sizeof(secretbytes); ++i) {
770                                 secretbytes[i] ^= 0x36;
771                                 secretbytes[i] ^= 0x5c;
772                         }
773
774                         md5_begin(&md5);
775                         md5_hash(secretbytes, sizeof(secretbytes), &md5);
776                         md5_hash(hash, 16, &md5);
777                         md5_end(hash, &md5);
778
779                         rcauth_ok = !memcmp(hash, serverhash, sizeof(hash));
780                 } else if (otype == DHCPV6_OPT_RECONF_MESSAGE && olen == 1) {
781                         rcmsg = odata[0];
782                 } else if ((otype == DHCPV6_OPT_IA_PD || otype == DHCPV6_OPT_IA_NA)) {
783                         ia_present = true;
784                         if (olen < -4 + sizeof(struct dhcpv6_ia_hdr))
785                                 options_valid = false;
786                 } else if ((otype == DHCPV6_OPT_IA_ADDR) || (otype == DHCPV6_OPT_IA_PREFIX) ||
787                                 (otype == DHCPV6_OPT_PD_EXCLUDE))
788                         // Options are not allowed on global level
789                         options_valid = false;
790         }
791
792         if (!options_valid || ((odata + olen) > end))
793                 return false;
794
795         if (type == DHCPV6_MSG_INFO_REQ && ia_present)
796                 return false;
797
798         if (rep->msg_type == DHCPV6_MSG_RECONF) {
799                 if ((rcmsg != DHCPV6_MSG_RENEW && rcmsg != DHCPV6_MSG_REBIND && rcmsg != DHCPV6_MSG_INFO_REQ) ||
800                         (rcmsg == DHCPV6_MSG_INFO_REQ && ia_present) ||
801                         !rcauth_ok || IN6_IS_ADDR_MULTICAST(daddr))
802                         return false;
803         }
804
805         return clientid_ok && serverid_ok;
806 }
807
808 int dhcpv6_poll_reconfigure(void)
809 {
810         int ret = dhcpv6_request(DHCPV6_MSG_UNKNOWN);
811
812         if (ret != -1)
813                 ret = dhcpv6_request(ret);
814
815         return ret;
816 }
817
818 static int dhcpv6_handle_reconfigure(enum dhcpv6_msg orig, const int rc,
819                 const void *opt, const void *end, _unused const struct sockaddr_in6 *from)
820 {
821         uint16_t otype, olen;
822         uint8_t *odata;
823         int msg = -1;
824
825         dhcpv6_for_each_option(opt, end, otype, olen, odata) {
826                 if (otype == DHCPV6_OPT_RECONF_MESSAGE && olen == 1) {
827                         switch (odata[0]) {
828                         case DHCPV6_MSG_REBIND:
829                                 if (t2 != UINT32_MAX)
830                                         t2 = 0;
831                         // Fall through
832                         case DHCPV6_MSG_RENEW:
833                                 if (t1 != UINT32_MAX)
834                                         t1 = 0;
835                         // Fall through
836                         case DHCPV6_MSG_INFO_REQ:
837                                 msg = odata[0];
838                                 break;
839
840                         default:
841                                 break;
842                         }
843                 }
844         }
845
846         dhcpv6_handle_reply(orig, rc, NULL, NULL, NULL);
847
848         return msg;
849 }
850
851 // Collect all advertised servers
852 static int dhcpv6_handle_advert(enum dhcpv6_msg orig, const int rc,
853                 const void *opt, const void *end, _unused const struct sockaddr_in6 *from)
854 {
855         uint16_t olen, otype;
856         uint8_t *odata, pref = 0;
857         struct dhcpv6_server_cand cand = {false, false, 0, 0, {0},
858                                         IN6ADDR_ANY_INIT, DHCPV6_SOL_MAX_RT,
859                                         DHCPV6_INF_MAX_RT, NULL, NULL, 0, 0};
860         bool have_na = false;
861         int have_pd = 0;
862
863         dhcpv6_for_each_option(opt, end, otype, olen, odata) {
864                 if (orig == DHCPV6_MSG_SOLICIT &&
865                                 (otype == DHCPV6_OPT_IA_PD || otype == DHCPV6_OPT_IA_NA) &&
866                                 olen > -4 + sizeof(struct dhcpv6_ia_hdr)) {
867                         struct dhcpv6_ia_hdr *ia_hdr = (void*)(&odata[-4]);
868                         dhcpv6_parse_ia(ia_hdr, odata + olen + sizeof(*ia_hdr));
869                 }
870
871                 if (otype == DHCPV6_OPT_SERVERID && olen <= 130) {
872                         memcpy(cand.duid, odata, olen);
873                         cand.duid_len = olen;
874                 } else if (otype == DHCPV6_OPT_PREF && olen >= 1 &&
875                                 cand.preference >= 0) {
876                         cand.preference = pref = odata[0];
877                 } else if (otype == DHCPV6_OPT_UNICAST && olen == sizeof(cand.server_addr)) {
878                         if (!(client_options & DHCPV6_IGNORE_OPT_UNICAST))
879                                 cand.server_addr = *(struct in6_addr *)odata;
880
881                 } else if (otype == DHCPV6_OPT_RECONF_ACCEPT) {
882                         cand.wants_reconfigure = true;
883                 } else if (otype == DHCPV6_OPT_SOL_MAX_RT && olen == 4) {
884                         uint32_t sol_max_rt = ntohl_unaligned(odata);
885                         if (sol_max_rt >= DHCPV6_SOL_MAX_RT_MIN &&
886                                         sol_max_rt <= DHCPV6_SOL_MAX_RT_MAX)
887                                 cand.sol_max_rt = sol_max_rt;
888
889                 } else if (otype == DHCPV6_OPT_INF_MAX_RT && olen == 4) {
890                         uint32_t inf_max_rt = ntohl_unaligned(odata);
891                         if (inf_max_rt >= DHCPV6_INF_MAX_RT_MIN &&
892                                         inf_max_rt <= DHCPV6_INF_MAX_RT_MAX)
893                                 cand.inf_max_rt = inf_max_rt;
894
895                 } else if (otype == DHCPV6_OPT_IA_PD &&
896                                         olen >= -4 + sizeof(struct dhcpv6_ia_hdr)) {
897                         struct dhcpv6_ia_hdr *h = (struct dhcpv6_ia_hdr*)&odata[-4];
898                         uint8_t *oend = odata + olen, *d;
899                         dhcpv6_for_each_option(&h[1], oend, otype, olen, d) {
900                                 if (otype == DHCPV6_OPT_IA_PREFIX &&
901                                                 olen >= -4 + sizeof(struct dhcpv6_ia_prefix)) {
902                                         struct dhcpv6_ia_prefix *p = (struct dhcpv6_ia_prefix*)&d[-4];
903                                         have_pd = p->prefix;
904                                 }
905                         }
906                 } else if (otype == DHCPV6_OPT_IA_NA &&
907                                         olen >= -4 + sizeof(struct dhcpv6_ia_hdr)) {
908                         struct dhcpv6_ia_hdr *h = (struct dhcpv6_ia_hdr*)&odata[-4];
909                         uint8_t *oend = odata + olen, *d;
910
911                         dhcpv6_for_each_option(&h[1], oend, otype, olen, d) {
912                                 if (otype == DHCPV6_OPT_IA_ADDR &&
913                                                 olen >= -4 + sizeof(struct dhcpv6_ia_addr))
914                                         have_na = true;
915                         }
916                 }
917         }
918
919         if ((!have_na && na_mode == IA_MODE_FORCE) ||
920                         (!have_pd && pd_mode == IA_MODE_FORCE)) {
921                 /*
922                  * RFC7083 states to process the SOL_MAX_RT and
923                  * INF_MAX_RT options even if the DHCPv6 server
924                  * did not propose any IA_NA and/or IA_PD
925                  */
926                 dhcpv6_retx[DHCPV6_MSG_SOLICIT].max_timeo = cand.sol_max_rt;
927                 dhcpv6_retx[DHCPV6_MSG_INFO_REQ].max_timeo = cand.inf_max_rt;
928                 return -1;
929         }
930
931         if (na_mode != IA_MODE_NONE && !have_na) {
932                 cand.has_noaddravail = true;
933                 cand.preference -= 1000;
934         }
935
936         if (pd_mode != IA_MODE_NONE) {
937                 if (have_pd)
938                         cand.preference += 2000 + (128 - have_pd);
939                 else
940                         cand.preference -= 2000;
941         }
942
943         if (cand.duid_len > 0) {
944                 cand.ia_na = odhcp6c_move_state(STATE_IA_NA, &cand.ia_na_len);
945                 cand.ia_pd = odhcp6c_move_state(STATE_IA_PD, &cand.ia_pd_len);
946                 dhcpv6_add_server_cand(&cand);
947         }
948
949         return (rc > 1 || (pref == 255 && cand.preference > 0)) ? 1 : -1;
950 }
951
952 static int dhcpv6_commit_advert(void)
953 {
954         return dhcpv6_promote_server_cand();
955 }
956
957 static int dhcpv6_handle_rebind_reply(enum dhcpv6_msg orig, const int rc,
958                 const void *opt, const void *end, const struct sockaddr_in6 *from)
959 {
960         dhcpv6_handle_advert(orig, rc, opt, end, from);
961         if (dhcpv6_commit_advert() < 0)
962                 return -1;
963
964         return dhcpv6_handle_reply(orig, rc, opt, end, from);
965 }
966
967 static int dhcpv6_handle_reply(enum dhcpv6_msg orig, _unused const int rc,
968                 const void *opt, const void *end, const struct sockaddr_in6 *from)
969 {
970         uint8_t *odata;
971         uint16_t otype, olen;
972         uint32_t refresh = 86400;
973         int ret = 1;
974         unsigned int updated_IAs = 0;
975         bool handled_status_codes[_DHCPV6_Status_Max] = { false, };
976
977         odhcp6c_expire();
978
979         if (orig == DHCPV6_MSG_UNKNOWN) {
980                 static time_t last_update = 0;
981                 time_t now = odhcp6c_get_milli_time() / 1000;
982
983                 uint32_t elapsed = (last_update > 0) ? now - last_update : 0;
984                 last_update = now;
985
986                 if (t1 != UINT32_MAX)
987                         t1 -= elapsed;
988
989                 if (t2 != UINT32_MAX)
990                         t2 -= elapsed;
991
992                 if (t3 != UINT32_MAX)
993                         t3 -= elapsed;
994
995                 if (t1 < 0)
996                         t1 = 0;
997
998                 if (t2 < 0)
999                         t2 = 0;
1000
1001                 if (t3 < 0)
1002                         t3 = 0;
1003         }
1004
1005         if (orig == DHCPV6_MSG_REQUEST && !odhcp6c_is_bound()) {
1006                 // Delete NA and PD we have in the state from the Advert
1007                 odhcp6c_clear_state(STATE_IA_NA);
1008                 odhcp6c_clear_state(STATE_IA_PD);
1009         }
1010
1011         if (opt) {
1012                 odhcp6c_clear_state(STATE_DNS);
1013                 odhcp6c_clear_state(STATE_SEARCH);
1014                 odhcp6c_clear_state(STATE_SNTP_IP);
1015                 odhcp6c_clear_state(STATE_NTP_IP);
1016                 odhcp6c_clear_state(STATE_NTP_FQDN);
1017                 odhcp6c_clear_state(STATE_SIP_IP);
1018                 odhcp6c_clear_state(STATE_SIP_FQDN);
1019                 odhcp6c_clear_state(STATE_AFTR_NAME);
1020                 odhcp6c_clear_state(STATE_CER);
1021                 odhcp6c_clear_state(STATE_S46_MAPT);
1022                 odhcp6c_clear_state(STATE_S46_MAPE);
1023                 odhcp6c_clear_state(STATE_S46_LW);
1024                 odhcp6c_clear_state(STATE_PASSTHRU);
1025                 odhcp6c_clear_state(STATE_CUSTOM_OPTS);
1026
1027                 // Parse and find all matching IAs
1028                 dhcpv6_for_each_option(opt, end, otype, olen, odata) {
1029                         struct odhcp6c_opt *dopt = odhcp6c_find_opt(otype);
1030
1031                         if ((otype == DHCPV6_OPT_IA_PD || otype == DHCPV6_OPT_IA_NA)
1032                                         && olen > -4 + sizeof(struct dhcpv6_ia_hdr)) {
1033                                 struct dhcpv6_ia_hdr *ia_hdr = (void*)(&odata[-4]);
1034
1035                                 if ((na_mode == IA_MODE_NONE && otype == DHCPV6_OPT_IA_NA) ||
1036                                         (pd_mode == IA_MODE_NONE && otype == DHCPV6_OPT_IA_PD))
1037                                         continue;
1038
1039                                 // Test ID
1040                                 if (ia_hdr->iaid != htonl(1) && otype == DHCPV6_OPT_IA_NA)
1041                                         continue;
1042
1043                                 uint16_t code = DHCPV6_Success;
1044                                 uint16_t stype, slen;
1045                                 uint8_t *sdata;
1046                                 // Get and handle status code
1047                                 dhcpv6_for_each_option(&ia_hdr[1], odata + olen,
1048                                                 stype, slen, sdata) {
1049                                         if (stype == DHCPV6_OPT_STATUS && slen >= 2) {
1050                                                 uint8_t *mdata = (slen > 2) ? &sdata[2] : NULL;
1051                                                 uint16_t mlen = (slen > 2) ? slen - 2 : 0;
1052
1053                                                 code = ((int)sdata[0]) << 8 | ((int)sdata[1]);
1054
1055                                                 if (code == DHCPV6_Success)
1056                                                         continue;
1057
1058                                                 dhcpv6_handle_ia_status_code(orig, ia_hdr,
1059                                                         code, mdata, mlen, handled_status_codes, &ret);
1060
1061                                                 if (ret > 0)
1062                                                         return ret;
1063
1064                                                 break;
1065                                         }
1066                                 }
1067
1068                                 if (code != DHCPV6_Success)
1069                                         continue;
1070
1071                                 updated_IAs += dhcpv6_parse_ia(ia_hdr, odata + olen);
1072                         } else if (otype == DHCPV6_OPT_UNICAST && olen == sizeof(server_addr)) {
1073                                 if (!(client_options & DHCPV6_IGNORE_OPT_UNICAST))
1074                                         server_addr = *(struct in6_addr *)odata;
1075
1076                         }
1077                         else if (otype == DHCPV6_OPT_STATUS && olen >= 2) {
1078                                 uint8_t *mdata = (olen > 2) ? &odata[2] : NULL;
1079                                 uint16_t mlen = (olen > 2) ? olen - 2 : 0;
1080                                 uint16_t code = ((int)odata[0]) << 8 | ((int)odata[1]);
1081
1082                                 dhcpv6_handle_status_code(orig, code, mdata, mlen, &ret);
1083                         } else if (otype == DHCPV6_OPT_DNS_SERVERS) {
1084                                 if (olen % 16 == 0)
1085                                         odhcp6c_add_state(STATE_DNS, odata, olen);
1086                         } else if (otype == DHCPV6_OPT_DNS_DOMAIN)
1087                                 odhcp6c_add_state(STATE_SEARCH, odata, olen);
1088                         else if (otype == DHCPV6_OPT_SNTP_SERVERS) {
1089                                 if (olen % 16 == 0)
1090                                         odhcp6c_add_state(STATE_SNTP_IP, odata, olen);
1091                         } else if (otype == DHCPV6_OPT_NTP_SERVER) {
1092                                 uint16_t stype, slen;
1093                                 uint8_t *sdata;
1094                                 // Test status and bail if error
1095                                 dhcpv6_for_each_option(odata, odata + olen,
1096                                                 stype, slen, sdata) {
1097                                         if (slen == 16 && (stype == NTP_MC_ADDR ||
1098                                                         stype == NTP_SRV_ADDR))
1099                                                 odhcp6c_add_state(STATE_NTP_IP,
1100                                                                 sdata, slen);
1101                                         else if (slen > 0 && stype == NTP_SRV_FQDN)
1102                                                 odhcp6c_add_state(STATE_NTP_FQDN,
1103                                                                 sdata, slen);
1104                                 }
1105                         } else if (otype == DHCPV6_OPT_SIP_SERVER_A) {
1106                                 if (olen == 16)
1107                                         odhcp6c_add_state(STATE_SIP_IP, odata, olen);
1108                         } else if (otype == DHCPV6_OPT_SIP_SERVER_D)
1109                                 odhcp6c_add_state(STATE_SIP_FQDN, odata, olen);
1110                         else if (otype == DHCPV6_OPT_INFO_REFRESH && olen >= 4) {
1111                                 refresh = ntohl_unaligned(odata);
1112                         } else if (otype == DHCPV6_OPT_AUTH) {
1113                                 if (olen == -4 + sizeof(struct dhcpv6_auth_reconfigure)) {
1114                                         struct dhcpv6_auth_reconfigure *r = (void*)&odata[-4];
1115                                         if (r->protocol == 3 && r->algorithm == 1 &&
1116                                                         r->reconf_type == 1)
1117                                                 memcpy(reconf_key, r->key, sizeof(r->key));
1118                                 }
1119                         } else if (otype == DHCPV6_OPT_AFTR_NAME && olen > 3) {
1120                                 size_t cur_len;
1121                                 odhcp6c_get_state(STATE_AFTR_NAME, &cur_len);
1122                                 if (cur_len == 0)
1123                                         odhcp6c_add_state(STATE_AFTR_NAME, odata, olen);
1124                         } else if (otype == DHCPV6_OPT_SOL_MAX_RT && olen == 4) {
1125                                 uint32_t sol_max_rt = ntohl_unaligned(odata);
1126                                 if (sol_max_rt >= DHCPV6_SOL_MAX_RT_MIN &&
1127                                                 sol_max_rt <= DHCPV6_SOL_MAX_RT_MAX)
1128                                         dhcpv6_retx[DHCPV6_MSG_SOLICIT].max_timeo = sol_max_rt;
1129                         } else if (otype == DHCPV6_OPT_INF_MAX_RT && olen == 4) {
1130                                 uint32_t inf_max_rt = ntohl_unaligned(odata);
1131                                 if (inf_max_rt >= DHCPV6_INF_MAX_RT_MIN &&
1132                                                 inf_max_rt <= DHCPV6_INF_MAX_RT_MAX)
1133                                         dhcpv6_retx[DHCPV6_MSG_INFO_REQ].max_timeo = inf_max_rt;
1134         #ifdef EXT_CER_ID
1135                         } else if (otype == DHCPV6_OPT_CER_ID && olen == -4 +
1136                                         sizeof(struct dhcpv6_cer_id)) {
1137                                 struct dhcpv6_cer_id *cer_id = (void*)&odata[-4];
1138                                 struct in6_addr any = IN6ADDR_ANY_INIT;
1139                                 if (memcmp(&cer_id->addr, &any, sizeof(any)))
1140                                         odhcp6c_add_state(STATE_CER, &cer_id->addr, sizeof(any));
1141         #endif
1142                         } else if (otype == DHCPV6_OPT_S46_CONT_MAPT) {
1143                                 odhcp6c_add_state(STATE_S46_MAPT, odata, olen);
1144                         } else if (otype == DHCPV6_OPT_S46_CONT_MAPE) {
1145                                 size_t mape_len;
1146                                 odhcp6c_get_state(STATE_S46_MAPE, &mape_len);
1147                                 if (mape_len == 0)
1148                                         odhcp6c_add_state(STATE_S46_MAPE, odata, olen);
1149                         } else if (otype == DHCPV6_OPT_S46_CONT_LW) {
1150                                 odhcp6c_add_state(STATE_S46_LW, odata, olen);
1151                         } else
1152                                 odhcp6c_add_state(STATE_CUSTOM_OPTS, &odata[-4], olen + 4);
1153
1154                         if (!dopt || !(dopt->flags & OPT_NO_PASSTHRU))
1155                                 odhcp6c_add_state(STATE_PASSTHRU, &odata[-4], olen + 4);
1156                 }
1157         }
1158
1159         switch (orig) {
1160         case DHCPV6_MSG_REQUEST:
1161         case DHCPV6_MSG_REBIND:
1162         case DHCPV6_MSG_RENEW:
1163                 // Update refresh timers if no fatal status code was received
1164                 if ((ret > 0) && (ret = dhcpv6_calc_refresh_timers())) {
1165                         if (orig == DHCPV6_MSG_REQUEST) {
1166                                 // All server candidates can be cleared if not yet bound
1167                                 if (!odhcp6c_is_bound())
1168                                         dhcpv6_clear_all_server_cand();
1169
1170                                 odhcp6c_clear_state(STATE_SERVER_ADDR);
1171                                 odhcp6c_add_state(STATE_SERVER_ADDR, &from->sin6_addr, 16);
1172                         } else if (orig == DHCPV6_MSG_RENEW) {
1173                                 // Send further renews if T1 is not set and
1174                                 // no updated IAs
1175                                 if (!t1) {
1176                                         if (!updated_IAs)
1177                                                 ret = -1;
1178                                         else if ((t2 - t1) > 1)
1179                                                 // Grace period of 1 second
1180                                                 t1 = 1;
1181                                 }
1182
1183                         } else if (orig == DHCPV6_MSG_REBIND) {
1184                                 // Send further rebinds if T1 and T2 is not set and
1185                                 // no updated IAs
1186                                 if (!t1 && !t2) {
1187                                         if (!updated_IAs)
1188                                                 ret = -1;
1189                                         else if ((t3 - t2) > 1)
1190                                                 // Grace period of 1 second
1191                                                 t2 = 1;
1192                                 }
1193
1194                                 odhcp6c_clear_state(STATE_SERVER_ADDR);
1195                                 odhcp6c_add_state(STATE_SERVER_ADDR, &from->sin6_addr, 16);
1196                         }
1197                 }
1198                 break;
1199
1200         case DHCPV6_MSG_INFO_REQ:
1201                 if (ret > 0) {
1202                         // All server candidates can be cleared if not yet bound
1203                         if (!odhcp6c_is_bound())
1204                                 dhcpv6_clear_all_server_cand();
1205
1206                         t1 = refresh;
1207                 }
1208                 break;
1209
1210         default:
1211                 break;
1212         }
1213
1214         return ret;
1215 }
1216
1217 static unsigned int dhcpv6_parse_ia(void *opt, void *end)
1218 {
1219         struct dhcpv6_ia_hdr *ia_hdr = (struct dhcpv6_ia_hdr *)opt;
1220         unsigned int updated_IAs = 0;
1221         uint32_t t1, t2;
1222         uint16_t otype, olen;
1223         uint8_t *odata;
1224
1225         t1 = ntohl(ia_hdr->t1);
1226         t2 = ntohl(ia_hdr->t2);
1227
1228         if (t1 > t2)
1229                 return 0;
1230
1231         // Update address IA
1232         dhcpv6_for_each_option(&ia_hdr[1], end, otype, olen, odata) {
1233                 struct odhcp6c_entry entry = {IN6ADDR_ANY_INIT, 0, 0, 0,
1234                                 IN6ADDR_ANY_INIT, 0, 0, 0, 0, 0};
1235
1236                 entry.iaid = ia_hdr->iaid;
1237
1238                 if (otype == DHCPV6_OPT_IA_PREFIX) {
1239                         struct dhcpv6_ia_prefix *prefix = (void*)&odata[-4];
1240                         if (olen + 4U < sizeof(*prefix))
1241                                 continue;
1242
1243                         entry.valid = ntohl(prefix->valid);
1244                         entry.preferred = ntohl(prefix->preferred);
1245
1246                         if (entry.preferred > entry.valid)
1247                                 continue;
1248
1249                         entry.t1 = (t1 ? t1 : (entry.preferred != UINT32_MAX ? 0.5 * entry.preferred : UINT32_MAX));
1250                         entry.t2 = (t2 ? t2 : (entry.preferred != UINT32_MAX ? 0.8 * entry.preferred : UINT32_MAX));
1251                         if (entry.t1 > entry.t2)
1252                                 entry.t1 = entry.t2;
1253
1254                         entry.length = prefix->prefix;
1255                         entry.target = prefix->addr;
1256                         uint16_t stype, slen;
1257                         uint8_t *sdata;
1258
1259                         // Parse PD-exclude
1260                         bool ok = true;
1261                         dhcpv6_for_each_option(odata + sizeof(*prefix) - 4U,
1262                                         odata + olen, stype, slen, sdata) {
1263                                 if (stype != DHCPV6_OPT_PD_EXCLUDE || slen < 2)
1264                                         continue;
1265
1266                                 uint8_t elen = sdata[0];
1267                                 if (elen > 64)
1268                                         elen = 64;
1269
1270                                 if (entry.length < 32 || elen <= entry.length) {
1271                                         ok = false;
1272                                         continue;
1273                                 }
1274
1275                                 uint8_t bytes = ((elen - entry.length - 1) / 8) + 1;
1276                                 if (slen <= bytes) {
1277                                         ok = false;
1278                                         continue;
1279                                 }
1280
1281                                 uint32_t exclude = 0;
1282                                 do {
1283                                         exclude = exclude << 8 | sdata[bytes];
1284                                 } while (--bytes);
1285
1286                                 exclude >>= 8 - ((elen - entry.length) % 8);
1287                                 exclude <<= 64 - elen;
1288
1289                                 // Abusing router & priority fields for exclusion
1290                                 entry.router = entry.target;
1291                                 entry.router.s6_addr32[1] |= htonl(exclude);
1292                                 entry.priority = elen;
1293                         }
1294
1295                         if (ok) {
1296                                 if (odhcp6c_update_entry(STATE_IA_PD, &entry, 0, 0))
1297                                         updated_IAs++;
1298                         }
1299
1300                         entry.priority = 0;
1301                         memset(&entry.router, 0, sizeof(entry.router));
1302                 } else if (otype == DHCPV6_OPT_IA_ADDR) {
1303                         struct dhcpv6_ia_addr *addr = (void*)&odata[-4];
1304                         if (olen + 4U < sizeof(*addr))
1305                                 continue;
1306
1307                         entry.preferred = ntohl(addr->preferred);
1308                         entry.valid = ntohl(addr->valid);
1309
1310                         if (entry.preferred > entry.valid)
1311                                 continue;
1312
1313                         entry.t1 = (t1 ? t1 : (entry.preferred != UINT32_MAX ? 0.5 * entry.preferred : UINT32_MAX));
1314                         entry.t2 = (t2 ? t2 : (entry.preferred != UINT32_MAX ? 0.8 * entry.preferred : UINT32_MAX));
1315                         if (entry.t1 > entry.t2)
1316                                 entry.t1 = entry.t2;
1317
1318                         entry.length = 128;
1319                         entry.target = addr->addr;
1320
1321                         if (odhcp6c_update_entry(STATE_IA_NA, &entry, 0, 0))
1322                                 updated_IAs++;
1323                 }
1324         }
1325         return updated_IAs;
1326 }
1327
1328 static int dhcpv6_calc_refresh_timers(void)
1329 {
1330         struct odhcp6c_entry *e;
1331         size_t ia_na_entries, ia_pd_entries, i;
1332         int64_t l_t1 = UINT32_MAX, l_t2 = UINT32_MAX, l_t3 = 0;
1333
1334         e = odhcp6c_get_state(STATE_IA_NA, &ia_na_entries);
1335         ia_na_entries /= sizeof(*e);
1336
1337         for (i = 0; i < ia_na_entries; i++) {
1338                 if (e[i].t1 < l_t1)
1339                         l_t1 = e[i].t1;
1340
1341                 if (e[i].t2 < l_t2)
1342                         l_t2 = e[i].t2;
1343
1344                 if (e[i].valid > l_t3)
1345                         l_t3 = e[i].valid;
1346         }
1347
1348         e = odhcp6c_get_state(STATE_IA_PD, &ia_pd_entries);
1349         ia_pd_entries /= sizeof(*e);
1350
1351         for (i = 0; i < ia_pd_entries; i++) {
1352                 if (e[i].t1 < l_t1)
1353                         l_t1 = e[i].t1;
1354
1355                 if (e[i].t2 < l_t2)
1356                         l_t2 = e[i].t2;
1357
1358                 if (e[i].valid > l_t3)
1359                         l_t3 = e[i].valid;
1360         }
1361
1362         if (ia_pd_entries || ia_na_entries) {
1363                 t1 = l_t1;
1364                 t2 = l_t2;
1365                 t3 = l_t3;
1366         }
1367
1368         return (int)(ia_pd_entries + ia_na_entries);
1369 }
1370
1371 static void dhcpv6_log_status_code(const uint16_t code, const char *scope,
1372                 const void *status_msg, int len)
1373 {
1374         const char *src = status_msg;
1375         char buf[len + 3];
1376         char *dst = buf;
1377
1378         if (len) {
1379                 *dst++ = '(';
1380                 while (len--) {
1381                         *dst = isprint((unsigned char)*src) ? *src : '?';
1382                         src++;
1383                         dst++;
1384                 }
1385                 *dst++ = ')';
1386         }
1387
1388         *dst = 0;
1389
1390         syslog(LOG_WARNING, "Server returned %s status %i %s",
1391                 scope, code, buf);
1392 }
1393
1394 static void dhcpv6_handle_status_code(const enum dhcpv6_msg orig,
1395                 const uint16_t code, const void *status_msg, const int len,
1396                 int *ret)
1397 {
1398         dhcpv6_log_status_code(code, "message", status_msg, len);
1399
1400         switch (code) {
1401         case DHCPV6_UnspecFail:
1402                 // Generic failure
1403                 *ret = 0;
1404                 break;
1405
1406         case DHCPV6_UseMulticast:
1407                 switch(orig) {
1408                 case DHCPV6_MSG_REQUEST:
1409                 case DHCPV6_MSG_RENEW:
1410                 case DHCPV6_MSG_RELEASE:
1411                 case DHCPV6_MSG_DECLINE:
1412                         // Message needs to be retransmitted according to RFC3315 chapter 18.1.8
1413                         server_addr = in6addr_any;
1414                         *ret = 0;
1415                         break;
1416                 default:
1417                         break;
1418                 }
1419                 break;
1420
1421         case DHCPV6_NoAddrsAvail:
1422         case DHCPV6_NoPrefixAvail:
1423                 if (orig == DHCPV6_MSG_REQUEST)
1424                         *ret = 0; // Failure
1425                 break;
1426
1427         default:
1428                 break;
1429         }
1430 }
1431
1432 static void dhcpv6_handle_ia_status_code(const enum dhcpv6_msg orig,
1433                 const struct dhcpv6_ia_hdr *ia_hdr, const uint16_t code,
1434                 const void *status_msg, const int len,
1435                 bool handled_status_codes[_DHCPV6_Status_Max], int *ret)
1436 {
1437         dhcpv6_log_status_code(code, ia_hdr->type == DHCPV6_OPT_IA_NA ?
1438                 "IA_NA" : "IA_PD", status_msg, len);
1439
1440         switch (code) {
1441         case DHCPV6_NoBinding:
1442                 switch (orig) {
1443                 case DHCPV6_MSG_RENEW:
1444                 case DHCPV6_MSG_REBIND:
1445                         if ((*ret > 0) && !handled_status_codes[code])
1446                                 *ret = dhcpv6_request(DHCPV6_MSG_REQUEST);
1447                         break;
1448
1449                 default:
1450                         break;
1451                 }
1452                 break;
1453
1454         default:
1455                 *ret = 0;
1456                 break;
1457         }
1458 }
1459
1460 // Note this always takes ownership of cand->ia_na and cand->ia_pd
1461 static void dhcpv6_add_server_cand(const struct dhcpv6_server_cand *cand)
1462 {
1463         size_t cand_len, i;
1464         struct dhcpv6_server_cand *c = odhcp6c_get_state(STATE_SERVER_CAND, &cand_len);
1465
1466         // Remove identical duid server candidate
1467         for (i = 0; i < cand_len / sizeof(*c); ++i) {
1468                 if (cand->duid_len == c[i].duid_len &&
1469                                 !memcmp(cand->duid, c[i].duid, cand->duid_len)) {
1470                         free(c[i].ia_na);
1471                         free(c[i].ia_pd);
1472                         odhcp6c_remove_state(STATE_SERVER_CAND, i * sizeof(*c), sizeof(*c));
1473                         break;
1474                 }
1475         }
1476
1477         for (i = 0, c = odhcp6c_get_state(STATE_SERVER_CAND, &cand_len);
1478                 i < cand_len / sizeof(*c); ++i) {
1479                 if (c[i].preference < cand->preference)
1480                         break;
1481         }
1482
1483         if (odhcp6c_insert_state(STATE_SERVER_CAND, i * sizeof(*c), cand, sizeof(*cand))) {
1484                 free(cand->ia_na);
1485                 free(cand->ia_pd);
1486         }
1487 }
1488
1489 static void dhcpv6_clear_all_server_cand(void)
1490 {
1491         size_t cand_len, i;
1492         struct dhcpv6_server_cand *c = odhcp6c_get_state(STATE_SERVER_CAND, &cand_len);
1493
1494         // Server candidates need deep delete for IA_NA/IA_PD
1495         for (i = 0; i < cand_len / sizeof(*c); ++i) {
1496                 free(c[i].ia_na);
1497                 free(c[i].ia_pd);
1498         }
1499         odhcp6c_clear_state(STATE_SERVER_CAND);
1500 }
1501
1502 int dhcpv6_promote_server_cand(void)
1503 {
1504         size_t cand_len;
1505         struct dhcpv6_server_cand *cand = odhcp6c_get_state(STATE_SERVER_CAND, &cand_len);
1506         uint16_t hdr[2];
1507         int ret = DHCPV6_STATELESS;
1508
1509         // Clear lingering candidate state info
1510         odhcp6c_clear_state(STATE_SERVER_ID);
1511         odhcp6c_clear_state(STATE_IA_NA);
1512         odhcp6c_clear_state(STATE_IA_PD);
1513
1514         if (!cand_len)
1515                 return -1;
1516
1517         if (cand->has_noaddravail && na_mode == IA_MODE_TRY) {
1518                 na_mode = IA_MODE_NONE;
1519
1520                 dhcpv6_retx[DHCPV6_MSG_SOLICIT].max_timeo = cand->sol_max_rt;
1521                 dhcpv6_retx[DHCPV6_MSG_INFO_REQ].max_timeo = cand->inf_max_rt;
1522
1523                 return dhcpv6_request(DHCPV6_MSG_SOLICIT);
1524         }
1525
1526         hdr[0] = htons(DHCPV6_OPT_SERVERID);
1527         hdr[1] = htons(cand->duid_len);
1528         odhcp6c_add_state(STATE_SERVER_ID, hdr, sizeof(hdr));
1529         odhcp6c_add_state(STATE_SERVER_ID, cand->duid, cand->duid_len);
1530         accept_reconfig = cand->wants_reconfigure;
1531
1532         if (cand->ia_na_len) {
1533                 odhcp6c_add_state(STATE_IA_NA, cand->ia_na, cand->ia_na_len);
1534                 free(cand->ia_na);
1535                 if (na_mode != IA_MODE_NONE)
1536                         ret = DHCPV6_STATEFUL;
1537         }
1538
1539         if (cand->ia_pd_len) {
1540                 odhcp6c_add_state(STATE_IA_PD, cand->ia_pd, cand->ia_pd_len);
1541                 free(cand->ia_pd);
1542                 if (pd_mode != IA_MODE_NONE)
1543                         ret = DHCPV6_STATEFUL;
1544         }
1545
1546         dhcpv6_retx[DHCPV6_MSG_SOLICIT].max_timeo = cand->sol_max_rt;
1547         dhcpv6_retx[DHCPV6_MSG_INFO_REQ].max_timeo = cand->inf_max_rt;
1548
1549         odhcp6c_remove_state(STATE_SERVER_CAND, 0, sizeof(*cand));
1550
1551         return ret;
1552 }