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