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