Update to dhcpcd-9.1.0 with the following changes:
[dragonfly.git] / contrib / dhcpcd / src / dhcp6.c
1 /* SPDX-License-Identifier: BSD-2-Clause */
2 /*
3  * dhcpcd - DHCP client daemon
4  * Copyright (c) 2006-2020 Roy Marples <roy@marples.name>
5  * All rights reserved
6
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28
29 #include <sys/utsname.h>
30 #include <sys/types.h>
31
32 #include <netinet/in.h>
33 #include <netinet/ip6.h>
34
35 #include <assert.h>
36 #include <ctype.h>
37 #include <errno.h>
38 #include <fcntl.h>
39 #include <inttypes.h>
40 #include <stdbool.h>
41 #include <stddef.h>
42 #include <stdlib.h>
43 #include <string.h>
44 #include <unistd.h>
45 #include <fcntl.h>
46 #include <syslog.h>
47
48 #define ELOOP_QUEUE     ELOOP_DHCP6
49 #include "config.h"
50 #include "common.h"
51 #include "dhcp.h"
52 #include "dhcp6.h"
53 #include "duid.h"
54 #include "eloop.h"
55 #include "if.h"
56 #include "if-options.h"
57 #include "ipv6nd.h"
58 #include "logerr.h"
59 #include "privsep.h"
60 #include "script.h"
61
62 #ifdef HAVE_SYS_BITOPS_H
63 #include <sys/bitops.h>
64 #else
65 #include "compat/bitops.h"
66 #endif
67
68 /* DHCPCD Project has been assigned an IANA PEN of 40712 */
69 #define DHCPCD_IANA_PEN 40712
70
71 /* Unsure if I want this */
72 //#define VENDOR_SPLIT
73
74 /* Support older systems with different defines */
75 #if !defined(IPV6_RECVPKTINFO) && defined(IPV6_PKTINFO)
76 #define IPV6_RECVPKTINFO IPV6_PKTINFO
77 #endif
78
79 #ifdef DHCP6
80
81 /* Assert the correct structure size for on wire */
82 struct dhcp6_message {
83         uint8_t type;
84         uint8_t xid[3];
85         /* followed by options */
86 };
87 __CTASSERT(sizeof(struct dhcp6_message) == 4);
88
89 struct dhcp6_option {
90         uint16_t code;
91         uint16_t len;
92         /* followed by data */
93 };
94 __CTASSERT(sizeof(struct dhcp6_option) == 4);
95
96 struct dhcp6_ia_na {
97         uint8_t iaid[4];
98         uint32_t t1;
99         uint32_t t2;
100 };
101 __CTASSERT(sizeof(struct dhcp6_ia_na) == 12);
102
103 struct dhcp6_ia_ta {
104         uint8_t iaid[4];
105 };
106 __CTASSERT(sizeof(struct dhcp6_ia_ta) == 4);
107
108 struct dhcp6_ia_addr {
109         struct in6_addr addr;
110         uint32_t pltime;
111         uint32_t vltime;
112 };
113 __CTASSERT(sizeof(struct dhcp6_ia_addr) == 16 + 8);
114
115 /* XXX FIXME: This is the only packed structure and it does not align.
116  * Maybe manually decode it? */
117 struct dhcp6_pd_addr {
118         uint32_t pltime;
119         uint32_t vltime;
120         uint8_t prefix_len;
121         struct in6_addr prefix;
122 } __packed;
123 __CTASSERT(sizeof(struct dhcp6_pd_addr) == 8 + 1 + 16);
124
125 struct dhcp6_op {
126         uint16_t type;
127         const char *name;
128 };
129
130 static const struct dhcp6_op dhcp6_ops[] = {
131         { DHCP6_SOLICIT, "SOLICIT6" },
132         { DHCP6_ADVERTISE, "ADVERTISE6" },
133         { DHCP6_REQUEST, "REQUEST6" },
134         { DHCP6_REPLY, "REPLY6" },
135         { DHCP6_RENEW, "RENEW6" },
136         { DHCP6_REBIND, "REBIND6" },
137         { DHCP6_CONFIRM, "CONFIRM6" },
138         { DHCP6_INFORMATION_REQ, "INFORM6" },
139         { DHCP6_RELEASE, "RELEASE6" },
140         { DHCP6_RECONFIGURE, "RECONFIGURE6" },
141         { DHCP6_DECLINE, "DECLINE6" },
142         { 0, NULL }
143 };
144
145 struct dhcp_compat {
146         uint8_t dhcp_opt;
147         uint16_t dhcp6_opt;
148 };
149
150 const struct dhcp_compat dhcp_compats[] = {
151         { DHO_DNSSERVER,        D6_OPTION_DNS_SERVERS },
152         { DHO_HOSTNAME,         D6_OPTION_FQDN },
153         { DHO_DNSDOMAIN,        D6_OPTION_FQDN },
154         { DHO_NISSERVER,        D6_OPTION_NIS_SERVERS },
155         { DHO_NTPSERVER,        D6_OPTION_SNTP_SERVERS },
156         { DHO_RAPIDCOMMIT,      D6_OPTION_RAPID_COMMIT },
157         { DHO_FQDN,             D6_OPTION_FQDN },
158         { DHO_VIVCO,            D6_OPTION_VENDOR_CLASS },
159         { DHO_VIVSO,            D6_OPTION_VENDOR_OPTS },
160         { DHO_DNSSEARCH,        D6_OPTION_DOMAIN_LIST },
161         { 0, 0 }
162 };
163
164 static const char * const dhcp6_statuses[] = {
165         "Success",
166         "Unspecified Failure",
167         "No Addresses Available",
168         "No Binding",
169         "Not On Link",
170         "Use Multicast",
171         "No Prefix Available"
172 };
173
174 static void dhcp6_bind(struct interface *, const char *, const char *);
175 static void dhcp6_failinform(void *);
176 static void dhcp6_recvaddr(void *);
177 static void dhcp6_startdecline(struct interface *);
178
179 #ifdef SMALL
180 #define dhcp6_hasprefixdelegation(a)    (0)
181 #else
182 static int dhcp6_hasprefixdelegation(struct interface *);
183 #endif
184
185 #define DECLINE_IA(ia) \
186         ((ia)->addr_flags & IN6_IFF_DUPLICATED && \
187         (ia)->ia_type != 0 && (ia)->ia_type != D6_OPTION_IA_PD && \
188         !((ia)->flags & IPV6_AF_STALE) && \
189         (ia)->prefix_vltime != 0)
190
191 void
192 dhcp6_printoptions(const struct dhcpcd_ctx *ctx,
193     const struct dhcp_opt *opts, size_t opts_len)
194 {
195         size_t i, j;
196         const struct dhcp_opt *opt, *opt2;
197         int cols;
198
199         for (i = 0, opt = ctx->dhcp6_opts;
200             i < ctx->dhcp6_opts_len; i++, opt++)
201         {
202                 for (j = 0, opt2 = opts; j < opts_len; j++, opt2++)
203                         if (opt2->option == opt->option)
204                                 break;
205                 if (j == opts_len) {
206                         cols = printf("%05d %s", opt->option, opt->var);
207                         dhcp_print_option_encoding(opt, cols);
208                 }
209         }
210         for (i = 0, opt = opts; i < opts_len; i++, opt++) {
211                 cols = printf("%05d %s", opt->option, opt->var);
212                 dhcp_print_option_encoding(opt, cols);
213         }
214 }
215
216 static size_t
217 dhcp6_makeuser(void *data, const struct interface *ifp)
218 {
219         const struct if_options *ifo = ifp->options;
220         struct dhcp6_option o;
221         uint8_t *p;
222         const uint8_t *up, *ue;
223         uint16_t ulen, unlen;
224         size_t olen;
225
226         /* Convert the DHCPv4 user class option to DHCPv6 */
227         up = ifo->userclass;
228         ulen = *up++;
229         if (ulen == 0)
230                 return 0;
231
232         p = data;
233         olen = 0;
234         if (p != NULL)
235                 p += sizeof(o);
236
237         ue = up + ulen;
238         for (; up < ue; up += ulen) {
239                 ulen = *up++;
240                 olen += sizeof(ulen) + ulen;
241                 if (data == NULL)
242                         continue;
243                 unlen = htons(ulen);
244                 memcpy(p, &unlen, sizeof(unlen));
245                 p += sizeof(unlen);
246                 memcpy(p, up, ulen);
247                 p += ulen;
248         }
249         if (data != NULL) {
250                 o.code = htons(D6_OPTION_USER_CLASS);
251                 o.len = htons((uint16_t)olen);
252                 memcpy(data, &o, sizeof(o));
253         }
254
255         return sizeof(o) + olen;
256 }
257
258 static size_t
259 dhcp6_makevendor(void *data, const struct interface *ifp)
260 {
261         const struct if_options *ifo;
262         size_t len, vlen, i;
263         uint8_t *p;
264         const struct vivco *vivco;
265         struct dhcp6_option o;
266
267         ifo = ifp->options;
268         len = sizeof(uint32_t); /* IANA PEN */
269         if (ifo->vivco_en) {
270                 vlen = 0;
271                 for (i = 0, vivco = ifo->vivco;
272                     i < ifo->vivco_len;
273                     i++, vivco++)
274                         vlen += sizeof(uint16_t) + vivco->len;
275                 len += vlen;
276         } else if (ifo->vendorclassid[0] != '\0') {
277                 /* dhcpcd owns DHCPCD_IANA_PEN.
278                  * If you need your own string, get your own IANA PEN. */
279                 vlen = strlen(ifp->ctx->vendor);
280                 len += sizeof(uint16_t) + vlen;
281         } else
282                 return 0;
283
284         if (len > UINT16_MAX) {
285                 logerrx("%s: DHCPv6 Vendor Class too big", ifp->name);
286                 return 0;
287         }
288
289         if (data != NULL) {
290                 uint32_t pen;
291                 uint16_t hvlen;
292
293                 p = data;
294                 o.code = htons(D6_OPTION_VENDOR_CLASS);
295                 o.len = htons((uint16_t)len);
296                 memcpy(p, &o, sizeof(o));
297                 p += sizeof(o);
298                 pen = htonl(ifo->vivco_en ? ifo->vivco_en : DHCPCD_IANA_PEN);
299                 memcpy(p, &pen, sizeof(pen));
300                 p += sizeof(pen);
301
302                 if (ifo->vivco_en) {
303                         for (i = 0, vivco = ifo->vivco;
304                             i < ifo->vivco_len;
305                             i++, vivco++)
306                         {
307                                 hvlen = htons((uint16_t)vivco->len);
308                                 memcpy(p, &hvlen, sizeof(hvlen));
309                                 p += sizeof(hvlen);
310                                 memcpy(p, vivco->data, vivco->len);
311                                 p += vivco->len;
312                         }
313                 } else if (ifo->vendorclassid[0] != '\0') {
314                         hvlen = htons((uint16_t)vlen);
315                         memcpy(p, &hvlen, sizeof(hvlen));
316                         p += sizeof(hvlen);
317                         memcpy(p, ifp->ctx->vendor, vlen);
318                 }
319         }
320
321         return sizeof(o) + len;
322 }
323
324 static void *
325 dhcp6_findoption(void *data, size_t data_len, uint16_t code, uint16_t *len)
326 {
327         uint8_t *d;
328         struct dhcp6_option o;
329
330         code = htons(code);
331         for (d = data; data_len != 0; d += o.len, data_len -= o.len) {
332                 if (data_len < sizeof(o)) {
333                         errno = EINVAL;
334                         return NULL;
335                 }
336                 memcpy(&o, d, sizeof(o));
337                 d += sizeof(o);
338                 data_len -= sizeof(o);
339                 o.len = htons(o.len);
340                 if (data_len < o.len) {
341                         errno = EINVAL;
342                         return NULL;
343                 }
344                 if (o.code == code) {
345                         if (len != NULL)
346                                 *len = o.len;
347                         return d;
348                 }
349         }
350
351         errno = ENOENT;
352         return NULL;
353 }
354
355 static void *
356 dhcp6_findmoption(void *data, size_t data_len, uint16_t code,
357     uint16_t *len)
358 {
359         uint8_t *d;
360
361         if (data_len < sizeof(struct dhcp6_message)) {
362                 errno = EINVAL;
363                 return false;
364         }
365         d = data;
366         d += sizeof(struct dhcp6_message);
367         data_len -= sizeof(struct dhcp6_message);
368         return dhcp6_findoption(d, data_len, code, len);
369 }
370
371 static const uint8_t *
372 dhcp6_getoption(struct dhcpcd_ctx *ctx,
373     size_t *os, unsigned int *code, size_t *len,
374     const uint8_t *od, size_t ol, struct dhcp_opt **oopt)
375 {
376         struct dhcp6_option o;
377         size_t i;
378         struct dhcp_opt *opt;
379
380         if (od != NULL) {
381                 *os = sizeof(o);
382                 if (ol < *os) {
383                         errno = EINVAL;
384                         return NULL;
385                 }
386                 memcpy(&o, od, sizeof(o));
387                 *len = ntohs(o.len);
388                 if (*len > ol - *os) {
389                         errno = ERANGE;
390                         return NULL;
391                 }
392                 *code = ntohs(o.code);
393         }
394
395         *oopt = NULL;
396         for (i = 0, opt = ctx->dhcp6_opts;
397             i < ctx->dhcp6_opts_len; i++, opt++)
398         {
399                 if (opt->option == *code) {
400                         *oopt = opt;
401                         break;
402                 }
403         }
404
405         if (od != NULL)
406                 return od + sizeof(o);
407         return NULL;
408 }
409
410 static bool
411 dhcp6_updateelapsed(struct interface *ifp, struct dhcp6_message *m, size_t len)
412 {
413         uint8_t *opt;
414         uint16_t opt_len;
415         struct dhcp6_state *state;
416         struct timespec tv;
417         unsigned long long hsec;
418         uint16_t sec;
419
420         opt = dhcp6_findmoption(m, len, D6_OPTION_ELAPSED, &opt_len);
421         if (opt == NULL)
422                 return false;
423         if (opt_len != sizeof(sec)) {
424                 errno = EINVAL;
425                 return false;
426         }
427
428         state = D6_STATE(ifp);
429         clock_gettime(CLOCK_MONOTONIC, &tv);
430         if (state->RTC == 0) {
431                 /* An RTC of zero means we're the first message
432                  * out of the door, so the elapsed time is zero. */
433                 state->started = tv;
434                 hsec = 0;
435         } else {
436                 unsigned long long secs;
437                 unsigned int nsecs;
438
439                 secs = eloop_timespec_diff(&tv, &state->started, &nsecs);
440                 /* Elapsed time is measured in centiseconds.
441                  * We need to be sure it will not potentially overflow. */
442                 if (secs >= (UINT16_MAX / CSEC_PER_SEC) + 1)
443                         hsec = UINT16_MAX;
444                 else {
445                         hsec = (secs * CSEC_PER_SEC) +
446                             (nsecs / NSEC_PER_CSEC);
447                         if (hsec > UINT16_MAX)
448                                 hsec = UINT16_MAX;
449                 }
450         }
451         sec = htons((uint16_t)hsec);
452         memcpy(opt, &sec, sizeof(sec));
453         return true;
454 }
455
456 static void
457 dhcp6_newxid(const struct interface *ifp, struct dhcp6_message *m)
458 {
459         const struct interface *ifp1;
460         const struct dhcp6_state *state1;
461         uint32_t xid;
462
463         if (ifp->options->options & DHCPCD_XID_HWADDR &&
464             ifp->hwlen >= sizeof(xid))
465                 /* The lower bits are probably more unique on the network */
466                 memcpy(&xid, (ifp->hwaddr + ifp->hwlen) - sizeof(xid),
467                     sizeof(xid));
468         else {
469 again:
470                 xid = arc4random();
471         }
472
473         m->xid[0] = (xid >> 16) & 0xff;
474         m->xid[1] = (xid >> 8) & 0xff;
475         m->xid[2] = xid & 0xff;
476
477         /* Ensure it's unique */
478         TAILQ_FOREACH(ifp1, ifp->ctx->ifaces, next) {
479                 if (ifp == ifp1)
480                         continue;
481                 if ((state1 = D6_CSTATE(ifp1)) == NULL)
482                         continue;
483                 if (state1->send != NULL &&
484                     state1->send->xid[0] == m->xid[0] &&
485                     state1->send->xid[1] == m->xid[1] &&
486                     state1->send->xid[2] == m->xid[2])
487                         break;
488         }
489
490         if (ifp1 != NULL) {
491                 if (ifp->options->options & DHCPCD_XID_HWADDR &&
492                     ifp->hwlen >= sizeof(xid))
493                 {
494                         logerrx("%s: duplicate xid on %s",
495                             ifp->name, ifp1->name);
496                             return;
497                 }
498                 goto again;
499         }
500 }
501
502 #ifndef SMALL
503 static const struct if_sla *
504 dhcp6_findselfsla(struct interface *ifp)
505 {
506         size_t i, j;
507         struct if_ia *ia;
508
509         for (i = 0; i < ifp->options->ia_len; i++) {
510                 ia = &ifp->options->ia[i];
511                 if (ia->ia_type != D6_OPTION_IA_PD)
512                         continue;
513                 for (j = 0; j < ia->sla_len; j++) {
514                         if (strcmp(ia->sla[j].ifname, ifp->name) == 0)
515                                 return &ia->sla[j];
516                 }
517         }
518         return NULL;
519 }
520
521 static int
522 dhcp6_delegateaddr(struct in6_addr *addr, struct interface *ifp,
523     const struct ipv6_addr *prefix, const struct if_sla *sla, struct if_ia *ia)
524 {
525         struct dhcp6_state *state;
526         struct if_sla asla;
527         char sabuf[INET6_ADDRSTRLEN];
528         const char *sa;
529
530         state = D6_STATE(ifp);
531         if (state == NULL) {
532                 ifp->if_data[IF_DATA_DHCP6] = calloc(1, sizeof(*state));
533                 state = D6_STATE(ifp);
534                 if (state == NULL) {
535                         logerr(__func__);
536                         return -1;
537                 }
538
539                 TAILQ_INIT(&state->addrs);
540                 state->state = DH6S_DELEGATED;
541                 state->reason = "DELEGATED6";
542         }
543
544         if (sla == NULL || sla->sla_set == 0) {
545                 /* No SLA set, so make an assumption of
546                  * desired SLA and prefix length. */
547                 asla.sla = ifp->index;
548                 asla.prefix_len = 0;
549                 asla.sla_set = 0;
550                 sla = &asla;
551         } else if (sla->prefix_len == 0) {
552                 /* An SLA was given, but prefix length was not.
553                  * We need to work out a suitable prefix length for
554                  * potentially more than one interface. */
555                 asla.sla = sla->sla;
556                 asla.prefix_len = 0;
557                 asla.sla_set = 0;
558                 sla = &asla;
559         }
560
561         if (sla->prefix_len == 0) {
562                 uint32_t sla_max;
563                 int bits;
564
565                 if (ia->sla_max == 0) {
566                         const struct interface *ifi;
567
568                         sla_max = 0;
569                         TAILQ_FOREACH(ifi, ifp->ctx->ifaces, next) {
570                                 if (ifi->index > sla_max)
571                                         sla_max = ifi->index;
572                         }
573                 } else
574                         sla_max = ia->sla_max;
575
576                 bits = fls32(sla_max);
577
578                 if (prefix->prefix_len + bits > (int)UINT8_MAX)
579                         asla.prefix_len = UINT8_MAX;
580                 else {
581                         asla.prefix_len = (uint8_t)(prefix->prefix_len + bits);
582
583                         /* Make a 64 prefix by default, as this makes SLAAC
584                          * possible.
585                          * Otherwise round up to the nearest 4 bits. */
586                         if (asla.prefix_len <= 64)
587                                 asla.prefix_len = 64;
588                         else
589                                 asla.prefix_len =
590                                     (uint8_t)ROUNDUP4(asla.prefix_len);
591                 }
592
593 #define BIT(n) (1UL << (n))
594 #define BIT_MASK(len) (BIT(len) - 1)
595                 if (ia->sla_max == 0) {
596                         /* Work out the real sla_max from our bits used */
597                         bits = asla.prefix_len - prefix->prefix_len;
598                         /* Make static analysis happy.
599                          * Bits cannot be bigger than 32 thanks to fls32. */
600                         assert(bits <= 32);
601                         ia->sla_max = (uint32_t)BIT_MASK(bits);
602                 }
603         }
604
605         if (ipv6_userprefix(&prefix->prefix, prefix->prefix_len,
606                 sla->sla, addr, sla->prefix_len) == -1)
607         {
608                 sa = inet_ntop(AF_INET6, &prefix->prefix,
609                     sabuf, sizeof(sabuf));
610                 logerr("%s: invalid prefix %s/%d + %d/%d",
611                     ifp->name, sa, prefix->prefix_len,
612                     sla->sla, sla->prefix_len);
613                 return -1;
614         }
615
616         if (prefix->prefix_exclude_len &&
617             IN6_ARE_ADDR_EQUAL(addr, &prefix->prefix_exclude))
618         {
619                 sa = inet_ntop(AF_INET6, &prefix->prefix_exclude,
620                     sabuf, sizeof(sabuf));
621                 logerrx("%s: cannot delegate excluded prefix %s/%d",
622                     ifp->name, sa, prefix->prefix_exclude_len);
623                 return -1;
624         }
625
626         return sla->prefix_len;
627 }
628 #endif
629
630 static int
631 dhcp6_makemessage(struct interface *ifp)
632 {
633         struct dhcp6_state *state;
634         struct dhcp6_message *m;
635         struct dhcp6_option o;
636         uint8_t *p, *si, *unicast, IA;
637         size_t n, l, len, ml, hl;
638         uint8_t type;
639         uint16_t si_len, uni_len, n_options;
640         uint8_t *o_lenp;
641         struct if_options *ifo;
642         const struct dhcp_opt *opt, *opt2;
643         const struct ipv6_addr *ap;
644         char hbuf[HOSTNAME_MAX_LEN + 1];
645         const char *hostname;
646         int fqdn;
647         struct dhcp6_ia_na ia_na;
648         uint16_t ia_na_len;
649         struct if_ia *ifia;
650 #ifdef AUTH
651         uint16_t auth_len;
652 #endif
653         uint8_t duid[DUID_LEN];
654         size_t duid_len = 0;
655
656         state = D6_STATE(ifp);
657         if (state->send) {
658                 free(state->send);
659                 state->send = NULL;
660         }
661
662         ifo = ifp->options;
663         fqdn = ifo->fqdn;
664
665         if (fqdn == FQDN_DISABLE && ifo->options & DHCPCD_HOSTNAME) {
666                 /* We're sending the DHCPv4 hostname option, so send FQDN as
667                  * DHCPv6 has no FQDN option and DHCPv4 must not send
668                  * hostname and FQDN according to RFC4702 */
669                 fqdn = FQDN_BOTH;
670         }
671         if (fqdn != FQDN_DISABLE)
672                 hostname = dhcp_get_hostname(hbuf, sizeof(hbuf), ifo);
673         else
674                 hostname = NULL; /* appearse gcc */
675
676         /* Work out option size first */
677         n_options = 0;
678         len = 0;
679         si = NULL;
680         hl = 0; /* Appease gcc */
681         if (state->state != DH6S_RELEASE && state->state != DH6S_DECLINE) {
682                 for (l = 0, opt = ifp->ctx->dhcp6_opts;
683                     l < ifp->ctx->dhcp6_opts_len;
684                     l++, opt++)
685                 {
686                         for (n = 0, opt2 = ifo->dhcp6_override;
687                             n < ifo->dhcp6_override_len;
688                             n++, opt2++)
689                         {
690                                 if (opt->option == opt2->option)
691                                         break;
692                         }
693                         if (n < ifo->dhcp6_override_len)
694                                 continue;
695                         if (!DHC_REQOPT(opt, ifo->requestmask6, ifo->nomask6))
696                                 continue;
697                         n_options++;
698                         len += sizeof(o.len);
699                 }
700 #ifndef SMALL
701                 for (l = 0, opt = ifo->dhcp6_override;
702                     l < ifo->dhcp6_override_len;
703                     l++, opt++)
704                 {
705                         if (!DHC_REQOPT(opt, ifo->requestmask6, ifo->nomask6))
706                                 continue;
707                         n_options++;
708                         len += sizeof(o.len);
709                 }
710                 if (dhcp6_findselfsla(ifp)) {
711                         n_options++;
712                         len += sizeof(o.len);
713                 }
714 #endif
715                 if (len)
716                         len += sizeof(o);
717
718                 if (fqdn != FQDN_DISABLE) {
719                         hl = encode_rfc1035(hostname, NULL);
720                         len += sizeof(o) + 1 + hl;
721                 }
722
723                 if (!has_option_mask(ifo->nomask6, D6_OPTION_MUDURL) &&
724                     ifo->mudurl[0])
725                         len += sizeof(o) + ifo->mudurl[0];
726
727 #ifdef AUTH
728                 if ((ifo->auth.options & DHCPCD_AUTH_SENDREQUIRE) !=
729                     DHCPCD_AUTH_SENDREQUIRE &&
730                     DHC_REQ(ifo->requestmask6, ifo->nomask6,
731                     D6_OPTION_RECONF_ACCEPT))
732                         len += sizeof(o); /* Reconfigure Accept */
733 #endif
734         }
735
736         len += sizeof(*state->send);
737         len += sizeof(o) + sizeof(uint16_t); /* elapsed */
738
739         if (ifo->options & DHCPCD_ANONYMOUS) {
740                 duid_len = duid_make(duid, ifp, DUID_LL);
741                 len += sizeof(o) + duid_len;
742         } else {
743                 len += sizeof(o) + ifp->ctx->duid_len;
744         }
745
746         if (!has_option_mask(ifo->nomask6, D6_OPTION_USER_CLASS))
747                 len += dhcp6_makeuser(NULL, ifp);
748         if (!has_option_mask(ifo->nomask6, D6_OPTION_VENDOR_CLASS))
749                 len += dhcp6_makevendor(NULL, ifp);
750
751         /* IA */
752         m = NULL;
753         ml = 0;
754         switch(state->state) {
755         case DH6S_REQUEST:
756                 m = state->recv;
757                 ml = state->recv_len;
758                 /* FALLTHROUGH */
759         case DH6S_DECLINE:
760                 /* FALLTHROUGH */
761         case DH6S_RELEASE:
762                 /* FALLTHROUGH */
763         case DH6S_RENEW:
764                 if (m == NULL) {
765                         m = state->new;
766                         ml = state->new_len;
767                 }
768                 si = dhcp6_findmoption(m, ml, D6_OPTION_SERVERID, &si_len);
769                 if (si == NULL)
770                         return -1;
771                 len += sizeof(o) + si_len;
772                 /* FALLTHROUGH */
773         case DH6S_REBIND:
774                 /* FALLTHROUGH */
775         case DH6S_CONFIRM:
776                 /* FALLTHROUGH */
777         case DH6S_DISCOVER:
778                 if (m == NULL) {
779                         m = state->new;
780                         ml = state->new_len;
781                 }
782                 TAILQ_FOREACH(ap, &state->addrs, next) {
783                         if (ap->flags & IPV6_AF_STALE)
784                                 continue;
785                         if (!(ap->flags & IPV6_AF_REQUEST) &&
786                             (ap->prefix_vltime == 0 ||
787                             state->state == DH6S_DISCOVER))
788                                 continue;
789                         if (DECLINE_IA(ap) && state->state != DH6S_DECLINE)
790                                 continue;
791                         if (ap->ia_type == D6_OPTION_IA_PD) {
792 #ifndef SMALL
793                                 len += sizeof(o) + sizeof(struct dhcp6_pd_addr);
794                                 if (ap->prefix_exclude_len)
795                                         len += sizeof(o) + 1 +
796                                             (uint8_t)((ap->prefix_exclude_len -
797                                             ap->prefix_len - 1) / NBBY) + 1;
798 #endif
799                         } else
800                                 len += sizeof(o) + sizeof(struct dhcp6_ia_addr);
801                 }
802                 /* FALLTHROUGH */
803         case DH6S_INIT:
804                 for (l = 0; l < ifo->ia_len; l++) {
805                         len += sizeof(o) + sizeof(uint32_t); /* IAID */
806                         /* IA_TA does not have T1 or T2 timers */
807                         if (ifo->ia[l].ia_type != D6_OPTION_IA_TA)
808                                 len += sizeof(uint32_t) + sizeof(uint32_t);
809                 }
810                 IA = 1;
811                 break;
812         default:
813                 IA = 0;
814         }
815
816         if (state->state == DH6S_DISCOVER &&
817             !(ifp->ctx->options & DHCPCD_TEST) &&
818             DHC_REQ(ifo->requestmask6, ifo->nomask6, D6_OPTION_RAPID_COMMIT))
819                 len += sizeof(o);
820
821         if (m == NULL) {
822                 m = state->new;
823                 ml = state->new_len;
824         }
825
826         switch(state->state) {
827         case DH6S_INIT: /* FALLTHROUGH */
828         case DH6S_DISCOVER:
829                 type = DHCP6_SOLICIT;
830                 break;
831         case DH6S_REQUEST:
832                 type = DHCP6_REQUEST;
833                 break;
834         case DH6S_CONFIRM:
835                 type = DHCP6_CONFIRM;
836                 break;
837         case DH6S_REBIND:
838                 type = DHCP6_REBIND;
839                 break;
840         case DH6S_RENEW:
841                 type = DHCP6_RENEW;
842                 break;
843         case DH6S_INFORM:
844                 type = DHCP6_INFORMATION_REQ;
845                 break;
846         case DH6S_RELEASE:
847                 type = DHCP6_RELEASE;
848                 break;
849         case DH6S_DECLINE:
850                 type = DHCP6_DECLINE;
851                 break;
852         default:
853                 errno = EINVAL;
854                 return -1;
855         }
856
857         switch(state->state) {
858         case DH6S_REQUEST: /* FALLTHROUGH */
859         case DH6S_RENEW:   /* FALLTHROUGH */
860         case DH6S_RELEASE:
861                 if (has_option_mask(ifo->nomask6, D6_OPTION_UNICAST)) {
862                         unicast = NULL;
863                         break;
864                 }
865                 unicast = dhcp6_findmoption(m, ml, D6_OPTION_UNICAST, &uni_len);
866                 break;
867         default:
868                 unicast = NULL;
869                 break;
870         }
871
872         /* In non master mode we listen and send from fixed addresses.
873          * We should try and match an address we have to unicast to,
874          * but for now this is the safest policy. */
875         if (unicast != NULL && !(ifp->ctx->options & DHCPCD_MASTER)) {
876                 logdebugx("%s: ignoring unicast option as not master",
877                     ifp->name);
878                 unicast = NULL;
879         }
880
881 #ifdef AUTH
882         auth_len = 0;
883         if (ifo->auth.options & DHCPCD_AUTH_SEND) {
884                 ssize_t alen = dhcp_auth_encode(&ifo->auth,
885                     state->auth.token, NULL, 0, 6, type, NULL, 0);
886                 if (alen != -1 && alen > UINT16_MAX) {
887                         errno = ERANGE;
888                         alen = -1;
889                 }
890                 if (alen == -1)
891                         logerr("%s: %s: dhcp_auth_encode", __func__, ifp->name);
892                 else if (alen != 0) {
893                         auth_len = (uint16_t)alen;
894                         len += sizeof(o) + auth_len;
895                 }
896         }
897 #endif
898
899         state->send = malloc(len);
900         if (state->send == NULL)
901                 return -1;
902
903         state->send_len = len;
904         state->send->type = type;
905
906         /* If we found a unicast option, copy it to our state for sending */
907         if (unicast && uni_len == sizeof(state->unicast))
908                 memcpy(&state->unicast, unicast, sizeof(state->unicast));
909         else
910                 state->unicast = in6addr_any;
911
912         dhcp6_newxid(ifp, state->send);
913
914 #define COPYIN1(_code, _len)            {       \
915         o.code = htons((_code));                \
916         o.len = htons((_len));                  \
917         memcpy(p, &o, sizeof(o));               \
918         p += sizeof(o);                         \
919 }
920 #define COPYIN(_code, _data, _len)      do {    \
921         COPYIN1((_code), (_len));               \
922         if ((_len) != 0) {                      \
923                 memcpy(p, (_data), (_len));     \
924                 p += (_len);                    \
925         }                                       \
926 } while (0 /* CONSTCOND */)
927 #define NEXTLEN (p + offsetof(struct dhcp6_option, len))
928
929         /* Options are listed in numerical order as per RFC 7844 Section 4.1
930          * XXX: They should be randomised. */
931
932         p = (uint8_t *)state->send + sizeof(*state->send);
933         if (ifo->options & DHCPCD_ANONYMOUS)
934                 COPYIN(D6_OPTION_CLIENTID, duid,
935                     (uint16_t)duid_len);
936         else
937                 COPYIN(D6_OPTION_CLIENTID, ifp->ctx->duid,
938                     (uint16_t)ifp->ctx->duid_len);
939
940         if (si != NULL)
941                 COPYIN(D6_OPTION_SERVERID, si, si_len);
942
943         for (l = 0; IA && l < ifo->ia_len; l++) {
944                 ifia = &ifo->ia[l];
945                 o_lenp = NEXTLEN;
946                 /* TA structure is the same as the others,
947                  * it just lacks the T1 and T2 timers.
948                  * These happen to be at the end of the struct,
949                  * so we just don't copy them in. */
950                 if (ifia->ia_type == D6_OPTION_IA_TA)
951                         ia_na_len = sizeof(struct dhcp6_ia_ta);
952                 else
953                         ia_na_len = sizeof(ia_na);
954                 memcpy(ia_na.iaid, ifia->iaid, sizeof(ia_na.iaid));
955                 ia_na.t1 = 0;
956                 ia_na.t2 = 0;
957                 COPYIN(ifia->ia_type, &ia_na, ia_na_len);
958                 TAILQ_FOREACH(ap, &state->addrs, next) {
959                         if (ap->flags & IPV6_AF_STALE)
960                                 continue;
961                         if (!(ap->flags & IPV6_AF_REQUEST) &&
962                             (ap->prefix_vltime == 0 ||
963                             state->state == DH6S_DISCOVER))
964                                 continue;
965                         if (DECLINE_IA(ap) && state->state != DH6S_DECLINE)
966                                 continue;
967                         if (ap->ia_type != ifia->ia_type)
968                                 continue;
969                         if (memcmp(ap->iaid, ifia->iaid, sizeof(ap->iaid)))
970                                 continue;
971                         if (ap->ia_type == D6_OPTION_IA_PD) {
972 #ifndef SMALL
973                                 struct dhcp6_pd_addr pdp;
974
975                                 pdp.pltime = htonl(ap->prefix_pltime);
976                                 pdp.vltime = htonl(ap->prefix_vltime);
977                                 pdp.prefix_len = ap->prefix_len;
978                                 /* pdp.prefix is not aligned, so copy it in. */
979                                 memcpy(&pdp.prefix, &ap->prefix, sizeof(pdp.prefix));
980                                 COPYIN(D6_OPTION_IAPREFIX, &pdp, sizeof(pdp));
981                                 ia_na_len = (uint16_t)
982                                     (ia_na_len + sizeof(o) + sizeof(pdp));
983
984                                 /* RFC6603 Section 4.2 */
985                                 if (ap->prefix_exclude_len) {
986                                         uint8_t exb[16], *ep, u8;
987                                         const uint8_t *pp;
988
989                                         n = (size_t)((ap->prefix_exclude_len -
990                                             ap->prefix_len - 1) / NBBY) + 1;
991                                         ep = exb;
992                                         *ep++ = (uint8_t)ap->prefix_exclude_len;
993                                         pp = ap->prefix_exclude.s6_addr;
994                                         pp += (size_t)
995                                             ((ap->prefix_len - 1) / NBBY) +
996                                             (n - 1);
997                                         u8 = ap->prefix_len % NBBY;
998                                         if (u8)
999                                                 n--;
1000                                         while (n-- > 0)
1001                                                 *ep++ = *pp--;
1002                                         if (u8)
1003                                                 *ep = (uint8_t)(*pp << u8);
1004                                         n++;
1005                                         COPYIN(D6_OPTION_PD_EXCLUDE, exb,
1006                                             (uint16_t)n);
1007                                         ia_na_len = (uint16_t)
1008                                             (ia_na_len + sizeof(o) + n);
1009                                 }
1010 #endif
1011                         } else {
1012                                 struct dhcp6_ia_addr ia;
1013
1014                                 ia.addr = ap->addr;
1015                                 ia.pltime = htonl(ap->prefix_pltime);
1016                                 ia.vltime = htonl(ap->prefix_vltime);
1017                                 COPYIN(D6_OPTION_IA_ADDR, &ia, sizeof(ia));
1018                                 ia_na_len = (uint16_t)
1019                                     (ia_na_len + sizeof(o) + sizeof(ia));
1020                         }
1021                 }
1022
1023                 /* Update the total option lenth. */
1024                 ia_na_len = htons(ia_na_len);
1025                 memcpy(o_lenp, &ia_na_len, sizeof(ia_na_len));
1026         }
1027
1028         if (state->send->type != DHCP6_RELEASE &&
1029             state->send->type != DHCP6_DECLINE &&
1030             n_options)
1031         {
1032                 o_lenp = NEXTLEN;
1033                 o.len = 0;
1034                 COPYIN1(D6_OPTION_ORO, 0);
1035                 for (l = 0, opt = ifp->ctx->dhcp6_opts;
1036                     l < ifp->ctx->dhcp6_opts_len;
1037                     l++, opt++)
1038                 {
1039 #ifndef SMALL
1040                         for (n = 0, opt2 = ifo->dhcp6_override;
1041                             n < ifo->dhcp6_override_len;
1042                             n++, opt2++)
1043                         {
1044                                 if (opt->option == opt2->option)
1045                                         break;
1046                         }
1047                         if (n < ifo->dhcp6_override_len)
1048                             continue;
1049 #endif
1050                         if (!DHC_REQOPT(opt, ifo->requestmask6, ifo->nomask6))
1051                                 continue;
1052                         o.code = htons((uint16_t)opt->option);
1053                         memcpy(p, &o.code, sizeof(o.code));
1054                         p += sizeof(o.code);
1055                         o.len = (uint16_t)(o.len + sizeof(o.code));
1056                 }
1057 #ifndef SMALL
1058                 for (l = 0, opt = ifo->dhcp6_override;
1059                     l < ifo->dhcp6_override_len;
1060                     l++, opt++)
1061                 {
1062                         if (!DHC_REQOPT(opt, ifo->requestmask6, ifo->nomask6))
1063                                 continue;
1064                         o.code = htons((uint16_t)opt->option);
1065                         memcpy(p, &o.code, sizeof(o.code));
1066                         p += sizeof(o.code);
1067                         o.len = (uint16_t)(o.len + sizeof(o.code));
1068                 }
1069                 if (dhcp6_findselfsla(ifp)) {
1070                         o.code = htons(D6_OPTION_PD_EXCLUDE);
1071                         memcpy(p, &o.code, sizeof(o.code));
1072                         p += sizeof(o.code);
1073                         o.len = (uint16_t)(o.len + sizeof(o.code));
1074                 }
1075 #endif
1076                 o.len = htons(o.len);
1077                 memcpy(o_lenp, &o.len, sizeof(o.len));
1078         }
1079
1080         si_len = 0;
1081         COPYIN(D6_OPTION_ELAPSED, &si_len, sizeof(si_len));
1082
1083         if (state->state == DH6S_DISCOVER &&
1084             !(ifp->ctx->options & DHCPCD_TEST) &&
1085             DHC_REQ(ifo->requestmask6, ifo->nomask6, D6_OPTION_RAPID_COMMIT))
1086                 COPYIN1(D6_OPTION_RAPID_COMMIT, 0);
1087
1088         if (!has_option_mask(ifo->nomask6, D6_OPTION_USER_CLASS))
1089                 p += dhcp6_makeuser(p, ifp);
1090         if (!has_option_mask(ifo->nomask6, D6_OPTION_VENDOR_CLASS))
1091                 p += dhcp6_makevendor(p, ifp);
1092
1093         if (state->send->type != DHCP6_RELEASE &&
1094             state->send->type != DHCP6_DECLINE)
1095         {
1096                 if (fqdn != FQDN_DISABLE) {
1097                         o_lenp = NEXTLEN;
1098                         COPYIN1(D6_OPTION_FQDN, 0);
1099                         if (hl == 0)
1100                                 *p = D6_FQDN_NONE;
1101                         else {
1102                                 switch (fqdn) {
1103                                 case FQDN_BOTH:
1104                                         *p = D6_FQDN_BOTH;
1105                                         break;
1106                                 case FQDN_PTR:
1107                                         *p = D6_FQDN_PTR;
1108                                         break;
1109                                 default:
1110                                         *p = D6_FQDN_NONE;
1111                                         break;
1112                                 }
1113                         }
1114                         p++;
1115                         encode_rfc1035(hostname, p);
1116                         p += hl;
1117                         o.len = htons((uint16_t)(hl + 1));
1118                         memcpy(o_lenp, &o.len, sizeof(o.len));
1119                 }
1120
1121                 if (!has_option_mask(ifo->nomask6, D6_OPTION_MUDURL) &&
1122                     ifo->mudurl[0])
1123                         COPYIN(D6_OPTION_MUDURL,
1124                             ifo->mudurl + 1, ifo->mudurl[0]);
1125
1126 #ifdef AUTH
1127                 if ((ifo->auth.options & DHCPCD_AUTH_SENDREQUIRE) !=
1128                     DHCPCD_AUTH_SENDREQUIRE &&
1129                     DHC_REQ(ifo->requestmask6, ifo->nomask6,
1130                     D6_OPTION_RECONF_ACCEPT))
1131                         COPYIN1(D6_OPTION_RECONF_ACCEPT, 0);
1132 #endif
1133
1134         }
1135
1136 #ifdef AUTH
1137         /* This has to be the last option */
1138         if (ifo->auth.options & DHCPCD_AUTH_SEND && auth_len != 0) {
1139                 COPYIN1(D6_OPTION_AUTH, auth_len);
1140                 /* data will be filled at send message time */
1141         }
1142 #endif
1143
1144         return 0;
1145 }
1146
1147 static const char *
1148 dhcp6_get_op(uint16_t type)
1149 {
1150         const struct dhcp6_op *d;
1151
1152         for (d = dhcp6_ops; d->name; d++)
1153                 if (d->type == type)
1154                         return d->name;
1155         return NULL;
1156 }
1157
1158 static void
1159 dhcp6_freedrop_addrs(struct interface *ifp, int drop,
1160     const struct interface *ifd)
1161 {
1162         struct dhcp6_state *state;
1163
1164         state = D6_STATE(ifp);
1165         if (state) {
1166                 ipv6_freedrop_addrs(&state->addrs, drop, ifd);
1167                 if (drop)
1168                         rt_build(ifp->ctx, AF_INET6);
1169         }
1170 }
1171
1172 #ifndef SMALL
1173 static void dhcp6_delete_delegates(struct interface *ifp)
1174 {
1175         struct interface *ifp0;
1176
1177         if (ifp->ctx->ifaces) {
1178                 TAILQ_FOREACH(ifp0, ifp->ctx->ifaces, next) {
1179                         if (ifp0 != ifp)
1180                                 dhcp6_freedrop_addrs(ifp0, 1, ifp);
1181                 }
1182         }
1183 }
1184 #endif
1185
1186 #ifdef AUTH
1187 static ssize_t
1188 dhcp6_update_auth(struct interface *ifp, struct dhcp6_message *m, size_t len)
1189 {
1190         struct dhcp6_state *state;
1191         uint8_t *opt;
1192         uint16_t opt_len;
1193
1194         opt = dhcp6_findmoption(m, len, D6_OPTION_AUTH, &opt_len);
1195         if (opt == NULL)
1196                 return -1;
1197
1198         state = D6_STATE(ifp);
1199         return dhcp_auth_encode(&ifp->options->auth, state->auth.token,
1200             (uint8_t *)state->send, state->send_len,
1201             6, state->send->type, opt, opt_len);
1202 }
1203 #endif
1204
1205 static const struct in6_addr alldhcp = IN6ADDR_LINKLOCAL_ALLDHCP_INIT;
1206 static int
1207 dhcp6_sendmessage(struct interface *ifp, void (*callback)(void *))
1208 {
1209         struct dhcp6_state *state = D6_STATE(ifp);
1210         struct dhcpcd_ctx *ctx = ifp->ctx;
1211         unsigned int RT;
1212         bool broadcast = true;
1213         struct sockaddr_in6 dst = {
1214             .sin6_family = AF_INET6,
1215             /* Setting the port on Linux gives EINVAL when sending.
1216              * This looks like a kernel bug as the equivalent works
1217              * fine with the DHCP counterpart. */
1218 #ifndef __linux__
1219             .sin6_port = htons(DHCP6_SERVER_PORT),
1220 #endif
1221         };
1222         struct udphdr udp = {
1223             .uh_sport = htons(DHCP6_CLIENT_PORT),
1224             .uh_dport = htons(DHCP6_SERVER_PORT),
1225             .uh_ulen = htons((uint16_t)(sizeof(udp) + state->send_len)),
1226         };
1227         struct iovec iov[] = {
1228             { .iov_base = &udp, .iov_len = sizeof(udp), },
1229             { .iov_base = state->send, .iov_len = state->send_len, },
1230         };
1231         union {
1232                 struct cmsghdr hdr;
1233                 uint8_t buf[CMSG_SPACE(sizeof(struct in6_pktinfo))];
1234         } cmsgbuf = { .buf = { 0 } };
1235         struct msghdr msg = {
1236             .msg_name = &dst, .msg_namelen = sizeof(dst),
1237             .msg_iov = iov, .msg_iovlen = __arraycount(iov),
1238         };
1239         char uaddr[INET6_ADDRSTRLEN];
1240
1241         if (!callback && ifp->carrier <= LINK_DOWN)
1242                 return 0;
1243
1244         if (!IN6_IS_ADDR_UNSPECIFIED(&state->unicast)) {
1245                 switch (state->send->type) {
1246                 case DHCP6_SOLICIT:     /* FALLTHROUGH */
1247                 case DHCP6_CONFIRM:     /* FALLTHROUGH */
1248                 case DHCP6_REBIND:
1249                         /* Unicasting is denied for these types. */
1250                         break;
1251                 default:
1252                         broadcast = false;
1253                         inet_ntop(AF_INET6, &state->unicast, uaddr,
1254                             sizeof(uaddr));
1255                         break;
1256                 }
1257         }
1258         dst.sin6_addr = broadcast ? alldhcp : state->unicast;
1259
1260         if (!callback) {
1261                 logdebugx("%s: %s %s with xid 0x%02x%02x%02x%s%s",
1262                     ifp->name,
1263                     broadcast ? "broadcasting" : "unicasting",
1264                     dhcp6_get_op(state->send->type),
1265                     state->send->xid[0],
1266                     state->send->xid[1],
1267                     state->send->xid[2],
1268                     !broadcast ? " " : "",
1269                     !broadcast ? uaddr : "");
1270                 RT = 0;
1271         } else {
1272                 if (state->IMD &&
1273                     !(ifp->options->options & DHCPCD_INITIAL_DELAY))
1274                         state->IMD = 0;
1275                 if (state->IMD) {
1276                         state->RT = state->IMD * MSEC_PER_SEC;
1277                         /* Some buggy PPP servers close the link too early
1278                          * after sending an invalid status in their reply
1279                          * which means this host won't see it.
1280                          * 1 second grace seems to be the sweet spot. */
1281                         if (ifp->flags & IFF_POINTOPOINT)
1282                                 state->RT += MSEC_PER_SEC;
1283                 } else if (state->RTC == 0)
1284                         state->RT = state->IRT * MSEC_PER_SEC;
1285
1286                 if (state->MRT != 0) {
1287                         unsigned int mrt = state->MRT * MSEC_PER_SEC;
1288
1289                         if (state->RT > mrt)
1290                                 state->RT = mrt;
1291                 }
1292
1293                 /* Add -.1 to .1 * RT randomness as per RFC8415 section 15 */
1294                 uint32_t lru = arc4random_uniform(
1295                     state->RTC == 0 ? DHCP6_RAND_MAX
1296                     : DHCP6_RAND_MAX - DHCP6_RAND_MIN);
1297                 int lr = (int)lru - (state->RTC == 0 ? 0 : DHCP6_RAND_MAX);
1298                 RT = state->RT
1299                     + (unsigned int)((float)state->RT
1300                     * ((float)lr / DHCP6_RAND_DIV));
1301
1302                 if (ifp->carrier > LINK_DOWN)
1303                         logdebugx("%s: %s %s (xid 0x%02x%02x%02x)%s%s,"
1304                             " next in %0.1f seconds",
1305                             ifp->name,
1306                             state->IMD != 0 ? "delaying" :
1307                             broadcast ? "broadcasting" : "unicasting",
1308                             dhcp6_get_op(state->send->type),
1309                             state->send->xid[0],
1310                             state->send->xid[1],
1311                             state->send->xid[2],
1312                             state->IMD == 0 && !broadcast ? " " : "",
1313                             state->IMD == 0 && !broadcast ? uaddr : "",
1314                             (float)RT / MSEC_PER_SEC);
1315
1316                 /* Wait the initial delay */
1317                 if (state->IMD != 0) {
1318                         state->IMD = 0;
1319                         eloop_timeout_add_msec(ctx->eloop, RT, callback, ifp);
1320                         return 0;
1321                 }
1322         }
1323
1324         if (ifp->carrier <= LINK_DOWN)
1325                 return 0;
1326
1327         /* Update the elapsed time */
1328         dhcp6_updateelapsed(ifp, state->send, state->send_len);
1329 #ifdef AUTH
1330         if (ifp->options->auth.options & DHCPCD_AUTH_SEND &&
1331             dhcp6_update_auth(ifp, state->send, state->send_len) == -1)
1332         {
1333                 logerr("%s: %s: dhcp6_updateauth", __func__, ifp->name);
1334                 if (errno != ESRCH)
1335                         return -1;
1336         }
1337 #endif
1338
1339         /* Set the outbound interface */
1340         if (broadcast) {
1341                 struct cmsghdr *cm;
1342                 struct in6_pktinfo pi = { .ipi6_ifindex = ifp->index };
1343
1344                 dst.sin6_scope_id = ifp->index;
1345                 msg.msg_control = cmsgbuf.buf;
1346                 msg.msg_controllen = sizeof(cmsgbuf.buf);
1347                 cm = CMSG_FIRSTHDR(&msg);
1348                 if (cm == NULL) /* unlikely */
1349                         return -1;
1350                 cm->cmsg_level = IPPROTO_IPV6;
1351                 cm->cmsg_type = IPV6_PKTINFO;
1352                 cm->cmsg_len = CMSG_LEN(sizeof(pi));
1353                 memcpy(CMSG_DATA(cm), &pi, sizeof(pi));
1354         }
1355
1356 #ifdef PRIVSEP
1357         if (IN_PRIVSEP(ifp->ctx)) {
1358                 if (ps_inet_senddhcp6(ifp, &msg) == -1)
1359                         logerr(__func__);
1360                 goto sent;
1361         }
1362 #endif
1363
1364         if (sendmsg(ctx->dhcp6_wfd, &msg, 0) == -1) {
1365                 logerr("%s: %s: sendmsg", __func__, ifp->name);
1366                 /* Allow DHCPv6 to continue .... the errors
1367                  * would be rate limited by the protocol.
1368                  * Generally the error is ENOBUFS when struggling to
1369                  * associate with an access point. */
1370         }
1371
1372 #ifdef PRIVSEP
1373 sent:
1374 #endif
1375         state->RTC++;
1376         if (callback) {
1377                 state->RT = RT * 2;
1378                 if (state->RT < RT) /* Check overflow */
1379                         state->RT = RT;
1380                 if (state->MRC == 0 || state->RTC < state->MRC)
1381                         eloop_timeout_add_msec(ctx->eloop,
1382                             RT, callback, ifp);
1383                 else if (state->MRC != 0 && state->MRCcallback)
1384                         eloop_timeout_add_msec(ctx->eloop,
1385                             RT, state->MRCcallback, ifp);
1386                 else
1387                         logwarnx("%s: sent %d times with no reply",
1388                             ifp->name, state->RTC);
1389         }
1390         return 0;
1391 }
1392
1393 static void
1394 dhcp6_sendinform(void *arg)
1395 {
1396
1397         dhcp6_sendmessage(arg, dhcp6_sendinform);
1398 }
1399
1400 static void
1401 dhcp6_senddiscover(void *arg)
1402 {
1403
1404         dhcp6_sendmessage(arg, dhcp6_senddiscover);
1405 }
1406
1407 static void
1408 dhcp6_sendrequest(void *arg)
1409 {
1410
1411         dhcp6_sendmessage(arg, dhcp6_sendrequest);
1412 }
1413
1414 static void
1415 dhcp6_sendrebind(void *arg)
1416 {
1417
1418         dhcp6_sendmessage(arg, dhcp6_sendrebind);
1419 }
1420
1421 static void
1422 dhcp6_sendrenew(void *arg)
1423 {
1424
1425         dhcp6_sendmessage(arg, dhcp6_sendrenew);
1426 }
1427
1428 static void
1429 dhcp6_sendconfirm(void *arg)
1430 {
1431
1432         dhcp6_sendmessage(arg, dhcp6_sendconfirm);
1433 }
1434
1435 static void
1436 dhcp6_senddecline(void *arg)
1437 {
1438
1439         dhcp6_sendmessage(arg, dhcp6_senddecline);
1440 }
1441
1442 static void
1443 dhcp6_sendrelease(void *arg)
1444 {
1445
1446         dhcp6_sendmessage(arg, dhcp6_sendrelease);
1447 }
1448
1449 static void
1450 dhcp6_startrenew(void *arg)
1451 {
1452         struct interface *ifp;
1453         struct dhcp6_state *state;
1454
1455         ifp = arg;
1456         if ((state = D6_STATE(ifp)) == NULL)
1457                 return;
1458
1459         /* Only renew in the bound or renew states */
1460         if (state->state != DH6S_BOUND &&
1461             state->state != DH6S_RENEW)
1462                 return;
1463
1464         /* Remove the timeout as the renew may have been forced. */
1465         eloop_timeout_delete(ifp->ctx->eloop, dhcp6_startrenew, ifp);
1466
1467         state->state = DH6S_RENEW;
1468         state->RTC = 0;
1469         state->IMD = REN_MAX_DELAY;
1470         state->IRT = REN_TIMEOUT;
1471         state->MRT = REN_MAX_RT;
1472         state->MRC = 0;
1473
1474         if (dhcp6_makemessage(ifp) == -1)
1475                 logerr("%s: %s", __func__, ifp->name);
1476         else
1477                 dhcp6_sendrenew(ifp);
1478 }
1479
1480 void dhcp6_renew(struct interface *ifp)
1481 {
1482
1483         dhcp6_startrenew(ifp);
1484 }
1485
1486 bool
1487 dhcp6_dadcompleted(const struct interface *ifp)
1488 {
1489         const struct dhcp6_state *state;
1490         const struct ipv6_addr *ap;
1491
1492         state = D6_CSTATE(ifp);
1493         TAILQ_FOREACH(ap, &state->addrs, next) {
1494                 if (ap->flags & IPV6_AF_ADDED &&
1495                     !(ap->flags & IPV6_AF_DADCOMPLETED))
1496                         return false;
1497         }
1498         return true;
1499 }
1500
1501 static void
1502 dhcp6_dadcallback(void *arg)
1503 {
1504         struct ipv6_addr *ia = arg;
1505         struct interface *ifp;
1506         struct dhcp6_state *state;
1507         struct ipv6_addr *ia2;
1508         bool completed, valid, oneduplicated;
1509
1510         completed = (ia->flags & IPV6_AF_DADCOMPLETED);
1511         ia->flags |= IPV6_AF_DADCOMPLETED;
1512         if (ia->addr_flags & IN6_IFF_DUPLICATED)
1513                 logwarnx("%s: DAD detected %s", ia->iface->name, ia->saddr);
1514
1515 #ifdef ND6_ADVERTISE
1516         else
1517                 ipv6nd_advertise(ia);
1518 #endif
1519         if (completed)
1520                 return;
1521
1522         ifp = ia->iface;
1523         state = D6_STATE(ifp);
1524         if (state->state != DH6S_BOUND && state->state != DH6S_DELEGATED)
1525                 return;
1526
1527 #ifdef SMALL
1528         valid = true;
1529 #else
1530         valid = (ia->delegating_prefix == NULL);
1531 #endif
1532         completed = true;
1533         oneduplicated = false;
1534         TAILQ_FOREACH(ia2, &state->addrs, next) {
1535                 if (ia2->flags & IPV6_AF_ADDED &&
1536                     !(ia2->flags & IPV6_AF_DADCOMPLETED))
1537                 {
1538                         completed = false;
1539                         break;
1540                 }
1541                 if (DECLINE_IA(ia))
1542                         oneduplicated = true;
1543         }
1544         if (!completed)
1545                 return;
1546
1547         logdebugx("%s: DHCPv6 DAD completed", ifp->name);
1548
1549         if (oneduplicated && state->state == DH6S_BOUND) {
1550                 dhcp6_startdecline(ifp);
1551                 return;
1552         }
1553
1554         script_runreason(ifp,
1555 #ifndef SMALL
1556             ia->delegating_prefix ? "DELEGATED6" :
1557 #endif
1558             state->reason);
1559         if (valid)
1560                 dhcpcd_daemonise(ifp->ctx);
1561 }
1562
1563 static void
1564 dhcp6_addrequestedaddrs(struct interface *ifp)
1565 {
1566         struct dhcp6_state *state;
1567         size_t i;
1568         struct if_ia *ia;
1569         struct ipv6_addr *a;
1570
1571         state = D6_STATE(ifp);
1572         /* Add any requested prefixes / addresses */
1573         for (i = 0; i < ifp->options->ia_len; i++) {
1574                 ia = &ifp->options->ia[i];
1575                 if (!((ia->ia_type == D6_OPTION_IA_PD && ia->prefix_len) ||
1576                     !IN6_IS_ADDR_UNSPECIFIED(&ia->addr)))
1577                         continue;
1578                 a = ipv6_newaddr(ifp, &ia->addr,
1579                         /*
1580                          * RFC 5942 Section 5
1581                          * We cannot assume any prefix length, nor tie the
1582                          * address to an existing one as it could expire
1583                          * before the address.
1584                          * As such we just give it a 128 prefix.
1585                          */
1586                     ia->ia_type == D6_OPTION_IA_PD ? ia->prefix_len : 128,
1587                     IPV6_AF_REQUEST);
1588                 if (a == NULL)
1589                         continue;
1590                 a->dadcallback = dhcp6_dadcallback;
1591                 memcpy(&a->iaid, &ia->iaid, sizeof(a->iaid));
1592                 a->ia_type = ia->ia_type;
1593                 TAILQ_INSERT_TAIL(&state->addrs, a, next);
1594         }
1595 }
1596
1597 static void
1598 dhcp6_startdiscover(void *arg)
1599 {
1600         struct interface *ifp;
1601         struct dhcp6_state *state;
1602         int llevel;
1603
1604         ifp = arg;
1605         state = D6_STATE(ifp);
1606 #ifndef SMALL
1607         if (state->reason == NULL || strcmp(state->reason, "TIMEOUT6") != 0)
1608                 dhcp6_delete_delegates(ifp);
1609 #endif
1610         if (state->new == NULL && !state->failed)
1611                 llevel = LOG_INFO;
1612         else
1613                 llevel = LOG_DEBUG;
1614         logmessage(llevel, "%s: soliciting a DHCPv6 lease", ifp->name);
1615         state->state = DH6S_DISCOVER;
1616         state->RTC = 0;
1617         state->IMD = SOL_MAX_DELAY;
1618         state->IRT = SOL_TIMEOUT;
1619         state->MRT = state->sol_max_rt;
1620         state->MRC = SOL_MAX_RC;
1621
1622         eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
1623         free(state->new);
1624         state->new = NULL;
1625         state->new_len = 0;
1626
1627         if (dhcp6_makemessage(ifp) == -1)
1628                 logerr("%s: %s", __func__, ifp->name);
1629         else
1630                 dhcp6_senddiscover(ifp);
1631 }
1632
1633 static void
1634 dhcp6_startinform(void *arg)
1635 {
1636         struct interface *ifp;
1637         struct dhcp6_state *state;
1638         int llevel;
1639
1640         ifp = arg;
1641         state = D6_STATE(ifp);
1642         if (state->new == NULL && !state->failed)
1643                 llevel = LOG_INFO;
1644         else
1645                 llevel = LOG_DEBUG;
1646         logmessage(llevel, "%s: requesting DHCPv6 information", ifp->name);
1647         state->state = DH6S_INFORM;
1648         state->RTC = 0;
1649         state->IMD = INF_MAX_DELAY;
1650         state->IRT = INF_TIMEOUT;
1651         state->MRT = state->inf_max_rt;
1652         state->MRC = 0;
1653
1654         eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
1655         if (dhcp6_makemessage(ifp) == -1) {
1656                 logerr("%s: %s", __func__, ifp->name);
1657                 return;
1658         }
1659         dhcp6_sendinform(ifp);
1660         /* RFC3315 18.1.2 says that if CONFIRM failed then the prior addresses
1661          * SHOULD be used. The wording here is poor, because the addresses are
1662          * merely one facet of the lease as a whole.
1663          * This poor wording might explain the lack of similar text for INFORM
1664          * in 18.1.5 because there are no addresses in the INFORM message. */
1665         eloop_timeout_add_sec(ifp->ctx->eloop,
1666             INF_MAX_RD, dhcp6_failinform, ifp);
1667 }
1668
1669 static bool
1670 dhcp6_startdiscoinform(struct interface *ifp)
1671 {
1672         unsigned long long opts = ifp->options->options;
1673
1674         if (opts & DHCPCD_IA_FORCED || ipv6nd_hasradhcp(ifp, true))
1675                 dhcp6_startdiscover(ifp);
1676         else if (opts & DHCPCD_INFORM6 || ipv6nd_hasradhcp(ifp, false))
1677                 dhcp6_startinform(ifp);
1678         else
1679                 return false;
1680         return true;
1681 }
1682
1683 static void
1684 dhcp6_leaseextend(struct interface *ifp)
1685 {
1686         struct dhcp6_state *state = D6_STATE(ifp);
1687         struct ipv6_addr *ia;
1688
1689         logwarnx("%s: extending DHCPv6 lease", ifp->name);
1690         TAILQ_FOREACH(ia, &state->addrs, next) {
1691                 ia->flags |= IPV6_AF_EXTENDED;
1692                 /* Set infinite lifetimes. */
1693                 ia->prefix_pltime = ND6_INFINITE_LIFETIME;
1694                 ia->prefix_vltime = ND6_INFINITE_LIFETIME;
1695         }
1696 }
1697
1698 static void
1699 dhcp6_fail(struct interface *ifp)
1700 {
1701         struct dhcp6_state *state = D6_STATE(ifp);
1702
1703         state->failed = true;
1704
1705         /* RFC3315 18.1.2 says that prior addresses SHOULD be used on failure.
1706          * RFC2131 3.2.3 says that MAY chose to use the prior address.
1707          * Because dhcpcd was written first for RFC2131, we have the LASTLEASE
1708          * option which defaults to off as that makes the most sense for
1709          * mobile clients.
1710          * dhcpcd also has LASTLEASE_EXTEND to extend this lease past it's
1711          * expiry, but this is strictly not RFC compliant in any way or form. */
1712         if (state->new != NULL &&
1713             ifp->options->options & DHCPCD_LASTLEASE_EXTEND)
1714         {
1715                 dhcp6_leaseextend(ifp);
1716                 dhcp6_bind(ifp, NULL, NULL);
1717         } else {
1718                 dhcp6_freedrop_addrs(ifp, 1, NULL);
1719 #ifndef SMALL
1720                 dhcp6_delete_delegates(ifp);
1721 #endif
1722                 free(state->old);
1723                 state->old = state->new;
1724                 state->old_len = state->new_len;
1725                 state->new = NULL;
1726                 state->new_len = 0;
1727                 if (state->old != NULL)
1728                         script_runreason(ifp, "EXPIRE6");
1729                 dhcp_unlink(ifp->ctx, state->leasefile);
1730         }
1731
1732         if (!dhcp6_startdiscoinform(ifp)) {
1733                 logwarnx("%s: no advertising IPv6 router wants DHCP",ifp->name);
1734                 state->state = DH6S_INIT;
1735                 eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
1736         }
1737 }
1738
1739 static int
1740 dhcp6_failloglevel(struct interface *ifp)
1741 {
1742         const struct dhcp6_state *state = D6_CSTATE(ifp);
1743
1744         return state->failed ? LOG_DEBUG : LOG_ERR;
1745 }
1746
1747 static void
1748 dhcp6_failconfirm(void *arg)
1749 {
1750         struct interface *ifp = arg;
1751         int llevel = dhcp6_failloglevel(ifp);
1752
1753         logmessage(llevel, "%s: failed to confirm prior DHCPv6 address",
1754             ifp->name);
1755         dhcp6_fail(ifp);
1756 }
1757
1758 static void
1759 dhcp6_failrequest(void *arg)
1760 {
1761         struct interface *ifp = arg;
1762         int llevel = dhcp6_failloglevel(ifp);
1763
1764         logmessage(llevel, "%s: failed to request DHCPv6 address", ifp->name);
1765         dhcp6_fail(ifp);
1766 }
1767
1768 static void
1769 dhcp6_failinform(void *arg)
1770 {
1771         struct interface *ifp = arg;
1772         int llevel = dhcp6_failloglevel(ifp);
1773
1774         logmessage(llevel, "%s: failed to request DHCPv6 information",
1775             ifp->name);
1776         dhcp6_fail(ifp);
1777 }
1778
1779 #ifndef SMALL
1780 static void
1781 dhcp6_failrebind(void *arg)
1782 {
1783         struct interface *ifp = arg;
1784
1785         logerrx("%s: failed to rebind prior DHCPv6 delegation", ifp->name);
1786         dhcp6_fail(ifp);
1787 }
1788
1789 static int
1790 dhcp6_hasprefixdelegation(struct interface *ifp)
1791 {
1792         size_t i;
1793         uint16_t t;
1794
1795         t = 0;
1796         for (i = 0; i < ifp->options->ia_len; i++) {
1797                 if (t && t != ifp->options->ia[i].ia_type) {
1798                         if (t == D6_OPTION_IA_PD ||
1799                             ifp->options->ia[i].ia_type == D6_OPTION_IA_PD)
1800                                 return 2;
1801                 }
1802                 t = ifp->options->ia[i].ia_type;
1803         }
1804         return t == D6_OPTION_IA_PD ? 1 : 0;
1805 }
1806 #endif
1807
1808 static void
1809 dhcp6_startrebind(void *arg)
1810 {
1811         struct interface *ifp;
1812         struct dhcp6_state *state;
1813 #ifndef SMALL
1814         int pd;
1815 #endif
1816
1817         ifp = arg;
1818         eloop_timeout_delete(ifp->ctx->eloop, dhcp6_sendrenew, ifp);
1819         state = D6_STATE(ifp);
1820         if (state->state == DH6S_RENEW)
1821                 logwarnx("%s: failed to renew DHCPv6, rebinding", ifp->name);
1822         else
1823                 loginfox("%s: rebinding prior DHCPv6 lease", ifp->name);
1824         state->state = DH6S_REBIND;
1825         state->RTC = 0;
1826         state->MRC = 0;
1827
1828 #ifndef SMALL
1829         /* RFC 3633 section 12.1 */
1830         pd = dhcp6_hasprefixdelegation(ifp);
1831         if (pd) {
1832                 state->IMD = CNF_MAX_DELAY;
1833                 state->IRT = CNF_TIMEOUT;
1834                 state->MRT = CNF_MAX_RT;
1835         } else
1836 #endif
1837         {
1838                 state->IMD = REB_MAX_DELAY;
1839                 state->IRT = REB_TIMEOUT;
1840                 state->MRT = REB_MAX_RT;
1841         }
1842
1843         if (dhcp6_makemessage(ifp) == -1)
1844                 logerr("%s: %s", __func__, ifp->name);
1845         else
1846                 dhcp6_sendrebind(ifp);
1847
1848 #ifndef SMALL
1849         /* RFC 3633 section 12.1 */
1850         if (pd)
1851                 eloop_timeout_add_sec(ifp->ctx->eloop,
1852                     CNF_MAX_RD, dhcp6_failrebind, ifp);
1853 #endif
1854 }
1855
1856
1857 static void
1858 dhcp6_startrequest(struct interface *ifp)
1859 {
1860         struct dhcp6_state *state;
1861
1862         eloop_timeout_delete(ifp->ctx->eloop, dhcp6_senddiscover, ifp);
1863         state = D6_STATE(ifp);
1864         state->state = DH6S_REQUEST;
1865         state->RTC = 0;
1866         state->IMD = 0;
1867         state->IRT = REQ_TIMEOUT;
1868         state->MRT = REQ_MAX_RT;
1869         state->MRC = REQ_MAX_RC;
1870         state->MRCcallback = dhcp6_failrequest;
1871
1872         if (dhcp6_makemessage(ifp) == -1) {
1873                 logerr("%s: %s", __func__, ifp->name);
1874                 return;
1875         }
1876
1877         dhcp6_sendrequest(ifp);
1878 }
1879
1880 static void
1881 dhcp6_startconfirm(struct interface *ifp)
1882 {
1883         struct dhcp6_state *state;
1884         struct ipv6_addr *ia;
1885
1886         state = D6_STATE(ifp);
1887
1888         TAILQ_FOREACH(ia, &state->addrs, next) {
1889                 if (!DECLINE_IA(ia))
1890                         continue;
1891                 logerrx("%s: prior DHCPv6 has a duplicated address", ifp->name);
1892                 dhcp6_startdecline(ifp);
1893                 return;
1894         }
1895
1896         state->state = DH6S_CONFIRM;
1897         state->RTC = 0;
1898         state->IMD = CNF_MAX_DELAY;
1899         state->IRT = CNF_TIMEOUT;
1900         state->MRT = CNF_MAX_RT;
1901         state->MRC = CNF_MAX_RC;
1902
1903         loginfox("%s: confirming prior DHCPv6 lease", ifp->name);
1904
1905         if (dhcp6_makemessage(ifp) == -1) {
1906                 logerr("%s: %s", __func__, ifp->name);
1907                 return;
1908         }
1909         dhcp6_sendconfirm(ifp);
1910         eloop_timeout_add_sec(ifp->ctx->eloop,
1911             CNF_MAX_RD, dhcp6_failconfirm, ifp);
1912 }
1913
1914 static void
1915 dhcp6_startexpire(void *arg)
1916 {
1917         struct interface *ifp;
1918
1919         ifp = arg;
1920         eloop_timeout_delete(ifp->ctx->eloop, dhcp6_sendrebind, ifp);
1921
1922         logerrx("%s: DHCPv6 lease expired", ifp->name);
1923         dhcp6_fail(ifp);
1924 }
1925
1926 static void
1927 dhcp6_faildecline(void *arg)
1928 {
1929         struct interface *ifp = arg;
1930
1931         logerrx("%s: failed to decline duplicated DHCPv6 addresses", ifp->name);
1932         dhcp6_fail(ifp);
1933 }
1934
1935 static void
1936 dhcp6_startdecline(struct interface *ifp)
1937 {
1938         struct dhcp6_state *state;
1939
1940         state = D6_STATE(ifp);
1941         loginfox("%s: declining failed DHCPv6 addresses", ifp->name);
1942         state->state = DH6S_DECLINE;
1943         state->RTC = 0;
1944         state->IMD = 0;
1945         state->IRT = DEC_TIMEOUT;
1946         state->MRT = 0;
1947         state->MRC = DEC_MAX_RC;
1948         state->MRCcallback = dhcp6_faildecline;
1949
1950         if (dhcp6_makemessage(ifp) == -1)
1951                 logerr("%s: %s", __func__, ifp->name);
1952         else
1953                 dhcp6_senddecline(ifp);
1954 }
1955
1956 static void
1957 dhcp6_finishrelease(void *arg)
1958 {
1959         struct interface *ifp;
1960         struct dhcp6_state *state;
1961
1962         ifp = (struct interface *)arg;
1963         if ((state = D6_STATE(ifp)) != NULL) {
1964                 state->state = DH6S_RELEASED;
1965                 dhcp6_drop(ifp, "RELEASE6");
1966         }
1967 }
1968
1969 static void
1970 dhcp6_startrelease(struct interface *ifp)
1971 {
1972         struct dhcp6_state *state;
1973
1974         state = D6_STATE(ifp);
1975         if (state->state != DH6S_BOUND)
1976                 return;
1977
1978         state->state = DH6S_RELEASE;
1979         state->RTC = 0;
1980         state->IMD = REL_MAX_DELAY;
1981         state->IRT = REL_TIMEOUT;
1982         state->MRT = REL_MAX_RT;
1983         /* MRC of REL_MAX_RC is optional in RFC 3315 18.1.6 */
1984 #if 0
1985         state->MRC = REL_MAX_RC;
1986         state->MRCcallback = dhcp6_finishrelease;
1987 #else
1988         state->MRC = 0;
1989         state->MRCcallback = NULL;
1990 #endif
1991
1992         if (dhcp6_makemessage(ifp) == -1)
1993                 logerr("%s: %s", __func__, ifp->name);
1994         else {
1995                 dhcp6_sendrelease(ifp);
1996                 dhcp6_finishrelease(ifp);
1997         }
1998 }
1999
2000 static int
2001 dhcp6_checkstatusok(const struct interface *ifp,
2002     struct dhcp6_message *m, uint8_t *p, size_t len)
2003 {
2004         struct dhcp6_state *state;
2005         uint8_t *opt;
2006         uint16_t opt_len, code;
2007         size_t mlen;
2008         void * (*f)(void *, size_t, uint16_t, uint16_t *), *farg;
2009         char buf[32], *sbuf;
2010         const char *status;
2011         int loglevel;
2012
2013         state = D6_STATE(ifp);
2014         f = p ? dhcp6_findoption : dhcp6_findmoption;
2015         if (p)
2016                 farg = p;
2017         else
2018                 farg = m;
2019         if ((opt = f(farg, len, D6_OPTION_STATUS_CODE, &opt_len)) == NULL) {
2020                 //logdebugx("%s: no status", ifp->name);
2021                 state->lerror = 0;
2022                 errno = ESRCH;
2023                 return 0;
2024         }
2025
2026         if (opt_len < sizeof(code)) {
2027                 logerrx("%s: status truncated", ifp->name);
2028                 return -1;
2029         }
2030         memcpy(&code, opt, sizeof(code));
2031         code = ntohs(code);
2032         if (code == D6_STATUS_OK) {
2033                 state->lerror = 0;
2034                 errno = 0;
2035                 return 0;
2036         }
2037
2038         /* Anything after the code is a message. */
2039         opt += sizeof(code);
2040         mlen = opt_len - sizeof(code);
2041         if (mlen == 0) {
2042                 sbuf = NULL;
2043                 if (code < sizeof(dhcp6_statuses) / sizeof(char *))
2044                         status = dhcp6_statuses[code];
2045                 else {
2046                         snprintf(buf, sizeof(buf), "Unknown Status (%d)", code);
2047                         status = buf;
2048                 }
2049         } else {
2050                 if ((sbuf = malloc(mlen + 1)) == NULL) {
2051                         logerr(__func__);
2052                         return -1;
2053                 }
2054                 memcpy(sbuf, opt, mlen);
2055                 sbuf[mlen] = '\0';
2056                 status = sbuf;
2057         }
2058
2059         if (state->lerror == code || state->state == DH6S_INIT)
2060                 loglevel = LOG_DEBUG;
2061         else
2062                 loglevel = LOG_ERR;
2063         logmessage(loglevel, "%s: DHCPv6 REPLY: %s", ifp->name, status);
2064         free(sbuf);
2065         state->lerror = code;
2066         errno = 0;
2067         return (int)code;
2068 }
2069
2070 const struct ipv6_addr *
2071 dhcp6_iffindaddr(const struct interface *ifp, const struct in6_addr *addr,
2072     unsigned int flags)
2073 {
2074         const struct dhcp6_state *state;
2075         const struct ipv6_addr *ap;
2076
2077         if ((state = D6_STATE(ifp)) != NULL) {
2078                 TAILQ_FOREACH(ap, &state->addrs, next) {
2079                         if (ipv6_findaddrmatch(ap, addr, flags))
2080                                 return ap;
2081                 }
2082         }
2083         return NULL;
2084 }
2085
2086 struct ipv6_addr *
2087 dhcp6_findaddr(struct dhcpcd_ctx *ctx, const struct in6_addr *addr,
2088     unsigned int flags)
2089 {
2090         struct interface *ifp;
2091         struct ipv6_addr *ap;
2092         struct dhcp6_state *state;
2093
2094         TAILQ_FOREACH(ifp, ctx->ifaces, next) {
2095                 if ((state = D6_STATE(ifp)) != NULL) {
2096                         TAILQ_FOREACH(ap, &state->addrs, next) {
2097                                 if (ipv6_findaddrmatch(ap, addr, flags))
2098                                         return ap;
2099                         }
2100                 }
2101         }
2102         return NULL;
2103 }
2104
2105 static int
2106 dhcp6_findna(struct interface *ifp, uint16_t ot, const uint8_t *iaid,
2107     uint8_t *d, size_t l, const struct timespec *acquired)
2108 {
2109         struct dhcp6_state *state;
2110         uint8_t *o, *nd;
2111         uint16_t ol;
2112         struct ipv6_addr *a;
2113         int i;
2114         struct dhcp6_ia_addr ia;
2115
2116         i = 0;
2117         state = D6_STATE(ifp);
2118         while ((o = dhcp6_findoption(d, l, D6_OPTION_IA_ADDR, &ol))) {
2119                 /* Set d and l first to ensure we find the next option. */
2120                 nd = o + ol;
2121                 l -= (size_t)(nd - d);
2122                 d = nd;
2123                 if (ol < sizeof(ia)) {
2124                         errno = EINVAL;
2125                         logerrx("%s: IA Address option truncated", ifp->name);
2126                         continue;
2127                 }
2128                 memcpy(&ia, o, sizeof(ia));
2129                 ia.pltime = ntohl(ia.pltime);
2130                 ia.vltime = ntohl(ia.vltime);
2131                 /* RFC 3315 22.6 */
2132                 if (ia.pltime > ia.vltime) {
2133                         errno = EINVAL;
2134                         logerr("%s: IA Address pltime %"PRIu32
2135                             " > vltime %"PRIu32,
2136                             ifp->name, ia.pltime, ia.vltime);
2137                         continue;
2138                 }
2139                 TAILQ_FOREACH(a, &state->addrs, next) {
2140                         if (ipv6_findaddrmatch(a, &ia.addr, 0))
2141                                 break;
2142                 }
2143                 if (a == NULL) {
2144                         /*
2145                          * RFC 5942 Section 5
2146                          * We cannot assume any prefix length, nor tie the
2147                          * address to an existing one as it could expire
2148                          * before the address.
2149                          * As such we just give it a 128 prefix.
2150                          */
2151                         a = ipv6_newaddr(ifp, &ia.addr, 128, IPV6_AF_ONLINK);
2152                         a->dadcallback = dhcp6_dadcallback;
2153                         a->ia_type = ot;
2154                         memcpy(a->iaid, iaid, sizeof(a->iaid));
2155                         a->created = *acquired;
2156
2157                         TAILQ_INSERT_TAIL(&state->addrs, a, next);
2158                 } else {
2159                         if (!(a->flags & IPV6_AF_ONLINK))
2160                                 a->flags |= IPV6_AF_ONLINK | IPV6_AF_NEW;
2161                         a->flags &= ~(IPV6_AF_STALE | IPV6_AF_EXTENDED);
2162                 }
2163                 a->acquired = *acquired;
2164                 a->prefix_pltime = ia.pltime;
2165                 if (a->prefix_vltime != ia.vltime) {
2166                         a->flags |= IPV6_AF_NEW;
2167                         a->prefix_vltime = ia.vltime;
2168                 }
2169                 if (a->prefix_pltime && a->prefix_pltime < state->lowpl)
2170                     state->lowpl = a->prefix_pltime;
2171                 if (a->prefix_vltime && a->prefix_vltime > state->expire)
2172                     state->expire = a->prefix_vltime;
2173                 i++;
2174         }
2175         return i;
2176 }
2177
2178 #ifndef SMALL
2179 static int
2180 dhcp6_findpd(struct interface *ifp, const uint8_t *iaid,
2181     uint8_t *d, size_t l, const struct timespec *acquired)
2182 {
2183         struct dhcp6_state *state;
2184         uint8_t *o, *nd;
2185         struct ipv6_addr *a;
2186         int i;
2187         uint8_t nb, *pw;
2188         uint16_t ol;
2189         struct dhcp6_pd_addr pdp;
2190         struct in6_addr pdp_prefix;
2191
2192         i = 0;
2193         state = D6_STATE(ifp);
2194         while ((o = dhcp6_findoption(d, l, D6_OPTION_IAPREFIX, &ol))) {
2195                 /* Set d and l first to ensure we find the next option. */
2196                 nd = o + ol;
2197                 l -= (size_t)(nd - d);
2198                 d = nd;
2199                 if (ol < sizeof(pdp)) {
2200                         errno = EINVAL;
2201                         logerrx("%s: IA Prefix option truncated", ifp->name);
2202                         continue;
2203                 }
2204
2205                 memcpy(&pdp, o, sizeof(pdp));
2206                 pdp.pltime = ntohl(pdp.pltime);
2207                 pdp.vltime = ntohl(pdp.vltime);
2208                 /* RFC 3315 22.6 */
2209                 if (pdp.pltime > pdp.vltime) {
2210                         errno = EINVAL;
2211                         logerrx("%s: IA Prefix pltime %"PRIu32
2212                             " > vltime %"PRIu32,
2213                             ifp->name, pdp.pltime, pdp.vltime);
2214                         continue;
2215                 }
2216
2217                 o += sizeof(pdp);
2218                 ol = (uint16_t)(ol - sizeof(pdp));
2219
2220                 /* pdp.prefix is not aligned so copy it out. */
2221                 memcpy(&pdp_prefix, &pdp.prefix, sizeof(pdp_prefix));
2222                 TAILQ_FOREACH(a, &state->addrs, next) {
2223                         if (IN6_ARE_ADDR_EQUAL(&a->prefix, &pdp_prefix))
2224                                 break;
2225                 }
2226
2227                 if (a == NULL) {
2228                         a = ipv6_newaddr(ifp, &pdp_prefix, pdp.prefix_len,
2229                             IPV6_AF_DELEGATEDPFX);
2230                         if (a == NULL)
2231                                 break;
2232                         a->created = *acquired;
2233                         a->dadcallback = dhcp6_dadcallback;
2234                         a->ia_type = D6_OPTION_IA_PD;
2235                         memcpy(a->iaid, iaid, sizeof(a->iaid));
2236                         TAILQ_INSERT_TAIL(&state->addrs, a, next);
2237                 } else {
2238                         if (!(a->flags & IPV6_AF_DELEGATEDPFX))
2239                                 a->flags |= IPV6_AF_NEW | IPV6_AF_DELEGATEDPFX;
2240                         a->flags &= ~(IPV6_AF_STALE |
2241                                       IPV6_AF_EXTENDED |
2242                                       IPV6_AF_REQUEST);
2243                         if (a->prefix_vltime != pdp.vltime)
2244                                 a->flags |= IPV6_AF_NEW;
2245                 }
2246
2247                 a->acquired = *acquired;
2248                 a->prefix_pltime = pdp.pltime;
2249                 a->prefix_vltime = pdp.vltime;
2250
2251                 if (a->prefix_pltime && a->prefix_pltime < state->lowpl)
2252                         state->lowpl = a->prefix_pltime;
2253                 if (a->prefix_vltime && a->prefix_vltime > state->expire)
2254                         state->expire = a->prefix_vltime;
2255                 i++;
2256
2257                 a->prefix_exclude_len = 0;
2258                 memset(&a->prefix_exclude, 0, sizeof(a->prefix_exclude));
2259                 o = dhcp6_findoption(o, ol, D6_OPTION_PD_EXCLUDE, &ol);
2260                 if (o == NULL)
2261                         continue;
2262
2263                 /* RFC 6603 4.2 says option length MUST be between 2 and 17.
2264                  * This allows 1 octet for prefix length and 16 for the
2265                  * subnet ID. */
2266                 if (ol < 2 || ol > 17) {
2267                         logerrx("%s: invalid PD Exclude option", ifp->name);
2268                         continue;
2269                 }
2270
2271                 /* RFC 6603 4.2 says prefix length MUST be between the
2272                  * length of the IAPREFIX prefix length + 1 and 128. */
2273                 if (*o < a->prefix_len + 1 || *o > 128) {
2274                         logerrx("%s: invalid PD Exclude length", ifp->name);
2275                         continue;
2276                 }
2277
2278                 ol--;
2279                 /* Check option length matches prefix length. */
2280                 if (((*o - a->prefix_len - 1) / NBBY) + 1 != ol) {
2281                         logerrx("%s: PD Exclude length mismatch", ifp->name);
2282                         continue;
2283                 }
2284                 a->prefix_exclude_len = *o++;
2285
2286                 memcpy(&a->prefix_exclude, &a->prefix,
2287                     sizeof(a->prefix_exclude));
2288                 nb = a->prefix_len % NBBY;
2289                 if (nb)
2290                         ol--;
2291                 pw = a->prefix_exclude.s6_addr +
2292                     (a->prefix_exclude_len / NBBY) - 1;
2293                 while (ol-- > 0)
2294                         *pw-- = *o++;
2295                 if (nb)
2296                         *pw = (uint8_t)(*pw | (*o >> nb));
2297         }
2298         return i;
2299 }
2300 #endif
2301
2302 static int
2303 dhcp6_findia(struct interface *ifp, struct dhcp6_message *m, size_t l,
2304     const char *sfrom, const struct timespec *acquired)
2305 {
2306         struct dhcp6_state *state;
2307         const struct if_options *ifo;
2308         struct dhcp6_option o;
2309         uint8_t *d, *p;
2310         struct dhcp6_ia_na ia;
2311         int i, e, error;
2312         size_t j;
2313         uint16_t nl;
2314         uint8_t iaid[4];
2315         char buf[sizeof(iaid) * 3];
2316         struct ipv6_addr *ap;
2317         struct if_ia *ifia;
2318
2319         if (l < sizeof(*m)) {
2320                 /* Should be impossible with guards at packet in
2321                  * and reading leases */
2322                 errno = EINVAL;
2323                 return -1;
2324         }
2325
2326         ifo = ifp->options;
2327         i = e = 0;
2328         state = D6_STATE(ifp);
2329         TAILQ_FOREACH(ap, &state->addrs, next) {
2330                 if (!(ap->flags & IPV6_AF_DELEGATED))
2331                         ap->flags |= IPV6_AF_STALE;
2332         }
2333
2334         d = (uint8_t *)m + sizeof(*m);
2335         l -= sizeof(*m);
2336         while (l > sizeof(o)) {
2337                 memcpy(&o, d, sizeof(o));
2338                 o.len = ntohs(o.len);
2339                 if (o.len > l || sizeof(o) + o.len > l) {
2340                         errno = EINVAL;
2341                         logerrx("%s: option overflow", ifp->name);
2342                         break;
2343                 }
2344                 p = d + sizeof(o);
2345                 d = p + o.len;
2346                 l -= sizeof(o) + o.len;
2347
2348                 o.code = ntohs(o.code);
2349                 switch(o.code) {
2350                 case D6_OPTION_IA_TA:
2351                         nl = 4;
2352                         break;
2353                 case D6_OPTION_IA_NA:
2354                 case D6_OPTION_IA_PD:
2355                         nl = 12;
2356                         break;
2357                 default:
2358                         continue;
2359                 }
2360                 if (o.len < nl) {
2361                         errno = EINVAL;
2362                         logerrx("%s: IA option truncated", ifp->name);
2363                         continue;
2364                 }
2365
2366                 memcpy(&ia, p, nl);
2367                 p += nl;
2368                 o.len = (uint16_t)(o.len - nl);
2369
2370                 for (j = 0; j < ifo->ia_len; j++) {
2371                         ifia = &ifo->ia[j];
2372                         if (ifia->ia_type == o.code &&
2373                             memcmp(ifia->iaid, ia.iaid, sizeof(ia.iaid)) == 0)
2374                                 break;
2375                 }
2376                 if (j == ifo->ia_len &&
2377                     !(ifo->ia_len == 0 && ifp->ctx->options & DHCPCD_DUMPLEASE))
2378                 {
2379                         logdebugx("%s: ignoring unrequested IAID %s",
2380                             ifp->name,
2381                             hwaddr_ntoa(ia.iaid, sizeof(ia.iaid),
2382                             buf, sizeof(buf)));
2383                         continue;
2384                 }
2385
2386                 if (o.code != D6_OPTION_IA_TA) {
2387                         ia.t1 = ntohl(ia.t1);
2388                         ia.t2 = ntohl(ia.t2);
2389                         /* RFC 3315 22.4 */
2390                         if (ia.t2 > 0 && ia.t1 > ia.t2) {
2391                                 logwarnx("%s: IAID %s T1(%d) > T2(%d) from %s",
2392                                     ifp->name,
2393                                     hwaddr_ntoa(iaid, sizeof(iaid), buf,
2394                                                 sizeof(buf)),
2395                                     ia.t1, ia.t2, sfrom);
2396                                 continue;
2397                         }
2398                 } else
2399                         ia.t1 = ia.t2 = 0; /* appease gcc */
2400                 if ((error = dhcp6_checkstatusok(ifp, NULL, p, o.len)) != 0) {
2401                         if (error == D6_STATUS_NOBINDING)
2402                                 state->has_no_binding = true;
2403                         e = 1;
2404                         continue;
2405                 }
2406                 if (o.code == D6_OPTION_IA_PD) {
2407 #ifndef SMALL
2408                         if (dhcp6_findpd(ifp, ia.iaid, p, o.len,
2409                                          acquired) == 0)
2410                         {
2411                                 logwarnx("%s: %s: DHCPv6 REPLY missing Prefix",
2412                                     ifp->name, sfrom);
2413                                 continue;
2414                         }
2415 #endif
2416                 } else {
2417                         if (dhcp6_findna(ifp, o.code, ia.iaid, p, o.len,
2418                                          acquired) == 0)
2419                         {
2420                                 logwarnx("%s: %s: DHCPv6 REPLY missing "
2421                                     "IA Address",
2422                                     ifp->name, sfrom);
2423                                 continue;
2424                         }
2425                 }
2426                 if (o.code != D6_OPTION_IA_TA) {
2427                         if (ia.t1 != 0 &&
2428                             (ia.t1 < state->renew || state->renew == 0))
2429                                 state->renew = ia.t1;
2430                         if (ia.t2 != 0 &&
2431                             (ia.t2 < state->rebind || state->rebind == 0))
2432                                 state->rebind = ia.t2;
2433                 }
2434                 i++;
2435         }
2436
2437         if (i == 0 && e)
2438                 return -1;
2439         return i;
2440 }
2441
2442 #ifndef SMALL
2443 static void
2444 dhcp6_deprecatedele(struct ipv6_addr *ia)
2445 {
2446         struct ipv6_addr *da, *dan, *dda;
2447         struct timespec now;
2448         struct dhcp6_state *state;
2449
2450         timespecclear(&now);
2451         TAILQ_FOREACH_SAFE(da, &ia->pd_pfxs, pd_next, dan) {
2452                 if (ia->prefix_vltime == 0) {
2453                         if (da->prefix_vltime != 0)
2454                                 da->prefix_vltime = 0;
2455                         else
2456                                 continue;
2457                 } else if (da->prefix_pltime != 0)
2458                         da->prefix_pltime = 0;
2459                 else
2460                         continue;
2461
2462                 if (ipv6_doaddr(da, &now) != -1)
2463                         continue;
2464
2465                 /* Delegation deleted, forget it. */
2466                 TAILQ_REMOVE(&ia->pd_pfxs, da, pd_next);
2467
2468                 /* Delete it from the interface. */
2469                 state = D6_STATE(da->iface);
2470                 TAILQ_FOREACH(dda, &state->addrs, next) {
2471                         if (IN6_ARE_ADDR_EQUAL(&dda->addr, &da->addr))
2472                                 break;
2473                 }
2474                 if (dda != NULL) {
2475                         TAILQ_REMOVE(&state->addrs, dda, next);
2476                         ipv6_freeaddr(dda);
2477                 }
2478         }
2479 }
2480 #endif
2481
2482 static void
2483 dhcp6_deprecateaddrs(struct ipv6_addrhead *addrs)
2484 {
2485         struct ipv6_addr *ia, *ian;
2486
2487         TAILQ_FOREACH_SAFE(ia, addrs, next, ian) {
2488                 if (ia->flags & IPV6_AF_EXTENDED)
2489                         ;
2490                 else if (ia->flags & IPV6_AF_STALE) {
2491                         if (ia->prefix_vltime != 0)
2492                                 logdebugx("%s: %s: became stale",
2493                                     ia->iface->name, ia->saddr);
2494                         /* Technically this violates RFC 8415 18.2.10.1,
2495                          * but we need a mechanism to tell the kernel to
2496                          * try and prefer other addresses. */
2497                         ia->prefix_pltime = 0;
2498                 } else if (ia->prefix_vltime == 0)
2499                         loginfox("%s: %s: no valid lifetime",
2500                             ia->iface->name, ia->saddr);
2501                 else
2502                         continue;
2503
2504 #ifndef SMALL
2505                 /* If we delegated from this prefix, deprecate or remove
2506                  * the delegations. */
2507                 if (ia->flags & IPV6_AF_DELEGATEDPFX)
2508                         dhcp6_deprecatedele(ia);
2509 #endif
2510
2511                 if (ia->flags & IPV6_AF_REQUEST) {
2512                         ia->prefix_vltime = ia->prefix_pltime = 0;
2513                         eloop_q_timeout_delete(ia->iface->ctx->eloop,
2514                             ELOOP_QUEUE_ALL, NULL, ia);
2515                         continue;
2516                 }
2517                 TAILQ_REMOVE(addrs, ia, next);
2518                 if (ia->flags & IPV6_AF_EXTENDED)
2519                         ipv6_deleteaddr(ia);
2520                 ipv6_freeaddr(ia);
2521         }
2522 }
2523
2524 static int
2525 dhcp6_validatelease(struct interface *ifp,
2526     struct dhcp6_message *m, size_t len,
2527     const char *sfrom, const struct timespec *acquired)
2528 {
2529         struct dhcp6_state *state;
2530         int nia, ok_errno;
2531         struct timespec aq;
2532
2533         if (len <= sizeof(*m)) {
2534                 logerrx("%s: DHCPv6 lease truncated", ifp->name);
2535                 return -1;
2536         }
2537
2538         state = D6_STATE(ifp);
2539         errno = 0;
2540         if (dhcp6_checkstatusok(ifp, m, NULL, len) != 0)
2541                 return -1;
2542         ok_errno = errno;
2543
2544         state->renew = state->rebind = state->expire = 0;
2545         state->lowpl = ND6_INFINITE_LIFETIME;
2546         if (!acquired) {
2547                 clock_gettime(CLOCK_MONOTONIC, &aq);
2548                 acquired = &aq;
2549         }
2550         state->has_no_binding = false;
2551         nia = dhcp6_findia(ifp, m, len, sfrom, acquired);
2552         if (nia == 0) {
2553                 if (state->state != DH6S_CONFIRM && ok_errno != 0) {
2554                         logerrx("%s: no useable IA found in lease", ifp->name);
2555                         return -1;
2556                 }
2557
2558                 /* We are confirming and have an OK,
2559                  * so look for ia's in our old lease.
2560                  * IA's must have existed here otherwise we would
2561                  * have rejected it earlier. */
2562                 assert(state->new != NULL && state->new_len != 0);
2563                 state->has_no_binding = false;
2564                 nia = dhcp6_findia(ifp, state->new, state->new_len,
2565                     sfrom, acquired);
2566         }
2567         return nia;
2568 }
2569
2570 static ssize_t
2571 dhcp6_readlease(struct interface *ifp, int validate)
2572 {
2573         union {
2574                 struct dhcp6_message dhcp6;
2575                 uint8_t buf[UDPLEN_MAX];
2576         } buf;
2577         struct dhcp6_state *state;
2578         ssize_t bytes;
2579         int fd;
2580         time_t mtime, now;
2581 #ifdef AUTH
2582         uint8_t *o;
2583         uint16_t ol;
2584 #endif
2585
2586         state = D6_STATE(ifp);
2587         if (state->leasefile[0] == '\0') {
2588                 logdebugx("reading standard input");
2589                 bytes = read(fileno(stdin), buf.buf, sizeof(buf.buf));
2590         } else {
2591                 logdebugx("%s: reading lease `%s'",
2592                     ifp->name, state->leasefile);
2593                 bytes = dhcp_readfile(ifp->ctx, state->leasefile,
2594                     buf.buf, sizeof(buf.buf));
2595         }
2596         if (bytes == -1)
2597                 goto ex;
2598
2599         if (ifp->ctx->options & DHCPCD_DUMPLEASE || state->leasefile[0] == '\0')
2600                 goto out;
2601
2602         if (bytes == 0)
2603                 goto ex;
2604
2605         /* If not validating IA's and if they have expired,
2606          * skip to the auth check. */
2607         if (!validate)
2608                 goto auth;
2609
2610         if (dhcp_filemtime(ifp->ctx, state->leasefile, &mtime) == -1)
2611                 goto ex;
2612         clock_gettime(CLOCK_MONOTONIC, &state->acquired);
2613         if ((now = time(NULL)) == -1)
2614                 goto ex;
2615         state->acquired.tv_sec -= now - mtime;
2616
2617         /* Check to see if the lease is still valid */
2618         fd = dhcp6_validatelease(ifp, &buf.dhcp6, (size_t)bytes, NULL,
2619             &state->acquired);
2620         if (fd == -1)
2621                 goto ex;
2622
2623         if (state->expire != ND6_INFINITE_LIFETIME &&
2624             (time_t)state->expire < now - mtime &&
2625             !(ifp->options->options & DHCPCD_LASTLEASE_EXTEND))
2626         {
2627                 logdebugx("%s: discarding expired lease", ifp->name);
2628                 bytes = 0;
2629                 goto ex;
2630         }
2631
2632 auth:
2633 #ifdef AUTH
2634         /* Authenticate the message */
2635         o = dhcp6_findmoption(&buf.dhcp6, (size_t)bytes, D6_OPTION_AUTH, &ol);
2636         if (o) {
2637                 if (dhcp_auth_validate(&state->auth, &ifp->options->auth,
2638                     buf.buf, (size_t)bytes, 6, buf.dhcp6.type, o, ol) == NULL)
2639                 {
2640                         logerr("%s: authentication failed", ifp->name);
2641                         bytes = 0;
2642                         goto ex;
2643                 }
2644                 if (state->auth.token)
2645                         logdebugx("%s: validated using 0x%08" PRIu32,
2646                             ifp->name, state->auth.token->secretid);
2647                 else
2648                         loginfox("%s: accepted reconfigure key", ifp->name);
2649         } else if ((ifp->options->auth.options & DHCPCD_AUTH_SENDREQUIRE) ==
2650             DHCPCD_AUTH_SENDREQUIRE)
2651         {
2652                 logerrx("%s: authentication now required", ifp->name);
2653                 goto ex;
2654         }
2655 #endif
2656
2657 out:
2658         free(state->new);
2659         state->new = malloc((size_t)bytes);
2660         if (state->new == NULL) {
2661                 logerr(__func__);
2662                 goto ex;
2663         }
2664
2665         memcpy(state->new, buf.buf, (size_t)bytes);
2666         state->new_len = (size_t)bytes;
2667         return bytes;
2668
2669 ex:
2670         dhcp6_freedrop_addrs(ifp, 0, NULL);
2671         dhcp_unlink(ifp->ctx, state->leasefile);
2672         free(state->new);
2673         state->new = NULL;
2674         state->new_len = 0;
2675         return bytes == 0 ? 0 : -1;
2676 }
2677
2678 static void
2679 dhcp6_startinit(struct interface *ifp)
2680 {
2681         struct dhcp6_state *state;
2682         ssize_t r;
2683         uint8_t has_ta, has_non_ta;
2684         size_t i;
2685
2686         state = D6_STATE(ifp);
2687         state->state = DH6S_INIT;
2688         state->expire = ND6_INFINITE_LIFETIME;
2689         state->lowpl = ND6_INFINITE_LIFETIME;
2690
2691         dhcp6_addrequestedaddrs(ifp);
2692         has_ta = has_non_ta = 0;
2693         for (i = 0; i < ifp->options->ia_len; i++) {
2694                 switch (ifp->options->ia[i].ia_type) {
2695                 case D6_OPTION_IA_TA:
2696                         has_ta = 1;
2697                         break;
2698                 default:
2699                         has_non_ta = 1;
2700                 }
2701         }
2702
2703         if (!(ifp->ctx->options & DHCPCD_TEST) &&
2704             !(has_ta && !has_non_ta) &&
2705             ifp->options->reboot != 0)
2706         {
2707                 r = dhcp6_readlease(ifp, 1);
2708                 if (r == -1) {
2709                         if (errno != ENOENT && errno != ESRCH)
2710                                 logerr("%s: %s", __func__, state->leasefile);
2711                 } else if (r != 0 &&
2712                     !(ifp->options->options & DHCPCD_ANONYMOUS))
2713                 {
2714                         /* RFC 3633 section 12.1 */
2715 #ifndef SMALL
2716                         if (dhcp6_hasprefixdelegation(ifp))
2717                                 dhcp6_startrebind(ifp);
2718                         else
2719 #endif
2720                                 dhcp6_startconfirm(ifp);
2721                         return;
2722                 }
2723         }
2724         dhcp6_startdiscoinform(ifp);
2725 }
2726
2727 #ifndef SMALL
2728 static struct ipv6_addr *
2729 dhcp6_ifdelegateaddr(struct interface *ifp, struct ipv6_addr *prefix,
2730     const struct if_sla *sla, struct if_ia *if_ia)
2731 {
2732         struct dhcp6_state *state;
2733         struct in6_addr addr, daddr;
2734         struct ipv6_addr *ia;
2735         int pfxlen, dadcounter;
2736         uint64_t vl;
2737
2738         /* RFC6603 Section 4.2 */
2739         if (strcmp(ifp->name, prefix->iface->name) == 0) {
2740                 if (prefix->prefix_exclude_len == 0) {
2741                         /* Don't spam the log automatically */
2742                         if (sla != NULL)
2743                                 logwarnx("%s: DHCPv6 server does not support "
2744                                     "OPTION_PD_EXCLUDE",
2745                                     ifp->name);
2746                         return NULL;
2747                 }
2748                 pfxlen = prefix->prefix_exclude_len;
2749                 memcpy(&addr, &prefix->prefix_exclude, sizeof(addr));
2750         } else if ((pfxlen = dhcp6_delegateaddr(&addr, ifp, prefix,
2751             sla, if_ia)) == -1)
2752                 return NULL;
2753
2754         if (sla != NULL && fls64(sla->suffix) > 128 - pfxlen) {
2755                 logerrx("%s: suffix %" PRIu64 " + prefix_len %d > 128",
2756                     ifp->name, sla->suffix, pfxlen);
2757                 return NULL;
2758         }
2759
2760         /* Add our suffix */
2761         if (sla != NULL && sla->suffix != 0) {
2762                 daddr = addr;
2763                 vl = be64dec(addr.s6_addr + 8);
2764                 vl |= sla->suffix;
2765                 be64enc(daddr.s6_addr + 8, vl);
2766         } else {
2767                 dadcounter = ipv6_makeaddr(&daddr, ifp, &addr, pfxlen, 0);
2768                 if (dadcounter == -1) {
2769                         logerrx("%s: error adding slaac to prefix_len %d",
2770                             ifp->name, pfxlen);
2771                         return NULL;
2772                 }
2773         }
2774
2775         /* Find an existing address */
2776         state = D6_STATE(ifp);
2777         TAILQ_FOREACH(ia, &state->addrs, next) {
2778                 if (IN6_ARE_ADDR_EQUAL(&ia->addr, &daddr))
2779                         break;
2780         }
2781         if (ia == NULL) {
2782                 ia = ipv6_newaddr(ifp, &daddr, (uint8_t)pfxlen, IPV6_AF_ONLINK);
2783                 if (ia == NULL)
2784                         return NULL;
2785                 ia->dadcallback = dhcp6_dadcallback;
2786                 memcpy(&ia->iaid, &prefix->iaid, sizeof(ia->iaid));
2787                 ia->created = prefix->acquired;
2788
2789                 TAILQ_INSERT_TAIL(&state->addrs, ia, next);
2790                 TAILQ_INSERT_TAIL(&prefix->pd_pfxs, ia, pd_next);
2791         }
2792         ia->delegating_prefix = prefix;
2793         ia->prefix = addr;
2794         ia->prefix_len = (uint8_t)pfxlen;
2795         ia->acquired = prefix->acquired;
2796         ia->prefix_pltime = prefix->prefix_pltime;
2797         ia->prefix_vltime = prefix->prefix_vltime;
2798
2799         /* If the prefix length hasn't changed,
2800          * don't install a reject route. */
2801         if (prefix->prefix_len == pfxlen)
2802                 prefix->flags |= IPV6_AF_NOREJECT;
2803         else
2804                 prefix->flags &= ~IPV6_AF_NOREJECT;
2805
2806         return ia;
2807 }
2808 #endif
2809
2810 static void
2811 dhcp6_script_try_run(struct interface *ifp, int delegated)
2812 {
2813         struct dhcp6_state *state;
2814         struct ipv6_addr *ap;
2815         int completed;
2816
2817         state = D6_STATE(ifp);
2818         completed = 1;
2819         /* If all addresses have completed DAD run the script */
2820         TAILQ_FOREACH(ap, &state->addrs, next) {
2821                 if (!(ap->flags & IPV6_AF_ADDED))
2822                         continue;
2823                 if (ap->flags & IPV6_AF_ONLINK) {
2824                         if (!(ap->flags & IPV6_AF_DADCOMPLETED) &&
2825                             ipv6_iffindaddr(ap->iface, &ap->addr,
2826                                             IN6_IFF_TENTATIVE))
2827                                 ap->flags |= IPV6_AF_DADCOMPLETED;
2828                         if ((ap->flags & IPV6_AF_DADCOMPLETED) == 0
2829 #ifndef SMALL
2830                             && ((delegated && ap->delegating_prefix) ||
2831                             (!delegated && !ap->delegating_prefix))
2832 #endif
2833                             )
2834                         {
2835                                 completed = 0;
2836                                 break;
2837                         }
2838                 }
2839         }
2840         if (completed) {
2841                 script_runreason(ifp, delegated ? "DELEGATED6" : state->reason);
2842                 if (!delegated)
2843                         dhcpcd_daemonise(ifp->ctx);
2844         } else
2845                 logdebugx("%s: waiting for DHCPv6 DAD to complete", ifp->name);
2846 }
2847
2848 #ifdef SMALL
2849 size_t
2850 dhcp6_find_delegates(__unused struct interface *ifp)
2851 {
2852
2853         return 0;
2854 }
2855 #else
2856 static void
2857 dhcp6_delegate_prefix(struct interface *ifp)
2858 {
2859         struct if_options *ifo;
2860         struct dhcp6_state *state;
2861         struct ipv6_addr *ap;
2862         size_t i, j, k;
2863         struct if_ia *ia;
2864         struct if_sla *sla;
2865         struct interface *ifd;
2866         bool carrier_warned;
2867
2868         ifo = ifp->options;
2869         state = D6_STATE(ifp);
2870
2871         /* Clear the logged flag. */
2872         TAILQ_FOREACH(ap, &state->addrs, next) {
2873                 ap->flags &= ~IPV6_AF_DELEGATEDLOG;
2874         }
2875
2876         TAILQ_FOREACH(ifd, ifp->ctx->ifaces, next) {
2877                 if (!ifd->active)
2878                         continue;
2879                 k = 0;
2880                 carrier_warned = false;
2881                 TAILQ_FOREACH(ap, &state->addrs, next) {
2882                         if (!(ap->flags & IPV6_AF_DELEGATEDPFX))
2883                                 continue;
2884                         if (!(ap->flags & IPV6_AF_DELEGATEDLOG)) {
2885                                 int loglevel;
2886
2887                                 if (ap->flags & IPV6_AF_NEW)
2888                                         loglevel = LOG_INFO;
2889                                 else
2890                                         loglevel = LOG_DEBUG;
2891                                 /* We only want to log this the once as we loop
2892                                  * through many interfaces first. */
2893                                 ap->flags |= IPV6_AF_DELEGATEDLOG;
2894                                 logmessage(loglevel, "%s: delegated prefix %s",
2895                                     ifp->name, ap->saddr);
2896                                 ap->flags &= ~IPV6_AF_NEW;
2897                         }
2898                         for (i = 0; i < ifo->ia_len; i++) {
2899                                 ia = &ifo->ia[i];
2900                                 if (ia->ia_type != D6_OPTION_IA_PD)
2901                                         continue;
2902                                 if (memcmp(ia->iaid, ap->iaid,
2903                                     sizeof(ia->iaid)))
2904                                         continue;
2905                                 if (ia->sla_len == 0) {
2906                                         /* no SLA configured, so lets
2907                                          * automate it */
2908                                         if (ifd->carrier != LINK_UP) {
2909                                                 logdebugx(
2910                                                     "%s: has no carrier, cannot"
2911                                                     " delegate addresses",
2912                                                     ifd->name);
2913                                                 carrier_warned = true;
2914                                                 break;
2915                                         }
2916                                         if (dhcp6_ifdelegateaddr(ifd, ap,
2917                                             NULL, ia))
2918                                                 k++;
2919                                 }
2920                                 for (j = 0; j < ia->sla_len; j++) {
2921                                         sla = &ia->sla[j];
2922                                         if (strcmp(ifd->name, sla->ifname))
2923                                                 continue;
2924                                         if (ifd->carrier != LINK_UP) {
2925                                                 logdebugx(
2926                                                     "%s: has no carrier, cannot"
2927                                                     " delegate addresses",
2928                                                     ifd->name);
2929                                                 carrier_warned = true;
2930                                                 break;
2931                                         }
2932                                         if (dhcp6_ifdelegateaddr(ifd, ap,
2933                                             sla, ia))
2934                                                 k++;
2935                                 }
2936                                 if (carrier_warned)
2937                                         break;
2938                         }
2939                         if (carrier_warned)
2940                                 break;
2941                 }
2942                 if (k && !carrier_warned) {
2943                         struct dhcp6_state *s = D6_STATE(ifd);
2944
2945                         ipv6_addaddrs(&s->addrs);
2946                         dhcp6_script_try_run(ifd, 1);
2947                 }
2948         }
2949
2950         /* Now all addresses have been added, rebuild the routing table. */
2951         rt_build(ifp->ctx, AF_INET6);
2952 }
2953
2954 static void
2955 dhcp6_find_delegates1(void *arg)
2956 {
2957
2958         dhcp6_find_delegates(arg);
2959 }
2960
2961 size_t
2962 dhcp6_find_delegates(struct interface *ifp)
2963 {
2964         struct if_options *ifo;
2965         struct dhcp6_state *state;
2966         struct ipv6_addr *ap;
2967         size_t i, j, k;
2968         struct if_ia *ia;
2969         struct if_sla *sla;
2970         struct interface *ifd;
2971
2972         k = 0;
2973         TAILQ_FOREACH(ifd, ifp->ctx->ifaces, next) {
2974                 ifo = ifd->options;
2975                 state = D6_STATE(ifd);
2976                 if (state == NULL || state->state != DH6S_BOUND)
2977                         continue;
2978                 TAILQ_FOREACH(ap, &state->addrs, next) {
2979                         if (!(ap->flags & IPV6_AF_DELEGATEDPFX))
2980                                 continue;
2981                         for (i = 0; i < ifo->ia_len; i++) {
2982                                 ia = &ifo->ia[i];
2983                                 if (ia->ia_type != D6_OPTION_IA_PD)
2984                                         continue;
2985                                 if (memcmp(ia->iaid, ap->iaid,
2986                                     sizeof(ia->iaid)))
2987                                         continue;
2988                                 for (j = 0; j < ia->sla_len; j++) {
2989                                         sla = &ia->sla[j];
2990                                         if (strcmp(ifp->name, sla->ifname))
2991                                                 continue;
2992                                         if (ipv6_linklocal(ifp) == NULL) {
2993                                                 logdebugx(
2994                                                     "%s: delaying adding"
2995                                                     " delegated addresses for"
2996                                                     " LL address",
2997                                                     ifp->name);
2998                                                 ipv6_addlinklocalcallback(ifp,
2999                                                     dhcp6_find_delegates1, ifp);
3000                                                 return 1;
3001                                         }
3002                                         if (dhcp6_ifdelegateaddr(ifp, ap,
3003                                             sla, ia))
3004                                             k++;
3005                                 }
3006                         }
3007                 }
3008         }
3009
3010         if (k) {
3011                 loginfox("%s: adding delegated prefixes", ifp->name);
3012                 state = D6_STATE(ifp);
3013                 state->state = DH6S_DELEGATED;
3014                 ipv6_addaddrs(&state->addrs);
3015                 rt_build(ifp->ctx, AF_INET6);
3016                 dhcp6_script_try_run(ifp, 1);
3017         }
3018         return k;
3019 }
3020 #endif
3021
3022 static void
3023 dhcp6_bind(struct interface *ifp, const char *op, const char *sfrom)
3024 {
3025         struct dhcp6_state *state = D6_STATE(ifp);
3026         bool timedout = (op == NULL), has_new = false, confirmed;
3027         struct ipv6_addr *ia;
3028         int loglevel;
3029         struct timespec now;
3030
3031         TAILQ_FOREACH(ia, &state->addrs, next) {
3032                 if (ia->flags & IPV6_AF_NEW) {
3033                         has_new = true;
3034                         break;
3035                 }
3036         }
3037         loglevel = has_new || state->state != DH6S_RENEW ? LOG_INFO : LOG_DEBUG;
3038         if (!timedout) {
3039                 logmessage(loglevel, "%s: %s received from %s",
3040                     ifp->name, op, sfrom);
3041 #ifndef SMALL
3042                 /* If we delegated from an unconfirmed lease we MUST drop
3043                  * them now. Hopefully we have new delegations. */
3044                 if (state->reason != NULL &&
3045                     strcmp(state->reason, "TIMEOUT6") == 0)
3046                         dhcp6_delete_delegates(ifp);
3047 #endif
3048                 state->reason = NULL;
3049         } else
3050                 state->reason = "TIMEOUT6";
3051
3052         eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
3053         clock_gettime(CLOCK_MONOTONIC, &now);
3054
3055         switch(state->state) {
3056         case DH6S_INFORM:
3057         {
3058                 struct dhcp6_option *o;
3059                 uint16_t ol;
3060
3061                 if (state->reason == NULL)
3062                         state->reason = "INFORM6";
3063                 o = dhcp6_findmoption(state->new, state->new_len,
3064                                       D6_OPTION_INFO_REFRESH_TIME, &ol);
3065                 if (o == NULL || ol != sizeof(uint32_t))
3066                         state->renew = IRT_DEFAULT;
3067                 else {
3068                         memcpy(&state->renew, o, ol);
3069                         state->renew = ntohl(state->renew);
3070                         if (state->renew < IRT_MINIMUM)
3071                                 state->renew = IRT_MINIMUM;
3072                 }
3073                 state->rebind = 0;
3074                 state->expire = ND6_INFINITE_LIFETIME;
3075                 state->lowpl = ND6_INFINITE_LIFETIME;
3076         }
3077                 break;
3078
3079         case DH6S_REQUEST:
3080                 if (state->reason == NULL)
3081                         state->reason = "BOUND6";
3082                 /* FALLTHROUGH */
3083         case DH6S_RENEW:
3084                 if (state->reason == NULL)
3085                         state->reason = "RENEW6";
3086                 /* FALLTHROUGH */
3087         case DH6S_REBIND:
3088                 if (state->reason == NULL)
3089                         state->reason = "REBIND6";
3090                 /* FALLTHROUGH */
3091         case DH6S_CONFIRM:
3092                 if (state->reason == NULL)
3093                         state->reason = "REBOOT6";
3094                 if (state->renew != 0) {
3095                         bool all_expired = true;
3096
3097                         TAILQ_FOREACH(ia, &state->addrs, next) {
3098                                 if (ia->flags & IPV6_AF_STALE)
3099                                         continue;
3100                                 if (!(state->renew == ND6_INFINITE_LIFETIME
3101                                     && ia->prefix_vltime == ND6_INFINITE_LIFETIME)
3102                                     && ia->prefix_vltime != 0
3103                                     && ia->prefix_vltime <= state->renew)
3104                                         logwarnx(
3105                                             "%s: %s will expire before renewal",
3106                                             ifp->name, ia->saddr);
3107                                 else
3108                                         all_expired = false;
3109                         }
3110                         if (all_expired) {
3111                                 /* All address's vltime happens at or before
3112                                  * the configured T1 in the IA.
3113                                  * This is a badly configured server and we
3114                                  * have to use our own notion of what
3115                                  * T1 and T2 should be as a result.
3116                                  *
3117                                  * Doing this violates RFC 3315 22.4:
3118                                  * In a message sent by a server to a client,
3119                                  * the client MUST use the values in the T1
3120                                  * and T2 fields for the T1 and T2 parameters,
3121                                  * unless those values in those fields are 0.
3122                                  */
3123                                 logwarnx("%s: ignoring T1 %"PRIu32
3124                                     " due to address expiry",
3125                                     ifp->name, state->renew);
3126                                 state->renew = state->rebind = 0;
3127                         }
3128                 }
3129                 if (state->renew == 0 && state->lowpl != ND6_INFINITE_LIFETIME)
3130                         state->renew = (uint32_t)(state->lowpl * 0.5);
3131                 if (state->rebind == 0 && state->lowpl != ND6_INFINITE_LIFETIME)
3132                         state->rebind = (uint32_t)(state->lowpl * 0.8);
3133                 break;
3134         default:
3135                 state->reason = "UNKNOWN6";
3136                 break;
3137         }
3138
3139         if (state->state != DH6S_CONFIRM && !timedout) {
3140                 state->acquired = now;
3141                 free(state->old);
3142                 state->old = state->new;
3143                 state->old_len = state->new_len;
3144                 state->new = state->recv;
3145                 state->new_len = state->recv_len;
3146                 state->recv = NULL;
3147                 state->recv_len = 0;
3148                 confirmed = false;
3149         } else {
3150                 /* Reduce timers based on when we got the lease. */
3151                 uint32_t elapsed;
3152
3153                 elapsed = (uint32_t)eloop_timespec_diff(&now,
3154                     &state->acquired, NULL);
3155                 if (state->renew && state->renew != ND6_INFINITE_LIFETIME) {
3156                         if (state->renew > elapsed)
3157                                 state->renew -= elapsed;
3158                         else
3159                                 state->renew = 0;
3160                 }
3161                 if (state->rebind && state->rebind != ND6_INFINITE_LIFETIME) {
3162                         if (state->rebind > elapsed)
3163                                 state->rebind -= elapsed;
3164                         else
3165                                 state->rebind = 0;
3166                 }
3167                 if (state->expire && state->expire != ND6_INFINITE_LIFETIME) {
3168                         if (state->expire > elapsed)
3169                                 state->expire -= elapsed;
3170                         else
3171                                 state->expire = 0;
3172                 }
3173                 confirmed = true;
3174         }
3175
3176         if (ifp->ctx->options & DHCPCD_TEST)
3177                 script_runreason(ifp, "TEST");
3178         else {
3179                 if (state->state == DH6S_INFORM)
3180                         state->state = DH6S_INFORMED;
3181                 else
3182                         state->state = DH6S_BOUND;
3183                 state->failed = false;
3184
3185                 if ((state->renew != 0 || state->rebind != 0) &&
3186                     state->renew != ND6_INFINITE_LIFETIME)
3187                         eloop_timeout_add_sec(ifp->ctx->eloop,
3188                             state->renew,
3189                             state->state == DH6S_INFORMED ?
3190                             dhcp6_startinform : dhcp6_startrenew, ifp);
3191                 if ((state->rebind != 0 || state->expire != 0) &&
3192                     state->rebind != ND6_INFINITE_LIFETIME)
3193                         eloop_timeout_add_sec(ifp->ctx->eloop,
3194                             state->rebind, dhcp6_startrebind, ifp);
3195                 if (state->expire != ND6_INFINITE_LIFETIME)
3196                         eloop_timeout_add_sec(ifp->ctx->eloop,
3197                             state->expire, dhcp6_startexpire, ifp);
3198
3199                 ipv6_addaddrs(&state->addrs);
3200                 if (!timedout)
3201                         dhcp6_deprecateaddrs(&state->addrs);
3202
3203                 if (state->state == DH6S_INFORMED)
3204                         logmessage(loglevel, "%s: refresh in %"PRIu32" seconds",
3205                             ifp->name, state->renew);
3206                 else if (state->renew == ND6_INFINITE_LIFETIME)
3207                         logmessage(loglevel, "%s: leased for infinity",
3208                             ifp->name);
3209                 else if (state->renew || state->rebind)
3210                         logmessage(loglevel, "%s: renew in %"PRIu32", "
3211                             "rebind in %"PRIu32", "
3212                             "expire in %"PRIu32" seconds",
3213                             ifp->name,
3214                             state->renew, state->rebind, state->expire);
3215                 else if (state->expire == 0)
3216                         logmessage(loglevel, "%s: will expire", ifp->name);
3217                 else
3218                         logmessage(loglevel, "%s: expire in %"PRIu32" seconds",
3219                             ifp->name, state->expire);
3220                 rt_build(ifp->ctx, AF_INET6);
3221                 if (!confirmed && !timedout) {
3222                         logdebugx("%s: writing lease `%s'",
3223                             ifp->name, state->leasefile);
3224                         if (dhcp_writefile(ifp->ctx, state->leasefile, 0640,
3225                             state->new, state->new_len) == -1)
3226                                 logerr("dhcp_writefile: %s",state->leasefile);
3227                 }
3228 #ifndef SMALL
3229                 dhcp6_delegate_prefix(ifp);
3230 #endif
3231                 dhcp6_script_try_run(ifp, 0);
3232         }
3233
3234         if (ifp->ctx->options & DHCPCD_TEST ||
3235             (ifp->options->options & DHCPCD_INFORM &&
3236             !(ifp->ctx->options & DHCPCD_MASTER)))
3237         {
3238                 eloop_exit(ifp->ctx->eloop, EXIT_SUCCESS);
3239         }
3240 }
3241
3242 static void
3243 dhcp6_recvif(struct interface *ifp, const char *sfrom,
3244     struct dhcp6_message *r, size_t len)
3245 {
3246         struct dhcpcd_ctx *ctx;
3247         size_t i;
3248         const char *op;
3249         struct dhcp6_state *state;
3250         uint8_t *o;
3251         uint16_t ol;
3252         const struct dhcp_opt *opt;
3253         const struct if_options *ifo;
3254         bool valid_op;
3255 #ifdef AUTH
3256         uint8_t *auth;
3257         uint16_t auth_len;
3258 #endif
3259
3260         ctx = ifp->ctx;
3261         state = D6_STATE(ifp);
3262         if (state == NULL || state->send == NULL) {
3263                 logdebugx("%s: DHCPv6 reply received but not running",
3264                     ifp->name);
3265                 return;
3266         }
3267
3268         /* We're already bound and this message is for another machine */
3269         /* XXX DELEGATED? */
3270         if (r->type != DHCP6_RECONFIGURE &&
3271             (state->state == DH6S_BOUND || state->state == DH6S_INFORMED))
3272         {
3273                 logdebugx("%s: DHCPv6 reply received but already bound",
3274                     ifp->name);
3275                 return;
3276         }
3277
3278         if (dhcp6_findmoption(r, len, D6_OPTION_SERVERID, NULL) == NULL) {
3279                 logdebugx("%s: no DHCPv6 server ID from %s", ifp->name, sfrom);
3280                 return;
3281         }
3282
3283         ifo = ifp->options;
3284         for (i = 0, opt = ctx->dhcp6_opts;
3285             i < ctx->dhcp6_opts_len;
3286             i++, opt++)
3287         {
3288                 if (has_option_mask(ifo->requiremask6, opt->option) &&
3289                     !dhcp6_findmoption(r, len, (uint16_t)opt->option, NULL))
3290                 {
3291                         logwarnx("%s: reject DHCPv6 (no option %s) from %s",
3292                             ifp->name, opt->var, sfrom);
3293                         return;
3294                 }
3295                 if (has_option_mask(ifo->rejectmask6, opt->option) &&
3296                     dhcp6_findmoption(r, len, (uint16_t)opt->option, NULL))
3297                 {
3298                         logwarnx("%s: reject DHCPv6 (option %s) from %s",
3299                             ifp->name, opt->var, sfrom);
3300                         return;
3301                 }
3302         }
3303
3304 #ifdef AUTH
3305         /* Authenticate the message */
3306         auth = dhcp6_findmoption(r, len, D6_OPTION_AUTH, &auth_len);
3307         if (auth != NULL) {
3308                 if (dhcp_auth_validate(&state->auth, &ifo->auth,
3309                     (uint8_t *)r, len, 6, r->type, auth, auth_len) == NULL)
3310                 {
3311                         logerr("%s: authentication failed from %s",
3312                             ifp->name, sfrom);
3313                         return;
3314                 }
3315                 if (state->auth.token)
3316                         logdebugx("%s: validated using 0x%08" PRIu32,
3317                             ifp->name, state->auth.token->secretid);
3318                 else
3319                         loginfox("%s: accepted reconfigure key", ifp->name);
3320         } else if (ifo->auth.options & DHCPCD_AUTH_SEND) {
3321                 if (ifo->auth.options & DHCPCD_AUTH_REQUIRE) {
3322                         logerr("%s: no authentication from %s",
3323                             ifp->name, sfrom);
3324                         return;
3325                 }
3326                 logwarnx("%s: no authentication from %s", ifp->name, sfrom);
3327         }
3328 #endif
3329
3330         op = dhcp6_get_op(r->type);
3331         valid_op = op != NULL;
3332         switch(r->type) {
3333         case DHCP6_REPLY:
3334                 switch(state->state) {
3335                 case DH6S_INFORM:
3336                         if (dhcp6_checkstatusok(ifp, r, NULL, len) != 0)
3337                                 return;
3338                         break;
3339                 case DH6S_CONFIRM:
3340                         if (dhcp6_validatelease(ifp, r, len, sfrom, NULL) == -1)
3341                         {
3342                                 dhcp6_startdiscoinform(ifp);
3343                                 return;
3344                         }
3345                         break;
3346                 case DH6S_DISCOVER:
3347                         /* Only accept REPLY in DISCOVER for RAPID_COMMIT.
3348                          * Normally we get an ADVERTISE for a DISCOVER. */
3349                         if (!has_option_mask(ifo->requestmask6,
3350                             D6_OPTION_RAPID_COMMIT) ||
3351                             !dhcp6_findmoption(r, len, D6_OPTION_RAPID_COMMIT,
3352                                               NULL))
3353                         {
3354                                 valid_op = false;
3355                                 break;
3356                         }
3357                         /* Validate lease before setting state to REQUEST. */
3358                         /* FALLTHROUGH */
3359                 case DH6S_REQUEST: /* FALLTHROUGH */
3360                 case DH6S_RENEW: /* FALLTHROUGH */
3361                 case DH6S_REBIND:
3362                         if (dhcp6_validatelease(ifp, r, len, sfrom, NULL) == -1)
3363                         {
3364                                 /*
3365                                  * If we can't use the lease, fallback to
3366                                  * DISCOVER and try and get a new one.
3367                                  *
3368                                  * This is needed become some servers
3369                                  * renumber the prefix or address
3370                                  * and deny the current one before it expires
3371                                  * rather than sending it back with a zero
3372                                  * lifetime along with the new prefix or
3373                                  * address to use.
3374                                  * This behavior is wrong, but moving to the
3375                                  * DISCOVER phase works around it.
3376                                  *
3377                                  * The currently held lease is still valid
3378                                  * until a new one is found.
3379                                  */
3380                                 if (state->state != DH6S_DISCOVER)
3381                                         dhcp6_startdiscoinform(ifp);
3382                                 return;
3383                         }
3384                         /* RFC8415 18.2.10.1 */
3385                         if ((state->state == DH6S_RENEW ||
3386                             state->state == DH6S_REBIND) &&
3387                             state->has_no_binding)
3388                         {
3389                                 dhcp6_startrequest(ifp);
3390                                 return;
3391                         }
3392                         if (state->state == DH6S_DISCOVER)
3393                                 state->state = DH6S_REQUEST;
3394                         break;
3395                 case DH6S_DECLINE:
3396                         /* This isnt really a failure, but an
3397                          * acknowledgement of one. */
3398                         loginfox("%s: %s acknowledged DECLINE6",
3399                             ifp->name, sfrom);
3400                         dhcp6_fail(ifp);
3401                         return;
3402                 default:
3403                         valid_op = false;
3404                         break;
3405                 }
3406                 break;
3407         case DHCP6_ADVERTISE:
3408                 if (state->state != DH6S_DISCOVER) {
3409                         valid_op = false;
3410                         break;
3411                 }
3412                 /* RFC7083 */
3413                 o = dhcp6_findmoption(r, len, D6_OPTION_SOL_MAX_RT, &ol);
3414                 if (o && ol == sizeof(uint32_t)) {
3415                         uint32_t max_rt;
3416
3417                         memcpy(&max_rt, o, sizeof(max_rt));
3418                         max_rt = ntohl(max_rt);
3419                         if (max_rt >= 60 && max_rt <= 86400) {
3420                                 logdebugx("%s: SOL_MAX_RT %llu -> %u",
3421                                     ifp->name,
3422                                     (unsigned long long)state->sol_max_rt,
3423                                     max_rt);
3424                                 state->sol_max_rt = max_rt;
3425                         } else
3426                                 logerr("%s: invalid SOL_MAX_RT %u",
3427                                     ifp->name, max_rt);
3428                 }
3429                 o = dhcp6_findmoption(r, len, D6_OPTION_INF_MAX_RT, &ol);
3430                 if (o && ol == sizeof(uint32_t)) {
3431                         uint32_t max_rt;
3432
3433                         memcpy(&max_rt, o, sizeof(max_rt));
3434                         max_rt = ntohl(max_rt);
3435                         if (max_rt >= 60 && max_rt <= 86400) {
3436                                 logdebugx("%s: INF_MAX_RT %llu -> %u",
3437                                     ifp->name,
3438                                     (unsigned long long)state->inf_max_rt,
3439                                     max_rt);
3440                                 state->inf_max_rt = max_rt;
3441                         } else
3442                                 logerrx("%s: invalid INF_MAX_RT %u",
3443                                     ifp->name, max_rt);
3444                 }
3445                 if (dhcp6_validatelease(ifp, r, len, sfrom, NULL) == -1)
3446                         return;
3447                 break;
3448         case DHCP6_RECONFIGURE:
3449 #ifdef AUTH
3450                 if (auth == NULL) {
3451 #endif
3452                         logerrx("%s: unauthenticated %s from %s",
3453                             ifp->name, op, sfrom);
3454                         if (ifo->auth.options & DHCPCD_AUTH_REQUIRE)
3455                                 return;
3456 #ifdef AUTH
3457                 }
3458                 loginfox("%s: %s from %s", ifp->name, op, sfrom);
3459                 o = dhcp6_findmoption(r, len, D6_OPTION_RECONF_MSG, &ol);
3460                 if (o == NULL) {
3461                         logerrx("%s: missing Reconfigure Message option",
3462                             ifp->name);
3463                         return;
3464                 }
3465                 if (ol != 1) {
3466                         logerrx("%s: missing Reconfigure Message type",
3467                             ifp->name);
3468                         return;
3469                 }
3470                 switch(*o) {
3471                 case DHCP6_RENEW:
3472                         if (state->state != DH6S_BOUND) {
3473                                 logerrx("%s: not bound, ignoring %s",
3474                                     ifp->name, op);
3475                                 return;
3476                         }
3477                         dhcp6_startrenew(ifp);
3478                         break;
3479                 case DHCP6_INFORMATION_REQ:
3480                         if (state->state != DH6S_INFORMED) {
3481                                 logerrx("%s: not informed, ignoring %s",
3482                                     ifp->name, op);
3483                                 return;
3484                         }
3485                         eloop_timeout_delete(ifp->ctx->eloop,
3486                             dhcp6_sendinform, ifp);
3487                         dhcp6_startinform(ifp);
3488                         break;
3489                 default:
3490                         logerr("%s: unsupported %s type %d",
3491                             ifp->name, op, *o);
3492                         break;
3493                 }
3494                 return;
3495 #else
3496                 break;
3497 #endif
3498         default:
3499                 logerrx("%s: invalid DHCP6 type %s (%d)",
3500                     ifp->name, op, r->type);
3501                 return;
3502         }
3503         if (!valid_op) {
3504                 logwarnx("%s: invalid state for DHCP6 type %s (%d)",
3505                     ifp->name, op, r->type);
3506                 return;
3507         }
3508
3509         if (state->recv_len < (size_t)len) {
3510                 free(state->recv);
3511                 state->recv = malloc(len);
3512                 if (state->recv == NULL) {
3513                         logerr(__func__);
3514                         return;
3515                 }
3516         }
3517         memcpy(state->recv, r, len);
3518         state->recv_len = len;
3519
3520         if (r->type == DHCP6_ADVERTISE) {
3521                 struct ipv6_addr *ia;
3522
3523                 if (state->state == DH6S_REQUEST) /* rapid commit */
3524                         goto bind;
3525                 TAILQ_FOREACH(ia, &state->addrs, next) {
3526                         if (!(ia->flags & (IPV6_AF_STALE | IPV6_AF_REQUEST)))
3527                                 break;
3528                 }
3529                 if (ia == NULL)
3530                         ia = TAILQ_FIRST(&state->addrs);
3531                 if (ia == NULL)
3532                         loginfox("%s: ADV (no address) from %s",
3533                             ifp->name, sfrom);
3534                 else
3535                         loginfox("%s: ADV %s from %s",
3536                             ifp->name, ia->saddr, sfrom);
3537                 dhcp6_startrequest(ifp);
3538                 return;
3539         }
3540
3541 bind:
3542         dhcp6_bind(ifp, op, sfrom);
3543 }
3544
3545 void
3546 dhcp6_recvmsg(struct dhcpcd_ctx *ctx, struct msghdr *msg, struct ipv6_addr *ia)
3547 {
3548         struct sockaddr_in6 *from = msg->msg_name;
3549         size_t len = msg->msg_iov[0].iov_len;
3550         char sfrom[INET6_ADDRSTRLEN];
3551         struct interface *ifp;
3552         struct dhcp6_message *r;
3553         const struct dhcp6_state *state;
3554         uint8_t *o;
3555         uint16_t ol;
3556
3557         inet_ntop(AF_INET6, &from->sin6_addr, sfrom, sizeof(sfrom));
3558         if (len < sizeof(struct dhcp6_message)) {
3559                 logerrx("DHCPv6 packet too short from %s", sfrom);
3560                 return;
3561         }
3562
3563         if (ia != NULL)
3564                 ifp = ia->iface;
3565         else {
3566                 ifp = if_findifpfromcmsg(ctx, msg, NULL);
3567                 if (ifp == NULL) {
3568                         logerr(__func__);
3569                         return;
3570                 }
3571         }
3572
3573         r = (struct dhcp6_message *)msg->msg_iov[0].iov_base;
3574
3575         uint8_t duid[DUID_LEN], *dp;
3576         size_t duid_len;
3577         o = dhcp6_findmoption(r, len, D6_OPTION_CLIENTID, &ol);
3578         if (ifp->options->options & DHCPCD_ANONYMOUS) {
3579                 duid_len = duid_make(duid, ifp, DUID_LL);
3580                 dp = duid;
3581         } else {
3582                 duid_len = ctx->duid_len;
3583                 dp = ctx->duid;
3584         }
3585         if (o == NULL || ol != duid_len || memcmp(o, dp, ol) != 0) {
3586                 logdebugx("%s: incorrect client ID from %s",
3587                     ifp->name, sfrom);
3588                 return;
3589         }
3590
3591         if (dhcp6_findmoption(r, len, D6_OPTION_SERVERID, NULL) == NULL) {
3592                 logdebugx("%s: no DHCPv6 server ID from %s",
3593                     ifp->name, sfrom);
3594                 return;
3595         }
3596
3597         if (r->type == DHCP6_RECONFIGURE) {
3598                 logdebugx("%s: RECONFIGURE6 recv from %s,"
3599                     " sending to all interfaces",
3600                     ifp->name, sfrom);
3601                 TAILQ_FOREACH(ifp, ctx->ifaces, next) {
3602                         state = D6_CSTATE(ifp);
3603                         if (state != NULL && state->send != NULL)
3604                                 dhcp6_recvif(ifp, sfrom, r, len);
3605                 }
3606                 return;
3607         }
3608
3609         state = D6_CSTATE(ifp);
3610         if (state == NULL ||
3611             r->xid[0] != state->send->xid[0] ||
3612             r->xid[1] != state->send->xid[1] ||
3613             r->xid[2] != state->send->xid[2])
3614         {
3615                 struct interface *ifp1;
3616                 const struct dhcp6_state *state1;
3617
3618                 /* Find an interface with a matching xid. */
3619                 TAILQ_FOREACH(ifp1, ctx->ifaces, next) {
3620                         state1 = D6_CSTATE(ifp1);
3621                         if (state1 == NULL || state1->send == NULL)
3622                                 continue;
3623                         if (r->xid[0] == state1->send->xid[0] &&
3624                             r->xid[1] == state1->send->xid[1] &&
3625                             r->xid[2] == state1->send->xid[2])
3626                                 break;
3627                 }
3628
3629                 if (ifp1 == NULL) {
3630                         if (state != NULL)
3631                                 logdebugx("%s: wrong xid 0x%02x%02x%02x"
3632                                     " (expecting 0x%02x%02x%02x) from %s",
3633                                     ifp->name,
3634                                     r->xid[0], r->xid[1], r->xid[2],
3635                                     state->send->xid[0],
3636                                     state->send->xid[1],
3637                                     state->send->xid[2],
3638                                     sfrom);
3639                         return;
3640                 }
3641                 logdebugx("%s: redirecting DHCP6 message to %s",
3642                     ifp->name, ifp1->name);
3643                 ifp = ifp1;
3644         }
3645
3646 #if 0
3647         /*
3648          * Handy code to inject raw DHCPv6 packets over responses
3649          * from our server.
3650          * This allows me to take a 3rd party wireshark trace and
3651          * replay it in my code.
3652          */
3653         static int replyn = 0;
3654         char fname[PATH_MAX], tbuf[UDPLEN_MAX];
3655         int fd;
3656         ssize_t tlen;
3657         uint8_t *si1, *si2;
3658         uint16_t si_len1, si_len2;
3659
3660         snprintf(fname, sizeof(fname),
3661             "/tmp/dhcp6.reply%d.raw", replyn++);
3662         fd = open(fname, O_RDONLY, 0);
3663         if (fd == -1) {
3664                 logerr("%s: open `%s'", __func__, fname);
3665                 return;
3666         }
3667         tlen = read(fd, tbuf, sizeof(tbuf));
3668         if (tlen == -1)
3669                 logerr("%s: read `%s'", __func__, fname);
3670         close(fd);
3671
3672         /* Copy across ServerID so we can work with our own server. */
3673         si1 = dhcp6_findmoption(r, len, D6_OPTION_SERVERID, &si_len1);
3674         si2 = dhcp6_findmoption(tbuf, (size_t)tlen,
3675             D6_OPTION_SERVERID, &si_len2);
3676         if (si1 != NULL && si2 != NULL && si_len1 == si_len2)
3677                 memcpy(si2, si1, si_len2);
3678         r = (struct dhcp6_message *)tbuf;
3679         len = (size_t)tlen;
3680 #endif
3681
3682         dhcp6_recvif(ifp, sfrom, r, len);
3683 }
3684
3685 static void
3686 dhcp6_recv(struct dhcpcd_ctx *ctx, struct ipv6_addr *ia)
3687 {
3688         struct sockaddr_in6 from;
3689         union {
3690                 struct dhcp6_message dhcp6;
3691                 uint8_t buf[UDPLEN_MAX]; /* Maximum UDP message size */
3692         } iovbuf;
3693         struct iovec iov = {
3694                 .iov_base = iovbuf.buf, .iov_len = sizeof(iovbuf.buf),
3695         };
3696         union {
3697                 struct cmsghdr hdr;
3698                 uint8_t buf[CMSG_SPACE(sizeof(struct in6_pktinfo))];
3699         } cmsgbuf = { .buf = { 0 } };
3700         struct msghdr msg = {
3701             .msg_name = &from, .msg_namelen = sizeof(from),
3702             .msg_iov = &iov, .msg_iovlen = 1,
3703             .msg_control = cmsgbuf.buf, .msg_controllen = sizeof(cmsgbuf.buf),
3704         };
3705         int s;
3706         ssize_t bytes;
3707
3708         s = ia != NULL ? ia->dhcp6_fd : ctx->dhcp6_rfd;
3709         bytes = recvmsg(s, &msg, 0);
3710         if (bytes == -1) {
3711                 logerr(__func__);
3712                 return;
3713         }
3714
3715         iov.iov_len = (size_t)bytes;
3716         dhcp6_recvmsg(ctx, &msg, ia);
3717 }
3718
3719 static void
3720 dhcp6_recvaddr(void *arg)
3721 {
3722         struct ipv6_addr *ia = arg;
3723
3724         dhcp6_recv(ia->iface->ctx, ia);
3725 }
3726
3727 static void
3728 dhcp6_recvctx(void *arg)
3729 {
3730         struct dhcpcd_ctx *ctx = arg;
3731
3732         dhcp6_recv(ctx, NULL);
3733 }
3734
3735 int
3736 dhcp6_openraw(void)
3737 {
3738         int fd, v;
3739
3740         fd = socket(PF_INET6, SOCK_RAW | SOCK_CXNB, IPPROTO_UDP);
3741         if (fd == -1)
3742                 return -1;
3743
3744         v = 1;
3745         if (setsockopt(fd, SOL_SOCKET, SO_BROADCAST, &v, sizeof(v)) == -1)
3746                 goto errexit;
3747
3748         v = offsetof(struct udphdr, uh_sum);
3749         if (setsockopt(fd, IPPROTO_IPV6, IPV6_CHECKSUM, &v, sizeof(v)) == -1)
3750                 goto errexit;
3751
3752         return fd;
3753
3754 errexit:
3755         close(fd);
3756         return -1;
3757 }
3758
3759 int
3760 dhcp6_openudp(unsigned int ifindex, struct in6_addr *ia)
3761 {
3762         struct sockaddr_in6 sa;
3763         int n, s;
3764
3765         s = xsocket(PF_INET6, SOCK_DGRAM | SOCK_CXNB, IPPROTO_UDP);
3766         if (s == -1)
3767                 goto errexit;
3768
3769         memset(&sa, 0, sizeof(sa));
3770         sa.sin6_family = AF_INET6;
3771         sa.sin6_port = htons(DHCP6_CLIENT_PORT);
3772 #ifdef BSD
3773         sa.sin6_len = sizeof(sa);
3774 #endif
3775
3776         if (ia != NULL) {
3777                 memcpy(&sa.sin6_addr, ia, sizeof(sa.sin6_addr));
3778                 ipv6_setscope(&sa, ifindex);
3779         }
3780
3781         if (bind(s, (struct sockaddr *)&sa, sizeof(sa)) == -1)
3782                 goto errexit;
3783
3784         n = 1;
3785         if (setsockopt(s, IPPROTO_IPV6, IPV6_RECVPKTINFO, &n, sizeof(n)) == -1)
3786                 goto errexit;
3787
3788 #ifdef SO_RERROR
3789         n = 1;
3790         if (setsockopt(s, SOL_SOCKET, SO_RERROR, &n, sizeof(n)) == -1)
3791                 goto errexit;
3792 #endif
3793
3794         return s;
3795
3796 errexit:
3797         logerr(__func__);
3798         if (s != -1)
3799                 close(s);
3800         return -1;
3801 }
3802
3803 #ifndef SMALL
3804 static void
3805 dhcp6_activateinterfaces(struct interface *ifp)
3806 {
3807         struct interface *ifd;
3808         size_t i, j;
3809         struct if_ia *ia;
3810         struct if_sla *sla;
3811
3812         for (i = 0; i < ifp->options->ia_len; i++) {
3813                 ia = &ifp->options->ia[i];
3814                 if (ia->ia_type != D6_OPTION_IA_PD)
3815                         continue;
3816                 for (j = 0; j < ia->sla_len; j++) {
3817                         sla = &ia->sla[j];
3818                         ifd = if_find(ifp->ctx->ifaces, sla->ifname);
3819                         if (ifd == NULL) {
3820                                 logwarn("%s: cannot delegate to %s",
3821                                     ifp->name, sla->ifname);
3822                                 continue;
3823                         }
3824                         if (!ifd->active) {
3825                                 loginfox("%s: activating for delegation",
3826                                     sla->ifname);
3827                                 dhcpcd_activateinterface(ifd,
3828                                     DHCPCD_IPV6 | DHCPCD_DHCP6);
3829                         }
3830                 }
3831         }
3832 }
3833 #endif
3834
3835 static void
3836 dhcp6_start1(void *arg)
3837 {
3838         struct interface *ifp = arg;
3839         struct dhcpcd_ctx *ctx = ifp->ctx;
3840         struct if_options *ifo = ifp->options;
3841         struct dhcp6_state *state;
3842         size_t i;
3843         const struct dhcp_compat *dhc;
3844
3845         if ((ctx->options & (DHCPCD_MASTER|DHCPCD_PRIVSEP)) == DHCPCD_MASTER &&
3846             ctx->dhcp6_rfd == -1)
3847         {
3848                 ctx->dhcp6_rfd = dhcp6_openudp(0, NULL);
3849                 if (ctx->dhcp6_rfd == -1) {
3850                         logerr(__func__);
3851                         return;
3852                 }
3853                 eloop_event_add(ctx->eloop, ctx->dhcp6_rfd, dhcp6_recvctx, ctx);
3854         }
3855
3856         if (!IN_PRIVSEP(ctx) && ctx->dhcp6_wfd == -1) {
3857                 ctx->dhcp6_wfd = dhcp6_openraw();
3858                 if (ctx->dhcp6_wfd == -1) {
3859                         logerr(__func__);
3860                         return;
3861                 }
3862         }
3863
3864         state = D6_STATE(ifp);
3865         /* If no DHCPv6 options are configured,
3866            match configured DHCPv4 options to DHCPv6 equivalents. */
3867         for (i = 0; i < sizeof(ifo->requestmask6); i++) {
3868                 if (ifo->requestmask6[i] != '\0')
3869                         break;
3870         }
3871         if (i == sizeof(ifo->requestmask6)) {
3872                 for (dhc = dhcp_compats; dhc->dhcp_opt; dhc++) {
3873                         if (DHC_REQ(ifo->requestmask, ifo->nomask, dhc->dhcp_opt))
3874                                 add_option_mask(ifo->requestmask6,
3875                                     dhc->dhcp6_opt);
3876                 }
3877                 if (ifo->fqdn != FQDN_DISABLE || ifo->options & DHCPCD_HOSTNAME)
3878                         add_option_mask(ifo->requestmask6, D6_OPTION_FQDN);
3879         }
3880
3881 #ifndef SMALL
3882         /* Rapid commit won't work with Prefix Delegation Exclusion */
3883         if (dhcp6_findselfsla(ifp))
3884                 del_option_mask(ifo->requestmask6, D6_OPTION_RAPID_COMMIT);
3885 #endif
3886
3887         if (state->state == DH6S_INFORM) {
3888                 add_option_mask(ifo->requestmask6, D6_OPTION_INFO_REFRESH_TIME);
3889                 dhcp6_startinform(ifp);
3890         } else {
3891                 del_option_mask(ifo->requestmask6, D6_OPTION_INFO_REFRESH_TIME);
3892                 dhcp6_startinit(ifp);
3893         }
3894
3895 #ifndef SMALL
3896         dhcp6_activateinterfaces(ifp);
3897 #endif
3898 }
3899
3900 int
3901 dhcp6_start(struct interface *ifp, enum DH6S init_state)
3902 {
3903         struct dhcp6_state *state;
3904
3905         state = D6_STATE(ifp);
3906         if (state != NULL) {
3907                 switch (init_state) {
3908                 case DH6S_INIT:
3909                         goto gogogo;
3910                 case DH6S_INFORM:
3911                         if (state->state == DH6S_INIT ||
3912                             state->state == DH6S_INFORMED ||
3913                             (state->state == DH6S_DISCOVER &&
3914                             !(ifp->options->options & DHCPCD_IA_FORCED) &&
3915                             !ipv6nd_hasradhcp(ifp, true)))
3916                                 dhcp6_startinform(ifp);
3917                         break;
3918                 case DH6S_REQUEST:
3919                         if (ifp->options->options & DHCPCD_DHCP6 &&
3920                             (state->state == DH6S_INIT ||
3921                              state->state == DH6S_INFORM ||
3922                              state->state == DH6S_INFORMED ||
3923                              state->state == DH6S_DELEGATED))
3924                         {
3925                                 /* Change from stateless to stateful */
3926                                 init_state = DH6S_INIT;
3927                                 goto gogogo;
3928                         }
3929                         break;
3930                 case DH6S_CONFIRM:
3931                         init_state = DH6S_INIT;
3932                         goto gogogo;
3933                 default:
3934                         /* Not possible, but sushes some compiler warnings. */
3935                         break;
3936                 }
3937                 return 0;
3938         } else {
3939                 switch (init_state) {
3940                 case DH6S_CONFIRM:
3941                         /* No DHCPv6 config, no existing state
3942                          * so nothing to do. */
3943                         return 0;
3944                 case DH6S_INFORM:
3945                         break;
3946                 default:
3947                         init_state = DH6S_INIT;
3948                         break;
3949                 }
3950         }
3951
3952         if (!(ifp->options->options & DHCPCD_DHCP6))
3953                 return 0;
3954
3955         ifp->if_data[IF_DATA_DHCP6] = calloc(1, sizeof(*state));
3956         state = D6_STATE(ifp);
3957         if (state == NULL)
3958                 return -1;
3959
3960         state->sol_max_rt = SOL_MAX_RT;
3961         state->inf_max_rt = INF_MAX_RT;
3962         TAILQ_INIT(&state->addrs);
3963
3964 gogogo:
3965         state->state = init_state;
3966         state->lerror = 0;
3967         state->failed = false;
3968         dhcp_set_leasefile(state->leasefile, sizeof(state->leasefile),
3969             AF_INET6, ifp);
3970         if (ipv6_linklocal(ifp) == NULL) {
3971                 logdebugx("%s: delaying DHCPv6 for LL address", ifp->name);
3972                 ipv6_addlinklocalcallback(ifp, dhcp6_start1, ifp);
3973                 return 0;
3974         }
3975
3976         dhcp6_start1(ifp);
3977         return 0;
3978 }
3979
3980 void
3981 dhcp6_reboot(struct interface *ifp)
3982 {
3983         struct dhcp6_state *state;
3984
3985         state = D6_STATE(ifp);
3986         if (state == NULL)
3987                 return;
3988
3989         state->lerror = 0;
3990         switch (state->state) {
3991         case DH6S_BOUND:
3992                 dhcp6_startrebind(ifp);
3993                 break;
3994         default:
3995                 dhcp6_startdiscoinform(ifp);
3996                 break;
3997         }
3998 }
3999
4000 static void
4001 dhcp6_freedrop(struct interface *ifp, int drop, const char *reason)
4002 {
4003         struct dhcp6_state *state;
4004         struct dhcpcd_ctx *ctx;
4005         unsigned long long options;
4006
4007         if (ifp->options)
4008                 options = ifp->options->options;
4009         else
4010                 options = ifp->ctx->options;
4011
4012         if (ifp->ctx->eloop)
4013                 eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
4014
4015 #ifndef SMALL
4016         /* If we're dropping the lease, drop delegated addresses.
4017          * If, for whatever reason, we don't drop them in the future
4018          * then they should at least be marked as deprecated (pltime 0). */
4019         if (drop && (options & DHCPCD_NODROP) != DHCPCD_NODROP)
4020                 dhcp6_delete_delegates(ifp);
4021 #endif
4022
4023         state = D6_STATE(ifp);
4024         if (state) {
4025                 /* Failure to send the release may cause this function to
4026                  * re-enter */
4027                 if (state->state == DH6S_RELEASE) {
4028                         dhcp6_finishrelease(ifp);
4029                         return;
4030                 }
4031
4032                 if (drop && options & DHCPCD_RELEASE &&
4033                     state->state != DH6S_DELEGATED)
4034                 {
4035                         if (ifp->carrier == LINK_UP &&
4036                             state->state != DH6S_RELEASED &&
4037                             state->state != DH6S_INFORMED)
4038                         {
4039                                 dhcp6_startrelease(ifp);
4040                                 return;
4041                         }
4042                         dhcp_unlink(ifp->ctx, state->leasefile);
4043                 }
4044                 dhcp6_freedrop_addrs(ifp, drop, NULL);
4045                 free(state->old);
4046                 state->old = state->new;
4047                 state->old_len = state->new_len;
4048                 state->new = NULL;
4049                 state->new_len = 0;
4050                 if (drop && state->old &&
4051                     (options & DHCPCD_NODROP) != DHCPCD_NODROP)
4052                 {
4053                         if (reason == NULL)
4054                                 reason = "STOP6";
4055                         script_runreason(ifp, reason);
4056                 }
4057                 free(state->old);
4058                 free(state->send);
4059                 free(state->recv);
4060                 free(state);
4061                 ifp->if_data[IF_DATA_DHCP6] = NULL;
4062         }
4063
4064         /* If we don't have any more DHCP6 enabled interfaces,
4065          * close the global socket and release resources */
4066         ctx = ifp->ctx;
4067         if (ctx->ifaces) {
4068                 TAILQ_FOREACH(ifp, ctx->ifaces, next) {
4069                         if (D6_STATE(ifp))
4070                                 break;
4071                 }
4072         }
4073         if (ifp == NULL && ctx->dhcp6_rfd != -1) {
4074                 eloop_event_delete(ctx->eloop, ctx->dhcp6_rfd);
4075                 close(ctx->dhcp6_rfd);
4076                 ctx->dhcp6_rfd = -1;
4077         }
4078 }
4079
4080 void
4081 dhcp6_drop(struct interface *ifp, const char *reason)
4082 {
4083
4084         dhcp6_freedrop(ifp, 1, reason);
4085 }
4086
4087 void
4088 dhcp6_free(struct interface *ifp)
4089 {
4090
4091         dhcp6_freedrop(ifp, 0, NULL);
4092 }
4093
4094 void
4095 dhcp6_abort(struct interface *ifp)
4096 {
4097         struct dhcp6_state *state;
4098 #ifdef ND6_ADVERTISE
4099         struct ipv6_addr *ia;
4100 #endif
4101
4102         eloop_timeout_delete(ifp->ctx->eloop, dhcp6_start1, ifp);
4103         state = D6_STATE(ifp);
4104         if (state == NULL)
4105                 return;
4106
4107 #ifdef ND6_ADVERTISE
4108         TAILQ_FOREACH(ia, &state->addrs, next) {
4109                 ipv6nd_advertise(ia);
4110         }
4111 #endif
4112
4113         eloop_timeout_delete(ifp->ctx->eloop, dhcp6_startdiscover, ifp);
4114         eloop_timeout_delete(ifp->ctx->eloop, dhcp6_senddiscover, ifp);
4115         eloop_timeout_delete(ifp->ctx->eloop, dhcp6_startinform, ifp);
4116         eloop_timeout_delete(ifp->ctx->eloop, dhcp6_sendinform, ifp);
4117
4118         switch (state->state) {
4119         case DH6S_DISCOVER:     /* FALLTHROUGH */
4120         case DH6S_REQUEST:      /* FALLTHROUGH */
4121         case DH6S_INFORM:
4122                 state->state = DH6S_INIT;
4123                 break;
4124         default:
4125                 break;
4126         }
4127 }
4128
4129 void
4130 dhcp6_handleifa(int cmd, struct ipv6_addr *ia, pid_t pid)
4131 {
4132         struct dhcp6_state *state;
4133         struct interface *ifp = ia->iface;
4134
4135         /* If not running in master mode, listen to this address */
4136         if (cmd == RTM_NEWADDR &&
4137             !(ia->addr_flags & IN6_IFF_NOTUSEABLE) &&
4138             ifp->active == IF_ACTIVE_USER &&
4139             !(ifp->ctx->options & DHCPCD_MASTER) &&
4140             ifp->options->options & DHCPCD_DHCP6)
4141         {
4142 #ifdef PRIVSEP
4143                 if (IN_PRIVSEP_SE(ifp->ctx)) {
4144                         if (ps_inet_opendhcp6(ia) == -1)
4145                                 logerr(__func__);
4146                 } else
4147 #endif
4148                 {
4149                         if (ia->dhcp6_fd == -1)
4150                                 ia->dhcp6_fd = dhcp6_openudp(ia->iface->index,
4151                                     &ia->addr);
4152                         if (ia->dhcp6_fd != -1)
4153                                 eloop_event_add(ia->iface->ctx->eloop,
4154                                 ia->dhcp6_fd, dhcp6_recvaddr, ia);
4155                 }
4156         }
4157
4158
4159         if ((state = D6_STATE(ifp)) != NULL)
4160                 ipv6_handleifa_addrs(cmd, &state->addrs, ia, pid);
4161 }
4162
4163 ssize_t
4164 dhcp6_env(FILE *fp, const char *prefix, const struct interface *ifp,
4165     const struct dhcp6_message *m, size_t len)
4166 {
4167         const struct if_options *ifo;
4168         struct dhcp_opt *opt, *vo;
4169         const uint8_t *p;
4170         struct dhcp6_option o;
4171         size_t i;
4172         char *pfx;
4173         uint32_t en;
4174         const struct dhcpcd_ctx *ctx;
4175 #ifndef SMALL
4176         const struct dhcp6_state *state;
4177         const struct ipv6_addr *ap;
4178 #endif
4179
4180         if (m == NULL)
4181                 goto delegated;
4182
4183         if (len < sizeof(*m)) {
4184                 /* Should be impossible with guards at packet in
4185                  * and reading leases */
4186                 errno = EINVAL;
4187                 return -1;
4188         }
4189
4190         ifo = ifp->options;
4191         ctx = ifp->ctx;
4192
4193         /* Zero our indexes */
4194         for (i = 0, opt = ctx->dhcp6_opts;
4195             i < ctx->dhcp6_opts_len;
4196             i++, opt++)
4197                 dhcp_zero_index(opt);
4198         for (i = 0, opt = ifp->options->dhcp6_override;
4199             i < ifp->options->dhcp6_override_len;
4200             i++, opt++)
4201                 dhcp_zero_index(opt);
4202         for (i = 0, opt = ctx->vivso;
4203             i < ctx->vivso_len;
4204             i++, opt++)
4205                 dhcp_zero_index(opt);
4206         if (asprintf(&pfx, "%s_dhcp6", prefix) == -1)
4207                 return -1;
4208
4209         /* Unlike DHCP, DHCPv6 options *may* occur more than once.
4210          * There is also no provision for option concatenation unlike DHCP. */
4211         p = (const uint8_t *)m + sizeof(*m);
4212         len -= sizeof(*m);
4213         for (; len != 0; p += o.len, len -= o.len) {
4214                 if (len < sizeof(o)) {
4215                         errno = EINVAL;
4216                         break;
4217                 }
4218                 memcpy(&o, p, sizeof(o));
4219                 p += sizeof(o);
4220                 len -= sizeof(o);
4221                 o.len = ntohs(o.len);
4222                 if (len < o.len) {
4223                         errno = EINVAL;
4224                         break;
4225                 }
4226                 o.code = ntohs(o.code);
4227                 if (has_option_mask(ifo->nomask6, o.code))
4228                         continue;
4229                 for (i = 0, opt = ifo->dhcp6_override;
4230                     i < ifo->dhcp6_override_len;
4231                     i++, opt++)
4232                         if (opt->option == o.code)
4233                                 break;
4234                 if (i == ifo->dhcp6_override_len &&
4235                     o.code == D6_OPTION_VENDOR_OPTS &&
4236                     o.len > sizeof(en))
4237                 {
4238                         memcpy(&en, p, sizeof(en));
4239                         en = ntohl(en);
4240                         vo = vivso_find(en, ifp);
4241                 } else
4242                         vo = NULL;
4243                 if (i == ifo->dhcp6_override_len) {
4244                         for (i = 0, opt = ctx->dhcp6_opts;
4245                             i < ctx->dhcp6_opts_len;
4246                             i++, opt++)
4247                                 if (opt->option == o.code)
4248                                         break;
4249                         if (i == ctx->dhcp6_opts_len)
4250                                 opt = NULL;
4251                 }
4252                 if (opt) {
4253                         dhcp_envoption(ifp->ctx,
4254                             fp, pfx, ifp->name,
4255                             opt, dhcp6_getoption, p, o.len);
4256                 }
4257                 if (vo) {
4258                         dhcp_envoption(ifp->ctx,
4259                             fp, pfx, ifp->name,
4260                             vo, dhcp6_getoption,
4261                             p + sizeof(en),
4262                             o.len - sizeof(en));
4263                 }
4264         }
4265         free(pfx);
4266
4267 delegated:
4268 #ifndef SMALL
4269         /* Needed for Delegated Prefixes */
4270         state = D6_CSTATE(ifp);
4271         TAILQ_FOREACH(ap, &state->addrs, next) {
4272                 if (ap->delegating_prefix)
4273                         break;
4274         }
4275         if (ap == NULL)
4276                 return 1;
4277         if (fprintf(fp, "%s_delegated_dhcp6_prefix=", prefix) == -1)
4278                 return -1;
4279         TAILQ_FOREACH(ap, &state->addrs, next) {
4280                 if (ap->delegating_prefix == NULL)
4281                         continue;
4282                 if (ap != TAILQ_FIRST(&state->addrs)) {
4283                         if (fputc(' ', fp) == EOF)
4284                                 return -1;
4285                 }
4286                 if (fprintf(fp, "%s", ap->saddr) == -1)
4287                         return -1;
4288         }
4289         if (fputc('\0', fp) == EOF)
4290                 return -1;
4291 #endif
4292
4293         return 1;
4294 }
4295 #endif
4296
4297 #ifndef SMALL
4298 int
4299 dhcp6_dump(struct interface *ifp)
4300 {
4301         struct dhcp6_state *state;
4302
4303         ifp->if_data[IF_DATA_DHCP6] = state = calloc(1, sizeof(*state));
4304         if (state == NULL) {
4305                 logerr(__func__);
4306                 return -1;
4307         }
4308         TAILQ_INIT(&state->addrs);
4309         if (dhcp6_readlease(ifp, 0) == -1) {
4310                 logerr("dhcp6_readlease");
4311                 return -1;
4312         }
4313         state->reason = "DUMP6";
4314         return script_runreason(ifp, state->reason);
4315 }
4316 #endif