Update to dhcpcd-9.2.0 with the following changes:
[dragonfly.git] / contrib / dhcpcd / src / dhcp.c
blob61cc256a85969b05a452dda7b9760d75cabf7e5d
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
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.
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.
29 #include <sys/param.h>
30 #include <sys/socket.h>
32 #include <arpa/inet.h>
33 #include <net/if.h>
34 #include <net/route.h>
35 #include <netinet/if_ether.h>
36 #include <netinet/in_systm.h>
37 #include <netinet/in.h>
38 #include <netinet/ip.h>
39 #define __FAVOR_BSD /* Nasty glibc hack so we can use BSD semantics for UDP */
40 #include <netinet/udp.h>
41 #undef __FAVOR_BSD
43 #ifdef AF_LINK
44 # include <net/if_dl.h>
45 #endif
47 #include <assert.h>
48 #include <ctype.h>
49 #include <errno.h>
50 #include <fcntl.h>
51 #include <inttypes.h>
52 #include <stdbool.h>
53 #include <stddef.h>
54 #include <stdio.h>
55 #include <stdlib.h>
56 #include <string.h>
57 #include <unistd.h>
58 #include <syslog.h>
60 #define ELOOP_QUEUE ELOOP_DHCP
61 #include "config.h"
62 #include "arp.h"
63 #include "bpf.h"
64 #include "common.h"
65 #include "dhcp.h"
66 #include "dhcpcd.h"
67 #include "dhcp-common.h"
68 #include "duid.h"
69 #include "eloop.h"
70 #include "if.h"
71 #include "ipv4.h"
72 #include "ipv4ll.h"
73 #include "logerr.h"
74 #include "privsep.h"
75 #include "sa.h"
76 #include "script.h"
78 #define DAD "Duplicate address detected"
79 #define DHCP_MIN_LEASE 20
81 #define IPV4A ADDRIPV4 | ARRAY
82 #define IPV4R ADDRIPV4 | REQUEST
84 /* We should define a maximum for the NAK exponential backoff */
85 #define NAKOFF_MAX 60
87 /* Wait N nanoseconds between sending a RELEASE and dropping the address.
88 * This gives the kernel enough time to actually send it. */
89 #define RELEASE_DELAY_S 0
90 #define RELEASE_DELAY_NS 10000000
92 #ifndef IPDEFTTL
93 #define IPDEFTTL 64 /* RFC1340 */
94 #endif
96 /* Support older systems with different defines */
97 #if !defined(IP_RECVPKTINFO) && defined(IP_PKTINFO)
98 #define IP_RECVPKTINFO IP_PKTINFO
99 #endif
101 /* Assert the correct structure size for on wire */
102 __CTASSERT(sizeof(struct ip) == 20);
103 __CTASSERT(sizeof(struct udphdr) == 8);
104 __CTASSERT(sizeof(struct bootp) == 300);
106 struct dhcp_op {
107 uint8_t value;
108 const char *name;
111 static const struct dhcp_op dhcp_ops[] = {
112 { DHCP_DISCOVER, "DISCOVER" },
113 { DHCP_OFFER, "OFFER" },
114 { DHCP_REQUEST, "REQUEST" },
115 { DHCP_DECLINE, "DECLINE" },
116 { DHCP_ACK, "ACK" },
117 { DHCP_NAK, "NAK" },
118 { DHCP_RELEASE, "RELEASE" },
119 { DHCP_INFORM, "INFORM" },
120 { DHCP_FORCERENEW, "FORCERENEW"},
121 { 0, NULL }
124 static const char * const dhcp_params[] = {
125 "ip_address",
126 "subnet_cidr",
127 "network_number",
128 "filename",
129 "server_name",
130 NULL
133 static int dhcp_openbpf(struct interface *);
134 static void dhcp_start1(void *);
135 #if defined(ARP) && (!defined(KERNEL_RFC5227) || defined(ARPING))
136 static void dhcp_arp_found(struct arp_state *, const struct arp_msg *);
137 #endif
138 static void dhcp_handledhcp(struct interface *, struct bootp *, size_t,
139 const struct in_addr *);
140 static void dhcp_handleifudp(void *);
141 static int dhcp_initstate(struct interface *);
143 void
144 dhcp_printoptions(const struct dhcpcd_ctx *ctx,
145 const struct dhcp_opt *opts, size_t opts_len)
147 const char * const *p;
148 size_t i, j;
149 const struct dhcp_opt *opt, *opt2;
150 int cols;
152 for (p = dhcp_params; *p; p++)
153 printf(" %s\n", *p);
155 for (i = 0, opt = ctx->dhcp_opts; i < ctx->dhcp_opts_len; i++, opt++) {
156 for (j = 0, opt2 = opts; j < opts_len; j++, opt2++)
157 if (opt->option == opt2->option)
158 break;
159 if (j == opts_len) {
160 cols = printf("%03d %s", opt->option, opt->var);
161 dhcp_print_option_encoding(opt, cols);
164 for (i = 0, opt = opts; i < opts_len; i++, opt++) {
165 cols = printf("%03d %s", opt->option, opt->var);
166 dhcp_print_option_encoding(opt, cols);
170 static const uint8_t *
171 get_option(struct dhcpcd_ctx *ctx,
172 const struct bootp *bootp, size_t bootp_len,
173 unsigned int opt, size_t *opt_len)
175 const uint8_t *p, *e;
176 uint8_t l, o, ol, overl, *bp;
177 const uint8_t *op;
178 size_t bl;
180 if (bootp == NULL || bootp_len < DHCP_MIN_LEN) {
181 errno = EINVAL;
182 return NULL;
185 /* Check we have the magic cookie */
186 if (!IS_DHCP(bootp)) {
187 errno = ENOTSUP;
188 return NULL;
191 p = bootp->vend + 4; /* options after the 4 byte cookie */
192 e = (const uint8_t *)bootp + bootp_len;
193 ol = o = overl = 0;
194 bp = NULL;
195 op = NULL;
196 bl = 0;
197 while (p < e) {
198 o = *p++;
199 switch (o) {
200 case DHO_PAD:
201 /* No length to read */
202 continue;
203 case DHO_END:
204 if (overl & 1) {
205 /* bit 1 set means parse boot file */
206 overl = (uint8_t)(overl & ~1);
207 p = bootp->file;
208 e = p + sizeof(bootp->file);
209 } else if (overl & 2) {
210 /* bit 2 set means parse server name */
211 overl = (uint8_t)(overl & ~2);
212 p = bootp->sname;
213 e = p + sizeof(bootp->sname);
214 } else
215 goto exit;
216 /* No length to read */
217 continue;
220 /* Check we can read the length */
221 if (p == e) {
222 errno = EINVAL;
223 return NULL;
225 l = *p++;
227 /* Check we can read the option data, if present */
228 if (p + l > e) {
229 errno = EINVAL;
230 return NULL;
233 if (o == DHO_OPTSOVERLOADED) {
234 /* Ensure we only get this option once by setting
235 * the last bit as well as the value.
236 * This is valid because only the first two bits
237 * actually mean anything in RFC2132 Section 9.3 */
238 if (l == 1 && !overl)
239 overl = 0x80 | p[0];
242 if (o == opt) {
243 if (op) {
244 /* We must concatonate the options. */
245 if (bl + l > ctx->opt_buffer_len) {
246 size_t pos;
247 uint8_t *nb;
249 if (bp)
250 pos = (size_t)
251 (bp - ctx->opt_buffer);
252 else
253 pos = 0;
254 nb = realloc(ctx->opt_buffer, bl + l);
255 if (nb == NULL)
256 return NULL;
257 ctx->opt_buffer = nb;
258 ctx->opt_buffer_len = bl + l;
259 bp = ctx->opt_buffer + pos;
261 if (bp == NULL)
262 bp = ctx->opt_buffer;
263 memcpy(bp, op, ol);
264 bp += ol;
266 ol = l;
267 op = p;
268 bl += ol;
270 p += l;
273 exit:
274 if (opt_len)
275 *opt_len = bl;
276 if (bp) {
277 memcpy(bp, op, ol);
278 return (const uint8_t *)ctx->opt_buffer;
280 if (op)
281 return op;
282 errno = ENOENT;
283 return NULL;
286 static int
287 get_option_addr(struct dhcpcd_ctx *ctx,
288 struct in_addr *a, const struct bootp *bootp, size_t bootp_len,
289 uint8_t option)
291 const uint8_t *p;
292 size_t len;
294 p = get_option(ctx, bootp, bootp_len, option, &len);
295 if (!p || len < (ssize_t)sizeof(a->s_addr))
296 return -1;
297 memcpy(&a->s_addr, p, sizeof(a->s_addr));
298 return 0;
301 static int
302 get_option_uint32(struct dhcpcd_ctx *ctx,
303 uint32_t *i, const struct bootp *bootp, size_t bootp_len, uint8_t option)
305 const uint8_t *p;
306 size_t len;
307 uint32_t d;
309 p = get_option(ctx, bootp, bootp_len, option, &len);
310 if (!p || len < (ssize_t)sizeof(d))
311 return -1;
312 memcpy(&d, p, sizeof(d));
313 if (i)
314 *i = ntohl(d);
315 return 0;
318 static int
319 get_option_uint16(struct dhcpcd_ctx *ctx,
320 uint16_t *i, const struct bootp *bootp, size_t bootp_len, uint8_t option)
322 const uint8_t *p;
323 size_t len;
324 uint16_t d;
326 p = get_option(ctx, bootp, bootp_len, option, &len);
327 if (!p || len < (ssize_t)sizeof(d))
328 return -1;
329 memcpy(&d, p, sizeof(d));
330 if (i)
331 *i = ntohs(d);
332 return 0;
335 static int
336 get_option_uint8(struct dhcpcd_ctx *ctx,
337 uint8_t *i, const struct bootp *bootp, size_t bootp_len, uint8_t option)
339 const uint8_t *p;
340 size_t len;
342 p = get_option(ctx, bootp, bootp_len, option, &len);
343 if (!p || len < (ssize_t)sizeof(*p))
344 return -1;
345 if (i)
346 *i = *(p);
347 return 0;
350 ssize_t
351 print_rfc3442(FILE *fp, const uint8_t *data, size_t data_len)
353 const uint8_t *p = data, *e;
354 size_t ocets;
355 uint8_t cidr;
356 struct in_addr addr;
358 /* Minimum is 5 -first is CIDR and a router length of 4 */
359 if (data_len < 5) {
360 errno = EINVAL;
361 return -1;
364 e = p + data_len;
365 while (p < e) {
366 if (p != data) {
367 if (fputc(' ', fp) == EOF)
368 return -1;
370 cidr = *p++;
371 if (cidr > 32) {
372 errno = EINVAL;
373 return -1;
375 ocets = (size_t)(cidr + 7) / NBBY;
376 if (p + 4 + ocets > e) {
377 errno = ERANGE;
378 return -1;
380 /* If we have ocets then we have a destination and netmask */
381 addr.s_addr = 0;
382 if (ocets > 0) {
383 memcpy(&addr.s_addr, p, ocets);
384 p += ocets;
386 if (fprintf(fp, "%s/%d", inet_ntoa(addr), cidr) == -1)
387 return -1;
389 /* Finally, snag the router */
390 memcpy(&addr.s_addr, p, 4);
391 p += 4;
392 if (fprintf(fp, " %s", inet_ntoa(addr)) == -1)
393 return -1;
396 if (fputc('\0', fp) == EOF)
397 return -1;
398 return 1;
401 static int
402 decode_rfc3442_rt(rb_tree_t *routes, struct interface *ifp,
403 const uint8_t *data, size_t dl, const struct bootp *bootp)
405 const uint8_t *p = data;
406 const uint8_t *e;
407 uint8_t cidr;
408 size_t ocets;
409 struct rt *rt = NULL;
410 struct in_addr dest, netmask, gateway;
411 int n;
413 /* Minimum is 5 -first is CIDR and a router length of 4 */
414 if (dl < 5) {
415 errno = EINVAL;
416 return -1;
419 n = 0;
420 e = p + dl;
421 while (p < e) {
422 cidr = *p++;
423 if (cidr > 32) {
424 errno = EINVAL;
425 return -1;
428 ocets = (size_t)(cidr + 7) / NBBY;
429 if (p + 4 + ocets > e) {
430 errno = ERANGE;
431 return -1;
434 if ((rt = rt_new(ifp)) == NULL)
435 return -1;
437 /* If we have ocets then we have a destination and netmask */
438 dest.s_addr = 0;
439 if (ocets > 0) {
440 memcpy(&dest.s_addr, p, ocets);
441 p += ocets;
442 netmask.s_addr = htonl(~0U << (32 - cidr));
443 } else
444 netmask.s_addr = 0;
446 /* Finally, snag the router */
447 memcpy(&gateway.s_addr, p, 4);
448 p += 4;
450 /* An on-link host route is normally set by having the
451 * gateway match the destination or assigned address */
452 if (gateway.s_addr == dest.s_addr ||
453 (gateway.s_addr == bootp->yiaddr ||
454 gateway.s_addr == bootp->ciaddr))
456 gateway.s_addr = INADDR_ANY;
457 netmask.s_addr = INADDR_BROADCAST;
459 if (netmask.s_addr == INADDR_BROADCAST)
460 rt->rt_flags = RTF_HOST;
462 sa_in_init(&rt->rt_dest, &dest);
463 sa_in_init(&rt->rt_netmask, &netmask);
464 sa_in_init(&rt->rt_gateway, &gateway);
465 if (rt_proto_add(routes, rt))
466 n = 1;
468 return n;
471 ssize_t
472 print_rfc3361(FILE *fp, const uint8_t *data, size_t dl)
474 uint8_t enc;
475 char sip[NS_MAXDNAME];
476 struct in_addr addr;
478 if (dl < 2) {
479 errno = EINVAL;
480 return 0;
483 enc = *data++;
484 dl--;
485 switch (enc) {
486 case 0:
487 if (decode_rfc1035(sip, sizeof(sip), data, dl) == -1)
488 return -1;
489 if (efprintf(fp, "%s", sip) == -1)
490 return -1;
491 break;
492 case 1:
493 if (dl % 4 != 0) {
494 errno = EINVAL;
495 break;
497 addr.s_addr = INADDR_BROADCAST;
498 for (;
499 dl != 0;
500 data += sizeof(addr.s_addr), dl -= sizeof(addr.s_addr))
502 memcpy(&addr.s_addr, data, sizeof(addr.s_addr));
503 if (fprintf(fp, "%s", inet_ntoa(addr)) == -1)
504 return -1;
505 if (dl != sizeof(addr.s_addr)) {
506 if (fputc(' ', fp) == EOF)
507 return -1;
510 if (fputc('\0', fp) == EOF)
511 return -1;
512 break;
513 default:
514 errno = EINVAL;
515 return 0;
518 return 1;
521 static char *
522 get_option_string(struct dhcpcd_ctx *ctx,
523 const struct bootp *bootp, size_t bootp_len, uint8_t option)
525 size_t len;
526 const uint8_t *p;
527 char *s;
529 p = get_option(ctx, bootp, bootp_len, option, &len);
530 if (!p || len == 0 || *p == '\0')
531 return NULL;
533 s = malloc(sizeof(char) * (len + 1));
534 if (s) {
535 memcpy(s, p, len);
536 s[len] = '\0';
538 return s;
541 /* This calculates the netmask that we should use for static routes.
542 * This IS different from the calculation used to calculate the netmask
543 * for an interface address. */
544 static uint32_t
545 route_netmask(uint32_t ip_in)
547 /* used to be unsigned long - check if error */
548 uint32_t p = ntohl(ip_in);
549 uint32_t t;
551 if (IN_CLASSA(p))
552 t = ~IN_CLASSA_NET;
553 else {
554 if (IN_CLASSB(p))
555 t = ~IN_CLASSB_NET;
556 else {
557 if (IN_CLASSC(p))
558 t = ~IN_CLASSC_NET;
559 else
560 t = 0;
564 while (t & p)
565 t >>= 1;
567 return (htonl(~t));
570 /* We need to obey routing options.
571 * If we have a CSR then we only use that.
572 * Otherwise we add static routes and then routers. */
573 static int
574 get_option_routes(rb_tree_t *routes, struct interface *ifp,
575 const struct bootp *bootp, size_t bootp_len)
577 struct if_options *ifo = ifp->options;
578 const uint8_t *p;
579 const uint8_t *e;
580 struct rt *rt = NULL;
581 struct in_addr dest, netmask, gateway;
582 size_t len;
583 const char *csr = "";
584 int n;
586 /* If we have CSR's then we MUST use these only */
587 if (!has_option_mask(ifo->nomask, DHO_CSR))
588 p = get_option(ifp->ctx, bootp, bootp_len, DHO_CSR, &len);
589 else
590 p = NULL;
591 /* Check for crappy MS option */
592 if (!p && !has_option_mask(ifo->nomask, DHO_MSCSR)) {
593 p = get_option(ifp->ctx, bootp, bootp_len, DHO_MSCSR, &len);
594 if (p)
595 csr = "MS ";
597 if (p && (n = decode_rfc3442_rt(routes, ifp, p, len, bootp)) != -1) {
598 const struct dhcp_state *state;
600 state = D_CSTATE(ifp);
601 if (!(ifo->options & DHCPCD_CSR_WARNED) &&
602 !(state->added & STATE_FAKE))
604 logdebugx("%s: using %sClassless Static Routes",
605 ifp->name, csr);
606 ifo->options |= DHCPCD_CSR_WARNED;
608 return n;
611 n = 0;
612 /* OK, get our static routes first. */
613 if (!has_option_mask(ifo->nomask, DHO_STATICROUTE))
614 p = get_option(ifp->ctx, bootp, bootp_len,
615 DHO_STATICROUTE, &len);
616 else
617 p = NULL;
618 /* RFC 2131 Section 5.8 states length MUST be in multiples of 8 */
619 if (p && len % 8 == 0) {
620 e = p + len;
621 while (p < e) {
622 memcpy(&dest.s_addr, p, sizeof(dest.s_addr));
623 p += 4;
624 memcpy(&gateway.s_addr, p, sizeof(gateway.s_addr));
625 p += 4;
626 /* RFC 2131 Section 5.8 states default route is
627 * illegal */
628 if (gateway.s_addr == INADDR_ANY)
629 continue;
630 if ((rt = rt_new(ifp)) == NULL)
631 return -1;
633 /* A on-link host route is normally set by having the
634 * gateway match the destination or assigned address */
635 if (gateway.s_addr == dest.s_addr ||
636 (gateway.s_addr == bootp->yiaddr ||
637 gateway.s_addr == bootp->ciaddr))
639 gateway.s_addr = INADDR_ANY;
640 netmask.s_addr = INADDR_BROADCAST;
641 } else
642 netmask.s_addr = route_netmask(dest.s_addr);
643 if (netmask.s_addr == INADDR_BROADCAST)
644 rt->rt_flags = RTF_HOST;
646 sa_in_init(&rt->rt_dest, &dest);
647 sa_in_init(&rt->rt_netmask, &netmask);
648 sa_in_init(&rt->rt_gateway, &gateway);
649 if (rt_proto_add(routes, rt))
650 n++;
654 /* Now grab our routers */
655 if (!has_option_mask(ifo->nomask, DHO_ROUTER))
656 p = get_option(ifp->ctx, bootp, bootp_len, DHO_ROUTER, &len);
657 else
658 p = NULL;
659 if (p && len % 4 == 0) {
660 e = p + len;
661 dest.s_addr = INADDR_ANY;
662 netmask.s_addr = INADDR_ANY;
663 while (p < e) {
664 if ((rt = rt_new(ifp)) == NULL)
665 return -1;
666 memcpy(&gateway.s_addr, p, sizeof(gateway.s_addr));
667 p += 4;
668 sa_in_init(&rt->rt_dest, &dest);
669 sa_in_init(&rt->rt_netmask, &netmask);
670 sa_in_init(&rt->rt_gateway, &gateway);
671 if (rt_proto_add(routes, rt))
672 n++;
676 return n;
679 uint16_t
680 dhcp_get_mtu(const struct interface *ifp)
682 const struct dhcp_state *state;
683 uint16_t mtu;
685 if (ifp->options->mtu)
686 return (uint16_t)ifp->options->mtu;
687 mtu = 0; /* bogus gcc warning */
688 if ((state = D_CSTATE(ifp)) == NULL ||
689 has_option_mask(ifp->options->nomask, DHO_MTU) ||
690 get_option_uint16(ifp->ctx, &mtu,
691 state->new, state->new_len, DHO_MTU) == -1)
692 return 0;
693 return mtu;
696 /* Grab our routers from the DHCP message and apply any MTU value
697 * the message contains */
699 dhcp_get_routes(rb_tree_t *routes, struct interface *ifp)
701 const struct dhcp_state *state;
703 if ((state = D_CSTATE(ifp)) == NULL || !(state->added & STATE_ADDED))
704 return 0;
705 return get_option_routes(routes, ifp, state->new, state->new_len);
708 /* Assumes DHCP options */
709 static int
710 dhcp_message_add_addr(struct bootp *bootp,
711 uint8_t type, struct in_addr addr)
713 uint8_t *p;
714 size_t len;
716 p = bootp->vend;
717 while (*p != DHO_END) {
718 p++;
719 p += *p + 1;
722 len = (size_t)(p - bootp->vend);
723 if (len + 6 > sizeof(bootp->vend)) {
724 errno = ENOMEM;
725 return -1;
728 *p++ = type;
729 *p++ = 4;
730 memcpy(p, &addr.s_addr, 4);
731 p += 4;
732 *p = DHO_END;
733 return 0;
736 static ssize_t
737 make_message(struct bootp **bootpm, const struct interface *ifp, uint8_t type)
739 struct bootp *bootp;
740 uint8_t *lp, *p, *e;
741 uint8_t *n_params = NULL;
742 uint32_t ul;
743 uint16_t sz;
744 size_t len, i;
745 const struct dhcp_opt *opt;
746 struct if_options *ifo = ifp->options;
747 const struct dhcp_state *state = D_CSTATE(ifp);
748 const struct dhcp_lease *lease = &state->lease;
749 char hbuf[HOSTNAME_MAX_LEN + 1];
750 const char *hostname;
751 const struct vivco *vivco;
752 int mtu;
753 #ifdef AUTH
754 uint8_t *auth, auth_len;
755 #endif
757 if ((mtu = if_getmtu(ifp)) == -1)
758 logerr("%s: if_getmtu", ifp->name);
759 else if (mtu < MTU_MIN) {
760 if (if_setmtu(ifp, MTU_MIN) == -1)
761 logerr("%s: if_setmtu", ifp->name);
762 mtu = MTU_MIN;
765 if (ifo->options & DHCPCD_BOOTP)
766 bootp = calloc(1, sizeof (*bootp));
767 else
768 /* Make the maximal message we could send */
769 bootp = calloc(1, (size_t)(mtu - IP_UDP_SIZE));
771 if (bootp == NULL)
772 return -1;
773 *bootpm = bootp;
775 if (state->addr != NULL &&
776 (type == DHCP_INFORM || type == DHCP_RELEASE ||
777 (type == DHCP_REQUEST &&
778 state->addr->mask.s_addr == lease->mask.s_addr &&
779 (state->new == NULL || IS_DHCP(state->new)) &&
780 !(state->added & (STATE_FAKE | STATE_EXPIRED)))))
781 bootp->ciaddr = state->addr->addr.s_addr;
783 bootp->op = BOOTREQUEST;
784 bootp->htype = (uint8_t)ifp->hwtype;
785 if (ifp->hwlen != 0 && ifp->hwlen < sizeof(bootp->chaddr)) {
786 bootp->hlen = (uint8_t)ifp->hwlen;
787 memcpy(&bootp->chaddr, &ifp->hwaddr, ifp->hwlen);
790 if (ifo->options & DHCPCD_BROADCAST &&
791 bootp->ciaddr == 0 &&
792 type != DHCP_DECLINE &&
793 type != DHCP_RELEASE)
794 bootp->flags = htons(BROADCAST_FLAG);
796 if (type != DHCP_DECLINE && type != DHCP_RELEASE) {
797 struct timespec tv;
798 unsigned long long secs;
800 clock_gettime(CLOCK_MONOTONIC, &tv);
801 secs = eloop_timespec_diff(&tv, &state->started, NULL);
802 if (secs > UINT16_MAX)
803 bootp->secs = htons((uint16_t)UINT16_MAX);
804 else
805 bootp->secs = htons((uint16_t)secs);
808 bootp->xid = htonl(state->xid);
810 if (ifo->options & DHCPCD_BOOTP)
811 return sizeof(*bootp);
813 p = bootp->vend;
814 e = (uint8_t *)bootp + (mtu - IP_UDP_SIZE) - 1; /* -1 for DHO_END */
816 ul = htonl(MAGIC_COOKIE);
817 memcpy(p, &ul, sizeof(ul));
818 p += sizeof(ul);
820 #define AREA_LEFT (size_t)(e - p)
821 #define AREA_FIT(s) if ((s) > AREA_LEFT) goto toobig
822 #define AREA_CHECK(s) if ((s) + 2UL > AREA_LEFT) goto toobig
823 #define PUT_ADDR(o, a) do { \
824 AREA_CHECK(4); \
825 *p++ = (o); \
826 *p++ = 4; \
827 memcpy(p, &(a)->s_addr, 4); \
828 p += 4; \
829 } while (0 /* CONSTCOND */)
831 /* Options are listed in numerical order as per RFC 7844 Section 3.1
832 * XXX: They should be randomised. */
834 bool putip = false;
835 if (lease->addr.s_addr && lease->cookie == htonl(MAGIC_COOKIE)) {
836 if (type == DHCP_DECLINE ||
837 (type == DHCP_REQUEST &&
838 (state->addr == NULL ||
839 state->added & (STATE_FAKE | STATE_EXPIRED) ||
840 lease->addr.s_addr != state->addr->addr.s_addr)))
842 putip = true;
843 PUT_ADDR(DHO_IPADDRESS, &lease->addr);
847 AREA_CHECK(3);
848 *p++ = DHO_MESSAGETYPE;
849 *p++ = 1;
850 *p++ = type;
852 if (lease->addr.s_addr && lease->cookie == htonl(MAGIC_COOKIE)) {
853 if (type == DHCP_RELEASE || putip) {
854 if (lease->server.s_addr)
855 PUT_ADDR(DHO_SERVERID, &lease->server);
859 if (type == DHCP_DECLINE) {
860 len = strlen(DAD);
861 if (len > AREA_LEFT) {
862 *p++ = DHO_MESSAGE;
863 *p++ = (uint8_t)len;
864 memcpy(p, DAD, len);
865 p += len;
869 #define DHCP_DIR(type) ((type) == DHCP_DISCOVER || (type) == DHCP_INFORM || \
870 (type) == DHCP_REQUEST)
872 if (DHCP_DIR(type)) {
873 /* vendor is already encoded correctly, so just add it */
874 if (ifo->vendor[0]) {
875 AREA_CHECK(ifo->vendor[0]);
876 *p++ = DHO_VENDOR;
877 memcpy(p, ifo->vendor, (size_t)ifo->vendor[0] + 1);
878 p += ifo->vendor[0] + 1;
882 if (type == DHCP_DISCOVER && ifo->options & DHCPCD_REQUEST)
883 PUT_ADDR(DHO_IPADDRESS, &ifo->req_addr);
885 if (DHCP_DIR(type)) {
886 if (type != DHCP_INFORM) {
887 if (ifo->leasetime != 0) {
888 AREA_CHECK(4);
889 *p++ = DHO_LEASETIME;
890 *p++ = 4;
891 ul = htonl(ifo->leasetime);
892 memcpy(p, &ul, 4);
893 p += 4;
897 AREA_CHECK(0);
898 *p++ = DHO_PARAMETERREQUESTLIST;
899 n_params = p;
900 *p++ = 0;
901 for (i = 0, opt = ifp->ctx->dhcp_opts;
902 i < ifp->ctx->dhcp_opts_len;
903 i++, opt++)
905 if (!DHC_REQOPT(opt, ifo->requestmask, ifo->nomask))
906 continue;
907 if (type == DHCP_INFORM &&
908 (opt->option == DHO_RENEWALTIME ||
909 opt->option == DHO_REBINDTIME))
910 continue;
911 AREA_FIT(1);
912 *p++ = (uint8_t)opt->option;
914 for (i = 0, opt = ifo->dhcp_override;
915 i < ifo->dhcp_override_len;
916 i++, opt++)
918 /* Check if added above */
919 for (lp = n_params + 1; lp < p; lp++)
920 if (*lp == (uint8_t)opt->option)
921 break;
922 if (lp < p)
923 continue;
924 if (!DHC_REQOPT(opt, ifo->requestmask, ifo->nomask))
925 continue;
926 if (type == DHCP_INFORM &&
927 (opt->option == DHO_RENEWALTIME ||
928 opt->option == DHO_REBINDTIME))
929 continue;
930 AREA_FIT(1);
931 *p++ = (uint8_t)opt->option;
933 *n_params = (uint8_t)(p - n_params - 1);
935 if (mtu != -1 &&
936 !(has_option_mask(ifo->nomask, DHO_MAXMESSAGESIZE)))
938 AREA_CHECK(2);
939 *p++ = DHO_MAXMESSAGESIZE;
940 *p++ = 2;
941 sz = htons((uint16_t)(mtu - IP_UDP_SIZE));
942 memcpy(p, &sz, 2);
943 p += 2;
946 if (ifo->userclass[0] &&
947 !has_option_mask(ifo->nomask, DHO_USERCLASS))
949 AREA_CHECK(ifo->userclass[0]);
950 *p++ = DHO_USERCLASS;
951 memcpy(p, ifo->userclass,
952 (size_t)ifo->userclass[0] + 1);
953 p += ifo->userclass[0] + 1;
957 if (state->clientid) {
958 AREA_CHECK(state->clientid[0]);
959 *p++ = DHO_CLIENTID;
960 memcpy(p, state->clientid, (size_t)state->clientid[0] + 1);
961 p += state->clientid[0] + 1;
964 if (DHCP_DIR(type) &&
965 !has_option_mask(ifo->nomask, DHO_VENDORCLASSID) &&
966 ifo->vendorclassid[0])
968 AREA_CHECK(ifo->vendorclassid[0]);
969 *p++ = DHO_VENDORCLASSID;
970 memcpy(p, ifo->vendorclassid, (size_t)ifo->vendorclassid[0]+1);
971 p += ifo->vendorclassid[0] + 1;
974 if (type == DHCP_DISCOVER &&
975 !(ifp->ctx->options & DHCPCD_TEST) &&
976 DHC_REQ(ifo->requestmask, ifo->nomask, DHO_RAPIDCOMMIT))
978 /* RFC 4039 Section 3 */
979 AREA_CHECK(0);
980 *p++ = DHO_RAPIDCOMMIT;
981 *p++ = 0;
984 if (DHCP_DIR(type)) {
985 hostname = dhcp_get_hostname(hbuf, sizeof(hbuf), ifo);
988 * RFC4702 3.1 States that if we send the Client FQDN option
989 * then we MUST NOT also send the Host Name option.
990 * Technically we could, but that is not RFC conformant and
991 * also seems to break some DHCP server implemetations such as
992 * Windows. On the other hand, ISC dhcpd is just as non RFC
993 * conformant by not accepting a partially qualified FQDN.
995 if (ifo->fqdn != FQDN_DISABLE) {
996 /* IETF DHC-FQDN option (81), RFC4702 */
997 i = 3;
998 if (hostname)
999 i += encode_rfc1035(hostname, NULL);
1000 AREA_CHECK(i);
1001 *p++ = DHO_FQDN;
1002 *p++ = (uint8_t)i;
1004 * Flags: 0000NEOS
1005 * S: 1 => Client requests Server to update
1006 * a RR in DNS as well as PTR
1007 * O: 1 => Server indicates to client that
1008 * DNS has been updated
1009 * E: 1 => Name data is DNS format
1010 * N: 1 => Client requests Server to not
1011 * update DNS
1013 if (hostname)
1014 *p++ = (uint8_t)((ifo->fqdn & 0x09) | 0x04);
1015 else
1016 *p++ = (FQDN_NONE & 0x09) | 0x04;
1017 *p++ = 0; /* from server for PTR RR */
1018 *p++ = 0; /* from server for A RR if S=1 */
1019 if (hostname) {
1020 i = encode_rfc1035(hostname, p);
1021 p += i;
1023 } else if (ifo->options & DHCPCD_HOSTNAME && hostname) {
1024 len = strlen(hostname);
1025 AREA_CHECK(len);
1026 *p++ = DHO_HOSTNAME;
1027 *p++ = (uint8_t)len;
1028 memcpy(p, hostname, len);
1029 p += len;
1033 #ifdef AUTH
1034 auth = NULL; /* appease GCC */
1035 auth_len = 0;
1036 if (ifo->auth.options & DHCPCD_AUTH_SEND) {
1037 ssize_t alen = dhcp_auth_encode(ifp->ctx, &ifo->auth,
1038 state->auth.token,
1039 NULL, 0, 4, type, NULL, 0);
1040 if (alen != -1 && alen > UINT8_MAX) {
1041 errno = ERANGE;
1042 alen = -1;
1044 if (alen == -1)
1045 logerr("%s: dhcp_auth_encode", ifp->name);
1046 else if (alen != 0) {
1047 auth_len = (uint8_t)alen;
1048 AREA_CHECK(auth_len);
1049 *p++ = DHO_AUTHENTICATION;
1050 *p++ = auth_len;
1051 auth = p;
1052 p += auth_len;
1055 #endif
1057 /* RFC 2563 Auto Configure */
1058 if (type == DHCP_DISCOVER && ifo->options & DHCPCD_IPV4LL &&
1059 !(has_option_mask(ifo->nomask, DHO_AUTOCONFIGURE)))
1061 AREA_CHECK(1);
1062 *p++ = DHO_AUTOCONFIGURE;
1063 *p++ = 1;
1064 *p++ = 1;
1067 if (DHCP_DIR(type)) {
1068 if (ifo->mudurl[0]) {
1069 AREA_CHECK(ifo->mudurl[0]);
1070 *p++ = DHO_MUDURL;
1071 memcpy(p, ifo->mudurl, (size_t)ifo->mudurl[0] + 1);
1072 p += ifo->mudurl[0] + 1;
1075 if (ifo->vivco_len &&
1076 !has_option_mask(ifo->nomask, DHO_VIVCO))
1078 AREA_CHECK(sizeof(ul));
1079 *p++ = DHO_VIVCO;
1080 lp = p++;
1081 *lp = sizeof(ul);
1082 ul = htonl(ifo->vivco_en);
1083 memcpy(p, &ul, sizeof(ul));
1084 p += sizeof(ul);
1085 for (i = 0, vivco = ifo->vivco;
1086 i < ifo->vivco_len;
1087 i++, vivco++)
1089 AREA_FIT(vivco->len);
1090 if (vivco->len + 2 + *lp > 255) {
1091 logerrx("%s: VIVCO option too big",
1092 ifp->name);
1093 free(bootp);
1094 return -1;
1096 *p++ = (uint8_t)vivco->len;
1097 memcpy(p, vivco->data, vivco->len);
1098 p += vivco->len;
1099 *lp = (uint8_t)(*lp + vivco->len + 1);
1103 #ifdef AUTH
1104 if ((ifo->auth.options & DHCPCD_AUTH_SENDREQUIRE) !=
1105 DHCPCD_AUTH_SENDREQUIRE &&
1106 !has_option_mask(ifo->nomask, DHO_FORCERENEW_NONCE))
1108 /* We support HMAC-MD5 */
1109 AREA_CHECK(1);
1110 *p++ = DHO_FORCERENEW_NONCE;
1111 *p++ = 1;
1112 *p++ = AUTH_ALG_HMAC_MD5;
1114 #endif
1117 *p++ = DHO_END;
1118 len = (size_t)(p - (uint8_t *)bootp);
1120 /* Pad out to the BOOTP message length.
1121 * Even if we send a DHCP packet with a variable length vendor area,
1122 * some servers / relay agents don't like packets smaller than
1123 * a BOOTP message which is fine because that's stipulated
1124 * in RFC1542 section 2.1. */
1125 while (len < sizeof(*bootp)) {
1126 *p++ = DHO_PAD;
1127 len++;
1130 #ifdef AUTH
1131 if (ifo->auth.options & DHCPCD_AUTH_SEND && auth_len != 0)
1132 dhcp_auth_encode(ifp->ctx, &ifo->auth, state->auth.token,
1133 (uint8_t *)bootp, len, 4, type, auth, auth_len);
1134 #endif
1136 return (ssize_t)len;
1138 toobig:
1139 logerrx("%s: DHCP message too big", ifp->name);
1140 free(bootp);
1141 return -1;
1144 static size_t
1145 read_lease(struct interface *ifp, struct bootp **bootp)
1147 union {
1148 struct bootp bootp;
1149 uint8_t buf[FRAMELEN_MAX];
1150 } buf;
1151 struct dhcp_state *state = D_STATE(ifp);
1152 ssize_t sbytes;
1153 size_t bytes;
1154 uint8_t type;
1155 #ifdef AUTH
1156 const uint8_t *auth;
1157 size_t auth_len;
1158 #endif
1160 /* Safety */
1161 *bootp = NULL;
1163 if (state->leasefile[0] == '\0') {
1164 logdebugx("reading standard input");
1165 sbytes = read(fileno(stdin), buf.buf, sizeof(buf.buf));
1166 } else {
1167 logdebugx("%s: reading lease `%s'",
1168 ifp->name, state->leasefile);
1169 sbytes = dhcp_readfile(ifp->ctx, state->leasefile,
1170 buf.buf, sizeof(buf.buf));
1172 if (sbytes == -1) {
1173 if (errno != ENOENT)
1174 logerr("%s: %s", ifp->name, state->leasefile);
1175 return 0;
1177 bytes = (size_t)sbytes;
1179 /* Ensure the packet is at lease BOOTP sized
1180 * with a vendor area of 4 octets
1181 * (it should be more, and our read packet enforces this so this
1182 * code should not be needed, but of course people could
1183 * scribble whatever in the stored lease file. */
1184 if (bytes < DHCP_MIN_LEN) {
1185 logerrx("%s: %s: truncated lease", ifp->name, __func__);
1186 return 0;
1189 if (ifp->ctx->options & DHCPCD_DUMPLEASE)
1190 goto out;
1192 /* We may have found a BOOTP server */
1193 if (get_option_uint8(ifp->ctx, &type, &buf.bootp, bytes,
1194 DHO_MESSAGETYPE) == -1)
1195 type = 0;
1197 #ifdef AUTH
1198 /* Authenticate the message */
1199 auth = get_option(ifp->ctx, &buf.bootp, bytes,
1200 DHO_AUTHENTICATION, &auth_len);
1201 if (auth) {
1202 if (dhcp_auth_validate(&state->auth, &ifp->options->auth,
1203 &buf.bootp, bytes, 4, type, auth, auth_len) == NULL)
1205 logerr("%s: authentication failed", ifp->name);
1206 return 0;
1208 if (state->auth.token)
1209 logdebugx("%s: validated using 0x%08" PRIu32,
1210 ifp->name, state->auth.token->secretid);
1211 else
1212 logdebugx("%s: accepted reconfigure key", ifp->name);
1213 } else if ((ifp->options->auth.options & DHCPCD_AUTH_SENDREQUIRE) ==
1214 DHCPCD_AUTH_SENDREQUIRE)
1216 logerrx("%s: authentication now required", ifp->name);
1217 return 0;
1219 #endif
1221 out:
1222 *bootp = malloc(bytes);
1223 if (*bootp == NULL) {
1224 logerr(__func__);
1225 return 0;
1227 memcpy(*bootp, buf.buf, bytes);
1228 return bytes;
1231 static const struct dhcp_opt *
1232 dhcp_getoverride(const struct if_options *ifo, unsigned int o)
1234 size_t i;
1235 const struct dhcp_opt *opt;
1237 for (i = 0, opt = ifo->dhcp_override;
1238 i < ifo->dhcp_override_len;
1239 i++, opt++)
1241 if (opt->option == o)
1242 return opt;
1244 return NULL;
1247 static const uint8_t *
1248 dhcp_getoption(struct dhcpcd_ctx *ctx,
1249 size_t *os, unsigned int *code, size_t *len,
1250 const uint8_t *od, size_t ol, struct dhcp_opt **oopt)
1252 size_t i;
1253 struct dhcp_opt *opt;
1255 if (od) {
1256 if (ol < 2) {
1257 errno = EINVAL;
1258 return NULL;
1260 *os = 2; /* code + len */
1261 *code = (unsigned int)*od++;
1262 *len = (size_t)*od++;
1263 if (*len > ol - *os) {
1264 errno = ERANGE;
1265 return NULL;
1269 *oopt = NULL;
1270 for (i = 0, opt = ctx->dhcp_opts; i < ctx->dhcp_opts_len; i++, opt++) {
1271 if (opt->option == *code) {
1272 *oopt = opt;
1273 break;
1277 return od;
1280 ssize_t
1281 dhcp_env(FILE *fenv, const char *prefix, const struct interface *ifp,
1282 const struct bootp *bootp, size_t bootp_len)
1284 const struct if_options *ifo;
1285 const uint8_t *p;
1286 struct in_addr addr;
1287 struct in_addr net;
1288 struct in_addr brd;
1289 struct dhcp_opt *opt, *vo;
1290 size_t i, pl;
1291 char safe[(BOOTP_FILE_LEN * 4) + 1];
1292 uint8_t overl = 0;
1293 uint32_t en;
1295 ifo = ifp->options;
1296 if (get_option_uint8(ifp->ctx, &overl, bootp, bootp_len,
1297 DHO_OPTSOVERLOADED) == -1)
1298 overl = 0;
1300 if (bootp->yiaddr || bootp->ciaddr) {
1301 /* Set some useful variables that we derive from the DHCP
1302 * message but are not necessarily in the options */
1303 addr.s_addr = bootp->yiaddr ? bootp->yiaddr : bootp->ciaddr;
1304 if (efprintf(fenv, "%s_ip_address=%s",
1305 prefix, inet_ntoa(addr)) == -1)
1306 return -1;
1307 if (get_option_addr(ifp->ctx, &net,
1308 bootp, bootp_len, DHO_SUBNETMASK) == -1) {
1309 net.s_addr = ipv4_getnetmask(addr.s_addr);
1310 if (efprintf(fenv, "%s_subnet_mask=%s",
1311 prefix, inet_ntoa(net)) == -1)
1312 return -1;
1314 if (efprintf(fenv, "%s_subnet_cidr=%d",
1315 prefix, inet_ntocidr(net))== -1)
1316 return -1;
1317 if (get_option_addr(ifp->ctx, &brd,
1318 bootp, bootp_len, DHO_BROADCAST) == -1)
1320 brd.s_addr = addr.s_addr | ~net.s_addr;
1321 if (efprintf(fenv, "%s_broadcast_address=%s",
1322 prefix, inet_ntoa(brd)) == -1)
1323 return -1;
1325 addr.s_addr = bootp->yiaddr & net.s_addr;
1326 if (efprintf(fenv, "%s_network_number=%s",
1327 prefix, inet_ntoa(addr)) == -1)
1328 return -1;
1331 if (*bootp->file && !(overl & 1)) {
1332 print_string(safe, sizeof(safe), OT_STRING,
1333 bootp->file, sizeof(bootp->file));
1334 if (efprintf(fenv, "%s_filename=%s", prefix, safe) == -1)
1335 return -1;
1337 if (*bootp->sname && !(overl & 2)) {
1338 print_string(safe, sizeof(safe), OT_STRING | OT_DOMAIN,
1339 bootp->sname, sizeof(bootp->sname));
1340 if (efprintf(fenv, "%s_server_name=%s", prefix, safe) == -1)
1341 return -1;
1344 /* Zero our indexes */
1345 for (i = 0, opt = ifp->ctx->dhcp_opts;
1346 i < ifp->ctx->dhcp_opts_len;
1347 i++, opt++)
1348 dhcp_zero_index(opt);
1349 for (i = 0, opt = ifp->options->dhcp_override;
1350 i < ifp->options->dhcp_override_len;
1351 i++, opt++)
1352 dhcp_zero_index(opt);
1353 for (i = 0, opt = ifp->ctx->vivso;
1354 i < ifp->ctx->vivso_len;
1355 i++, opt++)
1356 dhcp_zero_index(opt);
1358 for (i = 0, opt = ifp->ctx->dhcp_opts;
1359 i < ifp->ctx->dhcp_opts_len;
1360 i++, opt++)
1362 if (has_option_mask(ifo->nomask, opt->option))
1363 continue;
1364 if (dhcp_getoverride(ifo, opt->option))
1365 continue;
1366 p = get_option(ifp->ctx, bootp, bootp_len, opt->option, &pl);
1367 if (p == NULL)
1368 continue;
1369 dhcp_envoption(ifp->ctx, fenv, prefix, ifp->name,
1370 opt, dhcp_getoption, p, pl);
1372 if (opt->option != DHO_VIVSO || pl <= (int)sizeof(uint32_t))
1373 continue;
1374 memcpy(&en, p, sizeof(en));
1375 en = ntohl(en);
1376 vo = vivso_find(en, ifp);
1377 if (vo == NULL)
1378 continue;
1379 /* Skip over en + total size */
1380 p += sizeof(en) + 1;
1381 pl -= sizeof(en) + 1;
1382 dhcp_envoption(ifp->ctx, fenv, prefix, ifp->name,
1383 vo, dhcp_getoption, p, pl);
1386 for (i = 0, opt = ifo->dhcp_override;
1387 i < ifo->dhcp_override_len;
1388 i++, opt++)
1390 if (has_option_mask(ifo->nomask, opt->option))
1391 continue;
1392 p = get_option(ifp->ctx, bootp, bootp_len, opt->option, &pl);
1393 if (p == NULL)
1394 continue;
1395 dhcp_envoption(ifp->ctx, fenv, prefix, ifp->name,
1396 opt, dhcp_getoption, p, pl);
1399 return 1;
1402 static void
1403 get_lease(struct interface *ifp,
1404 struct dhcp_lease *lease, const struct bootp *bootp, size_t len)
1406 struct dhcpcd_ctx *ctx;
1408 assert(bootp != NULL);
1410 memcpy(&lease->cookie, bootp->vend, sizeof(lease->cookie));
1411 /* BOOTP does not set yiaddr for replies when ciaddr is set. */
1412 lease->addr.s_addr = bootp->yiaddr ? bootp->yiaddr : bootp->ciaddr;
1413 ctx = ifp->ctx;
1414 if (ifp->options->options & (DHCPCD_STATIC | DHCPCD_INFORM)) {
1415 if (ifp->options->req_addr.s_addr != INADDR_ANY) {
1416 lease->mask = ifp->options->req_mask;
1417 if (ifp->options->req_brd.s_addr != INADDR_ANY)
1418 lease->brd = ifp->options->req_brd;
1419 else
1420 lease->brd.s_addr =
1421 lease->addr.s_addr | ~lease->mask.s_addr;
1422 } else {
1423 const struct ipv4_addr *ia;
1425 ia = ipv4_iffindaddr(ifp, &lease->addr, NULL);
1426 assert(ia != NULL);
1427 lease->mask = ia->mask;
1428 lease->brd = ia->brd;
1430 } else {
1431 if (get_option_addr(ctx, &lease->mask, bootp, len,
1432 DHO_SUBNETMASK) == -1)
1433 lease->mask.s_addr =
1434 ipv4_getnetmask(lease->addr.s_addr);
1435 if (get_option_addr(ctx, &lease->brd, bootp, len,
1436 DHO_BROADCAST) == -1)
1437 lease->brd.s_addr =
1438 lease->addr.s_addr | ~lease->mask.s_addr;
1440 if (get_option_uint32(ctx, &lease->leasetime,
1441 bootp, len, DHO_LEASETIME) != 0)
1442 lease->leasetime = DHCP_INFINITE_LIFETIME;
1443 if (get_option_uint32(ctx, &lease->renewaltime,
1444 bootp, len, DHO_RENEWALTIME) != 0)
1445 lease->renewaltime = 0;
1446 if (get_option_uint32(ctx, &lease->rebindtime,
1447 bootp, len, DHO_REBINDTIME) != 0)
1448 lease->rebindtime = 0;
1449 if (get_option_addr(ctx, &lease->server, bootp, len, DHO_SERVERID) != 0)
1450 lease->server.s_addr = INADDR_ANY;
1453 static const char *
1454 get_dhcp_op(uint8_t type)
1456 const struct dhcp_op *d;
1458 for (d = dhcp_ops; d->name; d++)
1459 if (d->value == type)
1460 return d->name;
1461 return NULL;
1464 static void
1465 dhcp_fallback(void *arg)
1467 struct interface *iface;
1469 iface = (struct interface *)arg;
1470 dhcpcd_selectprofile(iface, iface->options->fallback);
1471 dhcpcd_startinterface(iface);
1474 static void
1475 dhcp_new_xid(struct interface *ifp)
1477 struct dhcp_state *state;
1478 const struct interface *ifp1;
1479 const struct dhcp_state *state1;
1481 state = D_STATE(ifp);
1482 if (ifp->options->options & DHCPCD_XID_HWADDR &&
1483 ifp->hwlen >= sizeof(state->xid))
1484 /* The lower bits are probably more unique on the network */
1485 memcpy(&state->xid,
1486 (ifp->hwaddr + ifp->hwlen) - sizeof(state->xid),
1487 sizeof(state->xid));
1488 else {
1489 again:
1490 state->xid = arc4random();
1493 /* Ensure it's unique */
1494 TAILQ_FOREACH(ifp1, ifp->ctx->ifaces, next) {
1495 if (ifp == ifp1)
1496 continue;
1497 if ((state1 = D_CSTATE(ifp1)) == NULL)
1498 continue;
1499 if (state1->xid == state->xid)
1500 break;
1502 if (ifp1 != NULL) {
1503 if (ifp->options->options & DHCPCD_XID_HWADDR &&
1504 ifp->hwlen >= sizeof(state->xid))
1506 logerrx("%s: duplicate xid on %s",
1507 ifp->name, ifp1->name);
1508 return;
1510 goto again;
1513 /* We can't do this when sharing leases across interfaes */
1514 #if 0
1515 /* As the XID changes, re-apply the filter. */
1516 if (state->bpf_fd != -1) {
1517 if (bpf_bootp(ifp, state->bpf_fd) == -1)
1518 logerr(__func__); /* try to continue */
1520 #endif
1523 void
1524 dhcp_close(struct interface *ifp)
1526 struct dhcpcd_ctx *ctx = ifp->ctx;
1527 struct dhcp_state *state = D_STATE(ifp);
1529 if (state == NULL)
1530 return;
1532 #ifdef PRIVSEP
1533 if (IN_PRIVSEP_SE(ctx)) {
1534 ps_bpf_closebootp(ifp);
1535 if (state->addr != NULL)
1536 ps_inet_closebootp(state->addr);
1538 #endif
1540 if (state->bpf != NULL) {
1541 eloop_event_delete(ctx->eloop, state->bpf->bpf_fd);
1542 bpf_close(state->bpf);
1543 state->bpf = NULL;
1545 if (state->udp_rfd != -1) {
1546 eloop_event_delete(ctx->eloop, state->udp_rfd);
1547 close(state->udp_rfd);
1548 state->udp_rfd = -1;
1551 state->interval = 0;
1555 dhcp_openudp(struct in_addr *ia)
1557 int s;
1558 struct sockaddr_in sin;
1559 int n;
1561 if ((s = xsocket(PF_INET, SOCK_DGRAM | SOCK_CXNB, IPPROTO_UDP)) == -1)
1562 return -1;
1564 n = 1;
1565 if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n)) == -1)
1566 goto errexit;
1567 #ifdef IP_RECVIF
1568 if (setsockopt(s, IPPROTO_IP, IP_RECVIF, &n, sizeof(n)) == -1)
1569 goto errexit;
1570 #else
1571 if (setsockopt(s, IPPROTO_IP, IP_RECVPKTINFO, &n, sizeof(n)) == -1)
1572 goto errexit;
1573 #endif
1574 #ifdef SO_RERROR
1575 if (setsockopt(s, SOL_SOCKET, SO_RERROR, &n, sizeof(n)) == -1)
1576 goto errexit;
1577 #endif
1579 memset(&sin, 0, sizeof(sin));
1580 sin.sin_family = AF_INET;
1581 sin.sin_port = htons(BOOTPC);
1582 if (ia != NULL)
1583 sin.sin_addr = *ia;
1584 if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) == -1)
1585 goto errexit;
1587 return s;
1589 errexit:
1590 close(s);
1591 return -1;
1594 static uint16_t
1595 in_cksum(const void *data, size_t len, uint32_t *isum)
1597 const uint16_t *word = data;
1598 uint32_t sum = isum != NULL ? *isum : 0;
1600 for (; len > 1; len -= sizeof(*word))
1601 sum += *word++;
1603 if (len == 1)
1604 sum += htons((uint16_t)(*(const uint8_t *)word << 8));
1606 if (isum != NULL)
1607 *isum = sum;
1609 sum = (sum >> 16) + (sum & 0xffff);
1610 sum += (sum >> 16);
1612 return (uint16_t)~sum;
1615 static struct bootp_pkt *
1616 dhcp_makeudppacket(size_t *sz, const uint8_t *data, size_t length,
1617 struct in_addr source, struct in_addr dest)
1619 struct bootp_pkt *udpp;
1620 struct ip *ip;
1621 struct udphdr *udp;
1623 if ((udpp = calloc(1, sizeof(*ip) + sizeof(*udp) + length)) == NULL)
1624 return NULL;
1625 ip = &udpp->ip;
1626 udp = &udpp->udp;
1628 /* OK, this is important :)
1629 * We copy the data to our packet and then create a small part of the
1630 * ip structure and an invalid ip_len (basically udp length).
1631 * We then fill the udp structure and put the checksum
1632 * of the whole packet into the udp checksum.
1633 * Finally we complete the ip structure and ip checksum.
1634 * If we don't do the ordering like so then the udp checksum will be
1635 * broken, so find another way of doing it! */
1637 memcpy(&udpp->bootp, data, length);
1639 ip->ip_p = IPPROTO_UDP;
1640 ip->ip_src.s_addr = source.s_addr;
1641 if (dest.s_addr == 0)
1642 ip->ip_dst.s_addr = INADDR_BROADCAST;
1643 else
1644 ip->ip_dst.s_addr = dest.s_addr;
1646 udp->uh_sport = htons(BOOTPC);
1647 udp->uh_dport = htons(BOOTPS);
1648 udp->uh_ulen = htons((uint16_t)(sizeof(*udp) + length));
1649 ip->ip_len = udp->uh_ulen;
1650 udp->uh_sum = in_cksum(udpp, sizeof(*ip) + sizeof(*udp) + length, NULL);
1652 ip->ip_v = IPVERSION;
1653 ip->ip_hl = sizeof(*ip) >> 2;
1654 ip->ip_id = (uint16_t)arc4random_uniform(UINT16_MAX);
1655 ip->ip_ttl = IPDEFTTL;
1656 ip->ip_len = htons((uint16_t)(sizeof(*ip) + sizeof(*udp) + length));
1657 ip->ip_sum = in_cksum(ip, sizeof(*ip), NULL);
1658 if (ip->ip_sum == 0)
1659 ip->ip_sum = 0xffff; /* RFC 768 */
1661 *sz = sizeof(*ip) + sizeof(*udp) + length;
1662 return udpp;
1665 static ssize_t
1666 dhcp_sendudp(struct interface *ifp, struct in_addr *to, void *data, size_t len)
1668 struct sockaddr_in sin = {
1669 .sin_family = AF_INET,
1670 .sin_addr = *to,
1671 .sin_port = htons(BOOTPS),
1672 #ifdef HAVE_SA_LEN
1673 .sin_len = sizeof(sin),
1674 #endif
1676 struct udphdr udp = {
1677 .uh_sport = htons(BOOTPC),
1678 .uh_dport = htons(BOOTPS),
1679 .uh_ulen = htons((uint16_t)(sizeof(udp) + len)),
1681 struct iovec iov[] = {
1682 { .iov_base = &udp, .iov_len = sizeof(udp), },
1683 { .iov_base = data, .iov_len = len, },
1685 struct msghdr msg = {
1686 .msg_name = (void *)&sin,
1687 .msg_namelen = sizeof(sin),
1688 .msg_iov = iov,
1689 .msg_iovlen = __arraycount(iov),
1691 struct dhcpcd_ctx *ctx = ifp->ctx;
1693 #ifdef PRIVSEP
1694 if (ctx->options & DHCPCD_PRIVSEP)
1695 return ps_inet_sendbootp(ifp, &msg);
1696 #endif
1697 return sendmsg(ctx->udp_wfd, &msg, 0);
1700 static void
1701 send_message(struct interface *ifp, uint8_t type,
1702 void (*callback)(void *))
1704 struct dhcp_state *state = D_STATE(ifp);
1705 struct if_options *ifo = ifp->options;
1706 struct bootp *bootp;
1707 struct bootp_pkt *udp;
1708 size_t len, ulen;
1709 ssize_t r;
1710 struct in_addr from, to;
1711 unsigned int RT;
1713 if (callback == NULL) {
1714 /* No carrier? Don't bother sending the packet. */
1715 if (ifp->carrier <= LINK_DOWN)
1716 return;
1717 logdebugx("%s: sending %s with xid 0x%x",
1718 ifp->name,
1719 ifo->options & DHCPCD_BOOTP ? "BOOTP" : get_dhcp_op(type),
1720 state->xid);
1721 RT = 0; /* bogus gcc warning */
1722 } else {
1723 if (state->interval == 0)
1724 state->interval = 4;
1725 else {
1726 state->interval *= 2;
1727 if (state->interval > 64)
1728 state->interval = 64;
1730 RT = (state->interval * MSEC_PER_SEC) +
1731 (arc4random_uniform(MSEC_PER_SEC * 2) - MSEC_PER_SEC);
1732 /* No carrier? Don't bother sending the packet.
1733 * However, we do need to advance the timeout. */
1734 if (ifp->carrier <= LINK_DOWN)
1735 goto fail;
1736 logdebugx("%s: sending %s (xid 0x%x), next in %0.1f seconds",
1737 ifp->name,
1738 ifo->options & DHCPCD_BOOTP ? "BOOTP" : get_dhcp_op(type),
1739 state->xid,
1740 (float)RT / MSEC_PER_SEC);
1743 r = make_message(&bootp, ifp, type);
1744 if (r == -1)
1745 goto fail;
1746 len = (size_t)r;
1748 if (!(state->added & (STATE_FAKE | STATE_EXPIRED)) &&
1749 state->addr != NULL &&
1750 ipv4_iffindaddr(ifp, &state->lease.addr, NULL) != NULL)
1751 from.s_addr = state->lease.addr.s_addr;
1752 else
1753 from.s_addr = INADDR_ANY;
1754 if (from.s_addr != INADDR_ANY &&
1755 state->lease.server.s_addr != INADDR_ANY)
1756 to.s_addr = state->lease.server.s_addr;
1757 else
1758 to.s_addr = INADDR_BROADCAST;
1761 * If not listening on the unspecified address we can
1762 * only receive broadcast messages via BPF.
1763 * Sockets bound to an address cannot receive broadcast messages
1764 * even if they are setup to send them.
1765 * Broadcasting from UDP is only an optimisation for rebinding
1766 * and on BSD, at least, is reliant on the subnet route being
1767 * correctly configured to receive the unicast reply.
1768 * As such, we always broadcast and receive the reply to it via BPF.
1769 * This also guarantees we have a DHCP server attached to the
1770 * interface we want to configure because we can't dictate the
1771 * interface via IP_PKTINFO unlike for IPv6.
1773 if (to.s_addr != INADDR_BROADCAST) {
1774 if (dhcp_sendudp(ifp, &to, bootp, len) != -1)
1775 goto out;
1776 logerr("%s: dhcp_sendudp", ifp->name);
1779 if (dhcp_openbpf(ifp) == -1)
1780 goto out;
1782 udp = dhcp_makeudppacket(&ulen, (uint8_t *)bootp, len, from, to);
1783 if (udp == NULL) {
1784 logerr("%s: dhcp_makeudppacket", ifp->name);
1785 r = 0;
1786 #ifdef PRIVSEP
1787 } else if (ifp->ctx->options & DHCPCD_PRIVSEP) {
1788 r = ps_bpf_sendbootp(ifp, udp, ulen);
1789 free(udp);
1790 #endif
1791 } else {
1792 r = bpf_send(state->bpf, ETHERTYPE_IP, udp, ulen);
1793 free(udp);
1795 /* If we failed to send a raw packet this normally means
1796 * we don't have the ability to work beneath the IP layer
1797 * for this interface.
1798 * As such we remove it from consideration without actually
1799 * stopping the interface. */
1800 if (r == -1) {
1801 logerr("%s: bpf_send", ifp->name);
1802 switch(errno) {
1803 case ENETDOWN:
1804 case ENETRESET:
1805 case ENETUNREACH:
1806 case ENOBUFS:
1807 break;
1808 default:
1809 if (!(ifp->ctx->options & DHCPCD_TEST))
1810 dhcp_drop(ifp, "FAIL");
1811 eloop_timeout_delete(ifp->ctx->eloop,
1812 NULL, ifp);
1813 callback = NULL;
1817 out:
1818 free(bootp);
1820 fail:
1821 /* Even if we fail to send a packet we should continue as we are
1822 * as our failure timeouts will change out codepath when needed. */
1823 if (callback != NULL)
1824 eloop_timeout_add_msec(ifp->ctx->eloop, RT, callback, ifp);
1827 static void
1828 send_inform(void *arg)
1831 send_message((struct interface *)arg, DHCP_INFORM, send_inform);
1834 static void
1835 send_discover(void *arg)
1838 send_message((struct interface *)arg, DHCP_DISCOVER, send_discover);
1841 static void
1842 send_request(void *arg)
1845 send_message((struct interface *)arg, DHCP_REQUEST, send_request);
1848 static void
1849 send_renew(void *arg)
1852 send_message((struct interface *)arg, DHCP_REQUEST, send_renew);
1855 static void
1856 send_rebind(void *arg)
1859 send_message((struct interface *)arg, DHCP_REQUEST, send_rebind);
1862 void
1863 dhcp_discover(void *arg)
1865 struct interface *ifp = arg;
1866 struct dhcp_state *state = D_STATE(ifp);
1867 struct if_options *ifo = ifp->options;
1869 state->state = DHS_DISCOVER;
1870 dhcp_new_xid(ifp);
1871 eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
1872 if (!(state->added & STATE_EXPIRED)) {
1873 if (ifo->fallback)
1874 eloop_timeout_add_sec(ifp->ctx->eloop,
1875 ifo->reboot, dhcp_fallback, ifp);
1876 #ifdef IPV4LL
1877 else if (ifo->options & DHCPCD_IPV4LL)
1878 eloop_timeout_add_sec(ifp->ctx->eloop,
1879 ifo->reboot, ipv4ll_start, ifp);
1880 #endif
1882 if (ifo->options & DHCPCD_REQUEST)
1883 loginfox("%s: soliciting a DHCP lease (requesting %s)",
1884 ifp->name, inet_ntoa(ifo->req_addr));
1885 else
1886 loginfox("%s: soliciting a %s lease",
1887 ifp->name, ifo->options & DHCPCD_BOOTP ? "BOOTP" : "DHCP");
1888 send_discover(ifp);
1891 static void
1892 dhcp_request(void *arg)
1894 struct interface *ifp = arg;
1895 struct dhcp_state *state = D_STATE(ifp);
1897 state->state = DHS_REQUEST;
1898 send_request(ifp);
1901 static void
1902 dhcp_expire(void *arg)
1904 struct interface *ifp = arg;
1905 struct dhcp_state *state = D_STATE(ifp);
1907 if (ifp->options->options & DHCPCD_LASTLEASE_EXTEND) {
1908 logwarnx("%s: DHCP lease expired, extending lease", ifp->name);
1909 state->added |= STATE_EXPIRED;
1910 } else {
1911 logerrx("%s: DHCP lease expired", ifp->name);
1912 dhcp_drop(ifp, "EXPIRE");
1913 dhcp_unlink(ifp->ctx, state->leasefile);
1915 state->interval = 0;
1916 dhcp_discover(ifp);
1919 #if defined(ARP) || defined(IN_IFF_DUPLICATED)
1920 static void
1921 dhcp_decline(struct interface *ifp)
1924 send_message(ifp, DHCP_DECLINE, NULL);
1926 #endif
1928 static void
1929 dhcp_startrenew(void *arg)
1931 struct interface *ifp = arg;
1932 struct dhcp_state *state;
1933 struct dhcp_lease *lease;
1935 if ((state = D_STATE(ifp)) == NULL)
1936 return;
1938 /* Only renew in the bound or renew states */
1939 if (state->state != DHS_BOUND &&
1940 state->state != DHS_RENEW)
1941 return;
1943 /* Remove the timeout as the renew may have been forced. */
1944 eloop_timeout_delete(ifp->ctx->eloop, dhcp_startrenew, ifp);
1946 lease = &state->lease;
1947 logdebugx("%s: renewing lease of %s", ifp->name,
1948 inet_ntoa(lease->addr));
1949 state->state = DHS_RENEW;
1950 dhcp_new_xid(ifp);
1951 state->interval = 0;
1952 send_renew(ifp);
1955 void
1956 dhcp_renew(struct interface *ifp)
1959 dhcp_startrenew(ifp);
1962 static void
1963 dhcp_rebind(void *arg)
1965 struct interface *ifp = arg;
1966 struct dhcp_state *state = D_STATE(ifp);
1967 struct dhcp_lease *lease = &state->lease;
1969 logwarnx("%s: failed to renew DHCP, rebinding", ifp->name);
1970 logdebugx("%s: expire in %"PRIu32" seconds",
1971 ifp->name, lease->leasetime - lease->rebindtime);
1972 state->state = DHS_REBIND;
1973 eloop_timeout_delete(ifp->ctx->eloop, send_renew, ifp);
1974 state->lease.server.s_addr = INADDR_ANY;
1975 state->interval = 0;
1976 ifp->options->options &= ~(DHCPCD_CSR_WARNED |
1977 DHCPCD_ROUTER_HOST_ROUTE_WARNED);
1978 send_rebind(ifp);
1981 #if defined(ARP) || defined(IN_IFF_DUPLICATED)
1982 static void
1983 dhcp_finish_dad(struct interface *ifp, struct in_addr *ia)
1985 struct dhcp_state *state = D_STATE(ifp);
1987 if (state->state != DHS_PROBE)
1988 return;
1989 if (state->offer == NULL || state->offer->yiaddr != ia->s_addr)
1990 return;
1992 logdebugx("%s: DAD completed for %s", ifp->name, inet_ntoa(*ia));
1993 if (!(ifp->options->options & DHCPCD_INFORM))
1994 dhcp_bind(ifp);
1995 #ifndef IN_IFF_DUPLICATED
1996 else {
1997 struct bootp *bootp;
1998 size_t len;
2000 bootp = state->new;
2001 len = state->new_len;
2002 state->new = state->offer;
2003 state->new_len = state->offer_len;
2004 get_lease(ifp, &state->lease, state->new, state->new_len);
2005 ipv4_applyaddr(ifp);
2006 state->new = bootp;
2007 state->new_len = len;
2009 #endif
2011 #ifdef IPV4LL
2012 /* Stop IPv4LL now we have a working DHCP address */
2013 ipv4ll_drop(ifp);
2014 #endif
2016 if (ifp->options->options & DHCPCD_INFORM)
2017 dhcp_inform(ifp);
2021 static bool
2022 dhcp_addr_duplicated(struct interface *ifp, struct in_addr *ia)
2024 struct dhcp_state *state = D_STATE(ifp);
2025 unsigned long long opts = ifp->options->options;
2026 struct dhcpcd_ctx *ctx = ifp->ctx;
2027 bool deleted = false;
2028 #ifdef IN_IFF_DUPLICATED
2029 struct ipv4_addr *iap;
2030 #endif
2032 if ((state->offer == NULL || state->offer->yiaddr != ia->s_addr) &&
2033 !IN_ARE_ADDR_EQUAL(ia, &state->lease.addr))
2034 return deleted;
2036 /* RFC 2131 3.1.5, Client-server interaction */
2037 logerrx("%s: DAD detected %s", ifp->name, inet_ntoa(*ia));
2038 dhcp_unlink(ifp->ctx, state->leasefile);
2039 if (!(opts & DHCPCD_STATIC) && !state->lease.frominfo)
2040 dhcp_decline(ifp);
2041 #ifdef IN_IFF_DUPLICATED
2042 if ((iap = ipv4_iffindaddr(ifp, ia, NULL)) != NULL) {
2043 ipv4_deladdr(iap, 0);
2044 deleted = true;
2046 #endif
2047 eloop_timeout_delete(ctx->eloop, NULL, ifp);
2048 if (opts & (DHCPCD_STATIC | DHCPCD_INFORM)) {
2049 state->reason = "EXPIRE";
2050 script_runreason(ifp, state->reason);
2051 #define NOT_ONLY_SELF (DHCPCD_MASTER | DHCPCD_IPV6RS | DHCPCD_DHCP6)
2052 if (!(ctx->options & NOT_ONLY_SELF))
2053 eloop_exit(ifp->ctx->eloop, EXIT_FAILURE);
2054 return deleted;
2056 eloop_timeout_add_sec(ifp->ctx->eloop,
2057 DHCP_RAND_MAX, dhcp_discover, ifp);
2058 return deleted;
2060 #endif
2062 #ifdef ARP
2063 #ifdef KERNEL_RFC5227
2064 static void
2065 dhcp_arp_announced(struct arp_state *state)
2068 arp_free(state);
2070 #else
2071 static void
2072 dhcp_arp_defend_failed(struct arp_state *astate)
2074 struct interface *ifp = astate->iface;
2076 dhcp_drop(ifp, "EXPIRED");
2077 dhcp_start1(ifp);
2079 #endif
2081 #if !defined(KERNEL_RFC5227) || defined(ARPING)
2082 static void dhcp_arp_not_found(struct arp_state *);
2084 static struct arp_state *
2085 dhcp_arp_new(struct interface *ifp, struct in_addr *addr)
2087 struct arp_state *astate;
2089 astate = arp_new(ifp, addr);
2090 if (astate == NULL)
2091 return NULL;
2093 astate->found_cb = dhcp_arp_found;
2094 astate->not_found_cb = dhcp_arp_not_found;
2095 #ifdef KERNEL_RFC5227
2096 astate->announced_cb = dhcp_arp_announced;
2097 #else
2098 astate->announced_cb = NULL;
2099 astate->defend_failed_cb = dhcp_arp_defend_failed;
2100 #endif
2101 return astate;
2103 #endif
2105 #ifdef ARPING
2106 static int
2107 dhcp_arping(struct interface *ifp)
2109 struct dhcp_state *state;
2110 struct if_options *ifo;
2111 struct arp_state *astate;
2112 struct in_addr addr;
2114 state = D_STATE(ifp);
2115 ifo = ifp->options;
2117 if (ifo->arping_len == 0 || state->arping_index > ifo->arping_len)
2118 return 0;
2120 if (state->arping_index + 1 == ifo->arping_len) {
2121 state->arping_index++;
2122 dhcpcd_startinterface(ifp);
2123 return 1;
2126 addr.s_addr = ifo->arping[++state->arping_index];
2127 astate = dhcp_arp_new(ifp, &addr);
2128 if (astate == NULL) {
2129 logerr(__func__);
2130 return -1;
2132 arp_probe(astate);
2133 return 1;
2135 #endif
2137 #if !defined(KERNEL_RFC5227) || defined(ARPING)
2138 static void
2139 dhcp_arp_not_found(struct arp_state *astate)
2141 struct interface *ifp;
2143 ifp = astate->iface;
2144 #ifdef ARPING
2145 if (dhcp_arping(ifp) == 1) {
2146 arp_free(astate);
2147 return;
2149 #endif
2151 dhcp_finish_dad(ifp, &astate->addr);
2154 static void
2155 dhcp_arp_found(struct arp_state *astate, const struct arp_msg *amsg)
2157 struct in_addr addr;
2158 struct interface *ifp = astate->iface;
2159 #ifdef ARPING
2160 struct dhcp_state *state;
2161 struct if_options *ifo;
2163 state = D_STATE(ifp);
2165 ifo = ifp->options;
2166 if (state->arping_index != -1 &&
2167 state->arping_index < ifo->arping_len &&
2168 amsg &&
2169 amsg->sip.s_addr == ifo->arping[state->arping_index])
2171 char buf[HWADDR_LEN * 3];
2173 hwaddr_ntoa(amsg->sha, ifp->hwlen, buf, sizeof(buf));
2174 if (dhcpcd_selectprofile(ifp, buf) == -1 &&
2175 dhcpcd_selectprofile(ifp, inet_ntoa(amsg->sip)) == -1)
2177 /* We didn't find a profile for this
2178 * address or hwaddr, so move to the next
2179 * arping profile */
2180 dhcp_arp_not_found(astate);
2181 return;
2183 arp_free(astate);
2184 eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
2185 dhcpcd_startinterface(ifp);
2186 return;
2188 #else
2189 UNUSED(amsg);
2190 #endif
2192 addr = astate->addr;
2193 arp_free(astate);
2194 dhcp_addr_duplicated(ifp, &addr);
2196 #endif
2198 #endif /* ARP */
2200 void
2201 dhcp_bind(struct interface *ifp)
2203 struct dhcpcd_ctx *ctx = ifp->ctx;
2204 struct dhcp_state *state = D_STATE(ifp);
2205 struct if_options *ifo = ifp->options;
2206 struct dhcp_lease *lease = &state->lease;
2207 uint8_t old_state;
2209 state->reason = NULL;
2210 /* If we don't have an offer, we are re-binding a lease on preference,
2211 * normally when two interfaces have a lease matching IP addresses. */
2212 if (state->offer) {
2213 free(state->old);
2214 state->old = state->new;
2215 state->old_len = state->new_len;
2216 state->new = state->offer;
2217 state->new_len = state->offer_len;
2218 state->offer = NULL;
2219 state->offer_len = 0;
2221 get_lease(ifp, lease, state->new, state->new_len);
2222 if (ifo->options & DHCPCD_STATIC) {
2223 loginfox("%s: using static address %s/%d",
2224 ifp->name, inet_ntoa(lease->addr),
2225 inet_ntocidr(lease->mask));
2226 lease->leasetime = DHCP_INFINITE_LIFETIME;
2227 state->reason = "STATIC";
2228 } else if (ifo->options & DHCPCD_INFORM) {
2229 loginfox("%s: received approval for %s",
2230 ifp->name, inet_ntoa(lease->addr));
2231 lease->leasetime = DHCP_INFINITE_LIFETIME;
2232 state->reason = "INFORM";
2233 } else {
2234 if (lease->frominfo)
2235 state->reason = "TIMEOUT";
2236 if (lease->leasetime == DHCP_INFINITE_LIFETIME) {
2237 lease->renewaltime =
2238 lease->rebindtime =
2239 lease->leasetime;
2240 loginfox("%s: leased %s for infinity",
2241 ifp->name, inet_ntoa(lease->addr));
2242 } else {
2243 if (lease->leasetime < DHCP_MIN_LEASE) {
2244 logwarnx("%s: minimum lease is %d seconds",
2245 ifp->name, DHCP_MIN_LEASE);
2246 lease->leasetime = DHCP_MIN_LEASE;
2248 if (lease->rebindtime == 0)
2249 lease->rebindtime =
2250 (uint32_t)(lease->leasetime * T2);
2251 else if (lease->rebindtime >= lease->leasetime) {
2252 lease->rebindtime =
2253 (uint32_t)(lease->leasetime * T2);
2254 logwarnx("%s: rebind time greater than lease "
2255 "time, forcing to %"PRIu32" seconds",
2256 ifp->name, lease->rebindtime);
2258 if (lease->renewaltime == 0)
2259 lease->renewaltime =
2260 (uint32_t)(lease->leasetime * T1);
2261 else if (lease->renewaltime > lease->rebindtime) {
2262 lease->renewaltime =
2263 (uint32_t)(lease->leasetime * T1);
2264 logwarnx("%s: renewal time greater than "
2265 "rebind time, forcing to %"PRIu32" seconds",
2266 ifp->name, lease->renewaltime);
2268 if (state->state == DHS_RENEW && state->addr &&
2269 lease->addr.s_addr == state->addr->addr.s_addr &&
2270 !(state->added & STATE_FAKE))
2271 logdebugx("%s: leased %s for %"PRIu32" seconds",
2272 ifp->name, inet_ntoa(lease->addr),
2273 lease->leasetime);
2274 else
2275 loginfox("%s: leased %s for %"PRIu32" seconds",
2276 ifp->name, inet_ntoa(lease->addr),
2277 lease->leasetime);
2280 if (ctx->options & DHCPCD_TEST) {
2281 state->reason = "TEST";
2282 script_runreason(ifp, state->reason);
2283 eloop_exit(ctx->eloop, EXIT_SUCCESS);
2284 return;
2286 if (state->reason == NULL) {
2287 if (state->old &&
2288 !(state->added & (STATE_FAKE | STATE_EXPIRED)))
2290 if (state->old->yiaddr == state->new->yiaddr &&
2291 lease->server.s_addr &&
2292 state->state != DHS_REBIND)
2293 state->reason = "RENEW";
2294 else
2295 state->reason = "REBIND";
2296 } else if (state->state == DHS_REBOOT)
2297 state->reason = "REBOOT";
2298 else
2299 state->reason = "BOUND";
2301 if (lease->leasetime == DHCP_INFINITE_LIFETIME)
2302 lease->renewaltime = lease->rebindtime = lease->leasetime;
2303 else {
2304 eloop_timeout_add_sec(ctx->eloop,
2305 lease->renewaltime, dhcp_startrenew, ifp);
2306 eloop_timeout_add_sec(ctx->eloop,
2307 lease->rebindtime, dhcp_rebind, ifp);
2308 eloop_timeout_add_sec(ctx->eloop,
2309 lease->leasetime, dhcp_expire, ifp);
2310 logdebugx("%s: renew in %"PRIu32" seconds, rebind in %"PRIu32
2311 " seconds",
2312 ifp->name, lease->renewaltime, lease->rebindtime);
2314 state->state = DHS_BOUND;
2315 if (!state->lease.frominfo &&
2316 !(ifo->options & (DHCPCD_INFORM | DHCPCD_STATIC))) {
2317 logdebugx("%s: writing lease `%s'",
2318 ifp->name, state->leasefile);
2319 if (dhcp_writefile(ifp->ctx, state->leasefile, 0640,
2320 state->new, state->new_len) == -1)
2321 logerr("dhcp_writefile: %s", state->leasefile);
2324 /* Close the BPF filter as we can now receive DHCP messages
2325 * on a UDP socket. */
2326 old_state = state->added;
2327 if (ctx->options & DHCPCD_MASTER ||
2328 state->old == NULL ||
2329 state->old->yiaddr != state->new->yiaddr || old_state & STATE_FAKE)
2330 dhcp_close(ifp);
2332 ipv4_applyaddr(ifp);
2334 /* If not in master mode, open an address specific socket. */
2335 if (ctx->options & DHCPCD_MASTER ||
2336 (state->old != NULL &&
2337 state->old->yiaddr == state->new->yiaddr &&
2338 old_state & STATE_ADDED && !(old_state & STATE_FAKE)))
2339 return;
2341 #ifdef PRIVSEP
2342 if (IN_PRIVSEP_SE(ctx)) {
2343 if (ps_inet_openbootp(state->addr) == -1)
2344 logerr(__func__);
2345 return;
2347 #endif
2349 state->udp_rfd = dhcp_openudp(&state->addr->addr);
2350 if (state->udp_rfd == -1) {
2351 logerr(__func__);
2352 /* Address sharing without master mode is not supported.
2353 * It's also possible another DHCP client could be running,
2354 * which is even worse.
2355 * We still need to work, so re-open BPF. */
2356 dhcp_openbpf(ifp);
2357 return;
2359 eloop_event_add(ctx->eloop, state->udp_rfd, dhcp_handleifudp, ifp);
2362 static size_t
2363 dhcp_message_new(struct bootp **bootp,
2364 const struct in_addr *addr, const struct in_addr *mask)
2366 uint8_t *p;
2367 uint32_t cookie;
2369 if ((*bootp = calloc(1, sizeof(**bootp))) == NULL)
2370 return 0;
2372 (*bootp)->yiaddr = addr->s_addr;
2373 p = (*bootp)->vend;
2375 cookie = htonl(MAGIC_COOKIE);
2376 memcpy(p, &cookie, sizeof(cookie));
2377 p += sizeof(cookie);
2379 if (mask->s_addr != INADDR_ANY) {
2380 *p++ = DHO_SUBNETMASK;
2381 *p++ = sizeof(mask->s_addr);
2382 memcpy(p, &mask->s_addr, sizeof(mask->s_addr));
2383 p+= sizeof(mask->s_addr);
2386 *p = DHO_END;
2387 return sizeof(**bootp);
2390 #if defined(ARP) || defined(KERNEL_RFC5227)
2391 static int
2392 dhcp_arp_address(struct interface *ifp)
2394 struct dhcp_state *state;
2395 struct in_addr addr;
2396 struct ipv4_addr *ia;
2398 eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
2400 state = D_STATE(ifp);
2401 addr.s_addr = state->offer->yiaddr == INADDR_ANY ?
2402 state->offer->ciaddr : state->offer->yiaddr;
2403 /* If the interface already has the address configured
2404 * then we can't ARP for duplicate detection. */
2405 ia = ipv4_iffindaddr(ifp, &addr, NULL);
2406 #ifdef IN_IFF_NOTUSEABLE
2407 if (ia == NULL || ia->addr_flags & IN_IFF_NOTUSEABLE) {
2408 state->state = DHS_PROBE;
2409 if (ia == NULL) {
2410 struct dhcp_lease l;
2412 get_lease(ifp, &l, state->offer, state->offer_len);
2413 /* Add the address now, let the kernel handle DAD. */
2414 ipv4_addaddr(ifp, &l.addr, &l.mask, &l.brd,
2415 l.leasetime, l.rebindtime);
2416 } else if (ia->addr_flags & IN_IFF_DUPLICATED)
2417 dhcp_addr_duplicated(ifp, &ia->addr);
2418 else
2419 loginfox("%s: waiting for DAD on %s",
2420 ifp->name, inet_ntoa(addr));
2421 return 0;
2423 #else
2424 if (!(ifp->flags & IFF_NOARP) &&
2425 ifp->options->options & DHCPCD_ARP)
2427 struct arp_state *astate;
2428 struct dhcp_lease l;
2430 /* Even if the address exists, we need to defend it. */
2431 astate = dhcp_arp_new(ifp, &addr);
2432 if (astate == NULL)
2433 return -1;
2435 if (ia == NULL) {
2436 state->state = DHS_PROBE;
2437 get_lease(ifp, &l, state->offer, state->offer_len);
2438 loginfox("%s: probing address %s/%d",
2439 ifp->name, inet_ntoa(l.addr), inet_ntocidr(l.mask));
2440 /* We need to handle DAD. */
2441 arp_probe(astate);
2442 return 0;
2445 #endif
2447 return 1;
2450 static void
2451 dhcp_arp_bind(struct interface *ifp)
2454 if (ifp->ctx->options & DHCPCD_TEST ||
2455 dhcp_arp_address(ifp) == 1)
2456 dhcp_bind(ifp);
2458 #endif
2460 static void
2461 dhcp_lastlease(void *arg)
2463 struct interface *ifp = arg;
2464 struct dhcp_state *state = D_STATE(ifp);
2466 loginfox("%s: timed out contacting a DHCP server, using last lease",
2467 ifp->name);
2468 #if defined(ARP) || defined(KERNEL_RFC5227)
2469 dhcp_arp_bind(ifp);
2470 #else
2471 dhcp_bind(ifp);
2472 #endif
2473 /* Set expired here because dhcp_bind() -> ipv4_addaddr() will reset
2474 * state */
2475 state->added |= STATE_EXPIRED;
2476 state->interval = 0;
2477 dhcp_discover(ifp);
2480 static void
2481 dhcp_static(struct interface *ifp)
2483 struct if_options *ifo;
2484 struct dhcp_state *state;
2485 struct ipv4_addr *ia;
2487 state = D_STATE(ifp);
2488 ifo = ifp->options;
2490 ia = NULL;
2491 if (ifo->req_addr.s_addr == INADDR_ANY &&
2492 (ia = ipv4_iffindaddr(ifp, NULL, NULL)) == NULL)
2494 loginfox("%s: waiting for 3rd party to "
2495 "configure IP address", ifp->name);
2496 state->reason = "3RDPARTY";
2497 script_runreason(ifp, state->reason);
2498 return;
2501 state->offer_len = dhcp_message_new(&state->offer,
2502 ia ? &ia->addr : &ifo->req_addr,
2503 ia ? &ia->mask : &ifo->req_mask);
2504 if (state->offer_len)
2505 #if defined(ARP) || defined(KERNEL_RFC5227)
2506 dhcp_arp_bind(ifp);
2507 #else
2508 dhcp_bind(ifp);
2509 #endif
2512 void
2513 dhcp_inform(struct interface *ifp)
2515 struct dhcp_state *state;
2516 struct if_options *ifo;
2517 struct ipv4_addr *ia;
2519 state = D_STATE(ifp);
2520 ifo = ifp->options;
2522 state->state = DHS_INFORM;
2523 free(state->offer);
2524 state->offer = NULL;
2525 state->offer_len = 0;
2527 if (ifo->req_addr.s_addr == INADDR_ANY) {
2528 ia = ipv4_iffindaddr(ifp, NULL, NULL);
2529 if (ia == NULL) {
2530 loginfox("%s: waiting for 3rd party to "
2531 "configure IP address",
2532 ifp->name);
2533 if (!(ifp->ctx->options & DHCPCD_TEST)) {
2534 state->reason = "3RDPARTY";
2535 script_runreason(ifp, state->reason);
2537 return;
2539 } else {
2540 ia = ipv4_iffindaddr(ifp, &ifo->req_addr, &ifo->req_mask);
2541 if (ia == NULL) {
2542 if (ifp->ctx->options & DHCPCD_TEST) {
2543 logerrx("%s: cannot add IP address in test mode",
2544 ifp->name);
2545 return;
2547 ia = ipv4_iffindaddr(ifp, &ifo->req_addr, NULL);
2548 if (ia != NULL)
2549 /* Netmask must be different, delete it. */
2550 ipv4_deladdr(ia, 1);
2551 state->offer_len = dhcp_message_new(&state->offer,
2552 &ifo->req_addr, &ifo->req_mask);
2553 #ifdef ARP
2554 if (dhcp_arp_address(ifp) != 1)
2555 return;
2556 #endif
2557 ia = ipv4_iffindaddr(ifp,
2558 &ifo->req_addr, &ifo->req_mask);
2559 assert(ia != NULL);
2563 state->addr = ia;
2564 state->offer_len = dhcp_message_new(&state->offer,
2565 &ia->addr, &ia->mask);
2566 if (state->offer_len) {
2567 dhcp_new_xid(ifp);
2568 get_lease(ifp, &state->lease, state->offer, state->offer_len);
2569 send_inform(ifp);
2573 void
2574 dhcp_reboot_newopts(struct interface *ifp, unsigned long long oldopts)
2576 struct if_options *ifo;
2577 struct dhcp_state *state = D_STATE(ifp);
2579 if (state == NULL || state->state == DHS_NONE)
2580 return;
2581 ifo = ifp->options;
2582 if ((ifo->options & (DHCPCD_INFORM | DHCPCD_STATIC) &&
2583 (state->addr == NULL ||
2584 state->addr->addr.s_addr != ifo->req_addr.s_addr)) ||
2585 (oldopts & (DHCPCD_INFORM | DHCPCD_STATIC) &&
2586 !(ifo->options & (DHCPCD_INFORM | DHCPCD_STATIC))))
2588 dhcp_drop(ifp, "EXPIRE");
2592 #ifdef ARP
2593 static int
2594 dhcp_activeaddr(const struct interface *ifp, const struct in_addr *addr)
2596 const struct interface *ifp1;
2597 const struct dhcp_state *state;
2599 TAILQ_FOREACH(ifp1, ifp->ctx->ifaces, next) {
2600 if (ifp1 == ifp)
2601 continue;
2602 if ((state = D_CSTATE(ifp1)) == NULL)
2603 continue;
2604 switch(state->state) {
2605 case DHS_REBOOT:
2606 case DHS_RENEW:
2607 case DHS_REBIND:
2608 case DHS_BOUND:
2609 case DHS_INFORM:
2610 break;
2611 default:
2612 continue;
2614 if (state->lease.addr.s_addr == addr->s_addr)
2615 return 1;
2617 return 0;
2619 #endif
2621 static void
2622 dhcp_reboot(struct interface *ifp)
2624 struct if_options *ifo;
2625 struct dhcp_state *state = D_STATE(ifp);
2626 #ifdef ARP
2627 struct ipv4_addr *ia;
2628 #endif
2630 if (state == NULL || state->state == DHS_NONE)
2631 return;
2632 ifo = ifp->options;
2633 state->state = DHS_REBOOT;
2634 state->interval = 0;
2636 if (ifo->options & DHCPCD_LINK && ifp->carrier <= LINK_DOWN) {
2637 loginfox("%s: waiting for carrier", ifp->name);
2638 return;
2640 if (ifo->options & DHCPCD_STATIC) {
2641 dhcp_static(ifp);
2642 return;
2644 if (ifo->options & DHCPCD_INFORM) {
2645 loginfox("%s: informing address of %s",
2646 ifp->name, inet_ntoa(state->lease.addr));
2647 dhcp_inform(ifp);
2648 return;
2650 if (ifo->reboot == 0 || state->offer == NULL) {
2651 dhcp_discover(ifp);
2652 return;
2654 if (!IS_DHCP(state->offer))
2655 return;
2657 loginfox("%s: rebinding lease of %s",
2658 ifp->name, inet_ntoa(state->lease.addr));
2660 #ifdef ARP
2661 #ifndef KERNEL_RFC5227
2662 /* Create the DHCP ARP state so we can defend it. */
2663 (void)dhcp_arp_new(ifp, &state->lease.addr);
2664 #endif
2666 /* If the address exists on the interface and no other interface
2667 * is currently using it then announce it to ensure this
2668 * interface gets the reply. */
2669 ia = ipv4_iffindaddr(ifp, &state->lease.addr, NULL);
2670 if (ia != NULL &&
2671 !(ifp->ctx->options & DHCPCD_TEST) &&
2672 #ifdef IN_IFF_NOTUSEABLE
2673 !(ia->addr_flags & IN_IFF_NOTUSEABLE) &&
2674 #endif
2675 dhcp_activeaddr(ifp, &state->lease.addr) == 0)
2676 arp_ifannounceaddr(ifp, &state->lease.addr);
2677 #endif
2679 dhcp_new_xid(ifp);
2680 state->lease.server.s_addr = INADDR_ANY;
2681 eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
2683 #ifdef IPV4LL
2684 /* Need to add this before dhcp_expire and friends. */
2685 if (!ifo->fallback && ifo->options & DHCPCD_IPV4LL)
2686 eloop_timeout_add_sec(ifp->ctx->eloop,
2687 ifo->reboot, ipv4ll_start, ifp);
2688 #endif
2690 if (ifo->options & DHCPCD_LASTLEASE && state->lease.frominfo)
2691 eloop_timeout_add_sec(ifp->ctx->eloop,
2692 ifo->reboot, dhcp_lastlease, ifp);
2693 else if (!(ifo->options & DHCPCD_INFORM))
2694 eloop_timeout_add_sec(ifp->ctx->eloop,
2695 ifo->reboot, dhcp_expire, ifp);
2697 /* Don't bother ARP checking as the server could NAK us first.
2698 * Don't call dhcp_request as that would change the state */
2699 send_request(ifp);
2702 void
2703 dhcp_drop(struct interface *ifp, const char *reason)
2705 struct dhcp_state *state;
2706 #ifdef RELEASE_SLOW
2707 struct timespec ts;
2708 #endif
2710 state = D_STATE(ifp);
2711 /* dhcp_start may just have been called and we don't yet have a state
2712 * but we do have a timeout, so punt it. */
2713 if (state == NULL || state->state == DHS_NONE) {
2714 eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
2715 return;
2718 #ifdef ARP
2719 if (state->addr != NULL)
2720 arp_freeaddr(ifp, &state->addr->addr);
2721 #endif
2722 #ifdef ARPING
2723 state->arping_index = -1;
2724 #endif
2726 if (ifp->options->options & DHCPCD_RELEASE &&
2727 !(ifp->options->options & DHCPCD_INFORM))
2729 /* Failure to send the release may cause this function to
2730 * re-enter so guard by setting the state. */
2731 if (state->state == DHS_RELEASE)
2732 return;
2733 state->state = DHS_RELEASE;
2735 dhcp_unlink(ifp->ctx, state->leasefile);
2736 if (ifp->carrier > LINK_DOWN &&
2737 state->new != NULL &&
2738 state->lease.server.s_addr != INADDR_ANY)
2740 loginfox("%s: releasing lease of %s",
2741 ifp->name, inet_ntoa(state->lease.addr));
2742 dhcp_new_xid(ifp);
2743 send_message(ifp, DHCP_RELEASE, NULL);
2744 #ifdef RELEASE_SLOW
2745 /* Give the packet a chance to go */
2746 ts.tv_sec = RELEASE_DELAY_S;
2747 ts.tv_nsec = RELEASE_DELAY_NS;
2748 nanosleep(&ts, NULL);
2749 #endif
2752 #ifdef AUTH
2753 else if (state->auth.reconf != NULL) {
2755 * Drop the lease as the token may only be present
2756 * in the initial reply message and not subsequent
2757 * renewals.
2758 * If dhcpcd is restarted, the token is lost.
2759 * XXX persist this in another file?
2761 dhcp_unlink(ifp->ctx, state->leasefile);
2763 #endif
2765 eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
2766 #ifdef AUTH
2767 dhcp_auth_reset(&state->auth);
2768 #endif
2770 /* Close DHCP ports so a changed interface family is picked
2771 * up by a new BPF state. */
2772 dhcp_close(ifp);
2774 state->state = DHS_NONE;
2775 free(state->offer);
2776 state->offer = NULL;
2777 state->offer_len = 0;
2778 free(state->old);
2779 state->old = state->new;
2780 state->old_len = state->new_len;
2781 state->new = NULL;
2782 state->new_len = 0;
2783 state->reason = reason;
2784 ipv4_applyaddr(ifp);
2785 free(state->old);
2786 state->old = NULL;
2787 state->old_len = 0;
2788 state->lease.addr.s_addr = 0;
2789 ifp->options->options &= ~(DHCPCD_CSR_WARNED |
2790 DHCPCD_ROUTER_HOST_ROUTE_WARNED);
2793 static int
2794 blacklisted_ip(const struct if_options *ifo, in_addr_t addr)
2796 size_t i;
2798 for (i = 0; i < ifo->blacklist_len; i += 2)
2799 if (ifo->blacklist[i] == (addr & ifo->blacklist[i + 1]))
2800 return 1;
2801 return 0;
2804 #define WHTLST_NONE 0
2805 #define WHTLST_MATCH 1
2806 #define WHTLST_NOMATCH 2
2807 static unsigned int
2808 whitelisted_ip(const struct if_options *ifo, in_addr_t addr)
2810 size_t i;
2812 if (ifo->whitelist_len == 0)
2813 return WHTLST_NONE;
2814 for (i = 0; i < ifo->whitelist_len; i += 2)
2815 if (ifo->whitelist[i] == (addr & ifo->whitelist[i + 1]))
2816 return WHTLST_MATCH;
2817 return WHTLST_NOMATCH;
2820 static void
2821 log_dhcp(int loglevel, const char *msg,
2822 const struct interface *ifp, const struct bootp *bootp, size_t bootp_len,
2823 const struct in_addr *from, int ad)
2825 const char *tfrom;
2826 char *a, sname[sizeof(bootp->sname) * 4];
2827 struct in_addr addr;
2828 int r;
2829 uint8_t overl;
2831 if (strcmp(msg, "NAK:") == 0) {
2832 a = get_option_string(ifp->ctx, bootp, bootp_len, DHO_MESSAGE);
2833 if (a) {
2834 char *tmp;
2835 size_t al, tmpl;
2837 al = strlen(a);
2838 tmpl = (al * 4) + 1;
2839 tmp = malloc(tmpl);
2840 if (tmp == NULL) {
2841 logerr(__func__);
2842 free(a);
2843 return;
2845 print_string(tmp, tmpl, OT_STRING, (uint8_t *)a, al);
2846 free(a);
2847 a = tmp;
2849 } else if (ad && bootp->yiaddr != 0) {
2850 addr.s_addr = bootp->yiaddr;
2851 a = strdup(inet_ntoa(addr));
2852 if (a == NULL) {
2853 logerr(__func__);
2854 return;
2856 } else
2857 a = NULL;
2859 tfrom = "from";
2860 r = get_option_addr(ifp->ctx, &addr, bootp, bootp_len, DHO_SERVERID);
2861 if (get_option_uint8(ifp->ctx, &overl, bootp, bootp_len,
2862 DHO_OPTSOVERLOADED) == -1)
2863 overl = 0;
2864 if (bootp->sname[0] && r == 0 && !(overl & 2)) {
2865 print_string(sname, sizeof(sname), OT_STRING | OT_DOMAIN,
2866 bootp->sname, sizeof(bootp->sname));
2867 if (a == NULL)
2868 logmessage(loglevel, "%s: %s %s %s `%s'",
2869 ifp->name, msg, tfrom, inet_ntoa(addr), sname);
2870 else
2871 logmessage(loglevel, "%s: %s %s %s %s `%s'",
2872 ifp->name, msg, a, tfrom, inet_ntoa(addr), sname);
2873 } else {
2874 if (r != 0) {
2875 tfrom = "via";
2876 addr = *from;
2878 if (a == NULL)
2879 logmessage(loglevel, "%s: %s %s %s",
2880 ifp->name, msg, tfrom, inet_ntoa(addr));
2881 else
2882 logmessage(loglevel, "%s: %s %s %s %s",
2883 ifp->name, msg, a, tfrom, inet_ntoa(addr));
2885 free(a);
2888 /* If we're sharing the same IP address with another interface on the
2889 * same network, we may receive the DHCP reply on the wrong interface.
2890 * Try and re-direct it here. */
2891 static void
2892 dhcp_redirect_dhcp(struct interface *ifp, struct bootp *bootp, size_t bootp_len,
2893 const struct in_addr *from)
2895 struct interface *ifn;
2896 const struct dhcp_state *state;
2897 uint32_t xid;
2899 xid = ntohl(bootp->xid);
2900 TAILQ_FOREACH(ifn, ifp->ctx->ifaces, next) {
2901 if (ifn == ifp)
2902 continue;
2903 state = D_CSTATE(ifn);
2904 if (state == NULL || state->state == DHS_NONE)
2905 continue;
2906 if (state->xid != xid)
2907 continue;
2908 if (ifn->hwlen <= sizeof(bootp->chaddr) &&
2909 memcmp(bootp->chaddr, ifn->hwaddr, ifn->hwlen))
2910 continue;
2911 logdebugx("%s: redirecting DHCP message to %s",
2912 ifp->name, ifn->name);
2913 dhcp_handledhcp(ifn, bootp, bootp_len, from);
2917 static void
2918 dhcp_handledhcp(struct interface *ifp, struct bootp *bootp, size_t bootp_len,
2919 const struct in_addr *from)
2921 struct dhcp_state *state = D_STATE(ifp);
2922 struct if_options *ifo = ifp->options;
2923 struct dhcp_lease *lease = &state->lease;
2924 uint8_t type, tmp;
2925 struct in_addr addr;
2926 unsigned int i;
2927 char *msg;
2928 bool bootp_copied;
2929 #ifdef AUTH
2930 const uint8_t *auth;
2931 size_t auth_len;
2932 #endif
2933 #ifdef IN_IFF_DUPLICATED
2934 struct ipv4_addr *ia;
2935 #endif
2937 #define LOGDHCP0(l, m) \
2938 log_dhcp((l), (m), ifp, bootp, bootp_len, from, 0)
2939 #define LOGDHCP(l, m) \
2940 log_dhcp((l), (m), ifp, bootp, bootp_len, from, 1)
2942 #define IS_STATE_ACTIVE(s) ((s)-state != DHS_NONE && \
2943 (s)->state != DHS_INIT && (s)->state != DHS_BOUND)
2945 if (bootp->op != BOOTREPLY) {
2946 if (IS_STATE_ACTIVE(state))
2947 logdebugx("%s: op (%d) is not BOOTREPLY",
2948 ifp->name, bootp->op);
2949 return;
2952 if (state->xid != ntohl(bootp->xid)) {
2953 if (IS_STATE_ACTIVE(state))
2954 logdebugx("%s: wrong xid 0x%x (expecting 0x%x) from %s",
2955 ifp->name, ntohl(bootp->xid), state->xid,
2956 inet_ntoa(*from));
2957 dhcp_redirect_dhcp(ifp, bootp, bootp_len, from);
2958 return;
2961 if (ifp->hwlen <= sizeof(bootp->chaddr) &&
2962 memcmp(bootp->chaddr, ifp->hwaddr, ifp->hwlen))
2964 if (IS_STATE_ACTIVE(state)) {
2965 char buf[sizeof(bootp->chaddr) * 3];
2967 logdebugx("%s: xid 0x%x is for hwaddr %s",
2968 ifp->name, ntohl(bootp->xid),
2969 hwaddr_ntoa(bootp->chaddr, sizeof(bootp->chaddr),
2970 buf, sizeof(buf)));
2972 dhcp_redirect_dhcp(ifp, bootp, bootp_len, from);
2973 return;
2976 if (!ifp->active)
2977 return;
2979 i = whitelisted_ip(ifp->options, from->s_addr);
2980 switch (i) {
2981 case WHTLST_NOMATCH:
2982 logwarnx("%s: non whitelisted DHCP packet from %s",
2983 ifp->name, inet_ntoa(*from));
2984 return;
2985 case WHTLST_MATCH:
2986 break;
2987 case WHTLST_NONE:
2988 if (blacklisted_ip(ifp->options, from->s_addr) == 1) {
2989 logwarnx("%s: blacklisted DHCP packet from %s",
2990 ifp->name, inet_ntoa(*from));
2991 return;
2995 /* We may have found a BOOTP server */
2996 if (get_option_uint8(ifp->ctx, &type,
2997 bootp, bootp_len, DHO_MESSAGETYPE) == -1)
2998 type = 0;
2999 else if (ifo->options & DHCPCD_BOOTP) {
3000 logdebugx("%s: ignoring DHCP reply (expecting BOOTP)",
3001 ifp->name);
3002 return;
3005 #ifdef AUTH
3006 /* Authenticate the message */
3007 auth = get_option(ifp->ctx, bootp, bootp_len,
3008 DHO_AUTHENTICATION, &auth_len);
3009 if (auth) {
3010 if (dhcp_auth_validate(&state->auth, &ifo->auth,
3011 (uint8_t *)bootp, bootp_len, 4, type,
3012 auth, auth_len) == NULL)
3014 LOGDHCP0(LOG_ERR, "authentication failed");
3015 return;
3017 if (state->auth.token)
3018 logdebugx("%s: validated using 0x%08" PRIu32,
3019 ifp->name, state->auth.token->secretid);
3020 else
3021 loginfox("%s: accepted reconfigure key", ifp->name);
3022 } else if (ifo->auth.options & DHCPCD_AUTH_SEND) {
3023 if (ifo->auth.options & DHCPCD_AUTH_REQUIRE) {
3024 LOGDHCP0(LOG_ERR, "no authentication");
3025 return;
3027 LOGDHCP0(LOG_WARNING, "no authentication");
3029 #endif
3031 /* RFC 3203 */
3032 if (type == DHCP_FORCERENEW) {
3033 if (from->s_addr == INADDR_ANY ||
3034 from->s_addr == INADDR_BROADCAST)
3036 LOGDHCP(LOG_ERR, "discarding Force Renew");
3037 return;
3039 #ifdef AUTH
3040 if (auth == NULL) {
3041 LOGDHCP(LOG_ERR, "unauthenticated Force Renew");
3042 if (ifo->auth.options & DHCPCD_AUTH_REQUIRE)
3043 return;
3045 if (state->state != DHS_BOUND && state->state != DHS_INFORM) {
3046 LOGDHCP(LOG_DEBUG, "not bound, ignoring Force Renew");
3047 return;
3049 LOGDHCP(LOG_INFO, "Force Renew from");
3050 /* The rebind and expire timings are still the same, we just
3051 * enter the renew state early */
3052 if (state->state == DHS_BOUND)
3053 dhcp_renew(ifp);
3054 else {
3055 eloop_timeout_delete(ifp->ctx->eloop,
3056 send_inform, ifp);
3057 dhcp_inform(ifp);
3059 #else
3060 LOGDHCP(LOG_ERR, "unauthenticated Force Renew");
3061 #endif
3062 return;
3065 if (state->state == DHS_BOUND) {
3066 LOGDHCP(LOG_DEBUG, "bound, ignoring");
3067 return;
3070 if (state->state == DHS_PROBE) {
3071 /* Ignore any DHCP messages whilst probing a lease to bind. */
3072 LOGDHCP(LOG_DEBUG, "probing, ignoring");
3073 return;
3076 /* reset the message counter */
3077 state->interval = 0;
3079 /* Ensure that no reject options are present */
3080 for (i = 1; i < 255; i++) {
3081 if (has_option_mask(ifo->rejectmask, i) &&
3082 get_option_uint8(ifp->ctx, &tmp,
3083 bootp, bootp_len, (uint8_t)i) == 0)
3085 LOGDHCP(LOG_WARNING, "reject DHCP");
3086 return;
3090 if (type == DHCP_NAK) {
3091 /* For NAK, only check if we require the ServerID */
3092 if (has_option_mask(ifo->requiremask, DHO_SERVERID) &&
3093 get_option_addr(ifp->ctx, &addr,
3094 bootp, bootp_len, DHO_SERVERID) == -1)
3096 LOGDHCP(LOG_WARNING, "reject NAK");
3097 return;
3100 /* We should restart on a NAK */
3101 LOGDHCP(LOG_WARNING, "NAK:");
3102 if ((msg = get_option_string(ifp->ctx,
3103 bootp, bootp_len, DHO_MESSAGE)))
3105 logwarnx("%s: message: %s", ifp->name, msg);
3106 free(msg);
3108 if (state->state == DHS_INFORM) /* INFORM should not be NAKed */
3109 return;
3110 if (!(ifp->ctx->options & DHCPCD_TEST)) {
3111 dhcp_drop(ifp, "NAK");
3112 dhcp_unlink(ifp->ctx, state->leasefile);
3115 /* If we constantly get NAKS then we should slowly back off */
3116 eloop_timeout_add_sec(ifp->ctx->eloop,
3117 state->nakoff, dhcp_discover, ifp);
3118 if (state->nakoff == 0)
3119 state->nakoff = 1;
3120 else {
3121 state->nakoff *= 2;
3122 if (state->nakoff > NAKOFF_MAX)
3123 state->nakoff = NAKOFF_MAX;
3125 return;
3128 /* Ensure that all required options are present */
3129 for (i = 1; i < 255; i++) {
3130 if (has_option_mask(ifo->requiremask, i) &&
3131 get_option_uint8(ifp->ctx, &tmp,
3132 bootp, bootp_len, (uint8_t)i) != 0)
3134 /* If we are BOOTP, then ignore the need for serverid.
3135 * To ignore BOOTP, require dhcp_message_type.
3136 * However, nothing really stops BOOTP from providing
3137 * DHCP style options as well so the above isn't
3138 * always true. */
3139 if (type == 0 && i == DHO_SERVERID)
3140 continue;
3141 LOGDHCP(LOG_WARNING, "reject DHCP");
3142 return;
3146 /* DHCP Auto-Configure, RFC 2563 */
3147 if (type == DHCP_OFFER && bootp->yiaddr == 0) {
3148 LOGDHCP(LOG_WARNING, "no address given");
3149 if ((msg = get_option_string(ifp->ctx,
3150 bootp, bootp_len, DHO_MESSAGE)))
3152 logwarnx("%s: message: %s", ifp->name, msg);
3153 free(msg);
3155 #ifdef IPV4LL
3156 if (state->state == DHS_DISCOVER &&
3157 get_option_uint8(ifp->ctx, &tmp, bootp, bootp_len,
3158 DHO_AUTOCONFIGURE) == 0)
3160 switch (tmp) {
3161 case 0:
3162 LOGDHCP(LOG_WARNING, "IPv4LL disabled from");
3163 ipv4ll_drop(ifp);
3164 #ifdef ARP
3165 arp_drop(ifp);
3166 #endif
3167 break;
3168 case 1:
3169 LOGDHCP(LOG_WARNING, "IPv4LL enabled from");
3170 ipv4ll_start(ifp);
3171 break;
3172 default:
3173 logerrx("%s: unknown auto configuration "
3174 "option %d",
3175 ifp->name, tmp);
3176 break;
3178 eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
3179 eloop_timeout_add_sec(ifp->ctx->eloop,
3180 DHCP_MAX, dhcp_discover, ifp);
3182 #endif
3183 return;
3186 /* Ensure that the address offered is valid */
3187 if ((type == 0 || type == DHCP_OFFER || type == DHCP_ACK) &&
3188 (bootp->ciaddr == INADDR_ANY || bootp->ciaddr == INADDR_BROADCAST)
3190 (bootp->yiaddr == INADDR_ANY || bootp->yiaddr == INADDR_BROADCAST))
3192 LOGDHCP(LOG_WARNING, "reject invalid address");
3193 return;
3196 #ifdef IN_IFF_DUPLICATED
3197 ia = ipv4_iffindaddr(ifp, &lease->addr, NULL);
3198 if (ia && ia->addr_flags & IN_IFF_DUPLICATED) {
3199 LOGDHCP(LOG_WARNING, "declined duplicate address");
3200 if (type)
3201 dhcp_decline(ifp);
3202 ipv4_deladdr(ia, 0);
3203 eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
3204 eloop_timeout_add_sec(ifp->ctx->eloop,
3205 DHCP_RAND_MAX, dhcp_discover, ifp);
3206 return;
3208 #endif
3210 bootp_copied = false;
3211 if ((type == 0 || type == DHCP_OFFER) && state->state == DHS_DISCOVER) {
3212 lease->frominfo = 0;
3213 lease->addr.s_addr = bootp->yiaddr;
3214 memcpy(&lease->cookie, bootp->vend, sizeof(lease->cookie));
3215 if (type == 0 ||
3216 get_option_addr(ifp->ctx,
3217 &lease->server, bootp, bootp_len, DHO_SERVERID) != 0)
3218 lease->server.s_addr = INADDR_ANY;
3220 /* Test for rapid commit in the OFFER */
3221 if (!(ifp->ctx->options & DHCPCD_TEST) &&
3222 has_option_mask(ifo->requestmask, DHO_RAPIDCOMMIT) &&
3223 get_option(ifp->ctx, bootp, bootp_len,
3224 DHO_RAPIDCOMMIT, NULL))
3226 state->state = DHS_REQUEST;
3227 goto rapidcommit;
3230 LOGDHCP(LOG_INFO, "offered");
3231 if (state->offer_len < bootp_len) {
3232 free(state->offer);
3233 if ((state->offer = malloc(bootp_len)) == NULL) {
3234 logerr(__func__);
3235 state->offer_len = 0;
3236 return;
3239 state->offer_len = bootp_len;
3240 memcpy(state->offer, bootp, bootp_len);
3241 bootp_copied = true;
3242 if (ifp->ctx->options & DHCPCD_TEST) {
3243 free(state->old);
3244 state->old = state->new;
3245 state->old_len = state->new_len;
3246 state->new = state->offer;
3247 state->new_len = state->offer_len;
3248 state->offer = NULL;
3249 state->offer_len = 0;
3250 state->reason = "TEST";
3251 script_runreason(ifp, state->reason);
3252 eloop_exit(ifp->ctx->eloop, EXIT_SUCCESS);
3253 state->bpf->bpf_flags |= BPF_EOF;
3254 return;
3256 eloop_timeout_delete(ifp->ctx->eloop, send_discover, ifp);
3257 /* We don't request BOOTP addresses */
3258 if (type) {
3259 /* We used to ARP check here, but that seems to be in
3260 * violation of RFC2131 where it only describes
3261 * DECLINE after REQUEST.
3262 * It also seems that some MS DHCP servers actually
3263 * ignore DECLINE if no REQUEST, ie we decline a
3264 * DISCOVER. */
3265 dhcp_request(ifp);
3266 return;
3270 if (type) {
3271 if (type == DHCP_OFFER) {
3272 LOGDHCP(LOG_WARNING, "ignoring offer of");
3273 return;
3276 /* We should only be dealing with acks */
3277 if (type != DHCP_ACK) {
3278 LOGDHCP(LOG_ERR, "not ACK or OFFER");
3279 return;
3282 if (state->state == DHS_DISCOVER) {
3283 /* We only allow ACK of rapid commit DISCOVER. */
3284 if (has_option_mask(ifo->requestmask,
3285 DHO_RAPIDCOMMIT) &&
3286 get_option(ifp->ctx, bootp, bootp_len,
3287 DHO_RAPIDCOMMIT, NULL))
3288 state->state = DHS_REQUEST;
3289 else {
3290 LOGDHCP(LOG_DEBUG, "ignoring ack of");
3291 return;
3295 rapidcommit:
3296 if (!(ifo->options & DHCPCD_INFORM))
3297 LOGDHCP(LOG_DEBUG, "acknowledged");
3298 else
3299 ifo->options &= ~DHCPCD_STATIC;
3302 /* No NAK, so reset the backoff
3303 * We don't reset on an OFFER message because the server could
3304 * potentially NAK the REQUEST. */
3305 state->nakoff = 0;
3307 /* BOOTP could have already assigned this above. */
3308 if (!bootp_copied) {
3309 if (state->offer_len < bootp_len) {
3310 free(state->offer);
3311 if ((state->offer = malloc(bootp_len)) == NULL) {
3312 logerr(__func__);
3313 state->offer_len = 0;
3314 return;
3317 state->offer_len = bootp_len;
3318 memcpy(state->offer, bootp, bootp_len);
3321 lease->frominfo = 0;
3322 eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
3324 #if defined(ARP) || defined(KERNEL_RFC5227)
3325 dhcp_arp_bind(ifp);
3326 #else
3327 dhcp_bind(ifp);
3328 #endif
3331 static void *
3332 get_udp_data(void *packet, size_t *len)
3334 const struct ip *ip = packet;
3335 size_t ip_hl = (size_t)ip->ip_hl * 4;
3336 char *p = packet;
3338 p += ip_hl + sizeof(struct udphdr);
3339 *len = (size_t)ntohs(ip->ip_len) - sizeof(struct udphdr) - ip_hl;
3340 return p;
3343 static bool
3344 is_packet_udp_bootp(void *packet, size_t plen)
3346 struct ip *ip = packet;
3347 size_t ip_hlen;
3348 struct udphdr udp;
3350 if (plen < sizeof(*ip))
3351 return false;
3353 if (ip->ip_v != IPVERSION || ip->ip_p != IPPROTO_UDP)
3354 return false;
3356 /* Sanity. */
3357 if (ntohs(ip->ip_len) > plen)
3358 return false;
3360 ip_hlen = (size_t)ip->ip_hl * 4;
3361 if (ip_hlen < sizeof(*ip))
3362 return false;
3364 /* Check we have a UDP header and BOOTP. */
3365 if (ip_hlen + sizeof(udp) + offsetof(struct bootp, vend) > plen)
3366 return false;
3368 /* Sanity. */
3369 memcpy(&udp, (char *)ip + ip_hlen, sizeof(udp));
3370 if (ntohs(udp.uh_ulen) < sizeof(udp))
3371 return false;
3372 if (ip_hlen + ntohs(udp.uh_ulen) > plen)
3373 return false;
3375 /* Check it's to and from the right ports. */
3376 if (udp.uh_dport != htons(BOOTPC) || udp.uh_sport != htons(BOOTPS))
3377 return false;
3379 return true;
3382 /* Lengths have already been checked. */
3383 static bool
3384 checksums_valid(void *packet,
3385 struct in_addr *from, unsigned int flags)
3387 struct ip *ip = packet;
3388 union pip {
3389 struct ip ip;
3390 uint16_t w[sizeof(struct ip) / 2];
3391 } pip = {
3392 .ip = {
3393 .ip_p = IPPROTO_UDP,
3394 .ip_src = ip->ip_src,
3395 .ip_dst = ip->ip_dst,
3398 size_t ip_hlen;
3399 struct udphdr udp;
3400 char *udpp, *uh_sump;
3401 uint32_t csum;
3403 if (from != NULL)
3404 from->s_addr = ip->ip_src.s_addr;
3406 ip_hlen = (size_t)ip->ip_hl * 4;
3407 if (in_cksum(ip, ip_hlen, NULL) != 0)
3408 return false;
3410 if (flags & BPF_PARTIALCSUM)
3411 return true;
3413 udpp = (char *)ip + ip_hlen;
3414 memcpy(&udp, udpp, sizeof(udp));
3415 if (udp.uh_sum == 0)
3416 return true;
3418 /* UDP checksum is based on a pseudo IP header alongside
3419 * the UDP header and payload. */
3420 pip.ip.ip_len = udp.uh_ulen;
3421 csum = 0;
3423 /* Need to zero the UDP sum in the packet for the checksum to work. */
3424 uh_sump = udpp + offsetof(struct udphdr, uh_sum);
3425 memset(uh_sump, 0, sizeof(udp.uh_sum));
3427 /* Checksum pseudo header and then UDP + payload. */
3428 in_cksum(pip.w, sizeof(pip.w), &csum);
3429 csum = in_cksum(udpp, ntohs(udp.uh_ulen), &csum);
3431 #if 0 /* Not needed, just here for completeness. */
3432 /* Put the checksum back. */
3433 memcpy(uh_sump, &udp.uh_sum, sizeof(udp.uh_sum));
3434 #endif
3436 return csum == udp.uh_sum;
3439 static void
3440 dhcp_handlebootp(struct interface *ifp, struct bootp *bootp, size_t len,
3441 struct in_addr *from)
3443 size_t v;
3445 if (len < offsetof(struct bootp, vend)) {
3446 logerrx("%s: truncated packet (%zu) from %s",
3447 ifp->name, len, inet_ntoa(*from));
3448 return;
3451 /* Unlikely, but appeases sanitizers. */
3452 if (len > FRAMELEN_MAX) {
3453 logerrx("%s: packet exceeded frame length (%zu) from %s",
3454 ifp->name, len, inet_ntoa(*from));
3455 return;
3458 /* To make our IS_DHCP macro easy, ensure the vendor
3459 * area has at least 4 octets. */
3460 v = len - offsetof(struct bootp, vend);
3461 while (v < 4) {
3462 bootp->vend[v++] = '\0';
3463 len++;
3466 dhcp_handledhcp(ifp, bootp, len, from);
3469 void
3470 dhcp_packet(struct interface *ifp, uint8_t *data, size_t len,
3471 unsigned int bpf_flags)
3473 struct bootp *bootp;
3474 struct in_addr from;
3475 size_t udp_len;
3476 size_t fl = bpf_frame_header_len(ifp);
3477 #ifdef PRIVSEP
3478 const struct dhcp_state *state = D_CSTATE(ifp);
3480 /* Ignore double reads */
3481 if (IN_PRIVSEP(ifp->ctx)) {
3482 switch (state->state) {
3483 case DHS_BOUND: /* FALLTHROUGH */
3484 case DHS_RENEW:
3485 return;
3486 default:
3487 break;
3490 #endif
3492 /* Trim frame header */
3493 if (fl != 0) {
3494 if (len < fl) {
3495 logerrx("%s: %s: short frame header %zu",
3496 __func__, ifp->name, len);
3497 return;
3499 len -= fl;
3500 /* Move the data to avoid alignment errors. */
3501 memmove(data, data + fl, len);
3504 /* Validate filter. */
3505 if (!is_packet_udp_bootp(data, len)) {
3506 #ifdef BPF_DEBUG
3507 logerrx("%s: DHCP BPF validation failure", ifp->name);
3508 #endif
3509 return;
3512 if (!checksums_valid(data, &from, bpf_flags)) {
3513 logerrx("%s: checksum failure from %s",
3514 ifp->name, inet_ntoa(from));
3515 return;
3519 * DHCP has a variable option area rather than a fixed vendor area.
3520 * Because DHCP uses the BOOTP protocol it should still send BOOTP
3521 * sized packets to be RFC compliant.
3522 * However some servers send a truncated vendor area.
3523 * dhcpcd can work fine without the vendor area being sent.
3525 bootp = get_udp_data(data, &udp_len);
3526 dhcp_handlebootp(ifp, bootp, udp_len, &from);
3529 static void
3530 dhcp_readbpf(void *arg)
3532 struct interface *ifp = arg;
3533 uint8_t buf[FRAMELEN_MAX];
3534 ssize_t bytes;
3535 struct dhcp_state *state = D_STATE(ifp);
3536 struct bpf *bpf = state->bpf;
3538 bpf->bpf_flags &= ~BPF_EOF;
3539 while (!(bpf->bpf_flags & BPF_EOF)) {
3540 bytes = bpf_read(bpf, buf, sizeof(buf));
3541 if (bytes == -1) {
3542 if (state->state != DHS_NONE) {
3543 logerr("%s: %s", __func__, ifp->name);
3544 dhcp_close(ifp);
3546 break;
3548 dhcp_packet(ifp, buf, (size_t)bytes, bpf->bpf_flags);
3549 /* Check we still have a state after processing. */
3550 if ((state = D_STATE(ifp)) == NULL)
3551 break;
3552 if ((bpf = state->bpf) == NULL)
3553 break;
3557 void
3558 dhcp_recvmsg(struct dhcpcd_ctx *ctx, struct msghdr *msg)
3560 struct sockaddr_in *from = (struct sockaddr_in *)msg->msg_name;
3561 struct iovec *iov = &msg->msg_iov[0];
3562 struct interface *ifp;
3563 const struct dhcp_state *state;
3565 ifp = if_findifpfromcmsg(ctx, msg, NULL);
3566 if (ifp == NULL) {
3567 logerr(__func__);
3568 return;
3570 state = D_CSTATE(ifp);
3571 if (state == NULL) {
3572 /* Try re-directing it to another interface. */
3573 dhcp_redirect_dhcp(ifp, (struct bootp *)iov->iov_base,
3574 iov->iov_len, &from->sin_addr);
3575 return;
3578 if (state->bpf != NULL) {
3579 /* Avoid a duplicate read if BPF is open for the interface. */
3580 return;
3582 #ifdef PRIVSEP
3583 if (IN_PRIVSEP(ctx)) {
3584 switch (state->state) {
3585 case DHS_BOUND: /* FALLTHROUGH */
3586 case DHS_RENEW:
3587 break;
3588 default:
3589 /* Any other state we ignore it or will receive
3590 * via BPF. */
3591 return;
3594 #endif
3596 dhcp_handlebootp(ifp, iov->iov_base, iov->iov_len,
3597 &from->sin_addr);
3600 static void
3601 dhcp_readudp(struct dhcpcd_ctx *ctx, struct interface *ifp)
3603 const struct dhcp_state *state;
3604 struct sockaddr_in from;
3605 union {
3606 struct bootp bootp;
3607 uint8_t buf[10 * 1024]; /* Maximum MTU */
3608 } iovbuf;
3609 struct iovec iov = {
3610 .iov_base = iovbuf.buf,
3611 .iov_len = sizeof(iovbuf.buf),
3613 union {
3614 struct cmsghdr hdr;
3615 #ifdef IP_RECVIF
3616 uint8_t buf[CMSG_SPACE(sizeof(struct sockaddr_dl))];
3617 #else
3618 uint8_t buf[CMSG_SPACE(sizeof(struct in_pktinfo))];
3619 #endif
3620 } cmsgbuf = { .buf = { 0 } };
3621 struct msghdr msg = {
3622 .msg_name = &from, .msg_namelen = sizeof(from),
3623 .msg_iov = &iov, .msg_iovlen = 1,
3624 .msg_control = cmsgbuf.buf, .msg_controllen = sizeof(cmsgbuf.buf),
3626 int s;
3627 ssize_t bytes;
3629 if (ifp != NULL) {
3630 state = D_CSTATE(ifp);
3631 s = state->udp_rfd;
3632 } else
3633 s = ctx->udp_rfd;
3635 bytes = recvmsg(s, &msg, 0);
3636 if (bytes == -1) {
3637 logerr(__func__);
3638 return;
3641 iov.iov_len = (size_t)bytes;
3642 dhcp_recvmsg(ctx, &msg);
3645 static void
3646 dhcp_handleudp(void *arg)
3648 struct dhcpcd_ctx *ctx = arg;
3650 dhcp_readudp(ctx, NULL);
3653 static void
3654 dhcp_handleifudp(void *arg)
3656 struct interface *ifp = arg;
3658 dhcp_readudp(ifp->ctx, ifp);
3661 static int
3662 dhcp_openbpf(struct interface *ifp)
3664 struct dhcp_state *state;
3666 state = D_STATE(ifp);
3668 #ifdef PRIVSEP
3669 if (IN_PRIVSEP_SE(ifp->ctx)) {
3670 if (ps_bpf_openbootp(ifp) == -1) {
3671 logerr(__func__);
3672 return -1;
3674 return 0;
3676 #endif
3678 if (state->bpf != NULL)
3679 return 0;
3681 state->bpf = bpf_open(ifp, bpf_bootp, NULL);
3682 if (state->bpf == NULL) {
3683 if (errno == ENOENT) {
3684 logerrx("%s not found", bpf_name);
3685 /* May as well disable IPv4 entirely at
3686 * this point as we really need it. */
3687 ifp->options->options &= ~DHCPCD_IPV4;
3688 } else
3689 logerr("%s: %s", __func__, ifp->name);
3690 return -1;
3693 eloop_event_add(ifp->ctx->eloop,
3694 state->bpf->bpf_fd, dhcp_readbpf, ifp);
3695 return 0;
3698 void
3699 dhcp_free(struct interface *ifp)
3701 struct dhcp_state *state = D_STATE(ifp);
3702 struct dhcpcd_ctx *ctx;
3704 dhcp_close(ifp);
3705 #ifdef ARP
3706 arp_drop(ifp);
3707 #endif
3708 if (state) {
3709 state->state = DHS_NONE;
3710 free(state->old);
3711 free(state->new);
3712 free(state->offer);
3713 free(state->clientid);
3714 free(state);
3717 ctx = ifp->ctx;
3718 /* If we don't have any more DHCP enabled interfaces,
3719 * close the global socket and release resources */
3720 if (ctx->ifaces) {
3721 TAILQ_FOREACH(ifp, ctx->ifaces, next) {
3722 state = D_STATE(ifp);
3723 if (state != NULL && state->state != DHS_NONE)
3724 break;
3727 if (ifp == NULL) {
3728 if (ctx->udp_rfd != -1) {
3729 eloop_event_delete(ctx->eloop, ctx->udp_rfd);
3730 close(ctx->udp_rfd);
3731 ctx->udp_rfd = -1;
3733 if (ctx->udp_wfd != -1) {
3734 close(ctx->udp_wfd);
3735 ctx->udp_wfd = -1;
3738 free(ctx->opt_buffer);
3739 ctx->opt_buffer = NULL;
3743 static int
3744 dhcp_initstate(struct interface *ifp)
3746 struct dhcp_state *state;
3748 state = D_STATE(ifp);
3749 if (state != NULL)
3750 return 0;
3752 ifp->if_data[IF_DATA_DHCP] = calloc(1, sizeof(*state));
3753 state = D_STATE(ifp);
3754 if (state == NULL)
3755 return -1;
3757 state->state = DHS_NONE;
3758 /* 0 is a valid fd, so init to -1 */
3759 state->udp_rfd = -1;
3760 #ifdef ARPING
3761 state->arping_index = -1;
3762 #endif
3763 return 1;
3766 static int
3767 dhcp_init(struct interface *ifp)
3769 struct dhcp_state *state;
3770 struct if_options *ifo;
3771 uint8_t len;
3772 char buf[(sizeof(ifo->clientid) - 1) * 3];
3774 if (dhcp_initstate(ifp) == -1)
3775 return -1;
3777 state = D_STATE(ifp);
3778 state->state = DHS_INIT;
3779 state->reason = "PREINIT";
3780 state->nakoff = 0;
3781 dhcp_set_leasefile(state->leasefile, sizeof(state->leasefile),
3782 AF_INET, ifp);
3784 ifo = ifp->options;
3785 /* We need to drop the leasefile so that dhcp_start
3786 * doesn't load it. */
3787 if (ifo->options & DHCPCD_REQUEST)
3788 dhcp_unlink(ifp->ctx, state->leasefile);
3790 free(state->clientid);
3791 state->clientid = NULL;
3793 if (ifo->options & DHCPCD_ANONYMOUS) {
3794 uint8_t duid[DUID_LEN];
3795 uint8_t duid_len;
3797 duid_len = (uint8_t)duid_make(duid, ifp, DUID_LL);
3798 if (duid_len != 0) {
3799 state->clientid = malloc((size_t)duid_len + 6);
3800 if (state->clientid == NULL)
3801 goto eexit;
3802 state->clientid[0] =(uint8_t)(duid_len + 5);
3803 state->clientid[1] = 255; /* RFC 4361 */
3804 memcpy(state->clientid + 2, ifo->iaid, 4);
3805 memset(state->clientid + 2, 0, 4); /* IAID */
3806 memcpy(state->clientid + 6, duid, duid_len);
3808 } else if (*ifo->clientid) {
3809 state->clientid = malloc((size_t)(ifo->clientid[0] + 1));
3810 if (state->clientid == NULL)
3811 goto eexit;
3812 memcpy(state->clientid, ifo->clientid,
3813 (size_t)(ifo->clientid[0]) + 1);
3814 } else if (ifo->options & DHCPCD_CLIENTID) {
3815 if (ifo->options & DHCPCD_DUID) {
3816 state->clientid = malloc(ifp->ctx->duid_len + 6);
3817 if (state->clientid == NULL)
3818 goto eexit;
3819 state->clientid[0] =(uint8_t)(ifp->ctx->duid_len + 5);
3820 state->clientid[1] = 255; /* RFC 4361 */
3821 memcpy(state->clientid + 2, ifo->iaid, 4);
3822 memcpy(state->clientid + 6, ifp->ctx->duid,
3823 ifp->ctx->duid_len);
3824 } else {
3825 len = (uint8_t)(ifp->hwlen + 1);
3826 state->clientid = malloc((size_t)len + 1);
3827 if (state->clientid == NULL)
3828 goto eexit;
3829 state->clientid[0] = len;
3830 state->clientid[1] = (uint8_t)ifp->hwtype;
3831 memcpy(state->clientid + 2, ifp->hwaddr,
3832 ifp->hwlen);
3836 if (ifo->options & DHCPCD_DUID)
3837 /* Don't bother logging as DUID and IAID are reported
3838 * at device start. */
3839 return 0;
3841 if (ifo->options & DHCPCD_CLIENTID && state->clientid != NULL)
3842 logdebugx("%s: using ClientID %s", ifp->name,
3843 hwaddr_ntoa(state->clientid + 1, state->clientid[0],
3844 buf, sizeof(buf)));
3845 else if (ifp->hwlen)
3846 logdebugx("%s: using hwaddr %s", ifp->name,
3847 hwaddr_ntoa(ifp->hwaddr, ifp->hwlen, buf, sizeof(buf)));
3848 return 0;
3850 eexit:
3851 logerr(__func__);
3852 return -1;
3855 static void
3856 dhcp_start1(void *arg)
3858 struct interface *ifp = arg;
3859 struct dhcpcd_ctx *ctx = ifp->ctx;
3860 struct if_options *ifo = ifp->options;
3861 struct dhcp_state *state;
3862 uint32_t l;
3863 int nolease;
3865 if (!(ifo->options & DHCPCD_IPV4))
3866 return;
3868 /* Listen on *.*.*.*:bootpc so that the kernel never sends an
3869 * ICMP port unreachable message back to the DHCP server.
3870 * Only do this in master mode so we don't swallow messages
3871 * for dhcpcd running on another interface. */
3872 if ((ctx->options & (DHCPCD_MASTER|DHCPCD_PRIVSEP)) == DHCPCD_MASTER
3873 && ctx->udp_rfd == -1)
3875 ctx->udp_rfd = dhcp_openudp(NULL);
3876 if (ctx->udp_rfd == -1) {
3877 logerr(__func__);
3878 return;
3880 eloop_event_add(ctx->eloop, ctx->udp_rfd, dhcp_handleudp, ctx);
3882 if (!IN_PRIVSEP(ctx) && ctx->udp_wfd == -1) {
3883 ctx->udp_wfd = xsocket(PF_INET, SOCK_RAW|SOCK_CXNB,IPPROTO_UDP);
3884 if (ctx->udp_wfd == -1) {
3885 logerr(__func__);
3886 return;
3890 if (dhcp_init(ifp) == -1) {
3891 logerr("%s: dhcp_init", ifp->name);
3892 return;
3895 state = D_STATE(ifp);
3896 clock_gettime(CLOCK_MONOTONIC, &state->started);
3897 state->interval = 0;
3898 free(state->offer);
3899 state->offer = NULL;
3900 state->offer_len = 0;
3902 #ifdef ARPING
3903 if (ifo->arping_len && state->arping_index < ifo->arping_len) {
3904 dhcp_arping(ifp);
3905 return;
3907 #endif
3909 if (ifo->options & DHCPCD_STATIC) {
3910 dhcp_static(ifp);
3911 return;
3914 if (ifo->options & DHCPCD_INFORM) {
3915 dhcp_inform(ifp);
3916 return;
3919 /* We don't want to read the old lease if we NAK an old test */
3920 nolease = state->offer && ifp->ctx->options & DHCPCD_TEST;
3921 if (!nolease && ifo->options & DHCPCD_DHCP) {
3922 state->offer_len = read_lease(ifp, &state->offer);
3923 /* Check the saved lease matches the type we want */
3924 if (state->offer) {
3925 #ifdef IN_IFF_DUPLICATED
3926 struct in_addr addr;
3927 struct ipv4_addr *ia;
3929 addr.s_addr = state->offer->yiaddr;
3930 ia = ipv4_iffindaddr(ifp, &addr, NULL);
3931 #endif
3933 if ((!IS_DHCP(state->offer) &&
3934 !(ifo->options & DHCPCD_BOOTP)) ||
3935 #ifdef IN_IFF_DUPLICATED
3936 (ia && ia->addr_flags & IN_IFF_DUPLICATED) ||
3937 #endif
3938 (IS_DHCP(state->offer) &&
3939 ifo->options & DHCPCD_BOOTP))
3941 free(state->offer);
3942 state->offer = NULL;
3943 state->offer_len = 0;
3947 if (state->offer) {
3948 struct ipv4_addr *ia;
3949 time_t mtime;
3951 get_lease(ifp, &state->lease, state->offer, state->offer_len);
3952 state->lease.frominfo = 1;
3953 if (state->new == NULL &&
3954 (ia = ipv4_iffindaddr(ifp,
3955 &state->lease.addr, &state->lease.mask)) != NULL)
3957 /* We still have the IP address from the last lease.
3958 * Fake add the address and routes from it so the lease
3959 * can be cleaned up. */
3960 state->new = malloc(state->offer_len);
3961 if (state->new) {
3962 memcpy(state->new,
3963 state->offer, state->offer_len);
3964 state->new_len = state->offer_len;
3965 state->addr = ia;
3966 state->added |= STATE_ADDED | STATE_FAKE;
3967 rt_build(ifp->ctx, AF_INET);
3968 } else
3969 logerr(__func__);
3971 if (!IS_DHCP(state->offer)) {
3972 free(state->offer);
3973 state->offer = NULL;
3974 state->offer_len = 0;
3975 } else if (!(ifo->options & DHCPCD_LASTLEASE_EXTEND) &&
3976 state->lease.leasetime != DHCP_INFINITE_LIFETIME &&
3977 dhcp_filemtime(ifp->ctx, state->leasefile, &mtime) == 0)
3979 time_t now;
3981 /* Offset lease times and check expiry */
3982 now = time(NULL);
3983 if (now == -1 ||
3984 (time_t)state->lease.leasetime < now - mtime)
3986 logdebugx("%s: discarding expired lease",
3987 ifp->name);
3988 free(state->offer);
3989 state->offer = NULL;
3990 state->offer_len = 0;
3991 state->lease.addr.s_addr = 0;
3992 /* Technically we should discard the lease
3993 * as it's expired, just as DHCPv6 addresses
3994 * would be by the kernel.
3995 * However, this may violate POLA so
3996 * we currently leave it be.
3997 * If we get a totally different lease from
3998 * the DHCP server we'll drop it anyway, as
3999 * we will on any other event which would
4000 * trigger a lease drop.
4001 * This should only happen if dhcpcd stops
4002 * running and the lease expires before
4003 * dhcpcd starts again. */
4004 #if 0
4005 if (state->new)
4006 dhcp_drop(ifp, "EXPIRE");
4007 #endif
4008 } else {
4009 l = (uint32_t)(now - mtime);
4010 state->lease.leasetime -= l;
4011 state->lease.renewaltime -= l;
4012 state->lease.rebindtime -= l;
4017 #ifdef IPV4LL
4018 if (!(ifo->options & DHCPCD_DHCP)) {
4019 if (ifo->options & DHCPCD_IPV4LL)
4020 ipv4ll_start(ifp);
4021 return;
4023 #endif
4025 if (state->offer == NULL ||
4026 !IS_DHCP(state->offer) ||
4027 ifo->options & DHCPCD_ANONYMOUS)
4028 dhcp_discover(ifp);
4029 else
4030 dhcp_reboot(ifp);
4033 void
4034 dhcp_start(struct interface *ifp)
4036 unsigned int delay;
4037 #ifdef ARPING
4038 const struct dhcp_state *state;
4039 #endif
4041 if (!(ifp->options->options & DHCPCD_IPV4))
4042 return;
4044 /* If we haven't been given a netmask for our requested address,
4045 * set it now. */
4046 if (ifp->options->req_addr.s_addr != INADDR_ANY &&
4047 ifp->options->req_mask.s_addr == INADDR_ANY)
4048 ifp->options->req_mask.s_addr =
4049 ipv4_getnetmask(ifp->options->req_addr.s_addr);
4051 /* If we haven't specified a ClientID and our hardware address
4052 * length is greater than BOOTP CHADDR then we enforce a ClientID
4053 * of the hardware address type and the hardware address.
4054 * If there is no hardware address and no ClientID set,
4055 * force a DUID based ClientID. */
4056 if (ifp->hwlen > 16)
4057 ifp->options->options |= DHCPCD_CLIENTID;
4058 else if (ifp->hwlen == 0 && !(ifp->options->options & DHCPCD_CLIENTID))
4059 ifp->options->options |= DHCPCD_CLIENTID | DHCPCD_DUID;
4061 /* Firewire and InfiniBand interfaces require ClientID and
4062 * the broadcast option being set. */
4063 switch (ifp->hwtype) {
4064 case ARPHRD_IEEE1394: /* FALLTHROUGH */
4065 case ARPHRD_INFINIBAND:
4066 ifp->options->options |= DHCPCD_CLIENTID | DHCPCD_BROADCAST;
4067 break;
4070 /* If we violate RFC2131 section 3.7 then require ARP
4071 * to detect if any other client wants our address. */
4072 if (ifp->options->options & DHCPCD_LASTLEASE_EXTEND)
4073 ifp->options->options |= DHCPCD_ARP;
4075 /* No point in delaying a static configuration */
4076 if (ifp->options->options & DHCPCD_STATIC ||
4077 !(ifp->options->options & DHCPCD_INITIAL_DELAY))
4079 dhcp_start1(ifp);
4080 return;
4083 #ifdef ARPING
4084 /* If we have arpinged then we have already delayed. */
4085 state = D_CSTATE(ifp);
4086 if (state != NULL && state->arping_index != -1) {
4087 dhcp_start1(ifp);
4088 return;
4090 #endif
4091 delay = MSEC_PER_SEC +
4092 (arc4random_uniform(MSEC_PER_SEC * 2) - MSEC_PER_SEC);
4093 logdebugx("%s: delaying IPv4 for %0.1f seconds",
4094 ifp->name, (float)delay / MSEC_PER_SEC);
4096 eloop_timeout_add_msec(ifp->ctx->eloop, delay, dhcp_start1, ifp);
4099 void
4100 dhcp_abort(struct interface *ifp)
4102 struct dhcp_state *state;
4104 state = D_STATE(ifp);
4105 #ifdef ARPING
4106 if (state != NULL)
4107 state->arping_index = -1;
4108 #endif
4110 eloop_timeout_delete(ifp->ctx->eloop, dhcp_start1, ifp);
4112 if (state != NULL && state->added) {
4113 rt_build(ifp->ctx, AF_INET);
4114 #ifdef ARP
4115 if (ifp->options->options & DHCPCD_ARP)
4116 arp_announceaddr(ifp->ctx, &state->addr->addr);
4117 #endif
4121 struct ipv4_addr *
4122 dhcp_handleifa(int cmd, struct ipv4_addr *ia, pid_t pid)
4124 struct interface *ifp;
4125 struct dhcp_state *state;
4126 struct if_options *ifo;
4127 uint8_t i;
4129 ifp = ia->iface;
4130 state = D_STATE(ifp);
4131 if (state == NULL || state->state == DHS_NONE)
4132 return ia;
4134 if (cmd == RTM_DELADDR) {
4135 if (state->addr == ia) {
4136 loginfox("%s: pid %d deleted IP address %s",
4137 ifp->name, pid, ia->saddr);
4138 dhcp_close(ifp);
4139 state->addr = NULL;
4140 /* Don't clear the added state as we need
4141 * to drop the lease. */
4142 dhcp_drop(ifp, "EXPIRE");
4143 dhcp_start1(ifp);
4144 return ia;
4148 if (cmd != RTM_NEWADDR)
4149 return ia;
4151 #ifdef IN_IFF_NOTUSEABLE
4152 if (!(ia->addr_flags & IN_IFF_NOTUSEABLE))
4153 dhcp_finish_dad(ifp, &ia->addr);
4154 else if (ia->addr_flags & IN_IFF_DUPLICATED)
4155 return dhcp_addr_duplicated(ifp, &ia->addr) ? NULL : ia;
4156 #endif
4158 ifo = ifp->options;
4159 if (ifo->options & DHCPCD_INFORM) {
4160 if (state->state != DHS_INFORM)
4161 dhcp_inform(ifp);
4162 return ia;
4165 if (!(ifo->options & DHCPCD_STATIC))
4166 return ia;
4167 if (ifo->req_addr.s_addr != INADDR_ANY)
4168 return ia;
4170 free(state->old);
4171 state->old = state->new;
4172 state->new_len = dhcp_message_new(&state->new, &ia->addr, &ia->mask);
4173 if (state->new == NULL)
4174 return ia;
4175 if (ifp->flags & IFF_POINTOPOINT) {
4176 for (i = 1; i < 255; i++)
4177 if (i != DHO_ROUTER && has_option_mask(ifo->dstmask,i))
4178 dhcp_message_add_addr(state->new, i, ia->brd);
4180 state->reason = "STATIC";
4181 rt_build(ifp->ctx, AF_INET);
4182 script_runreason(ifp, state->reason);
4183 if (ifo->options & DHCPCD_INFORM) {
4184 state->state = DHS_INFORM;
4185 dhcp_new_xid(ifp);
4186 state->lease.server.s_addr = INADDR_ANY;
4187 state->addr = ia;
4188 dhcp_inform(ifp);
4191 return ia;
4194 #ifndef SMALL
4196 dhcp_dump(struct interface *ifp)
4198 struct dhcp_state *state;
4200 ifp->if_data[IF_DATA_DHCP] = state = calloc(1, sizeof(*state));
4201 if (state == NULL) {
4202 logerr(__func__);
4203 return -1;
4205 state->new_len = read_lease(ifp, &state->new);
4206 if (state->new == NULL) {
4207 logerr("read_lease");
4208 return -1;
4210 state->reason = "DUMP";
4211 return script_runreason(ifp, state->reason);
4213 #endif