xref: /dragonfly/contrib/dhcpcd/src/dhcp.c (revision 54175cef)
1 /* SPDX-License-Identifier: BSD-2-Clause */
2 /*
3  * dhcpcd - DHCP client daemon
4  * Copyright (c) 2006-2023 Roy Marples <roy@marples.name>
5  * All rights reserved
6 
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 
29 #include <sys/param.h>
30 #include <sys/socket.h>
31 
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
42 
43 #ifdef AF_LINK
44 #  include <net/if_dl.h>
45 #endif
46 
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>
59 
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"
77 
78 #define DAD		"Duplicate address detected"
79 #define DHCP_MIN_LEASE	20
80 
81 #define IPV4A		ADDRIPV4 | ARRAY
82 #define IPV4R		ADDRIPV4 | REQUEST
83 
84 /* We should define a maximum for the NAK exponential backoff */
85 #define NAKOFF_MAX              60
86 
87 #ifndef IPDEFTTL
88 #define IPDEFTTL 64 /* RFC1340 */
89 #endif
90 
91 /* Support older systems with different defines */
92 #if !defined(IP_RECVPKTINFO) && defined(IP_PKTINFO)
93 #define IP_RECVPKTINFO IP_PKTINFO
94 #endif
95 
96 /* Assert the correct structure size for on wire */
97 __CTASSERT(sizeof(struct ip)		== 20);
98 __CTASSERT(sizeof(struct udphdr)	== 8);
99 __CTASSERT(sizeof(struct bootp)		== 300);
100 
101 struct dhcp_op {
102 	uint8_t value;
103 	const char *name;
104 };
105 
106 static const struct dhcp_op dhcp_ops[] = {
107 	{ DHCP_DISCOVER,   "DISCOVER" },
108 	{ DHCP_OFFER,      "OFFER" },
109 	{ DHCP_REQUEST,    "REQUEST" },
110 	{ DHCP_DECLINE,    "DECLINE" },
111 	{ DHCP_ACK,        "ACK" },
112 	{ DHCP_NAK,        "NAK" },
113 	{ DHCP_RELEASE,    "RELEASE" },
114 	{ DHCP_INFORM,     "INFORM" },
115 	{ DHCP_FORCERENEW, "FORCERENEW"},
116 	{ 0, NULL }
117 };
118 
119 static const char * const dhcp_params[] = {
120 	"ip_address",
121 	"subnet_cidr",
122 	"network_number",
123 	"filename",
124 	"server_name",
125 	NULL
126 };
127 
128 static int dhcp_openbpf(struct interface *);
129 static void dhcp_start1(void *);
130 #if defined(ARP) && (!defined(KERNEL_RFC5227) || defined(ARPING))
131 static void dhcp_arp_found(struct arp_state *, const struct arp_msg *);
132 #endif
133 static void dhcp_handledhcp(struct interface *, struct bootp *, size_t,
134     const struct in_addr *);
135 static void dhcp_handleifudp(void *, unsigned short);
136 static int dhcp_initstate(struct interface *);
137 
138 void
dhcp_printoptions(const struct dhcpcd_ctx * ctx,const struct dhcp_opt * opts,size_t opts_len)139 dhcp_printoptions(const struct dhcpcd_ctx *ctx,
140     const struct dhcp_opt *opts, size_t opts_len)
141 {
142 	const char * const *p;
143 	size_t i, j;
144 	const struct dhcp_opt *opt, *opt2;
145 	int cols;
146 
147 	for (p = dhcp_params; *p; p++)
148 		printf("    %s\n", *p);
149 
150 	for (i = 0, opt = ctx->dhcp_opts; i < ctx->dhcp_opts_len; i++, opt++) {
151 		for (j = 0, opt2 = opts; j < opts_len; j++, opt2++)
152 			if (opt->option == opt2->option)
153 				break;
154 		if (j == opts_len) {
155 			cols = printf("%03d %s", opt->option, opt->var);
156 			dhcp_print_option_encoding(opt, cols);
157 		}
158 	}
159 	for (i = 0, opt = opts; i < opts_len; i++, opt++) {
160 		cols = printf("%03d %s", opt->option, opt->var);
161 		dhcp_print_option_encoding(opt, cols);
162 	}
163 }
164 
165 static const uint8_t *
get_option(struct dhcpcd_ctx * ctx,const struct bootp * bootp,size_t bootp_len,unsigned int opt,size_t * opt_len)166 get_option(struct dhcpcd_ctx *ctx,
167     const struct bootp *bootp, size_t bootp_len,
168     unsigned int opt, size_t *opt_len)
169 {
170 	const uint8_t *p, *e;
171 	uint8_t l, o, ol, overl, *bp;
172 	const uint8_t *op;
173 	size_t bl;
174 
175 	if (bootp == NULL || bootp_len < DHCP_MIN_LEN) {
176 		errno = EINVAL;
177 		return NULL;
178 	}
179 
180 	/* Check we have the magic cookie */
181 	if (!IS_DHCP(bootp)) {
182 		errno = ENOTSUP;
183 		return NULL;
184 	}
185 
186 	p = bootp->vend + 4; /* options after the 4 byte cookie */
187 	e = (const uint8_t *)bootp + bootp_len;
188 	ol = o = overl = 0;
189 	bp = NULL;
190 	op = NULL;
191 	bl = 0;
192 	while (p < e) {
193 		o = *p++;
194 		switch (o) {
195 		case DHO_PAD:
196 			/* No length to read */
197 			continue;
198 		case DHO_END:
199 			if (overl & 1) {
200 				/* bit 1 set means parse boot file */
201 				overl = (uint8_t)(overl & ~1);
202 				p = bootp->file;
203 				e = p + sizeof(bootp->file);
204 			} else if (overl & 2) {
205 				/* bit 2 set means parse server name */
206 				overl = (uint8_t)(overl & ~2);
207 				p = bootp->sname;
208 				e = p + sizeof(bootp->sname);
209 			} else
210 				goto exit;
211 			/* No length to read */
212 			continue;
213 		}
214 
215 		/* Check we can read the length */
216 		if (p == e) {
217 			errno = EINVAL;
218 			return NULL;
219 		}
220 		l = *p++;
221 
222 		/* Check we can read the option data, if present */
223 		if (p + l > e) {
224 			errno = EINVAL;
225 			return NULL;
226 		}
227 
228 		if (o == DHO_OPTSOVERLOADED) {
229 			/* Ensure we only get this option once by setting
230 			 * the last bit as well as the value.
231 			 * This is valid because only the first two bits
232 			 * actually mean anything in RFC2132 Section 9.3 */
233 			if (l == 1 && !overl)
234 				overl = 0x80 | p[0];
235 		}
236 
237 		if (o == opt) {
238 			if (op) {
239 				/* We must concatonate the options. */
240 				if (bl + l > ctx->opt_buffer_len) {
241 					size_t pos;
242 					uint8_t *nb;
243 
244 					if (bp)
245 						pos = (size_t)
246 						    (bp - ctx->opt_buffer);
247 					else
248 						pos = 0;
249 					nb = realloc(ctx->opt_buffer, bl + l);
250 					if (nb == NULL)
251 						return NULL;
252 					ctx->opt_buffer = nb;
253 					ctx->opt_buffer_len = bl + l;
254 					bp = ctx->opt_buffer + pos;
255 				}
256 				if (bp == NULL)
257 					bp = ctx->opt_buffer;
258 				memcpy(bp, op, ol);
259 				bp += ol;
260 			}
261 			ol = l;
262 			op = p;
263 			bl += ol;
264 		}
265 		p += l;
266 	}
267 
268 exit:
269 	if (opt_len)
270 		*opt_len = bl;
271 	if (bp) {
272 		memcpy(bp, op, ol);
273 		return (const uint8_t *)ctx->opt_buffer;
274 	}
275 	if (op)
276 		return op;
277 	errno = ENOENT;
278 	return NULL;
279 }
280 
281 static int
get_option_addr(struct dhcpcd_ctx * ctx,struct in_addr * a,const struct bootp * bootp,size_t bootp_len,uint8_t option)282 get_option_addr(struct dhcpcd_ctx *ctx,
283     struct in_addr *a, const struct bootp *bootp, size_t bootp_len,
284     uint8_t option)
285 {
286 	const uint8_t *p;
287 	size_t len;
288 
289 	p = get_option(ctx, bootp, bootp_len, option, &len);
290 	if (!p || len < (ssize_t)sizeof(a->s_addr))
291 		return -1;
292 	memcpy(&a->s_addr, p, sizeof(a->s_addr));
293 	return 0;
294 }
295 
296 static int
get_option_uint32(struct dhcpcd_ctx * ctx,uint32_t * i,const struct bootp * bootp,size_t bootp_len,uint8_t option)297 get_option_uint32(struct dhcpcd_ctx *ctx,
298     uint32_t *i, const struct bootp *bootp, size_t bootp_len, uint8_t option)
299 {
300 	const uint8_t *p;
301 	size_t len;
302 	uint32_t d;
303 
304 	p = get_option(ctx, bootp, bootp_len, option, &len);
305 	if (!p || len < (ssize_t)sizeof(d))
306 		return -1;
307 	memcpy(&d, p, sizeof(d));
308 	if (i)
309 		*i = ntohl(d);
310 	return 0;
311 }
312 
313 static int
get_option_uint16(struct dhcpcd_ctx * ctx,uint16_t * i,const struct bootp * bootp,size_t bootp_len,uint8_t option)314 get_option_uint16(struct dhcpcd_ctx *ctx,
315     uint16_t *i, const struct bootp *bootp, size_t bootp_len, uint8_t option)
316 {
317 	const uint8_t *p;
318 	size_t len;
319 	uint16_t d;
320 
321 	p = get_option(ctx, bootp, bootp_len, option, &len);
322 	if (!p || len < (ssize_t)sizeof(d))
323 		return -1;
324 	memcpy(&d, p, sizeof(d));
325 	if (i)
326 		*i = ntohs(d);
327 	return 0;
328 }
329 
330 static int
get_option_uint8(struct dhcpcd_ctx * ctx,uint8_t * i,const struct bootp * bootp,size_t bootp_len,uint8_t option)331 get_option_uint8(struct dhcpcd_ctx *ctx,
332     uint8_t *i, const struct bootp *bootp, size_t bootp_len, uint8_t option)
333 {
334 	const uint8_t *p;
335 	size_t len;
336 
337 	p = get_option(ctx, bootp, bootp_len, option, &len);
338 	if (!p || len < (ssize_t)sizeof(*p))
339 		return -1;
340 	if (i)
341 		*i = *(p);
342 	return 0;
343 }
344 
345 ssize_t
print_rfc3442(FILE * fp,const uint8_t * data,size_t data_len)346 print_rfc3442(FILE *fp, const uint8_t *data, size_t data_len)
347 {
348 	const uint8_t *p = data, *e;
349 	size_t ocets;
350 	uint8_t cidr;
351 	struct in_addr addr;
352 
353 	/* Minimum is 5 -first is CIDR and a router length of 4 */
354 	if (data_len < 5) {
355 		errno = EINVAL;
356 		return -1;
357 	}
358 
359 	e = p + data_len;
360 	while (p < e) {
361 		if (p != data) {
362 			if (fputc(' ', fp) == EOF)
363 				return -1;
364 		}
365 		cidr = *p++;
366 		if (cidr > 32) {
367 			errno = EINVAL;
368 			return -1;
369 		}
370 		ocets = (size_t)(cidr + 7) / NBBY;
371 		if (p + 4 + ocets > e) {
372 			errno = ERANGE;
373 			return -1;
374 		}
375 		/* If we have ocets then we have a destination and netmask */
376 		addr.s_addr = 0;
377 		if (ocets > 0) {
378 			memcpy(&addr.s_addr, p, ocets);
379 			p += ocets;
380 		}
381 		if (fprintf(fp, "%s/%d", inet_ntoa(addr), cidr) == -1)
382 			return -1;
383 
384 		/* Finally, snag the router */
385 		memcpy(&addr.s_addr, p, 4);
386 		p += 4;
387 		if (fprintf(fp, " %s", inet_ntoa(addr)) == -1)
388 			return -1;
389 	}
390 
391 	if (fputc('\0', fp) == EOF)
392 		return -1;
393 	return 1;
394 }
395 
396 static int
decode_rfc3442_rt(rb_tree_t * routes,struct interface * ifp,const uint8_t * data,size_t dl)397 decode_rfc3442_rt(rb_tree_t *routes, struct interface *ifp,
398     const uint8_t *data, size_t dl)
399 {
400 	const uint8_t *p = data;
401 	const uint8_t *e;
402 	uint8_t cidr;
403 	size_t ocets;
404 	struct rt *rt = NULL;
405 	struct in_addr dest, netmask, gateway;
406 	int n;
407 
408 	/* Minimum is 5 -first is CIDR and a router length of 4 */
409 	if (dl < 5) {
410 		errno = EINVAL;
411 		return -1;
412 	}
413 
414 	n = 0;
415 	e = p + dl;
416 	while (p < e) {
417 		cidr = *p++;
418 		if (cidr > 32) {
419 			errno = EINVAL;
420 			return -1;
421 		}
422 
423 		ocets = (size_t)(cidr + 7) / NBBY;
424 		if (p + 4 + ocets > e) {
425 			errno = ERANGE;
426 			return -1;
427 		}
428 
429 		if ((rt = rt_new(ifp)) == NULL)
430 			return -1;
431 
432 		/* If we have ocets then we have a destination and netmask */
433 		dest.s_addr = 0;
434 		if (ocets > 0) {
435 			memcpy(&dest.s_addr, p, ocets);
436 			p += ocets;
437 			netmask.s_addr = htonl(~0U << (32 - cidr));
438 		} else
439 			netmask.s_addr = 0;
440 
441 		/* Finally, snag the router */
442 		memcpy(&gateway.s_addr, p, 4);
443 		p += 4;
444 
445 		if (netmask.s_addr == INADDR_BROADCAST)
446 			rt->rt_flags = RTF_HOST;
447 
448 		sa_in_init(&rt->rt_dest, &dest);
449 		sa_in_init(&rt->rt_netmask, &netmask);
450 		sa_in_init(&rt->rt_gateway, &gateway);
451 		if (rt_proto_add(routes, rt))
452 			n = 1;
453 	}
454 	return n;
455 }
456 
457 ssize_t
print_rfc3361(FILE * fp,const uint8_t * data,size_t dl)458 print_rfc3361(FILE *fp, const uint8_t *data, size_t dl)
459 {
460 	uint8_t enc;
461 	char sip[NS_MAXDNAME];
462 	struct in_addr addr;
463 
464 	if (dl < 2) {
465 		errno = EINVAL;
466 		return 0;
467 	}
468 
469 	enc = *data++;
470 	dl--;
471 	switch (enc) {
472 	case 0:
473 		if (decode_rfc1035(sip, sizeof(sip), data, dl) == -1)
474 			return -1;
475 		if (efprintf(fp, "%s", sip) == -1)
476 			return -1;
477 		break;
478 	case 1:
479 		if (dl % 4 != 0) {
480 			errno = EINVAL;
481 			break;
482 		}
483 		addr.s_addr = INADDR_BROADCAST;
484 		for (;
485 		    dl != 0;
486 		    data += sizeof(addr.s_addr), dl -= sizeof(addr.s_addr))
487 		{
488 			memcpy(&addr.s_addr, data, sizeof(addr.s_addr));
489 			if (fprintf(fp, "%s", inet_ntoa(addr)) == -1)
490 				return -1;
491 			if (dl != sizeof(addr.s_addr)) {
492 				if (fputc(' ', fp) == EOF)
493 					return -1;
494 			}
495 		}
496 		if (fputc('\0', fp) == EOF)
497 			return -1;
498 		break;
499 	default:
500 		errno = EINVAL;
501 		return 0;
502 	}
503 
504 	return 1;
505 }
506 
507 static char *
get_option_string(struct dhcpcd_ctx * ctx,const struct bootp * bootp,size_t bootp_len,uint8_t option)508 get_option_string(struct dhcpcd_ctx *ctx,
509     const struct bootp *bootp, size_t bootp_len, uint8_t option)
510 {
511 	size_t len;
512 	const uint8_t *p;
513 	char *s;
514 
515 	p = get_option(ctx, bootp, bootp_len, option, &len);
516 	if (!p || len == 0 || *p == '\0')
517 		return NULL;
518 
519 	s = malloc(sizeof(char) * (len + 1));
520 	if (s) {
521 		memcpy(s, p, len);
522 		s[len] = '\0';
523 	}
524 	return s;
525 }
526 
527 /* This calculates the netmask that we should use for static routes.
528  * This IS different from the calculation used to calculate the netmask
529  * for an interface address. */
530 static uint32_t
route_netmask(uint32_t ip_in)531 route_netmask(uint32_t ip_in)
532 {
533 	/* used to be unsigned long - check if error */
534 	uint32_t p = ntohl(ip_in);
535 	uint32_t t;
536 
537 	if (IN_CLASSA(p))
538 		t = ~IN_CLASSA_NET;
539 	else {
540 		if (IN_CLASSB(p))
541 			t = ~IN_CLASSB_NET;
542 		else {
543 			if (IN_CLASSC(p))
544 				t = ~IN_CLASSC_NET;
545 			else
546 				t = 0;
547 		}
548 	}
549 
550 	while (t & p)
551 		t >>= 1;
552 
553 	return (htonl(~t));
554 }
555 
556 /* We need to obey routing options.
557  * If we have a CSR then we only use that.
558  * Otherwise we add static routes and then routers. */
559 static int
get_option_routes(rb_tree_t * routes,struct interface * ifp,const struct bootp * bootp,size_t bootp_len)560 get_option_routes(rb_tree_t *routes, struct interface *ifp,
561     const struct bootp *bootp, size_t bootp_len)
562 {
563 	struct if_options *ifo = ifp->options;
564 	const uint8_t *p;
565 	const uint8_t *e;
566 	struct rt *rt = NULL;
567 	struct in_addr dest, netmask, gateway;
568 	size_t len;
569 	const char *csr = "";
570 	int n;
571 
572 	/* If we have CSR's then we MUST use these only */
573 	if (!has_option_mask(ifo->nomask, DHO_CSR))
574 		p = get_option(ifp->ctx, bootp, bootp_len, DHO_CSR, &len);
575 	else
576 		p = NULL;
577 	/* Check for crappy MS option */
578 	if (!p && !has_option_mask(ifo->nomask, DHO_MSCSR)) {
579 		p = get_option(ifp->ctx, bootp, bootp_len, DHO_MSCSR, &len);
580 		if (p)
581 			csr = "MS ";
582 	}
583 	if (p && (n = decode_rfc3442_rt(routes, ifp, p, len)) != -1) {
584 		const struct dhcp_state *state;
585 
586 		state = D_CSTATE(ifp);
587 		if (!(ifo->options & DHCPCD_CSR_WARNED) &&
588 		    !(state->added & STATE_FAKE))
589 		{
590 			logdebugx("%s: using %sClassless Static Routes",
591 			    ifp->name, csr);
592 			ifo->options |= DHCPCD_CSR_WARNED;
593 		}
594 		return n;
595 	}
596 
597 	n = 0;
598 	/* OK, get our static routes first. */
599 	if (!has_option_mask(ifo->nomask, DHO_STATICROUTE))
600 		p = get_option(ifp->ctx, bootp, bootp_len,
601 		    DHO_STATICROUTE, &len);
602 	else
603 		p = NULL;
604 	/* RFC 2131 Section 5.8 states length MUST be in multiples of 8 */
605 	if (p && len % 8 == 0) {
606 		e = p + len;
607 		while (p < e) {
608 			memcpy(&dest.s_addr, p, sizeof(dest.s_addr));
609 			p += 4;
610 			memcpy(&gateway.s_addr, p, sizeof(gateway.s_addr));
611 			p += 4;
612 			/* RFC 2131 Section 5.8 states default route is
613 			 * illegal */
614 			if (gateway.s_addr == INADDR_ANY)
615 				continue;
616 			if ((rt = rt_new(ifp)) == NULL)
617 				return -1;
618 
619 			/* A on-link host route is normally set by having the
620 			 * gateway match the destination or assigned address */
621 			if (gateway.s_addr == dest.s_addr ||
622 			     (gateway.s_addr == bootp->yiaddr ||
623 			      gateway.s_addr == bootp->ciaddr))
624 			{
625 				gateway.s_addr = INADDR_ANY;
626 				netmask.s_addr = INADDR_BROADCAST;
627 			} else
628 				netmask.s_addr = route_netmask(dest.s_addr);
629 			if (netmask.s_addr == INADDR_BROADCAST)
630 				rt->rt_flags = RTF_HOST;
631 
632 			sa_in_init(&rt->rt_dest, &dest);
633 			sa_in_init(&rt->rt_netmask, &netmask);
634 			sa_in_init(&rt->rt_gateway, &gateway);
635 			if (rt_proto_add(routes, rt))
636 				n++;
637 		}
638 	}
639 
640 	/* Now grab our routers */
641 	if (!has_option_mask(ifo->nomask, DHO_ROUTER))
642 		p = get_option(ifp->ctx, bootp, bootp_len, DHO_ROUTER, &len);
643 	else
644 		p = NULL;
645 	if (p && len % 4 == 0) {
646 		e = p + len;
647 		dest.s_addr = INADDR_ANY;
648 		netmask.s_addr = INADDR_ANY;
649 		while (p < e) {
650 			if ((rt = rt_new(ifp)) == NULL)
651 				return -1;
652 			memcpy(&gateway.s_addr, p, sizeof(gateway.s_addr));
653 			p += 4;
654 			sa_in_init(&rt->rt_dest, &dest);
655 			sa_in_init(&rt->rt_netmask, &netmask);
656 			sa_in_init(&rt->rt_gateway, &gateway);
657 			if (rt_proto_add(routes, rt))
658 				n++;
659 		}
660 	}
661 
662 	return n;
663 }
664 
665 uint16_t
dhcp_get_mtu(const struct interface * ifp)666 dhcp_get_mtu(const struct interface *ifp)
667 {
668 	const struct dhcp_state *state;
669 	uint16_t mtu;
670 
671 	if (ifp->options->mtu)
672 		return (uint16_t)ifp->options->mtu;
673 	mtu = 0; /* bogus gcc warning */
674 	if ((state = D_CSTATE(ifp)) == NULL ||
675 	    has_option_mask(ifp->options->nomask, DHO_MTU) ||
676 	    get_option_uint16(ifp->ctx, &mtu,
677 			      state->new, state->new_len, DHO_MTU) == -1)
678 		return 0;
679 	return mtu;
680 }
681 
682 /* Grab our routers from the DHCP message and apply any MTU value
683  * the message contains */
684 int
dhcp_get_routes(rb_tree_t * routes,struct interface * ifp)685 dhcp_get_routes(rb_tree_t *routes, struct interface *ifp)
686 {
687 	const struct dhcp_state *state;
688 
689 	if ((state = D_CSTATE(ifp)) == NULL || !(state->added & STATE_ADDED))
690 		return 0;
691 	return get_option_routes(routes, ifp, state->new, state->new_len);
692 }
693 
694 /* Assumes DHCP options */
695 static int
dhcp_message_add_addr(struct bootp * bootp,uint8_t type,struct in_addr addr)696 dhcp_message_add_addr(struct bootp *bootp,
697     uint8_t type, struct in_addr addr)
698 {
699 	uint8_t *p;
700 	size_t len;
701 
702 	p = bootp->vend;
703 	while (*p != DHO_END) {
704 		p++;
705 		p += *p + 1;
706 	}
707 
708 	len = (size_t)(p - bootp->vend);
709 	if (len + 6 > sizeof(bootp->vend)) {
710 		errno = ENOMEM;
711 		return -1;
712 	}
713 
714 	*p++ = type;
715 	*p++ = 4;
716 	memcpy(p, &addr.s_addr, 4);
717 	p += 4;
718 	*p = DHO_END;
719 	return 0;
720 }
721 
722 static ssize_t
make_message(struct bootp ** bootpm,const struct interface * ifp,uint8_t type)723 make_message(struct bootp **bootpm, const struct interface *ifp, uint8_t type)
724 {
725 	struct bootp *bootp;
726 	uint8_t *lp, *p, *e;
727 	uint8_t *n_params = NULL;
728 	uint32_t ul;
729 	uint16_t sz;
730 	size_t len, i;
731 	const struct dhcp_opt *opt;
732 	struct if_options *ifo = ifp->options;
733 	const struct dhcp_state *state = D_CSTATE(ifp);
734 	const struct dhcp_lease *lease = &state->lease;
735 	char hbuf[HOSTNAME_MAX_LEN + 1];
736 	const char *hostname;
737 	const struct vivco *vivco;
738 	int mtu;
739 #ifdef AUTH
740 	uint8_t *auth, auth_len;
741 #endif
742 
743 	if ((mtu = if_getmtu(ifp)) == -1)
744 		logerr("%s: if_getmtu", ifp->name);
745 	else if (mtu < MTU_MIN) {
746 		if (if_setmtu(ifp, MTU_MIN) == -1)
747 			logerr("%s: if_setmtu", ifp->name);
748 		mtu = MTU_MIN;
749 	}
750 
751 	if (ifo->options & DHCPCD_BOOTP)
752 		bootp = calloc(1, sizeof (*bootp));
753 	else
754 		/* Make the maximal message we could send */
755 		bootp = calloc(1, (size_t)(mtu - IP_UDP_SIZE));
756 
757 	if (bootp == NULL)
758 		return -1;
759 	*bootpm = bootp;
760 
761 	if (state->addr != NULL &&
762 	    (type == DHCP_INFORM || type == DHCP_RELEASE ||
763 	    (type == DHCP_REQUEST &&
764 	    state->addr->mask.s_addr == lease->mask.s_addr &&
765 	    (state->new == NULL || IS_DHCP(state->new)) &&
766 	    !(state->added & (STATE_FAKE | STATE_EXPIRED)))))
767 		bootp->ciaddr = state->addr->addr.s_addr;
768 
769 	bootp->op = BOOTREQUEST;
770 	bootp->htype = (uint8_t)ifp->hwtype;
771 	if (ifp->hwlen != 0 && ifp->hwlen <= sizeof(bootp->chaddr)) {
772 		bootp->hlen = (uint8_t)ifp->hwlen;
773 		memcpy(&bootp->chaddr, &ifp->hwaddr, ifp->hwlen);
774 	}
775 
776 	if (ifo->options & DHCPCD_BROADCAST &&
777 	    bootp->ciaddr == 0 &&
778 	    type != DHCP_DECLINE &&
779 	    type != DHCP_RELEASE)
780 		bootp->flags = htons(BROADCAST_FLAG);
781 
782 	if (type != DHCP_DECLINE && type != DHCP_RELEASE) {
783 		struct timespec tv;
784 		unsigned long long secs;
785 
786 		clock_gettime(CLOCK_MONOTONIC, &tv);
787 		secs = eloop_timespec_diff(&tv, &state->started, NULL);
788 		if (secs > UINT16_MAX)
789 			bootp->secs = htons((uint16_t)UINT16_MAX);
790 		else
791 			bootp->secs = htons((uint16_t)secs);
792 	}
793 
794 	bootp->xid = htonl(state->xid);
795 
796 	if (ifo->options & DHCPCD_BOOTP)
797 		return sizeof(*bootp);
798 
799 	p = bootp->vend;
800 	e = (uint8_t *)bootp + (mtu - IP_UDP_SIZE) - 1; /* -1 for DHO_END */
801 
802 	ul = htonl(MAGIC_COOKIE);
803 	memcpy(p, &ul, sizeof(ul));
804 	p += sizeof(ul);
805 
806 #define AREA_LEFT	(size_t)(e - p)
807 #define AREA_FIT(s)	if ((s) > AREA_LEFT) goto toobig
808 #define AREA_CHECK(s)	if ((s) + 2UL > AREA_LEFT) goto toobig
809 #define PUT_ADDR(o, a)	do {		\
810 	AREA_CHECK(4);			\
811 	*p++ = (o);			\
812 	*p++ = 4;			\
813 	memcpy(p, &(a)->s_addr, 4);	\
814 	p += 4;				\
815 } while (0 /* CONSTCOND */)
816 
817 	/* Options are listed in numerical order as per RFC 7844 Section 3.1
818 	 * XXX: They should be randomised. */
819 
820 	bool putip = false;
821 	if (lease->addr.s_addr && lease->cookie == htonl(MAGIC_COOKIE)) {
822 		if (type == DHCP_DECLINE ||
823 		    (type == DHCP_REQUEST &&
824 		    (state->addr == NULL ||
825 		    state->added & (STATE_FAKE | STATE_EXPIRED) ||
826 		    lease->addr.s_addr != state->addr->addr.s_addr)))
827 		{
828 			putip = true;
829 			PUT_ADDR(DHO_IPADDRESS, &lease->addr);
830 		}
831 	}
832 
833 	AREA_CHECK(3);
834 	*p++ = DHO_MESSAGETYPE;
835 	*p++ = 1;
836 	*p++ = type;
837 
838 	if (lease->addr.s_addr && lease->cookie == htonl(MAGIC_COOKIE)) {
839 		if (type == DHCP_RELEASE || putip) {
840 			if (lease->server.s_addr)
841 				PUT_ADDR(DHO_SERVERID, &lease->server);
842 		}
843 	}
844 
845 	if (type == DHCP_DECLINE) {
846 		len = strlen(DAD);
847 		if (len > AREA_LEFT) {
848 			*p++ = DHO_MESSAGE;
849 			*p++ = (uint8_t)len;
850 			memcpy(p, DAD, len);
851 			p += len;
852 		}
853 	}
854 
855 #define	DHCP_DIR(type) ((type) == DHCP_DISCOVER || (type) == DHCP_INFORM || \
856     (type) == DHCP_REQUEST)
857 
858 	if (DHCP_DIR(type)) {
859 		/* vendor is already encoded correctly, so just add it */
860 		if (ifo->vendor[0]) {
861 			AREA_CHECK(ifo->vendor[0]);
862 			*p++ = DHO_VENDOR;
863 			memcpy(p, ifo->vendor, (size_t)ifo->vendor[0] + 1);
864 			p += ifo->vendor[0] + 1;
865 		}
866 	}
867 
868 	if (type == DHCP_DISCOVER && ifo->options & DHCPCD_REQUEST)
869 		PUT_ADDR(DHO_IPADDRESS, &ifo->req_addr);
870 
871 	if (DHCP_DIR(type)) {
872 		if (type != DHCP_INFORM) {
873 			if (ifo->leasetime != 0) {
874 				AREA_CHECK(4);
875 				*p++ = DHO_LEASETIME;
876 				*p++ = 4;
877 				ul = htonl(ifo->leasetime);
878 				memcpy(p, &ul, 4);
879 				p += 4;
880 			}
881 		}
882 
883 		AREA_CHECK(0);
884 		*p++ = DHO_PARAMETERREQUESTLIST;
885 		n_params = p;
886 		*p++ = 0;
887 		for (i = 0, opt = ifp->ctx->dhcp_opts;
888 		    i < ifp->ctx->dhcp_opts_len;
889 		    i++, opt++)
890 		{
891 			if (!DHC_REQOPT(opt, ifo->requestmask, ifo->nomask))
892 				continue;
893 			if (type == DHCP_INFORM &&
894 			    (opt->option == DHO_RENEWALTIME ||
895 				opt->option == DHO_REBINDTIME))
896 				continue;
897 			AREA_FIT(1);
898 			*p++ = (uint8_t)opt->option;
899 		}
900 		for (i = 0, opt = ifo->dhcp_override;
901 		    i < ifo->dhcp_override_len;
902 		    i++, opt++)
903 		{
904 			/* Check if added above */
905 			for (lp = n_params + 1; lp < p; lp++)
906 				if (*lp == (uint8_t)opt->option)
907 					break;
908 			if (lp < p)
909 				continue;
910 			if (!DHC_REQOPT(opt, ifo->requestmask, ifo->nomask))
911 				continue;
912 			if (type == DHCP_INFORM &&
913 			    (opt->option == DHO_RENEWALTIME ||
914 				opt->option == DHO_REBINDTIME))
915 				continue;
916 			AREA_FIT(1);
917 			*p++ = (uint8_t)opt->option;
918 		}
919 		*n_params = (uint8_t)(p - n_params - 1);
920 
921 		if (mtu != -1 &&
922 		    !(has_option_mask(ifo->nomask, DHO_MAXMESSAGESIZE)))
923 		{
924 			AREA_CHECK(2);
925 			*p++ = DHO_MAXMESSAGESIZE;
926 			*p++ = 2;
927 			sz = htons((uint16_t)(mtu - IP_UDP_SIZE));
928 			memcpy(p, &sz, 2);
929 			p += 2;
930 		}
931 
932 		if (ifo->userclass[0] &&
933 		    !has_option_mask(ifo->nomask, DHO_USERCLASS))
934 		{
935 			AREA_CHECK(ifo->userclass[0]);
936 			*p++ = DHO_USERCLASS;
937 			memcpy(p, ifo->userclass,
938 			    (size_t)ifo->userclass[0] + 1);
939 			p += ifo->userclass[0] + 1;
940 		}
941 	}
942 
943 	if (state->clientid) {
944 		AREA_CHECK(state->clientid[0]);
945 		*p++ = DHO_CLIENTID;
946 		memcpy(p, state->clientid, (size_t)state->clientid[0] + 1);
947 		p += state->clientid[0] + 1;
948 	}
949 
950 	if (DHCP_DIR(type) &&
951 	    !has_option_mask(ifo->nomask, DHO_VENDORCLASSID) &&
952 	    ifo->vendorclassid[0])
953 	{
954 		AREA_CHECK(ifo->vendorclassid[0]);
955 		*p++ = DHO_VENDORCLASSID;
956 		memcpy(p, ifo->vendorclassid, (size_t)ifo->vendorclassid[0]+1);
957 		p += ifo->vendorclassid[0] + 1;
958 	}
959 
960 	if (type == DHCP_DISCOVER &&
961 	    !(ifp->ctx->options & DHCPCD_TEST) &&
962 	    DHC_REQ(ifo->requestmask, ifo->nomask, DHO_RAPIDCOMMIT))
963 	{
964 		/* RFC 4039 Section 3 */
965 		AREA_CHECK(0);
966 		*p++ = DHO_RAPIDCOMMIT;
967 		*p++ = 0;
968 	}
969 
970 	if (DHCP_DIR(type)) {
971 		hostname = dhcp_get_hostname(hbuf, sizeof(hbuf), ifo);
972 
973 		/*
974 		 * RFC4702 3.1 States that if we send the Client FQDN option
975 		 * then we MUST NOT also send the Host Name option.
976 		 * Technically we could, but that is not RFC conformant and
977 		 * also seems to break some DHCP server implemetations such as
978 		 * Windows. On the other hand, ISC dhcpd is just as non RFC
979 		 * conformant by not accepting a partially qualified FQDN.
980 		 */
981 		if (ifo->fqdn != FQDN_DISABLE) {
982 			/* IETF DHC-FQDN option (81), RFC4702 */
983 			i = 3;
984 			if (hostname)
985 				i += encode_rfc1035(hostname, NULL);
986 			AREA_CHECK(i);
987 			*p++ = DHO_FQDN;
988 			*p++ = (uint8_t)i;
989 			/*
990 			 * Flags: 0000NEOS
991 			 * S: 1 => Client requests Server to update
992 			 *         a RR in DNS as well as PTR
993 			 * O: 1 => Server indicates to client that
994 			 *         DNS has been updated
995 			 * E: 1 => Name data is DNS format
996 			 * N: 1 => Client requests Server to not
997 			 *         update DNS
998 			 */
999 			if (hostname)
1000 				*p++ = (uint8_t)((ifo->fqdn & 0x09) | 0x04);
1001 			else
1002 				*p++ = (FQDN_NONE & 0x09) | 0x04;
1003 			*p++ = 0; /* from server for PTR RR */
1004 			*p++ = 0; /* from server for A RR if S=1 */
1005 			if (hostname) {
1006 				i = encode_rfc1035(hostname, p);
1007 				p += i;
1008 			}
1009 		} else if (ifo->options & DHCPCD_HOSTNAME && hostname) {
1010 			len = strlen(hostname);
1011 			AREA_CHECK(len);
1012 			*p++ = DHO_HOSTNAME;
1013 			*p++ = (uint8_t)len;
1014 			memcpy(p, hostname, len);
1015 			p += len;
1016 		}
1017 	}
1018 
1019 #ifdef AUTH
1020 	auth = NULL;	/* appease GCC */
1021 	auth_len = 0;
1022 	if (ifo->auth.options & DHCPCD_AUTH_SEND) {
1023 		ssize_t alen = dhcp_auth_encode(ifp->ctx, &ifo->auth,
1024 		    state->auth.token,
1025 		    NULL, 0, 4, type, NULL, 0);
1026 		if (alen != -1 && alen > UINT8_MAX) {
1027 			errno = ERANGE;
1028 			alen = -1;
1029 		}
1030 		if (alen == -1)
1031 			logerr("%s: dhcp_auth_encode", ifp->name);
1032 		else if (alen != 0) {
1033 			auth_len = (uint8_t)alen;
1034 			AREA_CHECK(auth_len);
1035 			*p++ = DHO_AUTHENTICATION;
1036 			*p++ = auth_len;
1037 			auth = p;
1038 			p += auth_len;
1039 		}
1040 	}
1041 #endif
1042 
1043 	/* RFC 2563 Auto Configure */
1044 	if (type == DHCP_DISCOVER && ifo->options & DHCPCD_IPV4LL &&
1045 	    !(has_option_mask(ifo->nomask, DHO_AUTOCONFIGURE)))
1046 	{
1047 		AREA_CHECK(1);
1048 		*p++ = DHO_AUTOCONFIGURE;
1049 		*p++ = 1;
1050 		*p++ = 1;
1051 	}
1052 
1053 	if (DHCP_DIR(type)) {
1054 		if (ifo->mudurl[0]) {
1055 		       AREA_CHECK(ifo->mudurl[0]);
1056 		       *p++ = DHO_MUDURL;
1057 		       memcpy(p, ifo->mudurl, (size_t)ifo->mudurl[0] + 1);
1058 		       p += ifo->mudurl[0] + 1;
1059 		}
1060 
1061 		if (ifo->vivco_len &&
1062 		    !has_option_mask(ifo->nomask, DHO_VIVCO))
1063 		{
1064 			AREA_CHECK(sizeof(ul));
1065 			*p++ = DHO_VIVCO;
1066 			lp = p++;
1067 			*lp = sizeof(ul);
1068 			ul = htonl(ifo->vivco_en);
1069 			memcpy(p, &ul, sizeof(ul));
1070 			p += sizeof(ul);
1071 			for (i = 0, vivco = ifo->vivco;
1072 			    i < ifo->vivco_len;
1073 			    i++, vivco++)
1074 			{
1075 				AREA_FIT(vivco->len);
1076 				if (vivco->len + 2 + *lp > 255) {
1077 					logerrx("%s: VIVCO option too big",
1078 					    ifp->name);
1079 					free(bootp);
1080 					return -1;
1081 				}
1082 				*p++ = (uint8_t)vivco->len;
1083 				memcpy(p, vivco->data, vivco->len);
1084 				p += vivco->len;
1085 				*lp = (uint8_t)(*lp + vivco->len + 1);
1086 			}
1087 		}
1088 
1089 #ifdef AUTH
1090 		if ((ifo->auth.options & DHCPCD_AUTH_SENDREQUIRE) !=
1091 		    DHCPCD_AUTH_SENDREQUIRE &&
1092 		    !has_option_mask(ifo->nomask, DHO_FORCERENEW_NONCE))
1093 		{
1094 			/* We support HMAC-MD5 */
1095 			AREA_CHECK(1);
1096 			*p++ = DHO_FORCERENEW_NONCE;
1097 			*p++ = 1;
1098 			*p++ = AUTH_ALG_HMAC_MD5;
1099 		}
1100 #endif
1101 	}
1102 
1103 	*p++ = DHO_END;
1104 	len = (size_t)(p - (uint8_t *)bootp);
1105 
1106 	/* Pad out to the BOOTP message length.
1107 	 * Even if we send a DHCP packet with a variable length vendor area,
1108 	 * some servers / relay agents don't like packets smaller than
1109 	 * a BOOTP message which is fine because that's stipulated
1110 	 * in RFC1542 section 2.1. */
1111 	while (len < sizeof(*bootp)) {
1112 		*p++ = DHO_PAD;
1113 		len++;
1114 	}
1115 
1116 #ifdef AUTH
1117 	if (ifo->auth.options & DHCPCD_AUTH_SEND && auth_len != 0)
1118 		dhcp_auth_encode(ifp->ctx, &ifo->auth, state->auth.token,
1119 		    (uint8_t *)bootp, len, 4, type, auth, auth_len);
1120 #endif
1121 
1122 	return (ssize_t)len;
1123 
1124 toobig:
1125 	logerrx("%s: DHCP message too big", ifp->name);
1126 	free(bootp);
1127 	return -1;
1128 }
1129 
1130 static size_t
read_lease(struct interface * ifp,struct bootp ** bootp)1131 read_lease(struct interface *ifp, struct bootp **bootp)
1132 {
1133 	union {
1134 		struct bootp bootp;
1135 		uint8_t buf[FRAMELEN_MAX];
1136 	} buf;
1137 	struct dhcp_state *state = D_STATE(ifp);
1138 	ssize_t sbytes;
1139 	size_t bytes;
1140 	uint8_t type;
1141 #ifdef AUTH
1142 	const uint8_t *auth;
1143 	size_t auth_len;
1144 #endif
1145 
1146 	/* Safety */
1147 	*bootp = NULL;
1148 
1149 	if (state->leasefile[0] == '\0') {
1150 		logdebugx("reading standard input");
1151 		sbytes = read(fileno(stdin), buf.buf, sizeof(buf.buf));
1152 	} else {
1153 		logdebugx("%s: reading lease: %s",
1154 		    ifp->name, state->leasefile);
1155 		sbytes = dhcp_readfile(ifp->ctx, state->leasefile,
1156 		    buf.buf, sizeof(buf.buf));
1157 	}
1158 	if (sbytes == -1) {
1159 		if (errno != ENOENT)
1160 			logerr("%s: %s", ifp->name, state->leasefile);
1161 		return 0;
1162 	}
1163 	bytes = (size_t)sbytes;
1164 
1165 	/* Ensure the packet is at lease BOOTP sized
1166 	 * with a vendor area of 4 octets
1167 	 * (it should be more, and our read packet enforces this so this
1168 	 * code should not be needed, but of course people could
1169 	 * scribble whatever in the stored lease file. */
1170 	if (bytes < DHCP_MIN_LEN) {
1171 		logerrx("%s: %s: truncated lease", ifp->name, __func__);
1172 		return 0;
1173 	}
1174 
1175 	if (ifp->ctx->options & DHCPCD_DUMPLEASE)
1176 		goto out;
1177 
1178 	/* We may have found a BOOTP server */
1179 	if (get_option_uint8(ifp->ctx, &type, &buf.bootp, bytes,
1180 	    DHO_MESSAGETYPE) == -1)
1181 		type = 0;
1182 
1183 #ifdef AUTH
1184 	/* Authenticate the message */
1185 	auth = get_option(ifp->ctx, &buf.bootp, bytes,
1186 	    DHO_AUTHENTICATION, &auth_len);
1187 	if (auth) {
1188 		if (dhcp_auth_validate(&state->auth, &ifp->options->auth,
1189 		    &buf.bootp, bytes, 4, type, auth, auth_len) == NULL)
1190 		{
1191 			logerr("%s: authentication failed", ifp->name);
1192 			return 0;
1193 		}
1194 		if (state->auth.token)
1195 			logdebugx("%s: validated using 0x%08" PRIu32,
1196 			    ifp->name, state->auth.token->secretid);
1197 		else
1198 			logdebugx("%s: accepted reconfigure key", ifp->name);
1199 	} else if ((ifp->options->auth.options & DHCPCD_AUTH_SENDREQUIRE) ==
1200 	    DHCPCD_AUTH_SENDREQUIRE)
1201 	{
1202 		logerrx("%s: authentication now required", ifp->name);
1203 		return 0;
1204 	}
1205 #endif
1206 
1207 out:
1208 	*bootp = malloc(bytes);
1209 	if (*bootp == NULL) {
1210 		logerr(__func__);
1211 		return 0;
1212 	}
1213 	memcpy(*bootp, buf.buf, bytes);
1214 	return bytes;
1215 }
1216 
1217 static const struct dhcp_opt *
dhcp_getoverride(const struct if_options * ifo,unsigned int o)1218 dhcp_getoverride(const struct if_options *ifo, unsigned int o)
1219 {
1220 	size_t i;
1221 	const struct dhcp_opt *opt;
1222 
1223 	for (i = 0, opt = ifo->dhcp_override;
1224 	    i < ifo->dhcp_override_len;
1225 	    i++, opt++)
1226 	{
1227 		if (opt->option == o)
1228 			return opt;
1229 	}
1230 	return NULL;
1231 }
1232 
1233 static const uint8_t *
dhcp_getoption(struct dhcpcd_ctx * ctx,size_t * os,unsigned int * code,size_t * len,const uint8_t * od,size_t ol,struct dhcp_opt ** oopt)1234 dhcp_getoption(struct dhcpcd_ctx *ctx,
1235     size_t *os, unsigned int *code, size_t *len,
1236     const uint8_t *od, size_t ol, struct dhcp_opt **oopt)
1237 {
1238 	size_t i;
1239 	struct dhcp_opt *opt;
1240 
1241 	if (od) {
1242 		if (ol < 2) {
1243 			errno = EINVAL;
1244 			return NULL;
1245 		}
1246 		*os = 2; /* code + len */
1247 		*code = (unsigned int)*od++;
1248 		*len = (size_t)*od++;
1249 		if (*len > ol - *os) {
1250 			errno = ERANGE;
1251 			return NULL;
1252 		}
1253 	}
1254 
1255 	*oopt = NULL;
1256 	for (i = 0, opt = ctx->dhcp_opts; i < ctx->dhcp_opts_len; i++, opt++) {
1257 		if (opt->option == *code) {
1258 			*oopt = opt;
1259 			break;
1260 		}
1261 	}
1262 
1263 	return od;
1264 }
1265 
1266 ssize_t
dhcp_env(FILE * fenv,const char * prefix,const struct interface * ifp,const struct bootp * bootp,size_t bootp_len)1267 dhcp_env(FILE *fenv, const char *prefix, const struct interface *ifp,
1268     const struct bootp *bootp, size_t bootp_len)
1269 {
1270 	const struct if_options *ifo;
1271 	const uint8_t *p;
1272 	struct in_addr addr;
1273 	struct in_addr net;
1274 	struct in_addr brd;
1275 	struct dhcp_opt *opt, *vo;
1276 	size_t i, pl;
1277 	char safe[(BOOTP_FILE_LEN * 4) + 1];
1278 	uint8_t overl = 0;
1279 	uint32_t en;
1280 
1281 	ifo = ifp->options;
1282 	if (get_option_uint8(ifp->ctx, &overl, bootp, bootp_len,
1283 	    DHO_OPTSOVERLOADED) == -1)
1284 		overl = 0;
1285 
1286 	if (bootp->yiaddr || bootp->ciaddr) {
1287 		/* Set some useful variables that we derive from the DHCP
1288 		 * message but are not necessarily in the options */
1289 		addr.s_addr = bootp->yiaddr ? bootp->yiaddr : bootp->ciaddr;
1290 		if (efprintf(fenv, "%s_ip_address=%s",
1291 		    prefix, inet_ntoa(addr)) == -1)
1292 			return -1;
1293 		if (get_option_addr(ifp->ctx, &net,
1294 		    bootp, bootp_len, DHO_SUBNETMASK) == -1) {
1295 			net.s_addr = ipv4_getnetmask(addr.s_addr);
1296 			if (efprintf(fenv, "%s_subnet_mask=%s",
1297 			    prefix, inet_ntoa(net)) == -1)
1298 				return -1;
1299 		}
1300 		if (efprintf(fenv, "%s_subnet_cidr=%d",
1301 		    prefix, inet_ntocidr(net))== -1)
1302 			return -1;
1303 		if (get_option_addr(ifp->ctx, &brd,
1304 		    bootp, bootp_len, DHO_BROADCAST) == -1)
1305 		{
1306 			brd.s_addr = addr.s_addr | ~net.s_addr;
1307 			if (efprintf(fenv, "%s_broadcast_address=%s",
1308 			    prefix, inet_ntoa(brd)) == -1)
1309 				return -1;
1310 		}
1311 		addr.s_addr = bootp->yiaddr & net.s_addr;
1312 		if (efprintf(fenv, "%s_network_number=%s",
1313 		    prefix, inet_ntoa(addr)) == -1)
1314 			return -1;
1315 	}
1316 
1317 	if (*bootp->file && !(overl & 1)) {
1318 		print_string(safe, sizeof(safe), OT_STRING,
1319 		    bootp->file, sizeof(bootp->file));
1320 		if (efprintf(fenv, "%s_filename=%s", prefix, safe) == -1)
1321 			return -1;
1322 	}
1323 	if (*bootp->sname && !(overl & 2)) {
1324 		print_string(safe, sizeof(safe), OT_STRING | OT_DOMAIN,
1325 		    bootp->sname, sizeof(bootp->sname));
1326 		if (efprintf(fenv, "%s_server_name=%s", prefix, safe) == -1)
1327 			return -1;
1328 	}
1329 
1330 	/* Zero our indexes */
1331 	for (i = 0, opt = ifp->ctx->dhcp_opts;
1332 	    i < ifp->ctx->dhcp_opts_len;
1333 	    i++, opt++)
1334 		dhcp_zero_index(opt);
1335 	for (i = 0, opt = ifp->options->dhcp_override;
1336 	    i < ifp->options->dhcp_override_len;
1337 	    i++, opt++)
1338 		dhcp_zero_index(opt);
1339 	for (i = 0, opt = ifp->ctx->vivso;
1340 	    i < ifp->ctx->vivso_len;
1341 	    i++, opt++)
1342 		dhcp_zero_index(opt);
1343 
1344 	for (i = 0, opt = ifp->ctx->dhcp_opts;
1345 	    i < ifp->ctx->dhcp_opts_len;
1346 	    i++, opt++)
1347 	{
1348 		if (has_option_mask(ifo->nomask, opt->option))
1349 			continue;
1350 		if (dhcp_getoverride(ifo, opt->option))
1351 			continue;
1352 		p = get_option(ifp->ctx, bootp, bootp_len, opt->option, &pl);
1353 		if (p == NULL)
1354 			continue;
1355 		dhcp_envoption(ifp->ctx, fenv, prefix, ifp->name,
1356 		    opt, dhcp_getoption, p, pl);
1357 
1358 		if (opt->option != DHO_VIVSO || pl <= (int)sizeof(uint32_t))
1359 			continue;
1360 		memcpy(&en, p, sizeof(en));
1361 		en = ntohl(en);
1362 		vo = vivso_find(en, ifp);
1363 		if (vo == NULL)
1364 			continue;
1365 		/* Skip over en + total size */
1366 		p += sizeof(en) + 1;
1367 		pl -= sizeof(en) + 1;
1368 		dhcp_envoption(ifp->ctx, fenv, prefix, ifp->name,
1369 		    vo, dhcp_getoption, p, pl);
1370 	}
1371 
1372 	for (i = 0, opt = ifo->dhcp_override;
1373 	    i < ifo->dhcp_override_len;
1374 	    i++, opt++)
1375 	{
1376 		if (has_option_mask(ifo->nomask, opt->option))
1377 			continue;
1378 		p = get_option(ifp->ctx, bootp, bootp_len, opt->option, &pl);
1379 		if (p == NULL)
1380 			continue;
1381 		dhcp_envoption(ifp->ctx, fenv, prefix, ifp->name,
1382 		    opt, dhcp_getoption, p, pl);
1383 	}
1384 
1385 	return 1;
1386 }
1387 
1388 static void
get_lease(struct interface * ifp,struct dhcp_lease * lease,const struct bootp * bootp,size_t len)1389 get_lease(struct interface *ifp,
1390     struct dhcp_lease *lease, const struct bootp *bootp, size_t len)
1391 {
1392 	struct dhcpcd_ctx *ctx;
1393 
1394 	assert(bootp != NULL);
1395 
1396 	memcpy(&lease->cookie, bootp->vend, sizeof(lease->cookie));
1397 	/* BOOTP does not set yiaddr for replies when ciaddr is set. */
1398 	lease->addr.s_addr = bootp->yiaddr ? bootp->yiaddr : bootp->ciaddr;
1399 	ctx = ifp->ctx;
1400 	if (ifp->options->options & (DHCPCD_STATIC | DHCPCD_INFORM)) {
1401 		if (ifp->options->req_addr.s_addr != INADDR_ANY) {
1402 			lease->mask = ifp->options->req_mask;
1403 			if (ifp->options->req_brd.s_addr != INADDR_ANY)
1404 				lease->brd = ifp->options->req_brd;
1405 			else
1406 				lease->brd.s_addr =
1407 				    lease->addr.s_addr | ~lease->mask.s_addr;
1408 		} else {
1409 			const struct ipv4_addr *ia;
1410 
1411 			ia = ipv4_iffindaddr(ifp, &lease->addr, NULL);
1412 			assert(ia != NULL);
1413 			lease->mask = ia->mask;
1414 			lease->brd = ia->brd;
1415 		}
1416 	} else {
1417 		if (get_option_addr(ctx, &lease->mask, bootp, len,
1418 		    DHO_SUBNETMASK) == -1)
1419 			lease->mask.s_addr =
1420 			    ipv4_getnetmask(lease->addr.s_addr);
1421 		if (get_option_addr(ctx, &lease->brd, bootp, len,
1422 		    DHO_BROADCAST) == -1)
1423 			lease->brd.s_addr =
1424 			    lease->addr.s_addr | ~lease->mask.s_addr;
1425 	}
1426 	if (get_option_uint32(ctx, &lease->leasetime,
1427 	    bootp, len, DHO_LEASETIME) != 0)
1428 		lease->leasetime = DHCP_INFINITE_LIFETIME;
1429 	if (get_option_uint32(ctx, &lease->renewaltime,
1430 	    bootp, len, DHO_RENEWALTIME) != 0)
1431 		lease->renewaltime = 0;
1432 	if (get_option_uint32(ctx, &lease->rebindtime,
1433 	    bootp, len, DHO_REBINDTIME) != 0)
1434 		lease->rebindtime = 0;
1435 	if (get_option_addr(ctx, &lease->server, bootp, len, DHO_SERVERID) != 0)
1436 		lease->server.s_addr = INADDR_ANY;
1437 }
1438 
1439 static const char *
get_dhcp_op(uint8_t type)1440 get_dhcp_op(uint8_t type)
1441 {
1442 	const struct dhcp_op *d;
1443 
1444 	for (d = dhcp_ops; d->name; d++)
1445 		if (d->value == type)
1446 			return d->name;
1447 	return NULL;
1448 }
1449 
1450 static void
dhcp_fallback(void * arg)1451 dhcp_fallback(void *arg)
1452 {
1453 	struct interface *iface;
1454 
1455 	iface = (struct interface *)arg;
1456 	dhcpcd_selectprofile(iface, iface->options->fallback);
1457 	dhcpcd_startinterface(iface);
1458 }
1459 
1460 static void
dhcp_new_xid(struct interface * ifp)1461 dhcp_new_xid(struct interface *ifp)
1462 {
1463 	struct dhcp_state *state;
1464 	const struct interface *ifp1;
1465 	const struct dhcp_state *state1;
1466 
1467 	state = D_STATE(ifp);
1468 	if (ifp->options->options & DHCPCD_XID_HWADDR &&
1469 	    ifp->hwlen >= sizeof(state->xid))
1470 		/* The lower bits are probably more unique on the network */
1471 		memcpy(&state->xid,
1472 		    (ifp->hwaddr + ifp->hwlen) - sizeof(state->xid),
1473 		    sizeof(state->xid));
1474 	else {
1475 again:
1476 		state->xid = arc4random();
1477 	}
1478 
1479 	/* Ensure it's unique */
1480 	TAILQ_FOREACH(ifp1, ifp->ctx->ifaces, next) {
1481 		if (ifp == ifp1)
1482 			continue;
1483 		if ((state1 = D_CSTATE(ifp1)) == NULL)
1484 			continue;
1485 		if (state1->xid == state->xid)
1486 			break;
1487 	}
1488 	if (ifp1 != NULL) {
1489 		if (ifp->options->options & DHCPCD_XID_HWADDR &&
1490 		    ifp->hwlen >= sizeof(state->xid))
1491 		{
1492 			logerrx("%s: duplicate xid on %s",
1493 			    ifp->name, ifp1->name);
1494 			    return;
1495 		}
1496 		goto again;
1497 	}
1498 
1499 	/* We can't do this when sharing leases across interfaes */
1500 #if 0
1501 	/* As the XID changes, re-apply the filter. */
1502 	if (state->bpf_fd != -1) {
1503 		if (bpf_bootp(ifp, state->bpf_fd) == -1)
1504 			logerr(__func__); /* try to continue */
1505 	}
1506 #endif
1507 }
1508 
1509 static void
dhcp_closebpf(struct interface * ifp)1510 dhcp_closebpf(struct interface *ifp)
1511 {
1512 	struct dhcpcd_ctx *ctx = ifp->ctx;
1513 	struct dhcp_state *state = D_STATE(ifp);
1514 
1515 #ifdef PRIVSEP
1516 	if (IN_PRIVSEP_SE(ctx))
1517 		ps_bpf_closebootp(ifp);
1518 #endif
1519 
1520 	if (state->bpf != NULL) {
1521 		eloop_event_delete(ctx->eloop, state->bpf->bpf_fd);
1522 		bpf_close(state->bpf);
1523 		state->bpf = NULL;
1524 	}
1525 }
1526 
1527 static void
dhcp_closeinet(struct interface * ifp)1528 dhcp_closeinet(struct interface *ifp)
1529 {
1530 	struct dhcpcd_ctx *ctx = ifp->ctx;
1531 	struct dhcp_state *state = D_STATE(ifp);
1532 
1533 #ifdef PRIVSEP
1534 	if (IN_PRIVSEP_SE(ctx)) {
1535 		if (state->addr != NULL)
1536 			ps_inet_closebootp(state->addr);
1537 	}
1538 #endif
1539 
1540 	if (state->udp_rfd != -1) {
1541 		eloop_event_delete(ctx->eloop, state->udp_rfd);
1542 		close(state->udp_rfd);
1543 		state->udp_rfd = -1;
1544 	}
1545 }
1546 
1547 void
dhcp_close(struct interface * ifp)1548 dhcp_close(struct interface *ifp)
1549 {
1550 	struct dhcp_state *state = D_STATE(ifp);
1551 
1552 	if (state == NULL)
1553 		return;
1554 
1555 	dhcp_closebpf(ifp);
1556 	dhcp_closeinet(ifp);
1557 
1558 	state->interval = 0;
1559 }
1560 
1561 int
dhcp_openudp(struct in_addr * ia)1562 dhcp_openudp(struct in_addr *ia)
1563 {
1564 	int s;
1565 	struct sockaddr_in sin;
1566 	int n;
1567 
1568 	if ((s = xsocket(PF_INET, SOCK_DGRAM | SOCK_CXNB, IPPROTO_UDP)) == -1)
1569 		return -1;
1570 
1571 	n = 1;
1572 	if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n)) == -1)
1573 		goto errexit;
1574 #ifdef IP_RECVIF
1575 	if (setsockopt(s, IPPROTO_IP, IP_RECVIF, &n, sizeof(n)) == -1)
1576 		goto errexit;
1577 #else
1578 	if (setsockopt(s, IPPROTO_IP, IP_RECVPKTINFO, &n, sizeof(n)) == -1)
1579 		goto errexit;
1580 #endif
1581 #ifdef SO_RERROR
1582 	if (setsockopt(s, SOL_SOCKET, SO_RERROR, &n, sizeof(n)) == -1)
1583 		goto errexit;
1584 #endif
1585 
1586 	memset(&sin, 0, sizeof(sin));
1587 	sin.sin_family = AF_INET;
1588 	sin.sin_port = htons(BOOTPC);
1589 	if (ia != NULL)
1590 		sin.sin_addr = *ia;
1591 	if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) == -1)
1592 		goto errexit;
1593 
1594 	return s;
1595 
1596 errexit:
1597 	close(s);
1598 	return -1;
1599 }
1600 
1601 static uint16_t
in_cksum(const void * data,size_t len,uint32_t * isum)1602 in_cksum(const void *data, size_t len, uint32_t *isum)
1603 {
1604 	const uint16_t *word = data;
1605 	uint32_t sum = isum != NULL ? *isum : 0;
1606 
1607 	for (; len > 1; len -= sizeof(*word))
1608 		sum += *word++;
1609 
1610 	if (len == 1)
1611 		sum += htons((uint16_t)(*(const uint8_t *)word << 8));
1612 
1613 	if (isum != NULL)
1614 		*isum = sum;
1615 
1616 	sum = (sum >> 16) + (sum & 0xffff);
1617 	sum += (sum >> 16);
1618 
1619 	return (uint16_t)~sum;
1620 }
1621 
1622 static struct bootp_pkt *
dhcp_makeudppacket(size_t * sz,const uint8_t * data,size_t length,struct in_addr source,struct in_addr dest)1623 dhcp_makeudppacket(size_t *sz, const uint8_t *data, size_t length,
1624 	struct in_addr source, struct in_addr dest)
1625 {
1626 	struct bootp_pkt *udpp;
1627 	struct ip *ip;
1628 	struct udphdr *udp;
1629 
1630 	if ((udpp = calloc(1, sizeof(*ip) + sizeof(*udp) + length)) == NULL)
1631 		return NULL;
1632 	ip = &udpp->ip;
1633 	udp = &udpp->udp;
1634 
1635 	/* OK, this is important :)
1636 	 * We copy the data to our packet and then create a small part of the
1637 	 * ip structure and an invalid ip_len (basically udp length).
1638 	 * We then fill the udp structure and put the checksum
1639 	 * of the whole packet into the udp checksum.
1640 	 * Finally we complete the ip structure and ip checksum.
1641 	 * If we don't do the ordering like so then the udp checksum will be
1642 	 * broken, so find another way of doing it! */
1643 
1644 	memcpy(&udpp->bootp, data, length);
1645 
1646 	ip->ip_p = IPPROTO_UDP;
1647 	ip->ip_src.s_addr = source.s_addr;
1648 	if (dest.s_addr == 0)
1649 		ip->ip_dst.s_addr = INADDR_BROADCAST;
1650 	else
1651 		ip->ip_dst.s_addr = dest.s_addr;
1652 
1653 	udp->uh_sport = htons(BOOTPC);
1654 	udp->uh_dport = htons(BOOTPS);
1655 	udp->uh_ulen = htons((uint16_t)(sizeof(*udp) + length));
1656 	ip->ip_len = udp->uh_ulen;
1657 	udp->uh_sum = in_cksum(udpp, sizeof(*ip) + sizeof(*udp) + length, NULL);
1658 
1659 	ip->ip_v = IPVERSION;
1660 	ip->ip_hl = sizeof(*ip) >> 2;
1661 	ip->ip_id = (uint16_t)arc4random_uniform(UINT16_MAX);
1662 	ip->ip_ttl = IPDEFTTL;
1663 	ip->ip_len = htons((uint16_t)(sizeof(*ip) + sizeof(*udp) + length));
1664 	ip->ip_sum = in_cksum(ip, sizeof(*ip), NULL);
1665 	if (ip->ip_sum == 0)
1666 		ip->ip_sum = 0xffff; /* RFC 768 */
1667 
1668 	*sz = sizeof(*ip) + sizeof(*udp) + length;
1669 	return udpp;
1670 }
1671 
1672 static ssize_t
dhcp_sendudp(struct interface * ifp,struct in_addr * to,void * data,size_t len)1673 dhcp_sendudp(struct interface *ifp, struct in_addr *to, void *data, size_t len)
1674 {
1675 	struct sockaddr_in sin = {
1676 		.sin_family = AF_INET,
1677 		.sin_addr = *to,
1678 		.sin_port = htons(BOOTPS),
1679 #ifdef HAVE_SA_LEN
1680 		.sin_len = sizeof(sin),
1681 #endif
1682 	};
1683 	struct udphdr udp = {
1684 	    .uh_sport = htons(BOOTPC),
1685 	    .uh_dport = htons(BOOTPS),
1686 	    .uh_ulen = htons((uint16_t)(sizeof(udp) + len)),
1687 	};
1688 	struct iovec iov[] = {
1689 	    { .iov_base = &udp, .iov_len = sizeof(udp), },
1690 	    { .iov_base = data, .iov_len = len, },
1691 	};
1692 	struct msghdr msg = {
1693 		.msg_name = (void *)&sin,
1694 		.msg_namelen = sizeof(sin),
1695 		.msg_iov = iov,
1696 		.msg_iovlen = __arraycount(iov),
1697 	};
1698 	struct dhcpcd_ctx *ctx = ifp->ctx;
1699 
1700 #ifdef PRIVSEP
1701 	if (ctx->options & DHCPCD_PRIVSEP)
1702 		return ps_inet_sendbootp(ifp, &msg);
1703 #endif
1704 	return sendmsg(ctx->udp_wfd, &msg, 0);
1705 }
1706 
1707 static void
send_message(struct interface * ifp,uint8_t type,void (* callback)(void *))1708 send_message(struct interface *ifp, uint8_t type,
1709     void (*callback)(void *))
1710 {
1711 	struct dhcp_state *state = D_STATE(ifp);
1712 	struct if_options *ifo = ifp->options;
1713 	struct bootp *bootp;
1714 	struct bootp_pkt *udp;
1715 	size_t len, ulen;
1716 	ssize_t r;
1717 	struct in_addr from, to;
1718 	unsigned int RT;
1719 
1720 	if (callback == NULL) {
1721 		/* No carrier? Don't bother sending the packet. */
1722 		if (!if_is_link_up(ifp))
1723 			return;
1724 		logdebugx("%s: sending %s with xid 0x%x",
1725 		    ifp->name,
1726 		    ifo->options & DHCPCD_BOOTP ? "BOOTP" : get_dhcp_op(type),
1727 		    state->xid);
1728 		RT = 0; /* bogus gcc warning */
1729 	} else {
1730 		if (state->interval == 0)
1731 			state->interval = 4;
1732 		else {
1733 			state->interval *= 2;
1734 			if (state->interval > 64)
1735 				state->interval = 64;
1736 		}
1737 		RT = (state->interval * MSEC_PER_SEC) +
1738 		    (arc4random_uniform(MSEC_PER_SEC * 2) - MSEC_PER_SEC);
1739 		/* No carrier? Don't bother sending the packet.
1740 		 * However, we do need to advance the timeout. */
1741 		if (!if_is_link_up(ifp))
1742 			goto fail;
1743 		logdebugx("%s: sending %s (xid 0x%x), next in %0.1f seconds",
1744 		    ifp->name,
1745 		    ifo->options & DHCPCD_BOOTP ? "BOOTP" : get_dhcp_op(type),
1746 		    state->xid,
1747 		    (float)RT / MSEC_PER_SEC);
1748 	}
1749 
1750 	r = make_message(&bootp, ifp, type);
1751 	if (r == -1)
1752 		goto fail;
1753 	len = (size_t)r;
1754 
1755 	if (!(state->added & (STATE_FAKE | STATE_EXPIRED)) &&
1756 	    state->addr != NULL &&
1757 	    ipv4_iffindaddr(ifp, &state->lease.addr, NULL) != NULL)
1758 		from.s_addr = state->lease.addr.s_addr;
1759 	else
1760 		from.s_addr = INADDR_ANY;
1761 	if (from.s_addr != INADDR_ANY &&
1762 	    state->lease.server.s_addr != INADDR_ANY)
1763 		to.s_addr = state->lease.server.s_addr;
1764 	else
1765 		to.s_addr = INADDR_BROADCAST;
1766 
1767 	/*
1768 	 * If not listening on the unspecified address we can
1769 	 * only receive broadcast messages via BPF.
1770 	 * Sockets bound to an address cannot receive broadcast messages
1771 	 * even if they are setup to send them.
1772 	 * Broadcasting from UDP is only an optimisation for rebinding
1773 	 * and on BSD, at least, is reliant on the subnet route being
1774 	 * correctly configured to receive the unicast reply.
1775 	 * As such, we always broadcast and receive the reply to it via BPF.
1776 	 * This also guarantees we have a DHCP server attached to the
1777 	 * interface we want to configure because we can't dictate the
1778 	 * interface via IP_PKTINFO unlike for IPv6.
1779 	 */
1780 	if (to.s_addr != INADDR_BROADCAST) {
1781 		if (dhcp_sendudp(ifp, &to, bootp, len) != -1)
1782 			goto out;
1783 		logerr("%s: dhcp_sendudp", ifp->name);
1784 	}
1785 
1786 	if (dhcp_openbpf(ifp) == -1)
1787 		goto out;
1788 
1789 	udp = dhcp_makeudppacket(&ulen, (uint8_t *)bootp, len, from, to);
1790 	if (udp == NULL) {
1791 		logerr("%s: dhcp_makeudppacket", ifp->name);
1792 		r = 0;
1793 #ifdef PRIVSEP
1794 	} else if (ifp->ctx->options & DHCPCD_PRIVSEP) {
1795 		r = ps_bpf_sendbootp(ifp, udp, ulen);
1796 		free(udp);
1797 #endif
1798 	} else {
1799 		r = bpf_send(state->bpf, ETHERTYPE_IP, udp, ulen);
1800 		free(udp);
1801 	}
1802 	/* If we failed to send a raw packet this normally means
1803 	 * we don't have the ability to work beneath the IP layer
1804 	 * for this interface.
1805 	 * As such we remove it from consideration without actually
1806 	 * stopping the interface. */
1807 	if (r == -1) {
1808 		logerr("%s: bpf_send", ifp->name);
1809 		switch(errno) {
1810 		case ENETDOWN:
1811 		case ENETRESET:
1812 		case ENETUNREACH:
1813 		case ENOBUFS:
1814 			break;
1815 		default:
1816 			if (!(ifp->ctx->options & DHCPCD_TEST))
1817 				dhcp_drop(ifp, "FAIL");
1818 			eloop_timeout_delete(ifp->ctx->eloop,
1819 			    NULL, ifp);
1820 			callback = NULL;
1821 		}
1822 	}
1823 
1824 out:
1825 	free(bootp);
1826 
1827 fail:
1828 	/* Even if we fail to send a packet we should continue as we are
1829 	 * as our failure timeouts will change out codepath when needed. */
1830 	if (callback != NULL)
1831 		eloop_timeout_add_msec(ifp->ctx->eloop, RT, callback, ifp);
1832 }
1833 
1834 static void
send_inform(void * arg)1835 send_inform(void *arg)
1836 {
1837 
1838 	send_message((struct interface *)arg, DHCP_INFORM, send_inform);
1839 }
1840 
1841 static void
send_discover(void * arg)1842 send_discover(void *arg)
1843 {
1844 
1845 	send_message((struct interface *)arg, DHCP_DISCOVER, send_discover);
1846 }
1847 
1848 static void
send_request(void * arg)1849 send_request(void *arg)
1850 {
1851 
1852 	send_message((struct interface *)arg, DHCP_REQUEST, send_request);
1853 }
1854 
1855 static void
send_renew(void * arg)1856 send_renew(void *arg)
1857 {
1858 
1859 	send_message((struct interface *)arg, DHCP_REQUEST, send_renew);
1860 }
1861 
1862 static void
send_rebind(void * arg)1863 send_rebind(void *arg)
1864 {
1865 
1866 	send_message((struct interface *)arg, DHCP_REQUEST, send_rebind);
1867 }
1868 
1869 void
dhcp_discover(void * arg)1870 dhcp_discover(void *arg)
1871 {
1872 	struct interface *ifp = arg;
1873 	struct dhcp_state *state = D_STATE(ifp);
1874 	struct if_options *ifo = ifp->options;
1875 
1876 	state->state = DHS_DISCOVER;
1877 	dhcp_new_xid(ifp);
1878 	eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
1879 	if (!(state->added & STATE_EXPIRED)) {
1880 		if (ifo->fallback && ifo->fallback_time)
1881 			eloop_timeout_add_sec(ifp->ctx->eloop,
1882 			    ifo->fallback_time, dhcp_fallback, ifp);
1883 #ifdef IPV4LL
1884 		else if (ifo->options & DHCPCD_IPV4LL)
1885 			eloop_timeout_add_sec(ifp->ctx->eloop,
1886 			    ifo->ipv4ll_time, ipv4ll_start, ifp);
1887 #endif
1888 	}
1889 	if (ifo->options & DHCPCD_REQUEST)
1890 		loginfox("%s: soliciting a DHCP lease (requesting %s)",
1891 		    ifp->name, inet_ntoa(ifo->req_addr));
1892 	else
1893 		loginfox("%s: soliciting a %s lease",
1894 		    ifp->name, ifo->options & DHCPCD_BOOTP ? "BOOTP" : "DHCP");
1895 	send_discover(ifp);
1896 }
1897 
1898 static void
dhcp_requestfailed(void * arg)1899 dhcp_requestfailed(void *arg)
1900 {
1901 	struct interface *ifp = arg;
1902 	struct dhcp_state *state = D_STATE(ifp);
1903 
1904 	logwarnx("%s: failed to request the lease", ifp->name);
1905 	free(state->offer);
1906 	state->offer = NULL;
1907 	state->offer_len = 0;
1908 	state->interval = 0;
1909 	dhcp_discover(ifp);
1910 }
1911 
1912 static void
dhcp_request(void * arg)1913 dhcp_request(void *arg)
1914 {
1915 	struct interface *ifp = arg;
1916 	struct dhcp_state *state = D_STATE(ifp);
1917 	struct if_options *ifo = ifp->options;
1918 
1919 	state->state = DHS_REQUEST;
1920 	// Handle the server being silent to our request.
1921 	if (ifo->request_time != 0)
1922 		eloop_timeout_add_sec(ifp->ctx->eloop, ifo->request_time,
1923 		    dhcp_requestfailed, ifp);
1924 	send_request(ifp);
1925 }
1926 
1927 static void
dhcp_expire(void * arg)1928 dhcp_expire(void *arg)
1929 {
1930 	struct interface *ifp = arg;
1931 	struct dhcp_state *state = D_STATE(ifp);
1932 
1933 	if (ifp->options->options & DHCPCD_LASTLEASE_EXTEND) {
1934 		logwarnx("%s: DHCP lease expired, extending lease", ifp->name);
1935 		state->added |= STATE_EXPIRED;
1936 	} else {
1937 		logerrx("%s: DHCP lease expired", ifp->name);
1938 		dhcp_drop(ifp, "EXPIRE");
1939 		dhcp_unlink(ifp->ctx, state->leasefile);
1940 	}
1941 	state->interval = 0;
1942 	dhcp_discover(ifp);
1943 }
1944 
1945 #if defined(ARP) || defined(IN_IFF_DUPLICATED)
1946 static void
dhcp_decline(struct interface * ifp)1947 dhcp_decline(struct interface *ifp)
1948 {
1949 	struct dhcp_state *state = D_STATE(ifp);
1950 
1951 	// Set the expired state so we send over BPF as this could be
1952 	// an address defence failure.
1953 	state->added |= STATE_EXPIRED;
1954 	send_message(ifp, DHCP_DECLINE, NULL);
1955 }
1956 #endif
1957 
1958 static void
dhcp_startrenew(void * arg)1959 dhcp_startrenew(void *arg)
1960 {
1961 	struct interface *ifp = arg;
1962 	struct dhcp_state *state;
1963 	struct dhcp_lease *lease;
1964 
1965 	if ((state = D_STATE(ifp)) == NULL)
1966 		return;
1967 
1968 	/* Only renew in the bound or renew states */
1969 	if (state->state != DHS_BOUND &&
1970 	    state->state != DHS_RENEW)
1971 		return;
1972 
1973 	/* Remove the timeout as the renew may have been forced. */
1974 	eloop_timeout_delete(ifp->ctx->eloop, dhcp_startrenew, ifp);
1975 
1976 	lease = &state->lease;
1977 	logdebugx("%s: renewing lease of %s", ifp->name,
1978 	    inet_ntoa(lease->addr));
1979 	state->state = DHS_RENEW;
1980 	dhcp_new_xid(ifp);
1981 	state->interval = 0;
1982 	send_renew(ifp);
1983 }
1984 
1985 void
dhcp_renew(struct interface * ifp)1986 dhcp_renew(struct interface *ifp)
1987 {
1988 
1989 	dhcp_startrenew(ifp);
1990 }
1991 
1992 static void
dhcp_rebind(void * arg)1993 dhcp_rebind(void *arg)
1994 {
1995 	struct interface *ifp = arg;
1996 	struct dhcp_state *state = D_STATE(ifp);
1997 	struct dhcp_lease *lease = &state->lease;
1998 
1999 	logwarnx("%s: failed to renew DHCP, rebinding", ifp->name);
2000 	logdebugx("%s: expire in %"PRIu32" seconds",
2001 	    ifp->name, lease->leasetime - lease->rebindtime);
2002 	state->state = DHS_REBIND;
2003 	eloop_timeout_delete(ifp->ctx->eloop, send_renew, ifp);
2004 	state->lease.server.s_addr = INADDR_ANY;
2005 	state->interval = 0;
2006 	ifp->options->options &= ~(DHCPCD_CSR_WARNED |
2007 	    DHCPCD_ROUTER_HOST_ROUTE_WARNED);
2008 	send_rebind(ifp);
2009 }
2010 
2011 #if defined(ARP) || defined(IN_IFF_DUPLICATED)
2012 static void
dhcp_finish_dad(struct interface * ifp,struct in_addr * ia)2013 dhcp_finish_dad(struct interface *ifp, struct in_addr *ia)
2014 {
2015 	struct dhcp_state *state = D_STATE(ifp);
2016 
2017 	if (state->state == DHS_BOUND)
2018 		return;
2019 	if (state->offer == NULL || state->offer->yiaddr != ia->s_addr)
2020 		return;
2021 
2022 	logdebugx("%s: DAD completed for %s", ifp->name, inet_ntoa(*ia));
2023 	if (!(ifp->options->options & DHCPCD_INFORM))
2024 		dhcp_bind(ifp);
2025 #ifndef IN_IFF_DUPLICATED
2026 	else {
2027 		struct bootp *bootp;
2028 		size_t len;
2029 
2030 		bootp = state->new;
2031 		len = state->new_len;
2032 		state->new = state->offer;
2033 		state->new_len = state->offer_len;
2034 		get_lease(ifp, &state->lease, state->new, state->new_len);
2035 		ipv4_applyaddr(ifp);
2036 		state->new = bootp;
2037 		state->new_len = len;
2038 	}
2039 #endif
2040 
2041 #ifdef IPV4LL
2042 	/* Stop IPv4LL now we have a working DHCP address */
2043 	if (!IN_LINKLOCAL(ntohl(ia->s_addr)))
2044 		ipv4ll_drop(ifp);
2045 #endif
2046 
2047 	if (ifp->options->options & DHCPCD_INFORM)
2048 		dhcp_inform(ifp);
2049 }
2050 
2051 static bool
dhcp_addr_duplicated(struct interface * ifp,struct in_addr * ia)2052 dhcp_addr_duplicated(struct interface *ifp, struct in_addr *ia)
2053 {
2054 	struct dhcp_state *state = D_STATE(ifp);
2055 	unsigned long long opts = ifp->options->options;
2056 	struct dhcpcd_ctx *ctx = ifp->ctx;
2057 	bool deleted = false;
2058 #ifdef IN_IFF_DUPLICATED
2059 	struct ipv4_addr *iap;
2060 #endif
2061 
2062 	if ((state->offer == NULL || state->offer->yiaddr != ia->s_addr) &&
2063 	    !IN_ARE_ADDR_EQUAL(ia, &state->lease.addr))
2064 		return deleted;
2065 
2066 	/* RFC 2131 3.1.5, Client-server interaction */
2067 	logerrx("%s: DAD detected %s", ifp->name, inet_ntoa(*ia));
2068 	dhcp_unlink(ifp->ctx, state->leasefile);
2069 	if (!(opts & DHCPCD_STATIC) && !state->lease.frominfo)
2070 		dhcp_decline(ifp);
2071 #ifdef IN_IFF_DUPLICATED
2072 	if ((iap = ipv4_iffindaddr(ifp, ia, NULL)) != NULL) {
2073 		ipv4_deladdr(iap, 0);
2074 		deleted = true;
2075 	}
2076 #endif
2077 	eloop_timeout_delete(ctx->eloop, NULL, ifp);
2078 	if (opts & (DHCPCD_STATIC | DHCPCD_INFORM)) {
2079 		state->reason = "EXPIRE";
2080 		script_runreason(ifp, state->reason);
2081 #define NOT_ONLY_SELF (DHCPCD_MANAGER | DHCPCD_IPV6RS | DHCPCD_DHCP6)
2082 		if (!(ctx->options & NOT_ONLY_SELF))
2083 			eloop_exit(ifp->ctx->eloop, EXIT_FAILURE);
2084 		return deleted;
2085 	}
2086 	eloop_timeout_add_sec(ifp->ctx->eloop,
2087 	    DHCP_RAND_MAX, dhcp_discover, ifp);
2088 	return deleted;
2089 }
2090 #endif
2091 
2092 #ifdef ARP
2093 #ifdef KERNEL_RFC5227
2094 #ifdef ARPING
2095 static void
dhcp_arp_announced(struct arp_state * state)2096 dhcp_arp_announced(struct arp_state *state)
2097 {
2098 
2099 	arp_free(state);
2100 }
2101 #endif
2102 #else
2103 static void
dhcp_arp_defend_failed(struct arp_state * astate)2104 dhcp_arp_defend_failed(struct arp_state *astate)
2105 {
2106 	struct interface *ifp = astate->iface;
2107 	struct dhcp_state *state = D_STATE(ifp);
2108 
2109 	if (!(ifp->options->options & (DHCPCD_INFORM | DHCPCD_STATIC)))
2110 		dhcp_decline(ifp);
2111 	dhcp_drop(ifp, "EXPIRED");
2112 	dhcp_unlink(ifp->ctx, state->leasefile);
2113 	dhcp_start1(ifp);
2114 }
2115 #endif
2116 
2117 #if !defined(KERNEL_RFC5227) || defined(ARPING)
2118 static void dhcp_arp_not_found(struct arp_state *);
2119 
2120 static struct arp_state *
dhcp_arp_new(struct interface * ifp,struct in_addr * addr)2121 dhcp_arp_new(struct interface *ifp, struct in_addr *addr)
2122 {
2123 	struct arp_state *astate;
2124 
2125 	astate = arp_new(ifp, addr);
2126 	if (astate == NULL)
2127 		return NULL;
2128 
2129 	astate->found_cb = dhcp_arp_found;
2130 	astate->not_found_cb = dhcp_arp_not_found;
2131 #ifdef KERNEL_RFC5227
2132 	astate->announced_cb = dhcp_arp_announced;
2133 #else
2134 	astate->announced_cb = NULL;
2135 	astate->defend_failed_cb = dhcp_arp_defend_failed;
2136 #endif
2137 	return astate;
2138 }
2139 #endif
2140 
2141 #ifdef ARPING
2142 static int
dhcp_arping(struct interface * ifp)2143 dhcp_arping(struct interface *ifp)
2144 {
2145 	struct dhcp_state *state;
2146 	struct if_options *ifo;
2147 	struct arp_state *astate;
2148 	struct in_addr addr;
2149 
2150 	state = D_STATE(ifp);
2151 	ifo = ifp->options;
2152 
2153 	if (ifo->arping_len == 0 || state->arping_index > ifo->arping_len)
2154 		return 0;
2155 
2156 	if (state->arping_index + 1 == ifo->arping_len) {
2157 		state->arping_index++;
2158 		dhcpcd_startinterface(ifp);
2159 		return 1;
2160 	}
2161 
2162 	addr.s_addr = ifo->arping[++state->arping_index];
2163 	astate = dhcp_arp_new(ifp, &addr);
2164 	if (astate == NULL) {
2165 		logerr(__func__);
2166 		return -1;
2167 	}
2168 	arp_probe(astate);
2169 	return 1;
2170 }
2171 #endif
2172 
2173 #if !defined(KERNEL_RFC5227) || defined(ARPING)
2174 static void
dhcp_arp_not_found(struct arp_state * astate)2175 dhcp_arp_not_found(struct arp_state *astate)
2176 {
2177 	struct interface *ifp;
2178 
2179 	ifp = astate->iface;
2180 #ifdef ARPING
2181 	if (dhcp_arping(ifp) == 1) {
2182 		arp_free(astate);
2183 		return;
2184 	}
2185 #endif
2186 
2187 	dhcp_finish_dad(ifp, &astate->addr);
2188 }
2189 
2190 static void
dhcp_arp_found(struct arp_state * astate,const struct arp_msg * amsg)2191 dhcp_arp_found(struct arp_state *astate, const struct arp_msg *amsg)
2192 {
2193 	struct in_addr addr;
2194 	struct interface *ifp = astate->iface;
2195 #ifdef ARPING
2196 	struct dhcp_state *state;
2197 	struct if_options *ifo;
2198 
2199 	state = D_STATE(ifp);
2200 
2201 	ifo = ifp->options;
2202 	if (state->arping_index != -1 &&
2203 	    state->arping_index < ifo->arping_len &&
2204 	    amsg &&
2205 	    amsg->sip.s_addr == ifo->arping[state->arping_index])
2206 	{
2207 		char buf[HWADDR_LEN * 3];
2208 
2209 		hwaddr_ntoa(amsg->sha, ifp->hwlen, buf, sizeof(buf));
2210 		if (dhcpcd_selectprofile(ifp, buf) == -1 &&
2211 		    dhcpcd_selectprofile(ifp, inet_ntoa(amsg->sip)) == -1)
2212 		{
2213 			/* We didn't find a profile for this
2214 			 * address or hwaddr, so move to the next
2215 			 * arping profile */
2216 			dhcp_arp_not_found(astate);
2217 			return;
2218 		}
2219 		arp_free(astate);
2220 		eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
2221 		dhcpcd_startinterface(ifp);
2222 		return;
2223 	}
2224 #else
2225 	UNUSED(amsg);
2226 #endif
2227 
2228 	addr = astate->addr;
2229 	arp_free(astate);
2230 	dhcp_addr_duplicated(ifp, &addr);
2231 }
2232 #endif
2233 
2234 #endif /* ARP */
2235 
2236 void
dhcp_bind(struct interface * ifp)2237 dhcp_bind(struct interface *ifp)
2238 {
2239 	struct dhcpcd_ctx *ctx = ifp->ctx;
2240 	struct dhcp_state *state = D_STATE(ifp);
2241 	struct if_options *ifo = ifp->options;
2242 	struct dhcp_lease *lease = &state->lease;
2243 	uint8_t old_state;
2244 
2245 	state->reason = NULL;
2246 	/* If we don't have an offer, we are re-binding a lease on preference,
2247 	 * normally when two interfaces have a lease matching IP addresses. */
2248 	if (state->offer) {
2249 		free(state->old);
2250 		state->old = state->new;
2251 		state->old_len = state->new_len;
2252 		state->new = state->offer;
2253 		state->new_len = state->offer_len;
2254 		state->offer = NULL;
2255 		state->offer_len = 0;
2256 	}
2257 	get_lease(ifp, lease, state->new, state->new_len);
2258 	if (ifo->options & DHCPCD_STATIC) {
2259 		loginfox("%s: using static address %s/%d",
2260 		    ifp->name, inet_ntoa(lease->addr),
2261 		    inet_ntocidr(lease->mask));
2262 		lease->leasetime = DHCP_INFINITE_LIFETIME;
2263 		state->reason = "STATIC";
2264 	} else if (ifo->options & DHCPCD_INFORM) {
2265 		loginfox("%s: received approval for %s",
2266 		    ifp->name, inet_ntoa(lease->addr));
2267 		lease->leasetime = DHCP_INFINITE_LIFETIME;
2268 		state->reason = "INFORM";
2269 	} else {
2270 		if (lease->frominfo)
2271 			state->reason = "TIMEOUT";
2272 		if (lease->leasetime == DHCP_INFINITE_LIFETIME) {
2273 			lease->renewaltime =
2274 			    lease->rebindtime =
2275 			    lease->leasetime;
2276 			loginfox("%s: leased %s for infinity",
2277 			   ifp->name, inet_ntoa(lease->addr));
2278 		} else {
2279 			if (lease->leasetime < DHCP_MIN_LEASE) {
2280 				logwarnx("%s: minimum lease is %d seconds",
2281 				    ifp->name, DHCP_MIN_LEASE);
2282 				lease->leasetime = DHCP_MIN_LEASE;
2283 			}
2284 			if (lease->rebindtime == 0)
2285 				lease->rebindtime =
2286 				    (uint32_t)(lease->leasetime * T2);
2287 			else if (lease->rebindtime >= lease->leasetime) {
2288 				lease->rebindtime =
2289 				    (uint32_t)(lease->leasetime * T2);
2290 				logwarnx("%s: rebind time greater than lease "
2291 				    "time, forcing to %"PRIu32" seconds",
2292 				    ifp->name, lease->rebindtime);
2293 			}
2294 			if (lease->renewaltime == 0)
2295 				lease->renewaltime =
2296 				    (uint32_t)(lease->leasetime * T1);
2297 			else if (lease->renewaltime > lease->rebindtime) {
2298 				lease->renewaltime =
2299 				    (uint32_t)(lease->leasetime * T1);
2300 				logwarnx("%s: renewal time greater than "
2301 				    "rebind time, forcing to %"PRIu32" seconds",
2302 				    ifp->name, lease->renewaltime);
2303 			}
2304 			if (state->state == DHS_RENEW && state->addr &&
2305 			    lease->addr.s_addr == state->addr->addr.s_addr &&
2306 			    !(state->added & STATE_FAKE))
2307 				logdebugx("%s: leased %s for %"PRIu32" seconds",
2308 				    ifp->name, inet_ntoa(lease->addr),
2309 				    lease->leasetime);
2310 			else
2311 				loginfox("%s: leased %s for %"PRIu32" seconds",
2312 				    ifp->name, inet_ntoa(lease->addr),
2313 				    lease->leasetime);
2314 		}
2315 	}
2316 	if (ctx->options & DHCPCD_TEST) {
2317 		state->reason = "TEST";
2318 		script_runreason(ifp, state->reason);
2319 		eloop_exit(ctx->eloop, EXIT_SUCCESS);
2320 		return;
2321 	}
2322 	if (state->reason == NULL) {
2323 		if (state->old &&
2324 		    !(state->added & (STATE_FAKE | STATE_EXPIRED)))
2325 		{
2326 			if (state->old->yiaddr == state->new->yiaddr &&
2327 			    lease->server.s_addr &&
2328 			    state->state != DHS_REBIND)
2329 				state->reason = "RENEW";
2330 			else
2331 				state->reason = "REBIND";
2332 		} else if (state->state == DHS_REBOOT)
2333 			state->reason = "REBOOT";
2334 		else
2335 			state->reason = "BOUND";
2336 	}
2337 	if (lease->leasetime == DHCP_INFINITE_LIFETIME)
2338 		lease->renewaltime = lease->rebindtime = lease->leasetime;
2339 	else {
2340 		eloop_timeout_add_sec(ctx->eloop,
2341 		    lease->renewaltime, dhcp_startrenew, ifp);
2342 		eloop_timeout_add_sec(ctx->eloop,
2343 		    lease->rebindtime, dhcp_rebind, ifp);
2344 		eloop_timeout_add_sec(ctx->eloop,
2345 		    lease->leasetime, dhcp_expire, ifp);
2346 		logdebugx("%s: renew in %"PRIu32" seconds, rebind in %"PRIu32
2347 		    " seconds",
2348 		    ifp->name, lease->renewaltime, lease->rebindtime);
2349 	}
2350 	state->state = DHS_BOUND;
2351 	if (!state->lease.frominfo &&
2352 	    !(ifo->options & (DHCPCD_INFORM | DHCPCD_STATIC))) {
2353 		logdebugx("%s: writing lease: %s",
2354 		    ifp->name, state->leasefile);
2355 		if (dhcp_writefile(ifp->ctx, state->leasefile, 0640,
2356 		    state->new, state->new_len) == -1)
2357 			logerr("dhcp_writefile: %s", state->leasefile);
2358 	}
2359 
2360 	old_state = state->added;
2361 
2362 	if (!(ifo->options & DHCPCD_CONFIGURE)) {
2363 		struct ipv4_addr *ia;
2364 
2365 		script_runreason(ifp, state->reason);
2366 		dhcpcd_daemonise(ifp->ctx);
2367 
2368 		/* We we are not configuring the address, we need to keep
2369 		 * the BPF socket open if the address does not exist. */
2370 		ia = ipv4_iffindaddr(ifp, &state->lease.addr, NULL);
2371 		if (ia != NULL) {
2372 			state->addr = ia;
2373 			state->added = STATE_ADDED;
2374 			dhcp_closebpf(ifp);
2375 			goto openudp;
2376 		}
2377 		return;
2378 	}
2379 
2380 	/* Add the address */
2381 	if (ipv4_applyaddr(ifp) == NULL) {
2382 		/* There was an error adding the address.
2383 		 * If we are in oneshot, exit with a failure. */
2384 		if (ctx->options & DHCPCD_ONESHOT) {
2385 			loginfox("exiting due to oneshot");
2386 			eloop_exit(ctx->eloop, EXIT_FAILURE);
2387 		}
2388 		return;
2389 	}
2390 
2391 	/* Close the BPF filter as we can now receive DHCP messages
2392 	 * on a UDP socket. */
2393 	dhcp_closebpf(ifp);
2394 
2395 openudp:
2396 	/* If not in manager mode, open an address specific socket. */
2397 	if (ctx->options & DHCPCD_MANAGER ||
2398 	    ifo->options & DHCPCD_STATIC ||
2399 	    (state->old != NULL &&
2400 	     state->old->yiaddr == state->new->yiaddr &&
2401 	     old_state & STATE_ADDED && !(old_state & STATE_FAKE)))
2402 		return;
2403 
2404 	dhcp_closeinet(ifp);
2405 #ifdef PRIVSEP
2406 	if (IN_PRIVSEP_SE(ctx)) {
2407 		if (ps_inet_openbootp(state->addr) == -1)
2408 		    logerr(__func__);
2409 		return;
2410 	}
2411 #endif
2412 
2413 	state->udp_rfd = dhcp_openudp(&state->addr->addr);
2414 	if (state->udp_rfd == -1) {
2415 		logerr(__func__);
2416 		/* Address sharing without manager mode is not supported.
2417 		 * It's also possible another DHCP client could be running,
2418 		 * which is even worse.
2419 		 * We still need to work, so re-open BPF. */
2420 		dhcp_openbpf(ifp);
2421 		return;
2422 	}
2423 	if (eloop_event_add(ctx->eloop, state->udp_rfd, ELE_READ,
2424 	    dhcp_handleifudp, ifp) == -1)
2425 		logerr("%s: eloop_event_add", __func__);
2426 }
2427 
2428 static size_t
dhcp_message_new(struct bootp ** bootp,const struct in_addr * addr,const struct in_addr * mask)2429 dhcp_message_new(struct bootp **bootp,
2430     const struct in_addr *addr, const struct in_addr *mask)
2431 {
2432 	uint8_t *p;
2433 	uint32_t cookie;
2434 
2435 	if ((*bootp = calloc(1, sizeof(**bootp))) == NULL)
2436 		return 0;
2437 
2438 	(*bootp)->yiaddr = addr->s_addr;
2439 	p = (*bootp)->vend;
2440 
2441 	cookie = htonl(MAGIC_COOKIE);
2442 	memcpy(p, &cookie, sizeof(cookie));
2443 	p += sizeof(cookie);
2444 
2445 	if (mask->s_addr != INADDR_ANY) {
2446 		*p++ = DHO_SUBNETMASK;
2447 		*p++ = sizeof(mask->s_addr);
2448 		memcpy(p, &mask->s_addr, sizeof(mask->s_addr));
2449 		p+= sizeof(mask->s_addr);
2450 	}
2451 
2452 	*p = DHO_END;
2453 	return sizeof(**bootp);
2454 }
2455 
2456 #if defined(ARP) || defined(KERNEL_RFC5227)
2457 static int
dhcp_arp_address(struct interface * ifp)2458 dhcp_arp_address(struct interface *ifp)
2459 {
2460 	struct dhcp_state *state;
2461 	struct in_addr addr;
2462 	struct ipv4_addr *ia;
2463 
2464 	eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
2465 
2466 	state = D_STATE(ifp);
2467 	addr.s_addr = state->offer->yiaddr == INADDR_ANY ?
2468 	    state->offer->ciaddr : state->offer->yiaddr;
2469 	/* If the interface already has the address configured
2470 	 * then we can't ARP for duplicate detection. */
2471 	ia = ipv4_iffindaddr(ifp, &addr, NULL);
2472 #ifdef IN_IFF_NOTUSEABLE
2473 	if (ia == NULL || ia->addr_flags & IN_IFF_NOTUSEABLE) {
2474 		state->state = DHS_PROBE;
2475 		if (ia == NULL) {
2476 			struct dhcp_lease l;
2477 
2478 			get_lease(ifp, &l, state->offer, state->offer_len);
2479 			/* Add the address now, let the kernel handle DAD. */
2480 			ipv4_addaddr(ifp, &l.addr, &l.mask, &l.brd,
2481 			    l.leasetime, l.rebindtime);
2482 		} else if (ia->addr_flags & IN_IFF_DUPLICATED)
2483 			dhcp_addr_duplicated(ifp, &ia->addr);
2484 		else
2485 			loginfox("%s: waiting for DAD on %s",
2486 			    ifp->name, inet_ntoa(addr));
2487 		return 0;
2488 	}
2489 #else
2490 	if (!(ifp->flags & IFF_NOARP) &&
2491 	    ifp->options->options & DHCPCD_ARP)
2492 	{
2493 		struct arp_state *astate;
2494 		struct dhcp_lease l;
2495 
2496 		/* Even if the address exists, we need to defend it. */
2497 		astate = dhcp_arp_new(ifp, &addr);
2498 		if (astate == NULL)
2499 			return -1;
2500 
2501 		if (ia == NULL) {
2502 			state->state = DHS_PROBE;
2503 			get_lease(ifp, &l, state->offer, state->offer_len);
2504 			loginfox("%s: probing address %s/%d",
2505 			    ifp->name, inet_ntoa(l.addr), inet_ntocidr(l.mask));
2506 			/* We need to handle DAD. */
2507 			arp_probe(astate);
2508 			return 0;
2509 		}
2510 	}
2511 #endif
2512 
2513 	return 1;
2514 }
2515 
2516 static void
dhcp_arp_bind(struct interface * ifp)2517 dhcp_arp_bind(struct interface *ifp)
2518 {
2519 
2520 	if (ifp->ctx->options & DHCPCD_TEST ||
2521 	    dhcp_arp_address(ifp) == 1)
2522 		dhcp_bind(ifp);
2523 }
2524 #endif
2525 
2526 static void
dhcp_lastlease(void * arg)2527 dhcp_lastlease(void *arg)
2528 {
2529 	struct interface *ifp = arg;
2530 	struct dhcp_state *state = D_STATE(ifp);
2531 
2532 	loginfox("%s: timed out contacting a DHCP server, using last lease",
2533 	    ifp->name);
2534 #if defined(ARP) || defined(KERNEL_RFC5227)
2535 	dhcp_arp_bind(ifp);
2536 #else
2537 	dhcp_bind(ifp);
2538 #endif
2539 	/* Set expired here because dhcp_bind() -> ipv4_addaddr() will reset
2540 	 * state */
2541 	state->added |= STATE_EXPIRED;
2542 	state->interval = 0;
2543 	dhcp_discover(ifp);
2544 }
2545 
2546 static void
dhcp_static(struct interface * ifp)2547 dhcp_static(struct interface *ifp)
2548 {
2549 	struct if_options *ifo;
2550 	struct dhcp_state *state;
2551 	struct ipv4_addr *ia;
2552 
2553 	state = D_STATE(ifp);
2554 	ifo = ifp->options;
2555 
2556 	ia = NULL;
2557 	if (ifo->req_addr.s_addr == INADDR_ANY &&
2558 	    (ia = ipv4_iffindaddr(ifp, NULL, NULL)) == NULL)
2559 	{
2560 		loginfox("%s: waiting for 3rd party to "
2561 		    "configure IP address", ifp->name);
2562 		state->reason = "3RDPARTY";
2563 		script_runreason(ifp, state->reason);
2564 		return;
2565 	}
2566 
2567 	state->offer_len = dhcp_message_new(&state->offer,
2568 	    ia ? &ia->addr : &ifo->req_addr,
2569 	    ia ? &ia->mask : &ifo->req_mask);
2570 	if (state->offer_len)
2571 #if defined(ARP) || defined(KERNEL_RFC5227)
2572 		dhcp_arp_bind(ifp);
2573 #else
2574 		dhcp_bind(ifp);
2575 #endif
2576 }
2577 
2578 void
dhcp_inform(struct interface * ifp)2579 dhcp_inform(struct interface *ifp)
2580 {
2581 	struct dhcp_state *state;
2582 	struct if_options *ifo;
2583 	struct ipv4_addr *ia;
2584 
2585 	state = D_STATE(ifp);
2586 	ifo = ifp->options;
2587 
2588 	free(state->offer);
2589 	state->offer = NULL;
2590 	state->offer_len = 0;
2591 
2592 	if (ifo->req_addr.s_addr == INADDR_ANY) {
2593 		ia = ipv4_iffindaddr(ifp, NULL, NULL);
2594 		if (ia == NULL) {
2595 			loginfox("%s: waiting for 3rd party to "
2596 			    "configure IP address",
2597 			    ifp->name);
2598 			if (!(ifp->ctx->options & DHCPCD_TEST)) {
2599 				state->reason = "3RDPARTY";
2600 				script_runreason(ifp, state->reason);
2601 			}
2602 			return;
2603 		}
2604 	} else {
2605 		ia = ipv4_iffindaddr(ifp, &ifo->req_addr, &ifo->req_mask);
2606 		if (ia == NULL) {
2607 			if (ifp->ctx->options & DHCPCD_TEST) {
2608 				logerrx("%s: cannot add IP address in test mode",
2609 				    ifp->name);
2610 				return;
2611 			}
2612 			ia = ipv4_iffindaddr(ifp, &ifo->req_addr, NULL);
2613 			if (ia != NULL)
2614 				/* Netmask must be different, delete it. */
2615 				ipv4_deladdr(ia, 1);
2616 			state->offer_len = dhcp_message_new(&state->offer,
2617 			    &ifo->req_addr, &ifo->req_mask);
2618 #ifdef ARP
2619 			if (dhcp_arp_address(ifp) != 1)
2620 				return;
2621 #endif
2622 			ia = ipv4_iffindaddr(ifp,
2623 			    &ifo->req_addr, &ifo->req_mask);
2624 			assert(ia != NULL);
2625 		}
2626 	}
2627 
2628 	state->state = DHS_INFORM;
2629 	state->addr = ia;
2630 	state->offer_len = dhcp_message_new(&state->offer,
2631 	    &ia->addr, &ia->mask);
2632 	if (state->offer_len) {
2633 		dhcp_new_xid(ifp);
2634 		get_lease(ifp, &state->lease, state->offer, state->offer_len);
2635 		send_inform(ifp);
2636 	}
2637 }
2638 
2639 void
dhcp_reboot_newopts(struct interface * ifp,unsigned long long oldopts)2640 dhcp_reboot_newopts(struct interface *ifp, unsigned long long oldopts)
2641 {
2642 	struct if_options *ifo;
2643 	struct dhcp_state *state = D_STATE(ifp);
2644 
2645 	if (state == NULL || state->state == DHS_NONE)
2646 		return;
2647 	ifo = ifp->options;
2648 	if ((ifo->options & (DHCPCD_INFORM | DHCPCD_STATIC) &&
2649 		(state->addr == NULL ||
2650 		state->addr->addr.s_addr != ifo->req_addr.s_addr)) ||
2651 	    (oldopts & (DHCPCD_INFORM | DHCPCD_STATIC) &&
2652 		!(ifo->options & (DHCPCD_INFORM | DHCPCD_STATIC))))
2653 	{
2654 		dhcp_drop(ifp, "EXPIRE");
2655 	}
2656 }
2657 
2658 #ifdef ARP
2659 static int
dhcp_activeaddr(const struct interface * ifp,const struct in_addr * addr)2660 dhcp_activeaddr(const struct interface *ifp, const struct in_addr *addr)
2661 {
2662 	const struct interface *ifp1;
2663 	const struct dhcp_state *state;
2664 
2665 	TAILQ_FOREACH(ifp1, ifp->ctx->ifaces, next) {
2666 		if (ifp1 == ifp)
2667 			continue;
2668 		if ((state = D_CSTATE(ifp1)) == NULL)
2669 			continue;
2670 		switch(state->state) {
2671 		case DHS_REBOOT:
2672 		case DHS_RENEW:
2673 		case DHS_REBIND:
2674 		case DHS_BOUND:
2675 		case DHS_INFORM:
2676 			break;
2677 		default:
2678 			continue;
2679 		}
2680 		if (state->lease.addr.s_addr == addr->s_addr)
2681 			return 1;
2682 	}
2683 	return 0;
2684 }
2685 #endif
2686 
2687 static void
dhcp_reboot(struct interface * ifp)2688 dhcp_reboot(struct interface *ifp)
2689 {
2690 	struct if_options *ifo;
2691 	struct dhcp_state *state = D_STATE(ifp);
2692 #ifdef ARP
2693 	struct ipv4_addr *ia;
2694 #endif
2695 
2696 	if (state == NULL || state->state == DHS_NONE)
2697 		return;
2698 	ifo = ifp->options;
2699 	state->state = DHS_REBOOT;
2700 	state->interval = 0;
2701 
2702 	if (ifo->options & DHCPCD_LINK && !if_is_link_up(ifp)) {
2703 		loginfox("%s: waiting for carrier", ifp->name);
2704 		return;
2705 	}
2706 	if (ifo->options & DHCPCD_STATIC) {
2707 		dhcp_static(ifp);
2708 		return;
2709 	}
2710 	if (ifo->options & DHCPCD_INFORM) {
2711 		loginfox("%s: informing address of %s",
2712 		    ifp->name, inet_ntoa(state->lease.addr));
2713 		dhcp_inform(ifp);
2714 		return;
2715 	}
2716 	if (ifo->reboot == 0 || state->offer == NULL) {
2717 		dhcp_discover(ifp);
2718 		return;
2719 	}
2720 	if (!IS_DHCP(state->offer))
2721 		return;
2722 
2723 	loginfox("%s: rebinding lease of %s",
2724 	    ifp->name, inet_ntoa(state->lease.addr));
2725 
2726 #ifdef ARP
2727 #ifndef KERNEL_RFC5227
2728 	/* Create the DHCP ARP state so we can defend it. */
2729 	(void)dhcp_arp_new(ifp, &state->lease.addr);
2730 #endif
2731 
2732 	/* If the address exists on the interface and no other interface
2733 	 * is currently using it then announce it to ensure this
2734 	 * interface gets the reply. */
2735 	ia = ipv4_iffindaddr(ifp, &state->lease.addr, NULL);
2736 	if (ia != NULL &&
2737 	    !(ifp->ctx->options & DHCPCD_TEST) &&
2738 #ifdef IN_IFF_NOTUSEABLE
2739 	    !(ia->addr_flags & IN_IFF_NOTUSEABLE) &&
2740 #endif
2741 	    dhcp_activeaddr(ifp, &state->lease.addr) == 0)
2742 		arp_ifannounceaddr(ifp, &state->lease.addr);
2743 #endif
2744 
2745 	dhcp_new_xid(ifp);
2746 	state->lease.server.s_addr = INADDR_ANY;
2747 	eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
2748 
2749 #ifdef IPV4LL
2750 	/* Need to add this before dhcp_expire and friends. */
2751 	if (!ifo->fallback && ifo->options & DHCPCD_IPV4LL)
2752 		eloop_timeout_add_sec(ifp->ctx->eloop,
2753 		    ifo->ipv4ll_time, ipv4ll_start, ifp);
2754 #endif
2755 
2756 	if (ifo->options & DHCPCD_LASTLEASE && state->lease.frominfo)
2757 		eloop_timeout_add_sec(ifp->ctx->eloop,
2758 		    ifo->reboot, dhcp_lastlease, ifp);
2759 	else if (!(ifo->options & DHCPCD_INFORM))
2760 		eloop_timeout_add_sec(ifp->ctx->eloop,
2761 		    ifo->reboot, dhcp_expire, ifp);
2762 
2763 	/* Don't bother ARP checking as the server could NAK us first.
2764 	 * Don't call dhcp_request as that would change the state */
2765 	send_request(ifp);
2766 }
2767 
2768 void
dhcp_drop(struct interface * ifp,const char * reason)2769 dhcp_drop(struct interface *ifp, const char *reason)
2770 {
2771 	struct dhcp_state *state = D_STATE(ifp);
2772 
2773 	/* dhcp_start may just have been called and we don't yet have a state
2774 	 * but we do have a timeout, so punt it. */
2775 	if (state == NULL || state->state == DHS_NONE) {
2776 		eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
2777 		return;
2778 	}
2779 
2780 #ifdef ARP
2781 	if (state->addr != NULL)
2782 		arp_freeaddr(ifp, &state->addr->addr);
2783 #endif
2784 #ifdef ARPING
2785 	state->arping_index = -1;
2786 #endif
2787 
2788 	if (ifp->options->options & DHCPCD_RELEASE &&
2789 	    !(ifp->options->options & DHCPCD_INFORM))
2790 	{
2791 		/* Failure to send the release may cause this function to
2792 		 * re-enter so guard by setting the state. */
2793 		if (state->state == DHS_RELEASE)
2794 			return;
2795 		state->state = DHS_RELEASE;
2796 
2797 		dhcp_unlink(ifp->ctx, state->leasefile);
2798 		if (if_is_link_up(ifp) &&
2799 		    state->new != NULL &&
2800 		    state->lease.server.s_addr != INADDR_ANY)
2801 		{
2802 			loginfox("%s: releasing lease of %s",
2803 			    ifp->name, inet_ntoa(state->lease.addr));
2804 			dhcp_new_xid(ifp);
2805 			send_message(ifp, DHCP_RELEASE, NULL);
2806 		}
2807 	}
2808 #ifdef AUTH
2809 	else if (state->auth.reconf != NULL) {
2810 		/*
2811 		 * Drop the lease as the token may only be present
2812 		 * in the initial reply message and not subsequent
2813 		 * renewals.
2814 		 * If dhcpcd is restarted, the token is lost.
2815 		 * XXX persist this in another file?
2816 		 */
2817 		dhcp_unlink(ifp->ctx, state->leasefile);
2818 	}
2819 #endif
2820 
2821 	eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
2822 #ifdef AUTH
2823 	dhcp_auth_reset(&state->auth);
2824 #endif
2825 
2826 	state->state = DHS_NONE;
2827 	free(state->offer);
2828 	state->offer = NULL;
2829 	state->offer_len = 0;
2830 	free(state->old);
2831 	state->old = state->new;
2832 	state->old_len = state->new_len;
2833 	state->new = NULL;
2834 	state->new_len = 0;
2835 	state->reason = reason;
2836 	if (ifp->options->options & DHCPCD_CONFIGURE)
2837 		ipv4_applyaddr(ifp);
2838 	else {
2839 		state->addr = NULL;
2840 		state->added = 0;
2841 		script_runreason(ifp, state->reason);
2842 	}
2843 	free(state->old);
2844 	state->old = NULL;
2845 	state->old_len = 0;
2846 	state->lease.addr.s_addr = 0;
2847 	ifp->options->options &= ~(DHCPCD_CSR_WARNED |
2848 	    DHCPCD_ROUTER_HOST_ROUTE_WARNED);
2849 
2850 	/* Close DHCP ports so a changed interface family is picked
2851 	 * up by a new BPF state. */
2852 	dhcp_close(ifp);
2853 }
2854 
2855 static int
blacklisted_ip(const struct if_options * ifo,in_addr_t addr)2856 blacklisted_ip(const struct if_options *ifo, in_addr_t addr)
2857 {
2858 	size_t i;
2859 
2860 	for (i = 0; i < ifo->blacklist_len; i += 2)
2861 		if (ifo->blacklist[i] == (addr & ifo->blacklist[i + 1]))
2862 			return 1;
2863 	return 0;
2864 }
2865 
2866 #define	WHTLST_NONE	0
2867 #define	WHTLST_MATCH	1
2868 #define WHTLST_NOMATCH	2
2869 static unsigned int
whitelisted_ip(const struct if_options * ifo,in_addr_t addr)2870 whitelisted_ip(const struct if_options *ifo, in_addr_t addr)
2871 {
2872 	size_t i;
2873 
2874 	if (ifo->whitelist_len == 0)
2875 		return WHTLST_NONE;
2876 	for (i = 0; i < ifo->whitelist_len; i += 2)
2877 		if (ifo->whitelist[i] == (addr & ifo->whitelist[i + 1]))
2878 			return WHTLST_MATCH;
2879 	return WHTLST_NOMATCH;
2880 }
2881 
2882 static void
log_dhcp(int loglevel,const char * msg,const struct interface * ifp,const struct bootp * bootp,size_t bootp_len,const struct in_addr * from,int ad)2883 log_dhcp(int loglevel, const char *msg,
2884     const struct interface *ifp, const struct bootp *bootp, size_t bootp_len,
2885     const struct in_addr *from, int ad)
2886 {
2887 	const char *tfrom;
2888 	char *a, sname[sizeof(bootp->sname) * 4];
2889 	struct in_addr addr;
2890 	int r;
2891 	uint8_t overl;
2892 
2893 	if (strcmp(msg, "NAK:") == 0) {
2894 		a = get_option_string(ifp->ctx, bootp, bootp_len, DHO_MESSAGE);
2895 		if (a) {
2896 			char *tmp;
2897 			size_t al, tmpl;
2898 
2899 			al = strlen(a);
2900 			tmpl = (al * 4) + 1;
2901 			tmp = malloc(tmpl);
2902 			if (tmp == NULL) {
2903 				logerr(__func__);
2904 				free(a);
2905 				return;
2906 			}
2907 			print_string(tmp, tmpl, OT_STRING, (uint8_t *)a, al);
2908 			free(a);
2909 			a = tmp;
2910 		}
2911 	} else if (ad && bootp->yiaddr != 0) {
2912 		addr.s_addr = bootp->yiaddr;
2913 		a = strdup(inet_ntoa(addr));
2914 		if (a == NULL) {
2915 			logerr(__func__);
2916 			return;
2917 		}
2918 	} else
2919 		a = NULL;
2920 
2921 	tfrom = "from";
2922 	r = get_option_addr(ifp->ctx, &addr, bootp, bootp_len, DHO_SERVERID);
2923 	if (get_option_uint8(ifp->ctx, &overl, bootp, bootp_len,
2924 	    DHO_OPTSOVERLOADED) == -1)
2925 		overl = 0;
2926 	if (bootp->sname[0] && r == 0 && !(overl & 2)) {
2927 		print_string(sname, sizeof(sname), OT_STRING | OT_DOMAIN,
2928 		    bootp->sname, sizeof(bootp->sname));
2929 		if (a == NULL)
2930 			logmessage(loglevel, "%s: %s %s %s %s",
2931 			    ifp->name, msg, tfrom, inet_ntoa(addr), sname);
2932 		else
2933 			logmessage(loglevel, "%s: %s %s %s %s %s",
2934 			    ifp->name, msg, a, tfrom, inet_ntoa(addr), sname);
2935 	} else {
2936 		if (r != 0) {
2937 			tfrom = "via";
2938 			addr = *from;
2939 		}
2940 		if (a == NULL)
2941 			logmessage(loglevel, "%s: %s %s %s",
2942 			    ifp->name, msg, tfrom, inet_ntoa(addr));
2943 		else
2944 			logmessage(loglevel, "%s: %s %s %s %s",
2945 			    ifp->name, msg, a, tfrom, inet_ntoa(addr));
2946 	}
2947 	free(a);
2948 }
2949 
2950 /* If we're sharing the same IP address with another interface on the
2951  * same network, we may receive the DHCP reply on the wrong interface.
2952  * Try and re-direct it here. */
2953 static void
dhcp_redirect_dhcp(struct interface * ifp,struct bootp * bootp,size_t bootp_len,const struct in_addr * from)2954 dhcp_redirect_dhcp(struct interface *ifp, struct bootp *bootp, size_t bootp_len,
2955     const struct in_addr *from)
2956 {
2957 	struct interface *ifn;
2958 	const struct dhcp_state *state;
2959 	uint32_t xid;
2960 
2961 	xid = ntohl(bootp->xid);
2962 	TAILQ_FOREACH(ifn, ifp->ctx->ifaces, next) {
2963 		if (ifn == ifp)
2964 			continue;
2965 		state = D_CSTATE(ifn);
2966 		if (state == NULL || state->state == DHS_NONE)
2967 			continue;
2968 		if (state->xid != xid)
2969 			continue;
2970 		if (ifn->hwlen <= sizeof(bootp->chaddr) &&
2971 		    memcmp(bootp->chaddr, ifn->hwaddr, ifn->hwlen))
2972 			continue;
2973 		logdebugx("%s: redirecting DHCP message to %s",
2974 		    ifp->name, ifn->name);
2975 		dhcp_handledhcp(ifn, bootp, bootp_len, from);
2976 	}
2977 }
2978 
2979 static void
dhcp_handledhcp(struct interface * ifp,struct bootp * bootp,size_t bootp_len,const struct in_addr * from)2980 dhcp_handledhcp(struct interface *ifp, struct bootp *bootp, size_t bootp_len,
2981     const struct in_addr *from)
2982 {
2983 	struct dhcp_state *state = D_STATE(ifp);
2984 	struct if_options *ifo = ifp->options;
2985 	struct dhcp_lease *lease = &state->lease;
2986 	uint8_t type, tmp;
2987 	struct in_addr addr;
2988 	unsigned int i;
2989 	char *msg;
2990 	bool bootp_copied;
2991 	uint32_t v6only_time = 0;
2992 	bool use_v6only = false;
2993 #ifdef AUTH
2994 	const uint8_t *auth;
2995 	size_t auth_len;
2996 #endif
2997 #ifdef IN_IFF_DUPLICATED
2998 	struct ipv4_addr *ia;
2999 #endif
3000 
3001 #define LOGDHCP0(l, m) \
3002 	log_dhcp((l), (m), ifp, bootp, bootp_len, from, 0)
3003 #define LOGDHCP(l, m) \
3004 	log_dhcp((l), (m), ifp, bootp, bootp_len, from, 1)
3005 
3006 #define IS_STATE_ACTIVE(s) ((s)-state != DHS_NONE && \
3007 	(s)->state != DHS_INIT && (s)->state != DHS_BOUND)
3008 
3009 	if (bootp->op != BOOTREPLY) {
3010 		if (IS_STATE_ACTIVE(state))
3011 			logdebugx("%s: op (%d) is not BOOTREPLY",
3012 			    ifp->name, bootp->op);
3013 		return;
3014 	}
3015 
3016 	if (state->xid != ntohl(bootp->xid)) {
3017 		if (IS_STATE_ACTIVE(state))
3018 			logdebugx("%s: wrong xid 0x%x (expecting 0x%x) from %s",
3019 			    ifp->name, ntohl(bootp->xid), state->xid,
3020 			    inet_ntoa(*from));
3021 		dhcp_redirect_dhcp(ifp, bootp, bootp_len, from);
3022 		return;
3023 	}
3024 
3025 	if (ifp->hwlen <= sizeof(bootp->chaddr) &&
3026 	    memcmp(bootp->chaddr, ifp->hwaddr, ifp->hwlen))
3027 	{
3028 		if (IS_STATE_ACTIVE(state)) {
3029 			char buf[sizeof(bootp->chaddr) * 3];
3030 
3031 			logdebugx("%s: xid 0x%x is for hwaddr %s",
3032 			    ifp->name, ntohl(bootp->xid),
3033 			    hwaddr_ntoa(bootp->chaddr, sizeof(bootp->chaddr),
3034 				    buf, sizeof(buf)));
3035 		}
3036 		dhcp_redirect_dhcp(ifp, bootp, bootp_len, from);
3037 		return;
3038 	}
3039 
3040 	if (!ifp->active)
3041 		return;
3042 
3043 	i = whitelisted_ip(ifp->options, from->s_addr);
3044 	switch (i) {
3045 	case WHTLST_NOMATCH:
3046 		logwarnx("%s: non whitelisted DHCP packet from %s",
3047 		    ifp->name, inet_ntoa(*from));
3048 		return;
3049 	case WHTLST_MATCH:
3050 		break;
3051 	case WHTLST_NONE:
3052 		if (blacklisted_ip(ifp->options, from->s_addr) == 1) {
3053 			logwarnx("%s: blacklisted DHCP packet from %s",
3054 			    ifp->name, inet_ntoa(*from));
3055 			return;
3056 		}
3057 	}
3058 
3059 	/* We may have found a BOOTP server */
3060 	if (get_option_uint8(ifp->ctx, &type,
3061 	    bootp, bootp_len, DHO_MESSAGETYPE) == -1)
3062 		type = 0;
3063 	else if (ifo->options & DHCPCD_BOOTP) {
3064 		logdebugx("%s: ignoring DHCP reply (expecting BOOTP)",
3065 		    ifp->name);
3066 		return;
3067 	}
3068 
3069 #ifdef AUTH
3070 	/* Authenticate the message */
3071 	auth = get_option(ifp->ctx, bootp, bootp_len,
3072 	    DHO_AUTHENTICATION, &auth_len);
3073 	if (auth) {
3074 		if (dhcp_auth_validate(&state->auth, &ifo->auth,
3075 		    (uint8_t *)bootp, bootp_len, 4, type,
3076 		    auth, auth_len) == NULL)
3077 		{
3078 			LOGDHCP0(LOG_ERR, "authentication failed");
3079 			return;
3080 		}
3081 		if (state->auth.token)
3082 			logdebugx("%s: validated using 0x%08" PRIu32,
3083 			    ifp->name, state->auth.token->secretid);
3084 		else
3085 			loginfox("%s: accepted reconfigure key", ifp->name);
3086 	} else if (ifo->auth.options & DHCPCD_AUTH_SEND) {
3087 		if (ifo->auth.options & DHCPCD_AUTH_REQUIRE) {
3088 			LOGDHCP0(LOG_ERR, "no authentication");
3089 			return;
3090 		}
3091 		LOGDHCP0(LOG_WARNING, "no authentication");
3092 	}
3093 #endif
3094 
3095 	/* RFC 3203 */
3096 	if (type == DHCP_FORCERENEW) {
3097 		if (from->s_addr == INADDR_ANY ||
3098 		    from->s_addr == INADDR_BROADCAST)
3099 		{
3100 			LOGDHCP(LOG_ERR, "discarding Force Renew");
3101 			return;
3102 		}
3103 #ifdef AUTH
3104 		if (auth == NULL) {
3105 			LOGDHCP(LOG_ERR, "unauthenticated Force Renew");
3106 			if (ifo->auth.options & DHCPCD_AUTH_REQUIRE)
3107 				return;
3108 		}
3109 		if (state->state != DHS_BOUND && state->state != DHS_INFORM) {
3110 			LOGDHCP(LOG_DEBUG, "not bound, ignoring Force Renew");
3111 			return;
3112 		}
3113 		LOGDHCP(LOG_INFO, "Force Renew from");
3114 		/* The rebind and expire timings are still the same, we just
3115 		 * enter the renew state early */
3116 		if (state->state == DHS_BOUND)
3117 			dhcp_renew(ifp);
3118 		else {
3119 			eloop_timeout_delete(ifp->ctx->eloop,
3120 			    send_inform, ifp);
3121 			dhcp_inform(ifp);
3122 		}
3123 #else
3124 		LOGDHCP(LOG_ERR, "unauthenticated Force Renew");
3125 #endif
3126 		return;
3127 	}
3128 
3129 	if (state->state == DHS_BOUND) {
3130 		LOGDHCP(LOG_DEBUG, "bound, ignoring");
3131 		return;
3132 	}
3133 
3134 	if (state->state == DHS_PROBE) {
3135 		/* Ignore any DHCP messages whilst probing a lease to bind. */
3136 		LOGDHCP(LOG_DEBUG, "probing, ignoring");
3137 		return;
3138 	}
3139 
3140 	/* reset the message counter */
3141 	state->interval = 0;
3142 
3143 	/* Ensure that no reject options are present */
3144 	for (i = 1; i < 255; i++) {
3145 		if (has_option_mask(ifo->rejectmask, i) &&
3146 		    get_option_uint8(ifp->ctx, &tmp,
3147 		    bootp, bootp_len, (uint8_t)i) == 0)
3148 		{
3149 			LOGDHCP(LOG_WARNING, "reject DHCP");
3150 			return;
3151 		}
3152 	}
3153 
3154 	if (type == DHCP_NAK) {
3155 		/* For NAK, only check if we require the ServerID */
3156 		if (has_option_mask(ifo->requiremask, DHO_SERVERID) &&
3157 		    get_option_addr(ifp->ctx, &addr,
3158 		    bootp, bootp_len, DHO_SERVERID) == -1)
3159 		{
3160 			LOGDHCP(LOG_WARNING, "reject NAK");
3161 			return;
3162 		}
3163 
3164 		/* We should restart on a NAK */
3165 		LOGDHCP(LOG_WARNING, "NAK:");
3166 		if ((msg = get_option_string(ifp->ctx,
3167 		    bootp, bootp_len, DHO_MESSAGE)))
3168 		{
3169 			logwarnx("%s: message: %s", ifp->name, msg);
3170 			free(msg);
3171 		}
3172 		if (state->state == DHS_INFORM) /* INFORM should not be NAKed */
3173 			return;
3174 		if (!(ifp->ctx->options & DHCPCD_TEST)) {
3175 			dhcp_drop(ifp, "NAK");
3176 			dhcp_unlink(ifp->ctx, state->leasefile);
3177 		}
3178 
3179 		/* If we constantly get NAKS then we should slowly back off */
3180 		eloop_timeout_add_sec(ifp->ctx->eloop,
3181 		    state->nakoff, dhcp_discover, ifp);
3182 		if (state->nakoff == 0)
3183 			state->nakoff = 1;
3184 		else {
3185 			state->nakoff *= 2;
3186 			if (state->nakoff > NAKOFF_MAX)
3187 				state->nakoff = NAKOFF_MAX;
3188 		}
3189 		return;
3190 	}
3191 
3192 	/* Ensure that all required options are present */
3193 	for (i = 1; i < 255; i++) {
3194 		if (has_option_mask(ifo->requiremask, i) &&
3195 		    get_option_uint8(ifp->ctx, &tmp,
3196 		    bootp, bootp_len, (uint8_t)i) != 0)
3197 		{
3198 			/* If we are BOOTP, then ignore the need for serverid.
3199 			 * To ignore BOOTP, require dhcp_message_type.
3200 			 * However, nothing really stops BOOTP from providing
3201 			 * DHCP style options as well so the above isn't
3202 			 * always true. */
3203 			if (type == 0 && i == DHO_SERVERID)
3204 				continue;
3205 			LOGDHCP(LOG_WARNING, "reject DHCP");
3206 			return;
3207 		}
3208 	}
3209 
3210 	if (has_option_mask(ifo->requestmask, DHO_IPV6_PREFERRED_ONLY)) {
3211 		if (get_option_uint32(ifp->ctx, &v6only_time, bootp, bootp_len,
3212 		    DHO_IPV6_PREFERRED_ONLY) == 0 && (state->state == DHS_DISCOVER ||
3213 		    state->state == DHS_REBOOT || state->state == DHS_NONE))
3214 		{
3215 			char v6msg[128];
3216 
3217 			use_v6only = true;
3218 			if (v6only_time < MIN_V6ONLY_WAIT)
3219 				v6only_time = MIN_V6ONLY_WAIT;
3220 			snprintf(v6msg, sizeof(v6msg),
3221 			    "IPv6-Only Preferred received (%u seconds)",
3222 			    v6only_time);
3223 			LOGDHCP(LOG_INFO, v6msg);
3224 		}
3225 	}
3226 
3227 	/* DHCP Auto-Configure, RFC 2563 */
3228 	if (type == DHCP_OFFER && bootp->yiaddr == 0) {
3229 		LOGDHCP(LOG_WARNING, "no address given");
3230 		if ((msg = get_option_string(ifp->ctx,
3231 		    bootp, bootp_len, DHO_MESSAGE)))
3232 		{
3233 			logwarnx("%s: message: %s", ifp->name, msg);
3234 			free(msg);
3235 		}
3236 #ifdef IPV4LL
3237 		if (state->state == DHS_DISCOVER &&
3238 		    get_option_uint8(ifp->ctx, &tmp, bootp, bootp_len,
3239 		    DHO_AUTOCONFIGURE) == 0)
3240 		{
3241 			switch (tmp) {
3242 			case 0:
3243 				LOGDHCP(LOG_WARNING, "IPv4LL disabled from");
3244 				ipv4ll_drop(ifp);
3245 #ifdef ARP
3246 				arp_drop(ifp);
3247 #endif
3248 				break;
3249 			case 1:
3250 				LOGDHCP(LOG_WARNING, "IPv4LL enabled from");
3251 				ipv4ll_start(ifp);
3252 				break;
3253 			default:
3254 				logerrx("%s: unknown auto configuration "
3255 				    "option %d",
3256 				    ifp->name, tmp);
3257 				break;
3258 			}
3259 			eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
3260 			eloop_timeout_add_sec(ifp->ctx->eloop,
3261 			    use_v6only ? v6only_time : DHCP_MAX,
3262 			    dhcp_discover, ifp);
3263 		}
3264 #endif
3265 		return;
3266 	}
3267 
3268 	if (use_v6only) {
3269 		dhcp_drop(ifp, "EXPIRE");
3270 		dhcp_unlink(ifp->ctx, state->leasefile);
3271 		eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
3272 		eloop_timeout_add_sec(ifp->ctx->eloop, v6only_time,
3273 		    dhcp_discover, ifp);
3274 		return;
3275 	}
3276 
3277 	/* Ensure that the address offered is valid */
3278 	if ((type == 0 || type == DHCP_OFFER || type == DHCP_ACK) &&
3279 	    (bootp->ciaddr == INADDR_ANY || bootp->ciaddr == INADDR_BROADCAST)
3280 	    &&
3281 	    (bootp->yiaddr == INADDR_ANY || bootp->yiaddr == INADDR_BROADCAST))
3282 	{
3283 		LOGDHCP(LOG_WARNING, "reject invalid address");
3284 		return;
3285 	}
3286 
3287 #ifdef IN_IFF_DUPLICATED
3288 	ia = ipv4_iffindaddr(ifp, &lease->addr, NULL);
3289 	if (ia && ia->addr_flags & IN_IFF_DUPLICATED) {
3290 		LOGDHCP(LOG_WARNING, "declined duplicate address");
3291 		if (type)
3292 			dhcp_decline(ifp);
3293 		ipv4_deladdr(ia, 0);
3294 		eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
3295 		eloop_timeout_add_sec(ifp->ctx->eloop,
3296 		    DHCP_RAND_MAX, dhcp_discover, ifp);
3297 		return;
3298 	}
3299 #endif
3300 
3301 	bootp_copied = false;
3302 	if ((type == 0 || type == DHCP_OFFER) && state->state == DHS_DISCOVER) {
3303 		lease->frominfo = 0;
3304 		lease->addr.s_addr = bootp->yiaddr;
3305 		memcpy(&lease->cookie, bootp->vend, sizeof(lease->cookie));
3306 		if (type == 0 ||
3307 		    get_option_addr(ifp->ctx,
3308 		    &lease->server, bootp, bootp_len, DHO_SERVERID) != 0)
3309 			lease->server.s_addr = INADDR_ANY;
3310 
3311 		/* Test for rapid commit in the OFFER */
3312 		if (!(ifp->ctx->options & DHCPCD_TEST) &&
3313 		    has_option_mask(ifo->requestmask, DHO_RAPIDCOMMIT) &&
3314 		    get_option(ifp->ctx, bootp, bootp_len,
3315 		    DHO_RAPIDCOMMIT, NULL))
3316 		{
3317 			state->state = DHS_REQUEST;
3318 			goto rapidcommit;
3319 		}
3320 
3321 		LOGDHCP(LOG_INFO, "offered");
3322 		if (state->offer_len < bootp_len) {
3323 			free(state->offer);
3324 			if ((state->offer = malloc(bootp_len)) == NULL) {
3325 				logerr(__func__);
3326 				state->offer_len = 0;
3327 				return;
3328 			}
3329 		}
3330 		state->offer_len = bootp_len;
3331 		memcpy(state->offer, bootp, bootp_len);
3332 		bootp_copied = true;
3333 		if (ifp->ctx->options & DHCPCD_TEST) {
3334 			free(state->old);
3335 			state->old = state->new;
3336 			state->old_len = state->new_len;
3337 			state->new = state->offer;
3338 			state->new_len = state->offer_len;
3339 			state->offer = NULL;
3340 			state->offer_len = 0;
3341 			state->reason = "TEST";
3342 			script_runreason(ifp, state->reason);
3343 			eloop_exit(ifp->ctx->eloop, EXIT_SUCCESS);
3344 			if (state->bpf)
3345 				state->bpf->bpf_flags |= BPF_EOF;
3346 			return;
3347 		}
3348 		eloop_timeout_delete(ifp->ctx->eloop, send_discover, ifp);
3349 		/* We don't request BOOTP addresses */
3350 		if (type) {
3351 			/* We used to ARP check here, but that seems to be in
3352 			 * violation of RFC2131 where it only describes
3353 			 * DECLINE after REQUEST.
3354 			 * It also seems that some MS DHCP servers actually
3355 			 * ignore DECLINE if no REQUEST, ie we decline a
3356 			 * DISCOVER. */
3357 			dhcp_request(ifp);
3358 			return;
3359 		}
3360 	}
3361 
3362 	if (type) {
3363 		if (type == DHCP_OFFER) {
3364 			LOGDHCP(LOG_WARNING, "ignoring offer of");
3365 			return;
3366 		}
3367 
3368 		/* We should only be dealing with acks */
3369 		if (type != DHCP_ACK) {
3370 			LOGDHCP(LOG_ERR, "not ACK or OFFER");
3371 			return;
3372 		}
3373 
3374 		if (state->state == DHS_DISCOVER) {
3375 			/* We only allow ACK of rapid commit DISCOVER. */
3376 			if (has_option_mask(ifo->requestmask,
3377 			    DHO_RAPIDCOMMIT) &&
3378 			    get_option(ifp->ctx, bootp, bootp_len,
3379 			    DHO_RAPIDCOMMIT, NULL))
3380 				state->state = DHS_REQUEST;
3381 			else {
3382 				LOGDHCP(LOG_DEBUG, "ignoring ack of");
3383 				return;
3384 			}
3385 		}
3386 
3387 rapidcommit:
3388 		if (!(ifo->options & DHCPCD_INFORM))
3389 			LOGDHCP(LOG_DEBUG, "acknowledged");
3390 		else
3391 		    ifo->options &= ~DHCPCD_STATIC;
3392 	}
3393 
3394 	/* No NAK, so reset the backoff
3395 	 * We don't reset on an OFFER message because the server could
3396 	 * potentially NAK the REQUEST. */
3397 	state->nakoff = 0;
3398 
3399 	/* BOOTP could have already assigned this above. */
3400 	if (!bootp_copied) {
3401 		if (state->offer_len < bootp_len) {
3402 			free(state->offer);
3403 			if ((state->offer = malloc(bootp_len)) == NULL) {
3404 				logerr(__func__);
3405 				state->offer_len = 0;
3406 				return;
3407 			}
3408 		}
3409 		state->offer_len = bootp_len;
3410 		memcpy(state->offer, bootp, bootp_len);
3411 	}
3412 
3413 	lease->frominfo = 0;
3414 	eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
3415 
3416 #if defined(ARP) || defined(KERNEL_RFC5227)
3417 	dhcp_arp_bind(ifp);
3418 #else
3419 	dhcp_bind(ifp);
3420 #endif
3421 }
3422 
3423 static void *
get_udp_data(void * packet,size_t * len)3424 get_udp_data(void *packet, size_t *len)
3425 {
3426 	const struct ip *ip = packet;
3427 	size_t ip_hl = (size_t)ip->ip_hl * 4;
3428 	char *p = packet;
3429 
3430 	p += ip_hl + sizeof(struct udphdr);
3431 	*len = (size_t)ntohs(ip->ip_len) - sizeof(struct udphdr) - ip_hl;
3432 	return p;
3433 }
3434 
3435 static bool
is_packet_udp_bootp(void * packet,size_t plen)3436 is_packet_udp_bootp(void *packet, size_t plen)
3437 {
3438 	struct ip *ip = packet;
3439 	size_t ip_hlen;
3440 	struct udphdr udp;
3441 
3442 	if (plen < sizeof(*ip))
3443 		return false;
3444 
3445 	if (ip->ip_v != IPVERSION || ip->ip_p != IPPROTO_UDP)
3446 		return false;
3447 
3448 	/* Sanity. */
3449 	if (ntohs(ip->ip_len) > plen)
3450 		return false;
3451 
3452 	ip_hlen = (size_t)ip->ip_hl * 4;
3453 	if (ip_hlen < sizeof(*ip))
3454 		return false;
3455 
3456 	/* Check we have a UDP header and BOOTP. */
3457 	if (ip_hlen + sizeof(udp) + offsetof(struct bootp, vend) > plen)
3458 		return false;
3459 
3460 	/* Sanity. */
3461 	memcpy(&udp, (char *)ip + ip_hlen, sizeof(udp));
3462 	if (ntohs(udp.uh_ulen) < sizeof(udp))
3463 		return false;
3464 	if (ip_hlen + ntohs(udp.uh_ulen) > plen)
3465 		return false;
3466 
3467 	/* Check it's to the right port. */
3468 	if (udp.uh_dport != htons(BOOTPC))
3469 		return false;
3470 
3471 	return true;
3472 }
3473 
3474 /* Lengths have already been checked. */
3475 static bool
checksums_valid(void * packet,struct in_addr * from,unsigned int flags)3476 checksums_valid(void *packet,
3477     struct in_addr *from, unsigned int flags)
3478 {
3479 	struct ip *ip = packet;
3480 	union pip {
3481 		struct ip ip;
3482 		uint16_t w[sizeof(struct ip) / 2];
3483 	} pip = {
3484 		.ip = {
3485 			.ip_p = IPPROTO_UDP,
3486 			.ip_src = ip->ip_src,
3487 			.ip_dst = ip->ip_dst,
3488 		}
3489 	};
3490 	size_t ip_hlen;
3491 	struct udphdr udp;
3492 	char *udpp, *uh_sump;
3493 	uint32_t csum;
3494 
3495 	if (from != NULL)
3496 		from->s_addr = ip->ip_src.s_addr;
3497 
3498 	ip_hlen = (size_t)ip->ip_hl * 4;
3499 	if (in_cksum(ip, ip_hlen, NULL) != 0)
3500 		return false;
3501 
3502 	if (flags & BPF_PARTIALCSUM)
3503 		return true;
3504 
3505 	udpp = (char *)ip + ip_hlen;
3506 	memcpy(&udp, udpp, sizeof(udp));
3507 	if (udp.uh_sum == 0)
3508 		return true;
3509 
3510 	/* UDP checksum is based on a pseudo IP header alongside
3511 	 * the UDP header and payload. */
3512 	pip.ip.ip_len = udp.uh_ulen;
3513 	csum = 0;
3514 
3515 	/* Need to zero the UDP sum in the packet for the checksum to work. */
3516 	uh_sump = udpp + offsetof(struct udphdr, uh_sum);
3517 	memset(uh_sump, 0, sizeof(udp.uh_sum));
3518 
3519 	/* Checksum pseudo header and then UDP + payload. */
3520 	in_cksum(pip.w, sizeof(pip.w), &csum);
3521 	csum = in_cksum(udpp, ntohs(udp.uh_ulen), &csum);
3522 
3523 #if 0	/* Not needed, just here for completeness. */
3524 	/* Put the checksum back. */
3525 	memcpy(uh_sump, &udp.uh_sum, sizeof(udp.uh_sum));
3526 #endif
3527 
3528 	return csum == udp.uh_sum;
3529 }
3530 
3531 static void
dhcp_handlebootp(struct interface * ifp,struct bootp * bootp,size_t len,struct in_addr * from)3532 dhcp_handlebootp(struct interface *ifp, struct bootp *bootp, size_t len,
3533     struct in_addr *from)
3534 {
3535 	size_t v;
3536 
3537 	/* Unlikely, but appeases sanitizers. */
3538 	if (len > FRAMELEN_MAX) {
3539 		logerrx("%s: packet exceeded frame length (%zu) from %s",
3540 		    ifp->name, len, inet_ntoa(*from));
3541 		return;
3542 	}
3543 
3544 	/* To make our IS_DHCP macro easy, ensure the vendor
3545 	 * area has at least 4 octets. */
3546 	v = len - offsetof(struct bootp, vend);
3547 	while (v < 4) {
3548 		bootp->vend[v++] = '\0';
3549 		len++;
3550 	}
3551 
3552 	dhcp_handledhcp(ifp, bootp, len, from);
3553 }
3554 
3555 void
dhcp_packet(struct interface * ifp,uint8_t * data,size_t len,unsigned int bpf_flags)3556 dhcp_packet(struct interface *ifp, uint8_t *data, size_t len,
3557     unsigned int bpf_flags)
3558 {
3559 	struct bootp *bootp;
3560 	struct in_addr from;
3561 	size_t udp_len;
3562 	size_t fl = bpf_frame_header_len(ifp);
3563 #ifdef PRIVSEP
3564 	const struct dhcp_state *state = D_CSTATE(ifp);
3565 
3566 	/* It's possible that an interface departs and arrives in short
3567 	 * order to receive a BPF frame out of order.
3568 	 * There is a similar check in ARP, but much lower down the stack.
3569 	 * It's not needed for other inet protocols because we send the
3570 	 * message as a whole and select the interface off that and then
3571 	 * check state. BPF on the other hand is very interface
3572 	 * specific and we do need this check. */
3573 	if (state == NULL)
3574 		return;
3575 
3576 	/* Ignore double reads */
3577 	if (IN_PRIVSEP(ifp->ctx)) {
3578 		switch (state->state) {
3579 		case DHS_BOUND: /* FALLTHROUGH */
3580 		case DHS_RENEW:
3581 			return;
3582 		default:
3583 			break;
3584 		}
3585 	}
3586 #endif
3587 
3588 	/* Trim frame header */
3589 	if (fl != 0) {
3590 		if (len < fl) {
3591 			logerrx("%s: %s: short frame header %zu",
3592 			    __func__, ifp->name, len);
3593 			return;
3594 		}
3595 		len -= fl;
3596 		/* Move the data to avoid alignment errors. */
3597 		memmove(data, data + fl, len);
3598 	}
3599 
3600 	/* Validate filter. */
3601 	if (!is_packet_udp_bootp(data, len)) {
3602 #ifdef BPF_DEBUG
3603 		logerrx("%s: DHCP BPF validation failure", ifp->name);
3604 #endif
3605 		return;
3606 	}
3607 
3608 	if (!checksums_valid(data, &from, bpf_flags)) {
3609 		logerrx("%s: checksum failure from %s",
3610 		    ifp->name, inet_ntoa(from));
3611 		return;
3612 	}
3613 
3614 	/*
3615 	 * DHCP has a variable option area rather than a fixed vendor area.
3616 	 * Because DHCP uses the BOOTP protocol it should still send BOOTP
3617 	 * sized packets to be RFC compliant.
3618 	 * However some servers send a truncated vendor area.
3619 	 * dhcpcd can work fine without the vendor area being sent.
3620 	 */
3621 	bootp = get_udp_data(data, &udp_len);
3622 	dhcp_handlebootp(ifp, bootp, udp_len, &from);
3623 }
3624 
3625 static void
dhcp_readbpf(void * arg,unsigned short events)3626 dhcp_readbpf(void *arg, unsigned short events)
3627 {
3628 	struct interface *ifp = arg;
3629 	uint8_t buf[FRAMELEN_MAX];
3630 	ssize_t bytes;
3631 	struct dhcp_state *state = D_STATE(ifp);
3632 	struct bpf *bpf = state->bpf;
3633 
3634 	if (events != ELE_READ)
3635 		logerrx("%s: unexpected event 0x%04x", __func__, events);
3636 
3637 	bpf->bpf_flags &= ~BPF_EOF;
3638 	while (!(bpf->bpf_flags & BPF_EOF)) {
3639 		bytes = bpf_read(bpf, buf, sizeof(buf));
3640 		if (bytes == -1) {
3641 			if (state->state != DHS_NONE) {
3642 				logerr("%s: %s", __func__, ifp->name);
3643 				dhcp_close(ifp);
3644 			}
3645 			break;
3646 		}
3647 		dhcp_packet(ifp, buf, (size_t)bytes, bpf->bpf_flags);
3648 		/* Check we still have a state after processing. */
3649 		if ((state = D_STATE(ifp)) == NULL)
3650 			break;
3651 		if ((bpf = state->bpf) == NULL)
3652 			break;
3653 	}
3654 }
3655 
3656 void
dhcp_recvmsg(struct dhcpcd_ctx * ctx,struct msghdr * msg)3657 dhcp_recvmsg(struct dhcpcd_ctx *ctx, struct msghdr *msg)
3658 {
3659 	struct sockaddr_in *from = (struct sockaddr_in *)msg->msg_name;
3660 	struct iovec *iov = &msg->msg_iov[0];
3661 	struct interface *ifp;
3662 	const struct dhcp_state *state;
3663 
3664 	ifp = if_findifpfromcmsg(ctx, msg, NULL);
3665 	if (ifp == NULL) {
3666 		logerr(__func__);
3667 		return;
3668 	}
3669 
3670 	if (iov->iov_len < offsetof(struct bootp, vend)) {
3671 		logerrx("%s: truncated packet (%zu) from %s",
3672 		    ifp->name, iov->iov_len, inet_ntoa(from->sin_addr));
3673 		return;
3674 	}
3675 
3676 	state = D_CSTATE(ifp);
3677 	if (state == NULL) {
3678 		/* Try re-directing it to another interface. */
3679 		dhcp_redirect_dhcp(ifp, (struct bootp *)iov->iov_base,
3680 		    iov->iov_len, &from->sin_addr);
3681 		return;
3682 	}
3683 
3684 	if (state->bpf != NULL) {
3685 		/* Avoid a duplicate read if BPF is open for the interface. */
3686 		return;
3687 	}
3688 #ifdef PRIVSEP
3689 	if (IN_PRIVSEP(ctx)) {
3690 		switch (state->state) {
3691 		case DHS_BOUND: /* FALLTHROUGH */
3692 		case DHS_RENEW:
3693 			break;
3694 		default:
3695 			/* Any other state we ignore it or will receive
3696 			 * via BPF. */
3697 			return;
3698 		}
3699 	}
3700 #endif
3701 
3702 	dhcp_handlebootp(ifp, iov->iov_base, iov->iov_len,
3703 	    &from->sin_addr);
3704 }
3705 
3706 static void
dhcp_readudp(struct dhcpcd_ctx * ctx,struct interface * ifp,unsigned short events)3707 dhcp_readudp(struct dhcpcd_ctx *ctx, struct interface *ifp,
3708     unsigned short events)
3709 {
3710 	const struct dhcp_state *state;
3711 	struct sockaddr_in from;
3712 	union {
3713 		struct bootp bootp;
3714 		uint8_t buf[10 * 1024]; /* Maximum MTU */
3715 	} iovbuf;
3716 	struct iovec iov = {
3717 		.iov_base = iovbuf.buf,
3718 		.iov_len = sizeof(iovbuf.buf),
3719 	};
3720 	union {
3721 		struct cmsghdr hdr;
3722 #ifdef IP_RECVIF
3723 		uint8_t buf[CMSG_SPACE(sizeof(struct sockaddr_dl))];
3724 #else
3725 		uint8_t buf[CMSG_SPACE(sizeof(struct in_pktinfo))];
3726 #endif
3727 	} cmsgbuf = { .buf = { 0 } };
3728 	struct msghdr msg = {
3729 	    .msg_name = &from, .msg_namelen = sizeof(from),
3730 	    .msg_iov = &iov, .msg_iovlen = 1,
3731 	    .msg_control = cmsgbuf.buf, .msg_controllen = sizeof(cmsgbuf.buf),
3732 	};
3733 	int s;
3734 	ssize_t bytes;
3735 
3736 	if (events != ELE_READ)
3737 		logerrx("%s: unexpected event 0x%04x", __func__, events);
3738 
3739 	if (ifp != NULL) {
3740 		state = D_CSTATE(ifp);
3741 		s = state->udp_rfd;
3742 	} else
3743 		s = ctx->udp_rfd;
3744 
3745 	bytes = recvmsg(s, &msg, 0);
3746 	if (bytes == -1) {
3747 		logerr(__func__);
3748 		return;
3749 	}
3750 
3751 	iov.iov_len = (size_t)bytes;
3752 	dhcp_recvmsg(ctx, &msg);
3753 }
3754 
3755 static void
dhcp_handleudp(void * arg,unsigned short events)3756 dhcp_handleudp(void *arg, unsigned short events)
3757 {
3758 	struct dhcpcd_ctx *ctx = arg;
3759 
3760 	dhcp_readudp(ctx, NULL, events);
3761 }
3762 
3763 static void
dhcp_handleifudp(void * arg,unsigned short events)3764 dhcp_handleifudp(void *arg, unsigned short events)
3765 {
3766 	struct interface *ifp = arg;
3767 
3768 	dhcp_readudp(ifp->ctx, ifp, events);
3769 }
3770 
3771 static int
dhcp_openbpf(struct interface * ifp)3772 dhcp_openbpf(struct interface *ifp)
3773 {
3774 	struct dhcp_state *state;
3775 
3776 	state = D_STATE(ifp);
3777 
3778 #ifdef PRIVSEP
3779 	if (IN_PRIVSEP_SE(ifp->ctx)) {
3780 		if (ps_bpf_openbootp(ifp) == -1) {
3781 			logerr(__func__);
3782 			return -1;
3783 		}
3784 		return 0;
3785 	}
3786 #endif
3787 
3788 	if (state->bpf != NULL)
3789 		return 0;
3790 
3791 	state->bpf = bpf_open(ifp, bpf_bootp, NULL);
3792 	if (state->bpf == NULL) {
3793 		if (errno == ENOENT) {
3794 			logerrx("%s not found", bpf_name);
3795 			/* May as well disable IPv4 entirely at
3796 			 * this point as we really need it. */
3797 			ifp->options->options &= ~DHCPCD_IPV4;
3798 		} else
3799 			logerr("%s: %s", __func__, ifp->name);
3800 		return -1;
3801 	}
3802 
3803 	if (eloop_event_add(ifp->ctx->eloop, state->bpf->bpf_fd, ELE_READ,
3804 	    dhcp_readbpf, ifp) == -1)
3805 		logerr("%s: eloop_event_add", __func__);
3806 	return 0;
3807 }
3808 
3809 void
dhcp_free(struct interface * ifp)3810 dhcp_free(struct interface *ifp)
3811 {
3812 	struct dhcp_state *state = D_STATE(ifp);
3813 	struct dhcpcd_ctx *ctx;
3814 
3815 	dhcp_close(ifp);
3816 #ifdef ARP
3817 	arp_drop(ifp);
3818 #endif
3819 	if (state) {
3820 		state->state = DHS_NONE;
3821 		free(state->old);
3822 		free(state->new);
3823 		free(state->offer);
3824 		free(state->clientid);
3825 		free(state);
3826 	}
3827 
3828 	ctx = ifp->ctx;
3829 	/* If we don't have any more DHCP enabled interfaces,
3830 	 * close the global socket and release resources */
3831 	if (ctx->ifaces) {
3832 		TAILQ_FOREACH(ifp, ctx->ifaces, next) {
3833 			state = D_STATE(ifp);
3834 			if (state != NULL && state->state != DHS_NONE)
3835 				break;
3836 		}
3837 	}
3838 	if (ifp == NULL) {
3839 		if (ctx->udp_rfd != -1) {
3840 			eloop_event_delete(ctx->eloop, ctx->udp_rfd);
3841 			close(ctx->udp_rfd);
3842 			ctx->udp_rfd = -1;
3843 		}
3844 		if (ctx->udp_wfd != -1) {
3845 			close(ctx->udp_wfd);
3846 			ctx->udp_wfd = -1;
3847 		}
3848 
3849 		free(ctx->opt_buffer);
3850 		ctx->opt_buffer = NULL;
3851 		ctx->opt_buffer_len = 0;
3852 	}
3853 }
3854 
3855 static int
dhcp_initstate(struct interface * ifp)3856 dhcp_initstate(struct interface *ifp)
3857 {
3858 	struct dhcp_state *state;
3859 
3860 	state = D_STATE(ifp);
3861 	if (state != NULL)
3862 		return 0;
3863 
3864 	ifp->if_data[IF_DATA_DHCP] = calloc(1, sizeof(*state));
3865 	state = D_STATE(ifp);
3866 	if (state == NULL)
3867 		return -1;
3868 
3869 	state->state = DHS_NONE;
3870 	/* 0 is a valid fd, so init to -1 */
3871 	state->udp_rfd = -1;
3872 #ifdef ARPING
3873 	state->arping_index = -1;
3874 #endif
3875 	return 1;
3876 }
3877 
3878 static int
dhcp_init(struct interface * ifp)3879 dhcp_init(struct interface *ifp)
3880 {
3881 	struct dhcp_state *state;
3882 	struct if_options *ifo;
3883 	uint8_t len;
3884 	char buf[(sizeof(ifo->clientid) - 1) * 3];
3885 
3886 	if (dhcp_initstate(ifp) == -1)
3887 		return -1;
3888 
3889 	state = D_STATE(ifp);
3890 	state->state = DHS_INIT;
3891 	state->reason = "PREINIT";
3892 	state->nakoff = 0;
3893 	dhcp_set_leasefile(state->leasefile, sizeof(state->leasefile),
3894 	    AF_INET, ifp);
3895 
3896 	ifo = ifp->options;
3897 	/* We need to drop the leasefile so that dhcp_start
3898 	 * doesn't load it. */
3899 	if (ifo->options & DHCPCD_REQUEST)
3900 		dhcp_unlink(ifp->ctx, state->leasefile);
3901 
3902 	free(state->clientid);
3903 	state->clientid = NULL;
3904 
3905 	if (ifo->options & DHCPCD_ANONYMOUS) {
3906 		/* Removing the option could show that we want anonymous.
3907 		 * As such keep it as it's already in the hwaddr field. */
3908 		goto make_clientid;
3909 	} else if (*ifo->clientid) {
3910 		state->clientid = malloc((size_t)(ifo->clientid[0] + 1));
3911 		if (state->clientid == NULL)
3912 			goto eexit;
3913 		memcpy(state->clientid, ifo->clientid,
3914 		    (size_t)(ifo->clientid[0]) + 1);
3915 	} else if (ifo->options & DHCPCD_CLIENTID) {
3916 		if (ifo->options & DHCPCD_DUID) {
3917 			state->clientid = malloc(ifp->ctx->duid_len + 6);
3918 			if (state->clientid == NULL)
3919 				goto eexit;
3920 			state->clientid[0] =(uint8_t)(ifp->ctx->duid_len + 5);
3921 			state->clientid[1] = 255; /* RFC 4361 */
3922 			memcpy(state->clientid + 2, ifo->iaid, 4);
3923 			memcpy(state->clientid + 6, ifp->ctx->duid,
3924 			    ifp->ctx->duid_len);
3925 		} else {
3926 make_clientid:
3927 			len = (uint8_t)(ifp->hwlen + 1);
3928 			state->clientid = malloc((size_t)len + 1);
3929 			if (state->clientid == NULL)
3930 				goto eexit;
3931 			state->clientid[0] = len;
3932 			state->clientid[1] = (uint8_t)ifp->hwtype;
3933 			memcpy(state->clientid + 2, ifp->hwaddr,
3934 			    ifp->hwlen);
3935 		}
3936 	}
3937 
3938 	if (ifo->options & DHCPCD_DUID)
3939 		/* Don't bother logging as DUID and IAID are reported
3940 		 * at device start. */
3941 		return 0;
3942 
3943 	if (ifo->options & DHCPCD_CLIENTID && state->clientid != NULL)
3944 		logdebugx("%s: using ClientID %s", ifp->name,
3945 		    hwaddr_ntoa(state->clientid + 1, state->clientid[0],
3946 			buf, sizeof(buf)));
3947 	else if (ifp->hwlen)
3948 		logdebugx("%s: using hwaddr %s", ifp->name,
3949 		    hwaddr_ntoa(ifp->hwaddr, ifp->hwlen, buf, sizeof(buf)));
3950 	return 0;
3951 
3952 eexit:
3953 	logerr(__func__);
3954 	return -1;
3955 }
3956 
3957 static void
dhcp_start1(void * arg)3958 dhcp_start1(void *arg)
3959 {
3960 	struct interface *ifp = arg;
3961 	struct dhcpcd_ctx *ctx = ifp->ctx;
3962 	struct if_options *ifo = ifp->options;
3963 	struct dhcp_state *state;
3964 	uint32_t l;
3965 	int nolease;
3966 
3967 	if (!(ifo->options & DHCPCD_IPV4))
3968 		return;
3969 
3970 	/* Listen on *.*.*.*:bootpc so that the kernel never sends an
3971 	 * ICMP port unreachable message back to the DHCP server.
3972 	 * Only do this in manager mode so we don't swallow messages
3973 	 * for dhcpcd running on another interface. */
3974 	if ((ctx->options & (DHCPCD_MANAGER|DHCPCD_PRIVSEP)) == DHCPCD_MANAGER
3975 	    && ctx->udp_rfd == -1)
3976 	{
3977 		ctx->udp_rfd = dhcp_openudp(NULL);
3978 		if (ctx->udp_rfd == -1) {
3979 			logerr(__func__);
3980 			return;
3981 		}
3982 		if (eloop_event_add(ctx->eloop, ctx->udp_rfd, ELE_READ,
3983 		    dhcp_handleudp, ctx) == -1)
3984 			logerr("%s: eloop_event_add", __func__);
3985 	}
3986 	if (!IN_PRIVSEP(ctx) && ctx->udp_wfd == -1) {
3987 		ctx->udp_wfd = xsocket(PF_INET, SOCK_RAW|SOCK_CXNB,IPPROTO_UDP);
3988 		if (ctx->udp_wfd == -1) {
3989 			logerr(__func__);
3990 			return;
3991 		}
3992 	}
3993 
3994 	if (dhcp_init(ifp) == -1) {
3995 		logerr("%s: dhcp_init", ifp->name);
3996 		return;
3997 	}
3998 
3999 	state = D_STATE(ifp);
4000 	clock_gettime(CLOCK_MONOTONIC, &state->started);
4001 	state->interval = 0;
4002 	free(state->offer);
4003 	state->offer = NULL;
4004 	state->offer_len = 0;
4005 
4006 #ifdef ARPING
4007 	if (ifo->arping_len && state->arping_index < ifo->arping_len) {
4008 		dhcp_arping(ifp);
4009 		return;
4010 	}
4011 #endif
4012 
4013 	if (ifo->options & DHCPCD_STATIC) {
4014 		dhcp_static(ifp);
4015 		return;
4016 	}
4017 
4018 	if (ifo->options & DHCPCD_INFORM) {
4019 		dhcp_inform(ifp);
4020 		return;
4021 	}
4022 
4023 	/* We don't want to read the old lease if we NAK an old test */
4024 	nolease = state->offer && ifp->ctx->options & DHCPCD_TEST;
4025 	if (!nolease && ifo->options & DHCPCD_DHCP) {
4026 		state->offer_len = read_lease(ifp, &state->offer);
4027 		/* Check the saved lease matches the type we want */
4028 		if (state->offer) {
4029 #ifdef IN_IFF_DUPLICATED
4030 			struct in_addr addr;
4031 			struct ipv4_addr *ia;
4032 
4033 			addr.s_addr = state->offer->yiaddr;
4034 			ia = ipv4_iffindaddr(ifp, &addr, NULL);
4035 #endif
4036 
4037 			if ((!IS_DHCP(state->offer) &&
4038 			    !(ifo->options & DHCPCD_BOOTP)) ||
4039 #ifdef IN_IFF_DUPLICATED
4040 			    (ia && ia->addr_flags & IN_IFF_DUPLICATED) ||
4041 #endif
4042 			    (IS_DHCP(state->offer) &&
4043 			    ifo->options & DHCPCD_BOOTP))
4044 			{
4045 				free(state->offer);
4046 				state->offer = NULL;
4047 				state->offer_len = 0;
4048 			}
4049 		}
4050 	}
4051 	if (state->offer) {
4052 		struct ipv4_addr *ia;
4053 		time_t mtime;
4054 
4055 		get_lease(ifp, &state->lease, state->offer, state->offer_len);
4056 		state->lease.frominfo = 1;
4057 		if (state->new == NULL &&
4058 		    (ia = ipv4_iffindaddr(ifp,
4059 		    &state->lease.addr, &state->lease.mask)) != NULL)
4060 		{
4061 			/* We still have the IP address from the last lease.
4062 			 * Fake add the address and routes from it so the lease
4063 			 * can be cleaned up. */
4064 			state->new = malloc(state->offer_len);
4065 			if (state->new) {
4066 				memcpy(state->new,
4067 				    state->offer, state->offer_len);
4068 				state->new_len = state->offer_len;
4069 				state->addr = ia;
4070 				state->added |= STATE_ADDED | STATE_FAKE;
4071 				rt_build(ifp->ctx, AF_INET);
4072 			} else
4073 				logerr(__func__);
4074 		}
4075 		if (!IS_DHCP(state->offer)) {
4076 			free(state->offer);
4077 			state->offer = NULL;
4078 			state->offer_len = 0;
4079 		} else if (!(ifo->options & DHCPCD_LASTLEASE_EXTEND) &&
4080 		    state->lease.leasetime != DHCP_INFINITE_LIFETIME &&
4081 		    dhcp_filemtime(ifp->ctx, state->leasefile, &mtime) == 0)
4082 		{
4083 			time_t now;
4084 
4085 			/* Offset lease times and check expiry */
4086 			now = time(NULL);
4087 			if (now == -1 ||
4088 			    (time_t)state->lease.leasetime < now - mtime)
4089 			{
4090 				logdebugx("%s: discarding expired lease",
4091 				    ifp->name);
4092 				free(state->offer);
4093 				state->offer = NULL;
4094 				state->offer_len = 0;
4095 				state->lease.addr.s_addr = 0;
4096 				/* Technically we should discard the lease
4097 				 * as it's expired, just as DHCPv6 addresses
4098 				 * would be by the kernel.
4099 				 * However, this may violate POLA so
4100 				 * we currently leave it be.
4101 				 * If we get a totally different lease from
4102 				 * the DHCP server we'll drop it anyway, as
4103 				 * we will on any other event which would
4104 				 * trigger a lease drop.
4105 				 * This should only happen if dhcpcd stops
4106 				 * running and the lease expires before
4107 				 * dhcpcd starts again. */
4108 #if 0
4109 				if (state->new)
4110 					dhcp_drop(ifp, "EXPIRE");
4111 #endif
4112 			} else {
4113 				l = (uint32_t)(now - mtime);
4114 				state->lease.leasetime -= l;
4115 				state->lease.renewaltime -= l;
4116 				state->lease.rebindtime -= l;
4117 			}
4118 		}
4119 	}
4120 
4121 #ifdef IPV4LL
4122 	if (!(ifo->options & DHCPCD_DHCP)) {
4123 		if (ifo->options & DHCPCD_IPV4LL)
4124 			ipv4ll_start(ifp);
4125 		return;
4126 	}
4127 #endif
4128 
4129 	if (state->offer == NULL ||
4130 	    !IS_DHCP(state->offer) ||
4131 	    ifo->options & DHCPCD_ANONYMOUS)
4132 		dhcp_discover(ifp);
4133 	else
4134 		dhcp_reboot(ifp);
4135 }
4136 
4137 void
dhcp_start(struct interface * ifp)4138 dhcp_start(struct interface *ifp)
4139 {
4140 	unsigned int delay;
4141 #ifdef ARPING
4142 	const struct dhcp_state *state;
4143 #endif
4144 
4145 	if (!(ifp->options->options & DHCPCD_IPV4))
4146 		return;
4147 
4148 	/* If we haven't been given a netmask for our requested address,
4149 	 * set it now. */
4150 	if (ifp->options->req_addr.s_addr != INADDR_ANY &&
4151 	    ifp->options->req_mask.s_addr == INADDR_ANY)
4152 		ifp->options->req_mask.s_addr =
4153 		    ipv4_getnetmask(ifp->options->req_addr.s_addr);
4154 
4155 	/* If we haven't specified a ClientID and our hardware address
4156 	 * length is greater than BOOTP CHADDR then we enforce a ClientID
4157 	 * of the hardware address type and the hardware address.
4158 	 * If there is no hardware address and no ClientID set,
4159 	 * force a DUID based ClientID. */
4160 	if (ifp->hwlen > 16)
4161 		ifp->options->options |= DHCPCD_CLIENTID;
4162 	else if (ifp->hwlen == 0 && !(ifp->options->options & DHCPCD_CLIENTID))
4163 		ifp->options->options |= DHCPCD_CLIENTID | DHCPCD_DUID;
4164 
4165 	/* Firewire and InfiniBand interfaces require ClientID and
4166 	 * the broadcast option being set. */
4167 	switch (ifp->hwtype) {
4168 	case ARPHRD_IEEE1394:	/* FALLTHROUGH */
4169 	case ARPHRD_INFINIBAND:
4170 		ifp->options->options |= DHCPCD_CLIENTID | DHCPCD_BROADCAST;
4171 		break;
4172 	}
4173 
4174 	/* If we violate RFC2131 section 3.7 then require ARP
4175 	 * to detect if any other client wants our address. */
4176 	if (ifp->options->options & DHCPCD_LASTLEASE_EXTEND)
4177 		ifp->options->options |= DHCPCD_ARP;
4178 
4179 	/* No point in delaying a static configuration */
4180 	if (ifp->options->options & DHCPCD_STATIC ||
4181 	    !(ifp->options->options & DHCPCD_INITIAL_DELAY))
4182 	{
4183 		dhcp_start1(ifp);
4184 		return;
4185 	}
4186 
4187 #ifdef ARPING
4188 	/* If we have arpinged then we have already delayed. */
4189 	state = D_CSTATE(ifp);
4190 	if (state != NULL && state->arping_index != -1) {
4191 		dhcp_start1(ifp);
4192 		return;
4193 	}
4194 #endif
4195 	delay = MSEC_PER_SEC +
4196 		(arc4random_uniform(MSEC_PER_SEC * 2) - MSEC_PER_SEC);
4197 	logdebugx("%s: delaying IPv4 for %0.1f seconds",
4198 	    ifp->name, (float)delay / MSEC_PER_SEC);
4199 
4200 	eloop_timeout_add_msec(ifp->ctx->eloop, delay, dhcp_start1, ifp);
4201 }
4202 
4203 void
dhcp_abort(struct interface * ifp)4204 dhcp_abort(struct interface *ifp)
4205 {
4206 	struct dhcp_state *state;
4207 
4208 	state = D_STATE(ifp);
4209 #ifdef ARPING
4210 	if (state != NULL)
4211 		state->arping_index = -1;
4212 #endif
4213 
4214 	eloop_timeout_delete(ifp->ctx->eloop, dhcp_start1, ifp);
4215 
4216 	if (state != NULL && state->added) {
4217 		rt_build(ifp->ctx, AF_INET);
4218 #ifdef ARP
4219 		if (ifp->options->options & DHCPCD_ARP)
4220 			arp_announceaddr(ifp->ctx, &state->addr->addr);
4221 #endif
4222 	}
4223 }
4224 
4225 struct ipv4_addr *
dhcp_handleifa(int cmd,struct ipv4_addr * ia,pid_t pid)4226 dhcp_handleifa(int cmd, struct ipv4_addr *ia, pid_t pid)
4227 {
4228 	struct interface *ifp;
4229 	struct dhcp_state *state;
4230 	struct if_options *ifo;
4231 	uint8_t i;
4232 
4233 	ifp = ia->iface;
4234 	state = D_STATE(ifp);
4235 	if (state == NULL || state->state == DHS_NONE)
4236 		return ia;
4237 
4238 	if (cmd == RTM_DELADDR) {
4239 		if (state->addr == ia) {
4240 			loginfox("%s: pid %d deleted IP address %s",
4241 			    ifp->name, pid, ia->saddr);
4242 			dhcp_close(ifp);
4243 			state->addr = NULL;
4244 			/* Don't clear the added state as we need
4245 			 * to drop the lease. */
4246 			dhcp_drop(ifp, "EXPIRE");
4247 			dhcp_start1(ifp);
4248 			return ia;
4249 		}
4250 	}
4251 
4252 	if (cmd != RTM_NEWADDR)
4253 		return ia;
4254 
4255 #ifdef IN_IFF_NOTUSEABLE
4256 	if (!(ia->addr_flags & IN_IFF_NOTUSEABLE))
4257 		dhcp_finish_dad(ifp, &ia->addr);
4258 	else if (ia->addr_flags & IN_IFF_DUPLICATED)
4259 		return dhcp_addr_duplicated(ifp, &ia->addr) ? NULL : ia;
4260 #endif
4261 
4262 	ifo = ifp->options;
4263 
4264 #ifdef PRIVSEP
4265 	if (IN_PRIVSEP_SE(ifp->ctx) &&
4266 	    !(ifp->ctx->options & (DHCPCD_MANAGER | DHCPCD_CONFIGURE)) &&
4267 	    IN_ARE_ADDR_EQUAL(&state->lease.addr, &ia->addr))
4268 	{
4269 		state->addr = ia;
4270 		state->added = STATE_ADDED;
4271 		dhcp_closebpf(ifp);
4272 		if (ps_inet_openbootp(ia) == -1)
4273 		    logerr(__func__);
4274 	}
4275 #endif
4276 
4277 	/* If we have requested a specific address, return now.
4278 	 * The below code is only for when inform or static has been
4279 	 * requested without a specific address. */
4280 	if (ifo->req_addr.s_addr != INADDR_ANY)
4281 		return ia;
4282 
4283 	/* Only inform if we are NOT in the inform state or bound. */
4284 	if (ifo->options & DHCPCD_INFORM) {
4285 		if (state->state != DHS_INFORM && state->state != DHS_BOUND)
4286 			dhcp_inform(ifp);
4287 		return ia;
4288 	}
4289 
4290 	/* Static and inform are mutually exclusive. If not static, return. */
4291 	if (!(ifo->options & DHCPCD_STATIC))
4292 		return ia;
4293 
4294 	free(state->old);
4295 	state->old = state->new;
4296 	state->new_len = dhcp_message_new(&state->new, &ia->addr, &ia->mask);
4297 	if (state->new == NULL)
4298 		return ia;
4299 
4300 	if (ifp->flags & IFF_POINTOPOINT) {
4301 		for (i = 1; i < 255; i++)
4302 			if (i != DHO_ROUTER && has_option_mask(ifo->dstmask,i))
4303 				dhcp_message_add_addr(state->new, i, ia->brd);
4304 	}
4305 
4306 	state->reason = "STATIC";
4307 	rt_build(ifp->ctx, AF_INET);
4308 	script_runreason(ifp, state->reason);
4309 
4310 	return ia;
4311 }
4312 
4313 #ifndef SMALL
4314 int
dhcp_dump(struct interface * ifp)4315 dhcp_dump(struct interface *ifp)
4316 {
4317 	struct dhcp_state *state;
4318 
4319 	ifp->if_data[IF_DATA_DHCP] = state = calloc(1, sizeof(*state));
4320 	if (state == NULL) {
4321 		logerr(__func__);
4322 		return -1;
4323 	}
4324 	state->new_len = read_lease(ifp, &state->new);
4325 	if (state->new == NULL) {
4326 		logerr("read_lease");
4327 		return -1;
4328 	}
4329 	state->reason = "DUMP";
4330 	return script_runreason(ifp, state->reason);
4331 }
4332 #endif
4333