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