xref: /dragonfly/contrib/dhcpcd/src/dhcpcd.c (revision 4ce1b016)
1 /* SPDX-License-Identifier: BSD-2-Clause */
2 /*
3  * dhcpcd - DHCP client daemon
4  * Copyright (c) 2006-2020 Roy Marples <roy@marples.name>
5  * All rights reserved
6 
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 
29 const char dhcpcd_copyright[] = "Copyright (c) 2006-2020 Roy Marples";
30 
31 #include <sys/file.h>
32 #include <sys/ioctl.h>
33 #include <sys/socket.h>
34 #include <sys/stat.h>
35 #include <sys/time.h>
36 #include <sys/types.h>
37 #include <sys/uio.h>
38 #include <sys/wait.h>
39 
40 #include <ctype.h>
41 #include <errno.h>
42 #include <fcntl.h>
43 #include <getopt.h>
44 #include <limits.h>
45 #include <paths.h>
46 #include <signal.h>
47 #include <stdio.h>
48 #include <stdlib.h>
49 #include <string.h>
50 #include <syslog.h>
51 #include <unistd.h>
52 #include <time.h>
53 
54 #include "config.h"
55 #include "arp.h"
56 #include "common.h"
57 #include "control.h"
58 #include "dev.h"
59 #include "dhcp-common.h"
60 #include "dhcpcd.h"
61 #include "dhcp.h"
62 #include "dhcp6.h"
63 #include "duid.h"
64 #include "eloop.h"
65 #include "if.h"
66 #include "if-options.h"
67 #include "ipv4.h"
68 #include "ipv4ll.h"
69 #include "ipv6.h"
70 #include "ipv6nd.h"
71 #include "logerr.h"
72 #include "privsep.h"
73 #include "script.h"
74 
75 #ifdef HAVE_CAPSICUM
76 #include <sys/capsicum.h>
77 #endif
78 #ifdef HAVE_UTIL_H
79 #include <util.h>
80 #endif
81 
82 #ifdef USE_SIGNALS
83 const int dhcpcd_signals[] = {
84 	SIGTERM,
85 	SIGINT,
86 	SIGALRM,
87 	SIGHUP,
88 	SIGUSR1,
89 	SIGUSR2,
90 };
91 const size_t dhcpcd_signals_len = __arraycount(dhcpcd_signals);
92 
93 const int dhcpcd_signals_ignore[] = {
94 	SIGPIPE,
95 };
96 const size_t dhcpcd_signals_ignore_len = __arraycount(dhcpcd_signals_ignore);
97 #endif
98 
99 #define IF_UPANDRUNNING(a) \
100 	(((a)->flags & (IFF_UP | IFF_RUNNING)) == (IFF_UP | IFF_RUNNING))
101 
102 const char *dhcpcd_default_script = SCRIPT;
103 
104 static void
105 usage(void)
106 {
107 
108 printf("usage: "PACKAGE"\t[-146ABbDdEGgHJKLMNPpqTV]\n"
109 	"\t\t[-C, --nohook hook] [-c, --script script]\n"
110 	"\t\t[-e, --env value] [-F, --fqdn FQDN] [-f, --config file]\n"
111 	"\t\t[-h, --hostname hostname] [-I, --clientid clientid]\n"
112 	"\t\t[-i, --vendorclassid vendorclassid] [-j, --logfile logfile]\n"
113 	"\t\t[-l, --leasetime seconds] [-m, --metric metric]\n"
114 	"\t\t[-O, --nooption option] [-o, --option option]\n"
115 	"\t\t[-Q, --require option] [-r, --request address]\n"
116 	"\t\t[-S, --static value]\n"
117 	"\t\t[-s, --inform address[/cidr[/broadcast_address]]]\n [--inform6]"
118 	"\t\t[-t, --timeout seconds] [-u, --userclass class]\n"
119 	"\t\t[-v, --vendor code, value] [-W, --whitelist address[/cidr]] [-w]\n"
120 	"\t\t[--waitip [4 | 6]] [-y, --reboot seconds]\n"
121 	"\t\t[-X, --blacklist address[/cidr]] [-Z, --denyinterfaces pattern]\n"
122 	"\t\t[-z, --allowinterfaces pattern] [--inactive] [interface] [...]\n"
123 	"       "PACKAGE"\t-n, --rebind [interface]\n"
124 	"       "PACKAGE"\t-k, --release [interface]\n"
125 	"       "PACKAGE"\t-U, --dumplease interface\n"
126 	"       "PACKAGE"\t--version\n"
127 	"       "PACKAGE"\t-x, --exit [interface]\n");
128 }
129 
130 static void
131 free_globals(struct dhcpcd_ctx *ctx)
132 {
133 	struct dhcp_opt *opt;
134 
135 	if (ctx->ifac) {
136 		for (; ctx->ifac > 0; ctx->ifac--)
137 			free(ctx->ifav[ctx->ifac - 1]);
138 		free(ctx->ifav);
139 		ctx->ifav = NULL;
140 	}
141 	if (ctx->ifdc) {
142 		for (; ctx->ifdc > 0; ctx->ifdc--)
143 			free(ctx->ifdv[ctx->ifdc - 1]);
144 		free(ctx->ifdv);
145 		ctx->ifdv = NULL;
146 	}
147 	if (ctx->ifcc) {
148 		for (; ctx->ifcc > 0; ctx->ifcc--)
149 			free(ctx->ifcv[ctx->ifcc - 1]);
150 		free(ctx->ifcv);
151 		ctx->ifcv = NULL;
152 	}
153 
154 #ifdef INET
155 	if (ctx->dhcp_opts) {
156 		for (opt = ctx->dhcp_opts;
157 		    ctx->dhcp_opts_len > 0;
158 		    opt++, ctx->dhcp_opts_len--)
159 			free_dhcp_opt_embenc(opt);
160 		free(ctx->dhcp_opts);
161 		ctx->dhcp_opts = NULL;
162 	}
163 #endif
164 #ifdef INET6
165 	if (ctx->nd_opts) {
166 		for (opt = ctx->nd_opts;
167 		    ctx->nd_opts_len > 0;
168 		    opt++, ctx->nd_opts_len--)
169 			free_dhcp_opt_embenc(opt);
170 		free(ctx->nd_opts);
171 		ctx->nd_opts = NULL;
172 	}
173 #ifdef DHCP6
174 	if (ctx->dhcp6_opts) {
175 		for (opt = ctx->dhcp6_opts;
176 		    ctx->dhcp6_opts_len > 0;
177 		    opt++, ctx->dhcp6_opts_len--)
178 			free_dhcp_opt_embenc(opt);
179 		free(ctx->dhcp6_opts);
180 		ctx->dhcp6_opts = NULL;
181 	}
182 #endif
183 #endif
184 	if (ctx->vivso) {
185 		for (opt = ctx->vivso;
186 		    ctx->vivso_len > 0;
187 		    opt++, ctx->vivso_len--)
188 			free_dhcp_opt_embenc(opt);
189 		free(ctx->vivso);
190 		ctx->vivso = NULL;
191 	}
192 }
193 
194 static void
195 handle_exit_timeout(void *arg)
196 {
197 	struct dhcpcd_ctx *ctx;
198 
199 	ctx = arg;
200 	logerrx("timed out");
201 	if (!(ctx->options & DHCPCD_MASTER)) {
202 		struct interface *ifp;
203 
204 		TAILQ_FOREACH(ifp, ctx->ifaces, next) {
205 			if (ifp->active == IF_ACTIVE_USER)
206 				script_runreason(ifp, "STOPPED");
207 		}
208 		eloop_exit(ctx->eloop, EXIT_FAILURE);
209 		return;
210 	}
211 	ctx->options |= DHCPCD_NOWAITIP;
212 	dhcpcd_daemonise(ctx);
213 }
214 
215 static const char *
216 dhcpcd_af(int af)
217 {
218 
219 	switch (af) {
220 	case AF_UNSPEC:
221 		return "IP";
222 	case AF_INET:
223 		return "IPv4";
224 	case AF_INET6:
225 		return "IPv6";
226 	default:
227 		return NULL;
228 	}
229 }
230 
231 int
232 dhcpcd_ifafwaiting(const struct interface *ifp)
233 {
234 	unsigned long long opts;
235 	bool foundany = false;
236 
237 	if (ifp->active != IF_ACTIVE_USER)
238 		return AF_MAX;
239 
240 #define DHCPCD_WAITALL	(DHCPCD_WAITIP4 | DHCPCD_WAITIP6)
241 	opts = ifp->options->options;
242 #ifdef INET
243 	if (opts & DHCPCD_WAITIP4 ||
244 	    (opts & DHCPCD_WAITIP && !(opts & DHCPCD_WAITALL)))
245 	{
246 		bool foundaddr = ipv4_hasaddr(ifp);
247 
248 		if (opts & DHCPCD_WAITIP4 && !foundaddr)
249 			return AF_INET;
250 		if (foundaddr)
251 			foundany = true;
252 	}
253 #endif
254 #ifdef INET6
255 	if (opts & DHCPCD_WAITIP6 ||
256 	    (opts & DHCPCD_WAITIP && !(opts & DHCPCD_WAITALL)))
257 	{
258 		bool foundaddr = ipv6_hasaddr(ifp);
259 
260 		if (opts & DHCPCD_WAITIP6 && !foundaddr)
261 			return AF_INET;
262 		if (foundaddr)
263 			foundany = true;
264 	}
265 #endif
266 
267 	if (opts & DHCPCD_WAITIP && !(opts & DHCPCD_WAITALL) && !foundany)
268 		return AF_UNSPEC;
269 	return AF_MAX;
270 }
271 
272 int
273 dhcpcd_afwaiting(const struct dhcpcd_ctx *ctx)
274 {
275 	unsigned long long opts;
276 	const struct interface *ifp;
277 	int af;
278 
279 	if (!(ctx->options & DHCPCD_WAITOPTS))
280 		return AF_MAX;
281 
282 	opts = ctx->options;
283 	TAILQ_FOREACH(ifp, ctx->ifaces, next) {
284 #ifdef INET
285 		if (opts & (DHCPCD_WAITIP | DHCPCD_WAITIP4) &&
286 		    ipv4_hasaddr(ifp))
287 			opts &= ~(DHCPCD_WAITIP | DHCPCD_WAITIP4);
288 #endif
289 #ifdef INET6
290 		if (opts & (DHCPCD_WAITIP | DHCPCD_WAITIP6) &&
291 		    ipv6_hasaddr(ifp))
292 			opts &= ~(DHCPCD_WAITIP | DHCPCD_WAITIP6);
293 #endif
294 		if (!(opts & DHCPCD_WAITOPTS))
295 			break;
296 	}
297 	if (opts & DHCPCD_WAITIP)
298 		af = AF_UNSPEC;
299 	else if (opts & DHCPCD_WAITIP4)
300 		af = AF_INET;
301 	else if (opts & DHCPCD_WAITIP6)
302 		af = AF_INET6;
303 	else
304 		return AF_MAX;
305 	return af;
306 }
307 
308 static int
309 dhcpcd_ipwaited(struct dhcpcd_ctx *ctx)
310 {
311 	struct interface *ifp;
312 	int af;
313 
314 	TAILQ_FOREACH(ifp, ctx->ifaces, next) {
315 		if ((af = dhcpcd_ifafwaiting(ifp)) != AF_MAX) {
316 			logdebugx("%s: waiting for an %s address",
317 			    ifp->name, dhcpcd_af(af));
318 			return 0;
319 		}
320 	}
321 
322 	if ((af = dhcpcd_afwaiting(ctx)) != AF_MAX) {
323 		logdebugx("waiting for an %s address",
324 		    dhcpcd_af(af));
325 		return 0;
326 	}
327 
328 	return 1;
329 }
330 
331 /* Returns the pid of the child, otherwise 0. */
332 void
333 dhcpcd_daemonise(struct dhcpcd_ctx *ctx)
334 {
335 #ifdef THERE_IS_NO_FORK
336 	eloop_timeout_delete(ctx->eloop, handle_exit_timeout, ctx);
337 	errno = ENOSYS;
338 	return 0;
339 #else
340 	int i;
341 
342 	if (ctx->options & DHCPCD_DAEMONISE &&
343 	    !(ctx->options & (DHCPCD_DAEMONISED | DHCPCD_NOWAITIP)))
344 	{
345 		if (!dhcpcd_ipwaited(ctx))
346 			return;
347 	}
348 
349 	if (ctx->options & DHCPCD_ONESHOT) {
350 		loginfox("exiting due to oneshot");
351 		eloop_exit(ctx->eloop, EXIT_SUCCESS);
352 		return;
353 	}
354 
355 	eloop_timeout_delete(ctx->eloop, handle_exit_timeout, ctx);
356 	if (ctx->options & DHCPCD_DAEMONISED ||
357 	    !(ctx->options & DHCPCD_DAEMONISE))
358 		return;
359 
360 	/* Don't use loginfo because this makes no sense in a log. */
361 	if (!(loggetopts() & LOGERR_QUIET))
362 		(void)fprintf(stderr, "forked to background, child pid %d\n",
363 		    getpid());
364 	i = EXIT_SUCCESS;
365 	if (write(ctx->fork_fd, &i, sizeof(i)) == -1)
366 		logerr("write");
367 	ctx->options |= DHCPCD_DAEMONISED;
368 	eloop_event_delete(ctx->eloop, ctx->fork_fd);
369 	close(ctx->fork_fd);
370 	ctx->fork_fd = -1;
371 #ifdef PRIVSEP
372 	if (ctx->options & DHCPCD_PRIVSEP) {
373 		/* Aside from Linux, we don't have access to /dev/null */
374 		fclose(stdout);
375 		fclose(stderr);
376 	} else
377 #endif
378 	{
379 		(void)freopen(_PATH_DEVNULL, "w", stdout);
380 		(void)freopen(_PATH_DEVNULL, "w", stderr);
381 	}
382 #endif
383 }
384 
385 static void
386 dhcpcd_drop(struct interface *ifp, int stop)
387 {
388 
389 #ifdef DHCP6
390 	dhcp6_drop(ifp, stop ? NULL : "EXPIRE6");
391 #endif
392 #ifdef INET6
393 	ipv6nd_drop(ifp);
394 	ipv6_drop(ifp);
395 #endif
396 #ifdef IPV4LL
397 	ipv4ll_drop(ifp);
398 #endif
399 #ifdef INET
400 	dhcp_drop(ifp, stop ? "STOP" : "EXPIRE");
401 #endif
402 #ifdef ARP
403 	arp_drop(ifp);
404 #endif
405 #if !defined(DHCP6) && !defined(DHCP)
406 	UNUSED(stop);
407 #endif
408 }
409 
410 static void
411 stop_interface(struct interface *ifp)
412 {
413 	struct dhcpcd_ctx *ctx;
414 
415 	ctx = ifp->ctx;
416 	loginfox("%s: removing interface", ifp->name);
417 	ifp->options->options |= DHCPCD_STOPPING;
418 
419 	dhcpcd_drop(ifp, 1);
420 	if (ifp->options->options & DHCPCD_DEPARTED)
421 		script_runreason(ifp, "DEPARTED");
422 	else
423 		script_runreason(ifp, "STOPPED");
424 
425 	/* Delete all timeouts for the interfaces */
426 	eloop_q_timeout_delete(ctx->eloop, ELOOP_QUEUE_ALL, NULL, ifp);
427 
428 	/* De-activate the interface */
429 	ifp->active = IF_INACTIVE;
430 	ifp->options->options &= ~DHCPCD_STOPPING;
431 	/* Set the link state to unknown as we're no longer tracking it. */
432 	ifp->carrier = LINK_UNKNOWN;
433 
434 	if (!(ctx->options & (DHCPCD_MASTER | DHCPCD_TEST)))
435 		eloop_exit(ctx->eloop, EXIT_FAILURE);
436 }
437 
438 static void
439 configure_interface1(struct interface *ifp)
440 {
441 	struct if_options *ifo = ifp->options;
442 
443 	/* Do any platform specific configuration */
444 	if_conf(ifp);
445 
446 	/* If we want to release a lease, we can't really persist the
447 	 * address either. */
448 	if (ifo->options & DHCPCD_RELEASE)
449 		ifo->options &= ~DHCPCD_PERSISTENT;
450 
451 	if (ifp->flags & (IFF_POINTOPOINT | IFF_LOOPBACK)) {
452 		ifo->options &= ~DHCPCD_ARP;
453 		if (!(ifp->flags & IFF_MULTICAST))
454 			ifo->options &= ~DHCPCD_IPV6RS;
455 		if (!(ifo->options & (DHCPCD_INFORM | DHCPCD_WANTDHCP)))
456 			ifo->options |= DHCPCD_STATIC;
457 	}
458 
459 	if (ifo->metric != -1)
460 		ifp->metric = (unsigned int)ifo->metric;
461 
462 #ifdef INET6
463 	/* We want to setup INET6 on the interface as soon as possible. */
464 	if (ifp->active == IF_ACTIVE_USER &&
465 	    ifo->options & DHCPCD_IPV6 &&
466 	    !(ifp->ctx->options & (DHCPCD_DUMPLEASE | DHCPCD_TEST)))
467 	{
468 		/* If not doing any DHCP, disable the RDNSS requirement. */
469 		if (!(ifo->options & (DHCPCD_DHCP | DHCPCD_DHCP6)))
470 			ifo->options &= ~DHCPCD_IPV6RA_REQRDNSS;
471 		if_setup_inet6(ifp);
472 	}
473 #endif
474 
475 	if (!(ifo->options & DHCPCD_IAID)) {
476 		/*
477 		 * An IAID is for identifying a unqiue interface within
478 		 * the client. It is 4 bytes long. Working out a default
479 		 * value is problematic.
480 		 *
481 		 * Interface name and number are not stable
482 		 * between different OS's. Some OS's also cannot make
483 		 * up their mind what the interface should be called
484 		 * (yes, udev, I'm looking at you).
485 		 * Also, the name could be longer than 4 bytes.
486 		 * Also, with pluggable interfaces the name and index
487 		 * could easily get swapped per actual interface.
488 		 *
489 		 * The MAC address is 6 bytes long, the final 3
490 		 * being unique to the manufacturer and the initial 3
491 		 * being unique to the organisation which makes it.
492 		 * We could use the last 4 bytes of the MAC address
493 		 * as the IAID as it's the most stable part given the
494 		 * above, but equally it's not guaranteed to be
495 		 * unique.
496 		 *
497 		 * Given the above, and our need to reliably work
498 		 * between reboots without persitent storage,
499 		 * generating the IAID from the MAC address is the only
500 		 * logical default.
501 		 * Saying that, if a VLANID has been specified then we
502 		 * can use that. It's possible that different interfaces
503 		 * can have the same VLANID, but this is no worse than
504 		 * generating the IAID from the duplicate MAC address.
505 		 *
506 		 * dhclient uses the last 4 bytes of the MAC address.
507 		 * dibbler uses an increamenting counter.
508 		 * wide-dhcpv6 uses 0 or a configured value.
509 		 * odhcp6c uses 1.
510 		 * Windows 7 uses the first 3 bytes of the MAC address
511 		 * and an unknown byte.
512 		 * dhcpcd-6.1.0 and earlier used the interface name,
513 		 * falling back to interface index if name > 4.
514 		 */
515 		if (ifp->vlanid != 0) {
516 			uint32_t vlanid;
517 
518 			/* Maximal VLANID is 4095, so prefix with 0xff
519 			 * so we don't conflict with an interface index. */
520 			vlanid = htonl(ifp->vlanid | 0xff000000);
521 			memcpy(ifo->iaid, &vlanid, sizeof(vlanid));
522 		} else if (ifo->options & DHCPCD_ANONYMOUS)
523 			memset(ifo->iaid, 0, sizeof(ifo->iaid));
524 		else if (ifp->hwlen >= sizeof(ifo->iaid)) {
525 			memcpy(ifo->iaid,
526 			    ifp->hwaddr + ifp->hwlen - sizeof(ifo->iaid),
527 			    sizeof(ifo->iaid));
528 		} else {
529 			uint32_t len;
530 
531 			len = (uint32_t)strlen(ifp->name);
532 			if (len <= sizeof(ifo->iaid)) {
533 				memcpy(ifo->iaid, ifp->name, len);
534 				if (len < sizeof(ifo->iaid))
535 					memset(ifo->iaid + len, 0,
536 					    sizeof(ifo->iaid) - len);
537 			} else {
538 				/* IAID is the same size as a uint32_t */
539 				len = htonl(ifp->index);
540 				memcpy(ifo->iaid, &len, sizeof(ifo->iaid));
541 			}
542 		}
543 		ifo->options |= DHCPCD_IAID;
544 	}
545 
546 #ifdef DHCP6
547 	if (ifo->ia_len == 0 && ifo->options & DHCPCD_IPV6 &&
548 	    ifp->name[0] != '\0')
549 	{
550 		ifo->ia = malloc(sizeof(*ifo->ia));
551 		if (ifo->ia == NULL)
552 			logerr(__func__);
553 		else {
554 			ifo->ia_len = 1;
555 			ifo->ia->ia_type = D6_OPTION_IA_NA;
556 			memcpy(ifo->ia->iaid, ifo->iaid, sizeof(ifo->iaid));
557 			memset(&ifo->ia->addr, 0, sizeof(ifo->ia->addr));
558 #ifndef SMALL
559 			ifo->ia->sla = NULL;
560 			ifo->ia->sla_len = 0;
561 #endif
562 		}
563 	} else {
564 		size_t i;
565 
566 		for (i = 0; i < ifo->ia_len; i++) {
567 			if (!ifo->ia[i].iaid_set) {
568 				memcpy(&ifo->ia[i].iaid, ifo->iaid,
569 				    sizeof(ifo->ia[i].iaid));
570 				ifo->ia[i].iaid_set = 1;
571 			}
572 		}
573 	}
574 #endif
575 
576 	/* If root is network mounted, we don't want to kill the connection
577 	 * if the DHCP server goes the way of the dodo OR dhcpcd is rebooting
578 	 * and the lease file has expired. */
579 	if (is_root_local() == 0)
580 		ifo->options |= DHCPCD_LASTLEASE_EXTEND;
581 }
582 
583 int
584 dhcpcd_selectprofile(struct interface *ifp, const char *profile)
585 {
586 	struct if_options *ifo;
587 	char pssid[PROFILE_LEN];
588 
589 	if (ifp->ssid_len) {
590 		ssize_t r;
591 
592 		r = print_string(pssid, sizeof(pssid), OT_ESCSTRING,
593 		    ifp->ssid, ifp->ssid_len);
594 		if (r == -1) {
595 			logerr(__func__);
596 			pssid[0] = '\0';
597 		}
598 	} else
599 		pssid[0] = '\0';
600 	ifo = read_config(ifp->ctx, ifp->name, pssid, profile);
601 	if (ifo == NULL) {
602 		logdebugx("%s: no profile %s", ifp->name, profile);
603 		return -1;
604 	}
605 	if (profile != NULL) {
606 		strlcpy(ifp->profile, profile, sizeof(ifp->profile));
607 		loginfox("%s: selected profile %s", ifp->name, profile);
608 	} else
609 		*ifp->profile = '\0';
610 
611 	free_options(ifp->ctx, ifp->options);
612 	ifp->options = ifo;
613 	if (profile) {
614 		add_options(ifp->ctx, ifp->name, ifp->options,
615 		    ifp->ctx->argc, ifp->ctx->argv);
616 		configure_interface1(ifp);
617 	}
618 	return 1;
619 }
620 
621 static void
622 configure_interface(struct interface *ifp, int argc, char **argv,
623     unsigned long long options)
624 {
625 	time_t old;
626 
627 	old = ifp->options ? ifp->options->mtime : 0;
628 	dhcpcd_selectprofile(ifp, NULL);
629 	if (ifp->options == NULL) {
630 		/* dhcpcd cannot continue with this interface. */
631 		ifp->active = IF_INACTIVE;
632 		return;
633 	}
634 	add_options(ifp->ctx, ifp->name, ifp->options, argc, argv);
635 	ifp->options->options |= options;
636 	configure_interface1(ifp);
637 
638 	/* If the mtime has changed drop any old lease */
639 	if (old != 0 && ifp->options->mtime != old) {
640 		logwarnx("%s: config file changed, expiring leases",
641 		    ifp->name);
642 		dhcpcd_drop(ifp, 0);
643 	}
644 }
645 
646 static void
647 dhcpcd_initstate2(struct interface *ifp, unsigned long long options)
648 {
649 	struct if_options *ifo;
650 
651 	if (options) {
652 		if ((ifo = default_config(ifp->ctx)) == NULL) {
653 			logerr(__func__);
654 			return;
655 		}
656 		ifo->options |= options;
657 		free(ifp->options);
658 		ifp->options = ifo;
659 	} else
660 		ifo = ifp->options;
661 
662 #ifdef INET6
663 	if (ifo->options & DHCPCD_IPV6 && ipv6_init(ifp->ctx) == -1) {
664 		logerr(__func__);
665 		ifo->options &= ~DHCPCD_IPV6;
666 	}
667 #endif
668 }
669 
670 static void
671 dhcpcd_initstate1(struct interface *ifp, int argc, char **argv,
672     unsigned long long options)
673 {
674 
675 	configure_interface(ifp, argc, argv, options);
676 	if (ifp->active)
677 		dhcpcd_initstate2(ifp, 0);
678 }
679 
680 static void
681 dhcpcd_initstate(struct interface *ifp, unsigned long long options)
682 {
683 
684 	dhcpcd_initstate1(ifp, ifp->ctx->argc, ifp->ctx->argv, options);
685 }
686 
687 static void
688 dhcpcd_reportssid(struct interface *ifp)
689 {
690 	char pssid[IF_SSIDLEN * 4];
691 
692 	if (print_string(pssid, sizeof(pssid), OT_ESCSTRING,
693 	    ifp->ssid, ifp->ssid_len) == -1)
694 	{
695 		logerr(__func__);
696 		return;
697 	}
698 
699 	loginfox("%s: connected to Access Point `%s'", ifp->name, pssid);
700 }
701 
702 void
703 dhcpcd_handlecarrier(struct dhcpcd_ctx *ctx, int carrier, unsigned int flags,
704     const char *ifname)
705 {
706 	struct interface *ifp;
707 
708 	ifp = if_find(ctx->ifaces, ifname);
709 	if (ifp == NULL ||
710 	    ifp->options == NULL || !(ifp->options->options & DHCPCD_LINK) ||
711 	    !ifp->active)
712 		return;
713 
714 	if (carrier == LINK_UNKNOWN) {
715 		if (ifp->wireless) {
716 			carrier = LINK_DOWN;
717 			ifp->flags = flags;
718 		} else
719 			carrier = if_carrier(ifp);
720 	} else
721 		ifp->flags = flags;
722 	if (carrier == LINK_UNKNOWN)
723 		carrier = IF_UPANDRUNNING(ifp) ? LINK_UP : LINK_DOWN;
724 
725 	if (carrier == LINK_DOWN || (ifp->flags & IFF_UP) == 0) {
726 		if (ifp->carrier != LINK_DOWN) {
727 			if (ifp->carrier == LINK_UP)
728 				loginfox("%s: carrier lost", ifp->name);
729 #ifdef NOCARRIER_PRESERVE_IP
730 			if (ifp->flags & IFF_UP &&
731 			    !(ifp->options->options & DHCPCD_ANONYMOUS))
732 				ifp->carrier = LINK_DOWN_IFFUP;
733 			else
734 #endif
735 				ifp->carrier = LINK_DOWN;
736 			script_runreason(ifp, "NOCARRIER");
737 #ifdef NOCARRIER_PRESERVE_IP
738 			if (ifp->flags & IFF_UP &&
739 			    !(ifp->options->options & DHCPCD_ANONYMOUS))
740 			{
741 #ifdef ARP
742 				arp_drop(ifp);
743 #endif
744 #ifdef INET
745 				dhcp_abort(ifp);
746 #endif
747 #ifdef DHCP6
748 				dhcp6_abort(ifp);
749 #endif
750 			} else
751 #endif
752 				dhcpcd_drop(ifp, 0);
753 			if (ifp->options->options & DHCPCD_ANONYMOUS) {
754 				bool was_up = ifp->flags & IFF_UP;
755 
756 				if (was_up)
757 					if_down(ifp);
758 				if (if_randomisemac(ifp) == -1 && errno != ENXIO)
759 					logerr(__func__);
760 				if (was_up)
761 					if_up(ifp);
762 			}
763 		}
764 	} else if (carrier == LINK_UP && ifp->flags & IFF_UP) {
765 		if (ifp->carrier != LINK_UP) {
766 			loginfox("%s: carrier acquired", ifp->name);
767 			ifp->carrier = LINK_UP;
768 #if !defined(__linux__) && !defined(__NetBSD__)
769 			/* BSD does not emit RTM_NEWADDR or RTM_CHGADDR when the
770 			 * hardware address changes so we have to go
771 			 * through the disovery process to work it out. */
772 			dhcpcd_handleinterface(ctx, 0, ifp->name);
773 #endif
774 			if (ifp->wireless) {
775 				uint8_t ossid[IF_SSIDLEN];
776 				size_t olen;
777 
778 				olen = ifp->ssid_len;
779 				memcpy(ossid, ifp->ssid, ifp->ssid_len);
780 				if_getssid(ifp);
781 
782 				/* If we changed SSID network, drop leases */
783 				if (ifp->ssid_len != olen ||
784 				    memcmp(ifp->ssid, ossid, ifp->ssid_len))
785 				{
786 					dhcpcd_reportssid(ifp);
787 #ifdef NOCARRIER_PRESERVE_IP
788 					dhcpcd_drop(ifp, 0);
789 #endif
790 #ifdef IPV4LL
791 					ipv4ll_reset(ifp);
792 #endif
793 				}
794 			}
795 			dhcpcd_initstate(ifp, 0);
796 			script_runreason(ifp, "CARRIER");
797 #ifdef INET6
798 #ifdef NOCARRIER_PRESERVE_IP
799 			/* Set any IPv6 Routers we remembered to expire
800 			 * faster than they would normally as we
801 			 * maybe on a new network. */
802 			ipv6nd_startexpire(ifp);
803 #endif
804 #ifdef IPV6_MANAGETEMPADDR
805 			/* RFC4941 Section 3.5 */
806 			ipv6_regentempaddrs(ifp);
807 #endif
808 #endif
809 			dhcpcd_startinterface(ifp);
810 		}
811 	}
812 }
813 
814 static void
815 warn_iaid_conflict(struct interface *ifp, uint16_t ia_type, uint8_t *iaid)
816 {
817 	struct interface *ifn;
818 #ifdef INET6
819 	size_t i;
820 	struct if_ia *ia;
821 #endif
822 
823 	TAILQ_FOREACH(ifn, ifp->ctx->ifaces, next) {
824 		if (ifn == ifp || !ifn->active)
825 			continue;
826 		if (ifn->options->options & DHCPCD_ANONYMOUS)
827 			continue;
828 		if (ia_type == 0 &&
829 		    memcmp(ifn->options->iaid, iaid,
830 		    sizeof(ifn->options->iaid)) == 0)
831 			break;
832 #ifdef INET6
833 		for (i = 0; i < ifn->options->ia_len; i++) {
834 			ia = &ifn->options->ia[i];
835 			if (ia->ia_type == ia_type &&
836 			    memcmp(ia->iaid, iaid, sizeof(ia->iaid)) == 0)
837 				break;
838 		}
839 #endif
840 	}
841 
842 	/* This is only a problem if the interfaces are on the same network. */
843 	if (ifn)
844 		logerrx("%s: IAID conflicts with one assigned to %s",
845 		    ifp->name, ifn->name);
846 }
847 
848 static void
849 dhcpcd_initduid(struct dhcpcd_ctx *ctx, struct interface *ifp)
850 {
851 	char buf[DUID_LEN * 3];
852 
853 	if (ctx->duid != NULL)
854 		return;
855 
856 	duid_init(ctx, ifp);
857 	if (ctx->duid == NULL)
858 		return;
859 
860 	loginfox("DUID %s",
861 	    hwaddr_ntoa(ctx->duid, ctx->duid_len, buf, sizeof(buf)));
862 }
863 
864 void
865 dhcpcd_startinterface(void *arg)
866 {
867 	struct interface *ifp = arg;
868 	struct if_options *ifo = ifp->options;
869 	int carrier;
870 
871 	if (ifo->options & DHCPCD_LINK) {
872 		switch (ifp->carrier) {
873 		case LINK_UP:
874 			break;
875 		case LINK_DOWN:
876 			loginfox("%s: waiting for carrier", ifp->name);
877 			return;
878 		case LINK_UNKNOWN:
879 			/* No media state available.
880 			 * Loop until both IFF_UP and IFF_RUNNING are set */
881 			carrier = if_carrier(ifp);
882 			if (carrier == LINK_UNKNOWN) {
883 				if (IF_UPANDRUNNING(ifp))
884 					carrier = LINK_UP;
885 				else {
886 					eloop_timeout_add_msec(ifp->ctx->eloop,
887 					    IF_POLL_UP * MSEC_PER_SEC,
888 					    dhcpcd_startinterface, ifp);
889 					return;
890 				}
891 			}
892 			dhcpcd_handlecarrier(ifp->ctx, carrier,
893 			    ifp->flags, ifp->name);
894 			return;
895 		}
896 	}
897 
898 	if (ifo->options & (DHCPCD_DUID | DHCPCD_IPV6) &&
899 	    !(ifo->options & DHCPCD_ANONYMOUS))
900 	{
901 		char buf[sizeof(ifo->iaid) * 3];
902 #ifdef INET6
903 		size_t i;
904 		struct if_ia *ia;
905 #endif
906 
907 		/* Try and init DUID from the interface hardware address */
908 		dhcpcd_initduid(ifp->ctx, ifp);
909 
910 		/* Report IAIDs */
911 		loginfox("%s: IAID %s", ifp->name,
912 		    hwaddr_ntoa(ifo->iaid, sizeof(ifo->iaid),
913 		    buf, sizeof(buf)));
914 		warn_iaid_conflict(ifp, 0, ifo->iaid);
915 
916 #ifdef INET6
917 		for (i = 0; i < ifo->ia_len; i++) {
918 			ia = &ifo->ia[i];
919 			if (memcmp(ifo->iaid, ia->iaid, sizeof(ifo->iaid))) {
920 				loginfox("%s: IA type %u IAID %s",
921 				    ifp->name, ia->ia_type,
922 				    hwaddr_ntoa(ia->iaid, sizeof(ia->iaid),
923 				    buf, sizeof(buf)));
924 				warn_iaid_conflict(ifp, ia->ia_type, ia->iaid);
925 			}
926 		}
927 #endif
928 	}
929 
930 #ifdef INET6
931 	if (ifo->options & DHCPCD_IPV6 && ipv6_start(ifp) == -1) {
932 		logerr("%s: ipv6_start", ifp->name);
933 		ifo->options &= ~DHCPCD_IPV6;
934 	}
935 
936 	if (ifo->options & DHCPCD_IPV6) {
937 		if (ifp->active == IF_ACTIVE_USER) {
938 			ipv6_startstatic(ifp);
939 
940 			if (ifo->options & DHCPCD_IPV6RS)
941 				ipv6nd_startrs(ifp);
942 		}
943 
944 #ifdef DHCP6
945 		if (ifo->options & DHCPCD_DHCP6) {
946 			dhcp6_find_delegates(ifp);
947 
948 			if (ifp->active == IF_ACTIVE_USER) {
949 				enum DH6S d6_state;
950 
951 				if (ifo->options & DHCPCD_IA_FORCED)
952 					d6_state = DH6S_INIT;
953 				else if (ifo->options & DHCPCD_INFORM6)
954 					d6_state = DH6S_INFORM;
955 				else
956 					d6_state = DH6S_CONFIRM;
957 				if (dhcp6_start(ifp, d6_state) == -1)
958 					logerr("%s: dhcp6_start", ifp->name);
959 			}
960 		}
961 #endif
962 	}
963 #endif
964 
965 #ifdef INET
966 	if (ifo->options & DHCPCD_IPV4 && ifp->active == IF_ACTIVE_USER) {
967 		/* Ensure we have an IPv4 state before starting DHCP */
968 		if (ipv4_getstate(ifp) != NULL)
969 			dhcp_start(ifp);
970 	}
971 #endif
972 }
973 
974 static void
975 dhcpcd_prestartinterface(void *arg)
976 {
977 	struct interface *ifp = arg;
978 	bool anondown;
979 
980 	if (ifp->carrier == LINK_DOWN &&
981 	    ifp->options->options & DHCPCD_ANONYMOUS &&
982 	    ifp->flags & IFF_UP)
983 	{
984 		if_down(ifp);
985 		anondown = true;
986 	} else
987 		anondown = false;
988 
989 	if ((!(ifp->ctx->options & DHCPCD_MASTER) ||
990 	    ifp->options->options & DHCPCD_IF_UP || anondown) &&
991 	    !(ifp->flags & IFF_UP))
992 	{
993 		if (ifp->options->options & DHCPCD_ANONYMOUS &&
994 		    if_randomisemac(ifp) == -1)
995 			logerr(__func__);
996 		if (if_up(ifp) == -1)
997 			logerr(__func__);
998 	}
999 
1000 	dhcpcd_startinterface(ifp);
1001 }
1002 
1003 static void
1004 run_preinit(struct interface *ifp)
1005 {
1006 
1007 	if (ifp->ctx->options & DHCPCD_TEST)
1008 		return;
1009 
1010 	script_runreason(ifp, "PREINIT");
1011 	if (ifp->wireless && ifp->carrier == LINK_UP)
1012 		dhcpcd_reportssid(ifp);
1013 	if (ifp->options->options & DHCPCD_LINK && ifp->carrier != LINK_UNKNOWN)
1014 		script_runreason(ifp,
1015 		    ifp->carrier == LINK_UP ? "CARRIER" : "NOCARRIER");
1016 }
1017 
1018 void
1019 dhcpcd_activateinterface(struct interface *ifp, unsigned long long options)
1020 {
1021 
1022 	if (!ifp->active) {
1023 		ifp->active = IF_ACTIVE;
1024 		dhcpcd_initstate2(ifp, options);
1025 		/* It's possible we might not have been able to load
1026 		 * a config. */
1027 		if (ifp->active) {
1028 			configure_interface1(ifp);
1029 			run_preinit(ifp);
1030 			dhcpcd_prestartinterface(ifp);
1031 		}
1032 	}
1033 }
1034 
1035 int
1036 dhcpcd_handleinterface(void *arg, int action, const char *ifname)
1037 {
1038 	struct dhcpcd_ctx *ctx;
1039 	struct ifaddrs *ifaddrs;
1040 	struct if_head *ifs;
1041 	struct interface *ifp, *iff;
1042 	const char * const argv[] = { ifname };
1043 	int e;
1044 
1045 	ctx = arg;
1046 	if (action == -1) {
1047 		ifp = if_find(ctx->ifaces, ifname);
1048 		if (ifp == NULL) {
1049 			errno = ESRCH;
1050 			return -1;
1051 		}
1052 		if (ifp->active) {
1053 			logdebugx("%s: interface departed", ifp->name);
1054 			ifp->options->options |= DHCPCD_DEPARTED;
1055 			stop_interface(ifp);
1056 		}
1057 		TAILQ_REMOVE(ctx->ifaces, ifp, next);
1058 		if_free(ifp);
1059 		return 0;
1060 	}
1061 
1062 	ifs = if_discover(ctx, &ifaddrs, -1, UNCONST(argv));
1063 	if (ifs == NULL) {
1064 		logerr(__func__);
1065 		return -1;
1066 	}
1067 
1068 	ifp = if_find(ifs, ifname);
1069 	if (ifp == NULL) {
1070 		/* This can happen if an interface is quickly added
1071 		 * and then removed. */
1072 		errno = ENOENT;
1073 		e = -1;
1074 		goto out;
1075 	}
1076 	e = 1;
1077 
1078 	/* Check if we already have the interface */
1079 	iff = if_find(ctx->ifaces, ifp->name);
1080 
1081 	if (iff != NULL) {
1082 		if (iff->active)
1083 			logdebugx("%s: interface updated", iff->name);
1084 		/* The flags and hwaddr could have changed */
1085 		iff->flags = ifp->flags;
1086 		iff->hwlen = ifp->hwlen;
1087 		if (ifp->hwlen != 0)
1088 			memcpy(iff->hwaddr, ifp->hwaddr, iff->hwlen);
1089 	} else {
1090 		TAILQ_REMOVE(ifs, ifp, next);
1091 		TAILQ_INSERT_TAIL(ctx->ifaces, ifp, next);
1092 		if (ifp->active) {
1093 			logdebugx("%s: interface added", ifp->name);
1094 			dhcpcd_initstate(ifp, 0);
1095 			run_preinit(ifp);
1096 		}
1097 		iff = ifp;
1098 	}
1099 
1100 	if (action > 0) {
1101 		if_learnaddrs(ctx, ifs, &ifaddrs);
1102 		if (iff->active)
1103 			dhcpcd_prestartinterface(iff);
1104 	}
1105 
1106 out:
1107 	/* Free our discovered list */
1108 	while ((ifp = TAILQ_FIRST(ifs))) {
1109 		TAILQ_REMOVE(ifs, ifp, next);
1110 		if_free(ifp);
1111 	}
1112 	free(ifs);
1113 
1114 	return e;
1115 }
1116 
1117 static void
1118 dhcpcd_handlelink(void *arg)
1119 {
1120 	struct dhcpcd_ctx *ctx = arg;
1121 
1122 	if (if_handlelink(ctx) == -1) {
1123 		if (errno == ENOBUFS || errno == ENOMEM) {
1124 			dhcpcd_linkoverflow(ctx);
1125 			return;
1126 		}
1127 		if (errno != ENOTSUP)
1128 			logerr(__func__);
1129 	}
1130 }
1131 
1132 static void
1133 dhcpcd_checkcarrier(void *arg)
1134 {
1135 	struct interface *ifp = arg;
1136 	int carrier;
1137 
1138 	/* Check carrier here rather than setting LINK_UNKNOWN.
1139 	 * This is because we force LINK_UNKNOWN as down for wireless which
1140 	 * we do not want when dealing with a route socket overflow. */
1141 	carrier = if_carrier(ifp);
1142 	dhcpcd_handlecarrier(ifp->ctx, carrier, ifp->flags, ifp->name);
1143 }
1144 
1145 #ifndef SMALL
1146 static void
1147 dhcpcd_setlinkrcvbuf(struct dhcpcd_ctx *ctx)
1148 {
1149 	socklen_t socklen;
1150 
1151 	if (ctx->link_rcvbuf == 0)
1152 		return;
1153 
1154 	logdebugx("setting route socket receive buffer size to %d bytes",
1155 	    ctx->link_rcvbuf);
1156 
1157 	socklen = sizeof(ctx->link_rcvbuf);
1158 	if (setsockopt(ctx->link_fd, SOL_SOCKET,
1159 	    SO_RCVBUF, &ctx->link_rcvbuf, socklen) == -1)
1160 		logerr(__func__);
1161 }
1162 #endif
1163 
1164 void
1165 dhcpcd_linkoverflow(struct dhcpcd_ctx *ctx)
1166 {
1167 	socklen_t socklen;
1168 	int rcvbuflen;
1169 	char buf[2048];
1170 	ssize_t rlen;
1171 	size_t rcnt;
1172 	struct if_head *ifaces;
1173 	struct ifaddrs *ifaddrs;
1174 	struct interface *ifp, *ifn, *ifp1;
1175 
1176 	socklen = sizeof(rcvbuflen);
1177 	if (getsockopt(ctx->link_fd, SOL_SOCKET,
1178 	    SO_RCVBUF, &rcvbuflen, &socklen) == -1)
1179 		rcvbuflen = 0;
1180 #ifdef __linux__
1181 	else
1182 		rcvbuflen /= 2;
1183 #endif
1184 
1185 	logerrx("route socket overflowed (rcvbuflen %d)"
1186 	    " - learning interface state", rcvbuflen);
1187 
1188 	/* Drain the socket.
1189 	 * We cannot open a new one due to privsep. */
1190 	rcnt = 0;
1191 	do {
1192 		rlen = read(ctx->link_fd, buf, sizeof(buf));
1193 		if (++rcnt % 1000 == 0)
1194 			logwarnx("drained %zu messages", rcnt);
1195 	} while (rlen != -1 || errno == ENOBUFS || errno == ENOMEM);
1196 	if (rcnt % 1000 != 0)
1197 		logwarnx("drained %zu messages", rcnt);
1198 
1199 	/* Work out the current interfaces. */
1200 	ifaces = if_discover(ctx, &ifaddrs, ctx->ifc, ctx->ifv);
1201 	if (ifaces == NULL) {
1202 		logerr(__func__);
1203 		return;
1204 	}
1205 
1206 	/* Punt departed interfaces */
1207 	TAILQ_FOREACH_SAFE(ifp, ctx->ifaces, next, ifn) {
1208 		if (if_find(ifaces, ifp->name) != NULL)
1209 			continue;
1210 		dhcpcd_handleinterface(ctx, -1, ifp->name);
1211 	}
1212 
1213 	/* Add new interfaces */
1214 	while ((ifp = TAILQ_FIRST(ifaces)) != NULL ) {
1215 		TAILQ_REMOVE(ifaces, ifp, next);
1216 		ifp1 = if_find(ctx->ifaces, ifp->name);
1217 		if (ifp1 != NULL) {
1218 			/* If the interface already exists,
1219 			 * check carrier state. */
1220 			eloop_timeout_add_sec(ctx->eloop, 0,
1221 			    dhcpcd_checkcarrier, ifp1);
1222 			if_free(ifp);
1223 			continue;
1224 		}
1225 		TAILQ_INSERT_TAIL(ctx->ifaces, ifp, next);
1226 		if (ifp->active)
1227 			eloop_timeout_add_sec(ctx->eloop, 0,
1228 			    dhcpcd_prestartinterface, ifp);
1229 	}
1230 	free(ifaces);
1231 
1232 	/* Update address state. */
1233 	if_markaddrsstale(ctx->ifaces);
1234 	if_learnaddrs(ctx, ctx->ifaces, &ifaddrs);
1235 	if_deletestaleaddrs(ctx->ifaces);
1236 }
1237 
1238 void
1239 dhcpcd_handlehwaddr(struct interface *ifp,
1240     uint16_t hwtype, const void *hwaddr, uint8_t hwlen)
1241 {
1242 	char buf[sizeof(ifp->hwaddr) * 3];
1243 
1244 	if (hwaddr == NULL || !if_valid_hwaddr(hwaddr, hwlen))
1245 		hwlen = 0;
1246 
1247 	if (hwlen > sizeof(ifp->hwaddr)) {
1248 		errno = ENOBUFS;
1249 		logerr("%s: %s", __func__, ifp->name);
1250 		return;
1251 	}
1252 
1253 	if (ifp->hwtype != hwtype) {
1254 		loginfox("%s: hardware address type changed from %d to %d",
1255 		    ifp->name, ifp->hwtype, hwtype);
1256 		ifp->hwtype = hwtype;
1257 	}
1258 
1259 	if (ifp->hwlen == hwlen &&
1260 	    (hwlen == 0 || memcmp(ifp->hwaddr, hwaddr, hwlen) == 0))
1261 		return;
1262 
1263 	loginfox("%s: new hardware address: %s", ifp->name,
1264 	    hwaddr_ntoa(hwaddr, hwlen, buf, sizeof(buf)));
1265 	ifp->hwlen = hwlen;
1266 	if (hwaddr != NULL)
1267 		memcpy(ifp->hwaddr, hwaddr, hwlen);
1268 }
1269 
1270 static void
1271 if_reboot(struct interface *ifp, int argc, char **argv)
1272 {
1273 #ifdef INET
1274 	unsigned long long oldopts;
1275 
1276 	oldopts = ifp->options->options;
1277 #endif
1278 	script_runreason(ifp, "RECONFIGURE");
1279 	dhcpcd_initstate1(ifp, argc, argv, 0);
1280 #ifdef INET
1281 	dhcp_reboot_newopts(ifp, oldopts);
1282 #endif
1283 #ifdef DHCP6
1284 	dhcp6_reboot(ifp);
1285 #endif
1286 	dhcpcd_prestartinterface(ifp);
1287 }
1288 
1289 static void
1290 reload_config(struct dhcpcd_ctx *ctx)
1291 {
1292 	struct if_options *ifo;
1293 
1294 	free_globals(ctx);
1295 	if ((ifo = read_config(ctx, NULL, NULL, NULL)) == NULL)
1296 		return;
1297 	add_options(ctx, NULL, ifo, ctx->argc, ctx->argv);
1298 	/* We need to preserve these two options. */
1299 	if (ctx->options & DHCPCD_MASTER)
1300 		ifo->options |= DHCPCD_MASTER;
1301 	if (ctx->options & DHCPCD_DAEMONISED)
1302 		ifo->options |= DHCPCD_DAEMONISED;
1303 	if (ctx->options & DHCPCD_PRIVSEP)
1304 		ifo->options |= DHCPCD_PRIVSEP;
1305 	ctx->options = ifo->options;
1306 	free_options(ctx, ifo);
1307 }
1308 
1309 static void
1310 reconf_reboot(struct dhcpcd_ctx *ctx, int action, int argc, char **argv, int oi)
1311 {
1312 	int i;
1313 	struct interface *ifp;
1314 
1315 	TAILQ_FOREACH(ifp, ctx->ifaces, next) {
1316 		for (i = oi; i < argc; i++) {
1317 			if (strcmp(ifp->name, argv[i]) == 0)
1318 				break;
1319 		}
1320 		if (oi != argc && i == argc)
1321 			continue;
1322 		if (ifp->active == IF_ACTIVE_USER) {
1323 			if (action)
1324 				if_reboot(ifp, argc, argv);
1325 #ifdef INET
1326 			else
1327 				ipv4_applyaddr(ifp);
1328 #endif
1329 		} else if (i != argc) {
1330 			ifp->active = IF_ACTIVE_USER;
1331 			dhcpcd_initstate1(ifp, argc, argv, 0);
1332 			run_preinit(ifp);
1333 			dhcpcd_prestartinterface(ifp);
1334 		}
1335 	}
1336 }
1337 
1338 static void
1339 stop_all_interfaces(struct dhcpcd_ctx *ctx, unsigned long long opts)
1340 {
1341 	struct interface *ifp;
1342 
1343 	ctx->options |= DHCPCD_EXITING;
1344 	/* Drop the last interface first */
1345 	TAILQ_FOREACH_REVERSE(ifp, ctx->ifaces, if_head, next) {
1346 		if (!ifp->active)
1347 			continue;
1348 		ifp->options->options |= opts;
1349 		if (ifp->options->options & DHCPCD_RELEASE)
1350 			ifp->options->options &= ~DHCPCD_PERSISTENT;
1351 		ifp->options->options |= DHCPCD_EXITING;
1352 		stop_interface(ifp);
1353 	}
1354 }
1355 
1356 static void
1357 dhcpcd_ifrenew(struct interface *ifp)
1358 {
1359 
1360 	if (!ifp->active)
1361 		return;
1362 
1363 	if (ifp->options->options & DHCPCD_LINK &&
1364 	    ifp->carrier == LINK_DOWN)
1365 		return;
1366 
1367 #ifdef INET
1368 	dhcp_renew(ifp);
1369 #endif
1370 #ifdef INET6
1371 #define DHCPCD_RARENEW (DHCPCD_IPV6 | DHCPCD_IPV6RS)
1372 	if ((ifp->options->options & DHCPCD_RARENEW) == DHCPCD_RARENEW)
1373 		ipv6nd_startrs(ifp);
1374 #endif
1375 #ifdef DHCP6
1376 	dhcp6_renew(ifp);
1377 #endif
1378 }
1379 
1380 static void
1381 dhcpcd_renew(struct dhcpcd_ctx *ctx)
1382 {
1383 	struct interface *ifp;
1384 
1385 	TAILQ_FOREACH(ifp, ctx->ifaces, next) {
1386 		dhcpcd_ifrenew(ifp);
1387 	}
1388 }
1389 
1390 #ifdef USE_SIGNALS
1391 #define sigmsg "received %s, %s"
1392 static void
1393 dhcpcd_signal_cb(int sig, void *arg)
1394 {
1395 	struct dhcpcd_ctx *ctx = arg;
1396 	unsigned long long opts;
1397 	int exit_code;
1398 
1399 	if (ctx->options & DHCPCD_FORKED) {
1400 		pid_t pid = pidfile_read(ctx->pidfile);
1401 		if (pid == -1) {
1402 			if (errno != ENOENT)
1403 				logerr("%s: pidfile_read",__func__);
1404 		} else if (pid == 0)
1405 			logerr("%s: pid cannot be zero", __func__);
1406 		else if (kill(pid, sig) == -1)
1407 			logerr("%s: kill", __func__);
1408 		return;
1409 	}
1410 
1411 	opts = 0;
1412 	exit_code = EXIT_FAILURE;
1413 	switch (sig) {
1414 	case SIGINT:
1415 		loginfox(sigmsg, "SIGINT", "stopping");
1416 		break;
1417 	case SIGTERM:
1418 		loginfox(sigmsg, "SIGTERM", "stopping");
1419 		exit_code = EXIT_SUCCESS;
1420 		break;
1421 	case SIGALRM:
1422 		loginfox(sigmsg, "SIGALRM", "releasing");
1423 		opts |= DHCPCD_RELEASE;
1424 		exit_code = EXIT_SUCCESS;
1425 		break;
1426 	case SIGHUP:
1427 		loginfox(sigmsg, "SIGHUP", "rebinding");
1428 		reload_config(ctx);
1429 		/* Preserve any options passed on the commandline
1430 		 * when we were started. */
1431 		reconf_reboot(ctx, 1, ctx->argc, ctx->argv,
1432 		    ctx->argc - ctx->ifc);
1433 		return;
1434 	case SIGUSR1:
1435 		loginfox(sigmsg, "SIGUSR1", "renewing");
1436 		dhcpcd_renew(ctx);
1437 		return;
1438 	case SIGUSR2:
1439 		loginfox(sigmsg, "SIGUSR2", "reopening log");
1440 		/* XXX This may not work that well in a chroot */
1441 		logclose();
1442 		if (logopen(ctx->logfile) == -1)
1443 			logerr(__func__);
1444 		return;
1445 	default:
1446 		logerrx("received signal %d but don't know what to do with it",
1447 		    sig);
1448 		return;
1449 	}
1450 
1451 	if (!(ctx->options & DHCPCD_TEST))
1452 		stop_all_interfaces(ctx, opts);
1453 	eloop_exit(ctx->eloop, exit_code);
1454 }
1455 #endif
1456 
1457 static void
1458 dhcpcd_getinterfaces(void *arg)
1459 {
1460 	struct fd_list *fd = arg;
1461 	struct interface *ifp;
1462 	size_t len;
1463 
1464 	len = 0;
1465 	TAILQ_FOREACH(ifp, fd->ctx->ifaces, next) {
1466 		if (!ifp->active)
1467 			continue;
1468 		len++;
1469 #ifdef INET
1470 		if (D_STATE_RUNNING(ifp))
1471 			len++;
1472 #endif
1473 #ifdef IPV4LL
1474 		if (IPV4LL_STATE_RUNNING(ifp))
1475 			len++;
1476 #endif
1477 #ifdef INET6
1478 		if (IPV6_STATE_RUNNING(ifp))
1479 			len++;
1480 		if (RS_STATE_RUNNING(ifp))
1481 			len++;
1482 #endif
1483 #ifdef DHCP6
1484 		if (D6_STATE_RUNNING(ifp))
1485 			len++;
1486 #endif
1487 	}
1488 	if (write(fd->fd, &len, sizeof(len)) != sizeof(len))
1489 		return;
1490 	eloop_event_remove_writecb(fd->ctx->eloop, fd->fd);
1491 	TAILQ_FOREACH(ifp, fd->ctx->ifaces, next) {
1492 		if (!ifp->active)
1493 			continue;
1494 		if (send_interface(fd, ifp, AF_UNSPEC) == -1)
1495 			logerr(__func__);
1496 	}
1497 }
1498 
1499 int
1500 dhcpcd_handleargs(struct dhcpcd_ctx *ctx, struct fd_list *fd,
1501     int argc, char **argv)
1502 {
1503 	struct interface *ifp;
1504 	unsigned long long opts;
1505 	int opt, oi, do_reboot, do_renew, af = AF_UNSPEC;
1506 	size_t len, l;
1507 	char *tmp, *p;
1508 
1509 	/* Special commands for our control socket
1510 	 * as the other end should be blocking until it gets the
1511 	 * expected reply we should be safely able just to change the
1512 	 * write callback on the fd */
1513 	if (strcmp(*argv, "--version") == 0) {
1514 		return control_queue(fd, UNCONST(VERSION),
1515 		    strlen(VERSION) + 1, false);
1516 	} else if (strcmp(*argv, "--getconfigfile") == 0) {
1517 		return control_queue(fd, UNCONST(fd->ctx->cffile),
1518 		    strlen(fd->ctx->cffile) + 1, false);
1519 	} else if (strcmp(*argv, "--getinterfaces") == 0) {
1520 		eloop_event_add_w(fd->ctx->eloop, fd->fd,
1521 		    dhcpcd_getinterfaces, fd);
1522 		return 0;
1523 	} else if (strcmp(*argv, "--listen") == 0) {
1524 		fd->flags |= FD_LISTEN;
1525 		return 0;
1526 	}
1527 
1528 	/* Log the command */
1529 	len = 1;
1530 	for (opt = 0; opt < argc; opt++)
1531 		len += strlen(argv[opt]) + 1;
1532 	tmp = malloc(len);
1533 	if (tmp == NULL)
1534 		return -1;
1535 	p = tmp;
1536 	for (opt = 0; opt < argc; opt++) {
1537 		l = strlen(argv[opt]);
1538 		strlcpy(p, argv[opt], len);
1539 		len -= l + 1;
1540 		p += l;
1541 		*p++ = ' ';
1542 	}
1543 	*--p = '\0';
1544 	loginfox("control command: %s", tmp);
1545 	free(tmp);
1546 
1547 	optind = 0;
1548 	oi = 0;
1549 	opts = 0;
1550 	do_reboot = do_renew = 0;
1551 	while ((opt = getopt_long(argc, argv, IF_OPTS, cf_options, &oi)) != -1)
1552 	{
1553 		switch (opt) {
1554 		case 'g':
1555 			/* Assumed if below not set */
1556 			break;
1557 		case 'k':
1558 			opts |= DHCPCD_RELEASE;
1559 			break;
1560 		case 'n':
1561 			do_reboot = 1;
1562 			break;
1563 		case 'p':
1564 			opts |= DHCPCD_PERSISTENT;
1565 			break;
1566 		case 'x':
1567 			opts |= DHCPCD_EXITING;
1568 			break;
1569 		case 'N':
1570 			do_renew = 1;
1571 			break;
1572 		case 'U':
1573 			opts |= DHCPCD_DUMPLEASE;
1574 			break;
1575 		case '4':
1576 			af = AF_INET;
1577 			break;
1578 		case '6':
1579 			af = AF_INET6;
1580 			break;
1581 		}
1582 	}
1583 
1584 	if (opts & DHCPCD_DUMPLEASE) {
1585 		ctx->options |= DHCPCD_DUMPLEASE;
1586 		size_t nifaces = 0;
1587 
1588 		TAILQ_FOREACH(ifp, ctx->ifaces, next) {
1589 			if (!ifp->active)
1590 				continue;
1591 			for (oi = optind; oi < argc; oi++) {
1592 				if (strcmp(ifp->name, argv[oi]) == 0)
1593 					break;
1594 			}
1595 			if (optind == argc || oi < argc) {
1596 				opt = send_interface(NULL, ifp, af);
1597 				if (opt == -1)
1598 					goto dumperr;
1599 				nifaces += (size_t)opt;
1600 			}
1601 		}
1602 		if (write(fd->fd, &nifaces, sizeof(nifaces)) != sizeof(nifaces))
1603 			goto dumperr;
1604 		TAILQ_FOREACH(ifp, ctx->ifaces, next) {
1605 			if (!ifp->active)
1606 				continue;
1607 			for (oi = optind; oi < argc; oi++) {
1608 				if (strcmp(ifp->name, argv[oi]) == 0)
1609 					break;
1610 			}
1611 			if (optind == argc || oi < argc) {
1612 				if (send_interface(fd, ifp, af) == -1)
1613 					goto dumperr;
1614 			}
1615 		}
1616 		ctx->options &= ~DHCPCD_DUMPLEASE;
1617 		return 0;
1618 dumperr:
1619 		ctx->options &= ~DHCPCD_DUMPLEASE;
1620 		return -1;
1621 	}
1622 
1623 	/* Only privileged users can control dhcpcd via the socket. */
1624 	if (fd->flags & FD_UNPRIV) {
1625 		errno = EPERM;
1626 		return -1;
1627 	}
1628 
1629 	if (opts & (DHCPCD_EXITING | DHCPCD_RELEASE)) {
1630 		if (optind == argc) {
1631 			stop_all_interfaces(ctx, opts);
1632 			eloop_exit(ctx->eloop, EXIT_SUCCESS);
1633 			return 0;
1634 		}
1635 		for (oi = optind; oi < argc; oi++) {
1636 			if ((ifp = if_find(ctx->ifaces, argv[oi])) == NULL)
1637 				continue;
1638 			if (!ifp->active)
1639 				continue;
1640 			ifp->options->options |= opts;
1641 			if (opts & DHCPCD_RELEASE)
1642 				ifp->options->options &= ~DHCPCD_PERSISTENT;
1643 			stop_interface(ifp);
1644 		}
1645 		return 0;
1646 	}
1647 
1648 	if (do_renew) {
1649 		if (optind == argc) {
1650 			dhcpcd_renew(ctx);
1651 			return 0;
1652 		}
1653 		for (oi = optind; oi < argc; oi++) {
1654 			if ((ifp = if_find(ctx->ifaces, argv[oi])) == NULL)
1655 				continue;
1656 			dhcpcd_ifrenew(ifp);
1657 		}
1658 		return 0;
1659 	}
1660 
1661 	reload_config(ctx);
1662 	/* XXX: Respect initial commandline options? */
1663 	reconf_reboot(ctx, do_reboot, argc, argv, optind - 1);
1664 	return 0;
1665 }
1666 
1667 static int
1668 dhcpcd_readdump(struct dhcpcd_ctx *ctx)
1669 {
1670 	int error = 0;
1671 	size_t nifaces, buflen = 0, dlen;
1672 	ssize_t len;
1673 	char *buf = NULL;
1674 
1675 again1:
1676 	len = read(ctx->control_fd, &nifaces, sizeof(nifaces));
1677 	if (len == -1) {
1678 		if (errno == EAGAIN)
1679 			goto again1;
1680 		return -1;
1681 	}
1682 	if (len != sizeof(nifaces)) {
1683 		errno = EINVAL;
1684 		return -1;
1685 	}
1686 	for (; nifaces > 0; nifaces--) {
1687 again2:
1688 		len = read(ctx->control_fd, &dlen, sizeof(dlen));
1689 		if (len == -1) {
1690 			if (errno == EAGAIN)
1691 				goto again2;
1692 			error = -1;
1693 			goto out;
1694 		}
1695 		if (len != sizeof(dlen)) {
1696 			errno = EINVAL;
1697 			goto out;
1698 		}
1699 		if (dlen > buflen) {
1700 			char *nbuf = realloc(buf, dlen);
1701 			if (nbuf == NULL) {
1702 				error = -1;
1703 				goto out;
1704 			}
1705 			buf = nbuf;
1706 			buflen = dlen;
1707 		}
1708 		if (dlen == 0) {
1709 			errno = EINVAL;
1710 			error = -1;
1711 			goto out;
1712 		}
1713 again3:
1714 		if (read(ctx->control_fd, buf, dlen) != (ssize_t)dlen) {
1715 			if (errno == EAGAIN)
1716 				goto again3;
1717 			error = -1;
1718 			goto out;
1719 		}
1720 		script_dump(buf, dlen);
1721 		fflush(stdout);
1722 		if (nifaces != 1)
1723 			putchar('\n');
1724 	}
1725 
1726 out:
1727 	free(buf);
1728 	return error;
1729 }
1730 
1731 static void
1732 dhcpcd_fork_cb(void *arg)
1733 {
1734 	struct dhcpcd_ctx *ctx = arg;
1735 	int exit_code;
1736 	ssize_t len;
1737 
1738 	len = read(ctx->fork_fd, &exit_code, sizeof(exit_code));
1739 	if (len == -1) {
1740 		logerr(__func__);
1741 		exit_code = EXIT_FAILURE;
1742 	} else if ((size_t)len < sizeof(exit_code)) {
1743 		logerrx("%s: truncated read %zd (expected %zu)",
1744 		    __func__, len, sizeof(exit_code));
1745 		exit_code = EXIT_FAILURE;
1746 	}
1747 	eloop_exit(ctx->eloop, exit_code);
1748 }
1749 
1750 int
1751 main(int argc, char **argv)
1752 {
1753 	struct dhcpcd_ctx ctx;
1754 	struct ifaddrs *ifaddrs = NULL;
1755 	struct if_options *ifo;
1756 	struct interface *ifp;
1757 	sa_family_t family = AF_UNSPEC;
1758 	int opt, oi = 0, i;
1759 	unsigned int logopts, t;
1760 	ssize_t len;
1761 #if defined(USE_SIGNALS) || !defined(THERE_IS_NO_FORK)
1762 	pid_t pid;
1763 	int sigpipe[2];
1764 #endif
1765 #ifdef USE_SIGNALS
1766 	int sig = 0;
1767 	const char *siga = NULL;
1768 	size_t si;
1769 #endif
1770 
1771 	/* Test for --help and --version */
1772 	if (argc > 1) {
1773 		if (strcmp(argv[1], "--help") == 0) {
1774 			usage();
1775 			return EXIT_SUCCESS;
1776 		} else if (strcmp(argv[1], "--version") == 0) {
1777 			printf(""PACKAGE" "VERSION"\n%s\n", dhcpcd_copyright);
1778 			printf("Compiled in features:"
1779 #ifdef INET
1780 			" INET"
1781 #endif
1782 #ifdef ARP
1783 			" ARP"
1784 #endif
1785 #ifdef ARPING
1786 			" ARPing"
1787 #endif
1788 #ifdef IPV4LL
1789 			" IPv4LL"
1790 #endif
1791 #ifdef INET6
1792 			" INET6"
1793 #endif
1794 #ifdef DHCP6
1795 			" DHCPv6"
1796 #endif
1797 #ifdef AUTH
1798 			" AUTH"
1799 #endif
1800 #ifdef PRIVSEP
1801 			" PRIVSEP"
1802 #endif
1803 			"\n");
1804 			return EXIT_SUCCESS;
1805 		}
1806 	}
1807 
1808 	memset(&ctx, 0, sizeof(ctx));
1809 
1810 	ifo = NULL;
1811 	ctx.cffile = CONFIG;
1812 	ctx.script = UNCONST(dhcpcd_default_script);
1813 	ctx.control_fd = ctx.control_unpriv_fd = ctx.link_fd = -1;
1814 	ctx.pf_inet_fd = -1;
1815 
1816 	TAILQ_INIT(&ctx.control_fds);
1817 #ifdef USE_SIGNALS
1818 	ctx.fork_fd = -1;
1819 #endif
1820 #ifdef PLUGIN_DEV
1821 	ctx.dev_fd = -1;
1822 #endif
1823 #ifdef INET
1824 	ctx.udp_rfd = -1;
1825 	ctx.udp_wfd = -1;
1826 #endif
1827 #if defined(INET6) && !defined(__sun)
1828 	ctx.nd_fd = -1;
1829 #endif
1830 #ifdef DHCP6
1831 	ctx.dhcp6_rfd = -1;
1832 	ctx.dhcp6_wfd = -1;
1833 #endif
1834 #ifdef PRIVSEP
1835 	ctx.ps_root_fd = ctx.ps_data_fd = -1;
1836 	TAILQ_INIT(&ctx.ps_processes);
1837 #endif
1838 	rt_init(&ctx);
1839 
1840 	logopts = LOGERR_ERR|LOGERR_LOG|LOGERR_LOG_DATE|LOGERR_LOG_PID;
1841 	i = 0;
1842 	while ((opt = getopt_long(argc, argv,
1843 	    ctx.options & DHCPCD_PRINT_PIDFILE ? NOERR_IF_OPTS : IF_OPTS,
1844 	    cf_options, &oi)) != -1)
1845 	{
1846 		switch (opt) {
1847 		case '4':
1848 			family = AF_INET;
1849 			break;
1850 		case '6':
1851 			family = AF_INET6;
1852 			break;
1853 		case 'f':
1854 			ctx.cffile = optarg;
1855 			break;
1856 		case 'j':
1857 			free(ctx.logfile);
1858 			ctx.logfile = strdup(optarg);
1859 			break;
1860 #ifdef USE_SIGNALS
1861 		case 'k':
1862 			sig = SIGALRM;
1863 			siga = "ALRM";
1864 			break;
1865 		case 'n':
1866 			sig = SIGHUP;
1867 			siga = "HUP";
1868 			break;
1869 		case 'g':
1870 		case 'p':
1871 			/* Force going via command socket as we're
1872 			 * out of user definable signals. */
1873 			i = 4;
1874 			break;
1875 		case 'q':
1876 			/* -qq disables console output entirely.
1877 			 * This is important for systemd because it logs
1878 			 * both console AND syslog to the same log
1879 			 * resulting in untold confusion. */
1880 			if (logopts & LOGERR_QUIET)
1881 				logopts &= ~LOGERR_ERR;
1882 			else
1883 				logopts |= LOGERR_QUIET;
1884 			break;
1885 		case 'x':
1886 			sig = SIGTERM;
1887 			siga = "TERM";
1888 			break;
1889 		case 'N':
1890 			sig = SIGUSR1;
1891 			siga = "USR1";
1892 			break;
1893 #endif
1894 		case 'P':
1895 			ctx.options |= DHCPCD_PRINT_PIDFILE;
1896 			logopts &= ~(LOGERR_LOG | LOGERR_ERR);
1897 			break;
1898 		case 'T':
1899 			i = 1;
1900 			logopts &= ~LOGERR_LOG;
1901 			break;
1902 		case 'U':
1903 			i = 3;
1904 			break;
1905 		case 'V':
1906 			i = 2;
1907 			break;
1908 		case '?':
1909 			if (ctx.options & DHCPCD_PRINT_PIDFILE)
1910 				continue;
1911 			usage();
1912 			goto exit_failure;
1913 		}
1914 	}
1915 
1916 	logsetopts(logopts);
1917 	logopen(ctx.logfile);
1918 
1919 	ctx.argv = argv;
1920 	ctx.argc = argc;
1921 	ctx.ifc = argc - optind;
1922 	ctx.ifv = argv + optind;
1923 
1924 	ifo = read_config(&ctx, NULL, NULL, NULL);
1925 	if (ifo == NULL) {
1926 		if (ctx.options & DHCPCD_PRINT_PIDFILE)
1927 			goto printpidfile;
1928 		goto exit_failure;
1929 	}
1930 	opt = add_options(&ctx, NULL, ifo, argc, argv);
1931 	if (opt != 1) {
1932 		if (ctx.options & DHCPCD_PRINT_PIDFILE)
1933 			goto printpidfile;
1934 		if (opt == 0)
1935 			usage();
1936 		goto exit_failure;
1937 	}
1938 	if (i == 2) {
1939 		printf("Interface options:\n");
1940 		if (optind == argc - 1) {
1941 			free_options(&ctx, ifo);
1942 			ifo = read_config(&ctx, argv[optind], NULL, NULL);
1943 			if (ifo == NULL)
1944 				goto exit_failure;
1945 			add_options(&ctx, NULL, ifo, argc, argv);
1946 		}
1947 		if_printoptions();
1948 #ifdef INET
1949 		if (family == 0 || family == AF_INET) {
1950 			printf("\nDHCPv4 options:\n");
1951 			dhcp_printoptions(&ctx,
1952 			    ifo->dhcp_override, ifo->dhcp_override_len);
1953 		}
1954 #endif
1955 #ifdef INET6
1956 		if (family == 0 || family == AF_INET6) {
1957 			printf("\nND options:\n");
1958 			ipv6nd_printoptions(&ctx,
1959 			    ifo->nd_override, ifo->nd_override_len);
1960 #ifdef DHCP6
1961 			printf("\nDHCPv6 options:\n");
1962 			dhcp6_printoptions(&ctx,
1963 			    ifo->dhcp6_override, ifo->dhcp6_override_len);
1964 #endif
1965 		}
1966 #endif
1967 		goto exit_success;
1968 	}
1969 	ctx.options |= ifo->options;
1970 	if (i == 1 || i == 3) {
1971 		if (i == 1)
1972 			ctx.options |= DHCPCD_TEST;
1973 		else
1974 			ctx.options |= DHCPCD_DUMPLEASE;
1975 		ctx.options |= DHCPCD_PERSISTENT;
1976 		ctx.options &= ~DHCPCD_DAEMONISE;
1977 	}
1978 
1979 #ifdef THERE_IS_NO_FORK
1980 	ctx.options &= ~DHCPCD_DAEMONISE;
1981 #endif
1982 
1983 	if (ctx.options & DHCPCD_DEBUG)
1984 		logsetopts(logopts | LOGERR_DEBUG);
1985 
1986 	if (!(ctx.options & (DHCPCD_TEST | DHCPCD_DUMPLEASE))) {
1987 printpidfile:
1988 		/* If we have any other args, we should run as a single dhcpcd
1989 		 *  instance for that interface. */
1990 		if (optind == argc - 1 && !(ctx.options & DHCPCD_MASTER)) {
1991 			const char *per;
1992 			const char *ifname;
1993 
1994 			ifname = *ctx.ifv;
1995 			if (ifname == NULL || strlen(ifname) > IF_NAMESIZE) {
1996 				errno = ifname == NULL ? EINVAL : E2BIG;
1997 				logerr("%s: ", ifname);
1998 				goto exit_failure;
1999 			}
2000 			/* Allow a dhcpcd interface per address family */
2001 			switch(family) {
2002 			case AF_INET:
2003 				per = "-4";
2004 				break;
2005 			case AF_INET6:
2006 				per = "-6";
2007 				break;
2008 			default:
2009 				per = "";
2010 			}
2011 			snprintf(ctx.pidfile, sizeof(ctx.pidfile),
2012 			    PIDFILE, ifname, per, ".");
2013 		} else {
2014 			snprintf(ctx.pidfile, sizeof(ctx.pidfile),
2015 			    PIDFILE, "", "", "");
2016 			ctx.options |= DHCPCD_MASTER;
2017 		}
2018 		if (ctx.options & DHCPCD_PRINT_PIDFILE) {
2019 			printf("%s\n", ctx.pidfile);
2020 			goto exit_success;
2021 		}
2022 	}
2023 
2024 	if (chdir("/") == -1)
2025 		logerr("%s: chdir `/'", __func__);
2026 
2027 	/* Freeing allocated addresses from dumping leases can trigger
2028 	 * eloop removals as well, so init here. */
2029 	if ((ctx.eloop = eloop_new()) == NULL) {
2030 		logerr("%s: eloop_init", __func__);
2031 		goto exit_failure;
2032 	}
2033 
2034 #ifdef USE_SIGNALS
2035 	for (si = 0; si < dhcpcd_signals_ignore_len; si++)
2036 		signal(dhcpcd_signals_ignore[si], SIG_IGN);
2037 
2038 	/* Save signal mask, block and redirect signals to our handler */
2039 	if (eloop_signal_set_cb(ctx.eloop,
2040 	    dhcpcd_signals, dhcpcd_signals_len,
2041 	    dhcpcd_signal_cb, &ctx) == -1)
2042 	{
2043 		logerr("%s: eloop_signal_set_cb", __func__);
2044 		goto exit_failure;
2045 	}
2046 	if (eloop_signal_mask(ctx.eloop, &ctx.sigset) == -1) {
2047 		logerr("%s: eloop_signal_mask", __func__);
2048 		goto exit_failure;
2049 	}
2050 
2051 	if (sig != 0) {
2052 		pid = pidfile_read(ctx.pidfile);
2053 		if (pid != 0 && pid != -1)
2054 			loginfox("sending signal %s to pid %d", siga, pid);
2055 		if (pid == 0 || pid == -1 || kill(pid, sig) != 0) {
2056 			if (sig != SIGHUP && sig != SIGUSR1 && errno != EPERM)
2057 				logerrx(PACKAGE" not running");
2058 			if (pid != 0 && pid != -1 && errno != ESRCH) {
2059 				logerr("kill");
2060 				goto exit_failure;
2061 			}
2062 			unlink(ctx.pidfile);
2063 			if (sig != SIGHUP && sig != SIGUSR1)
2064 				goto exit_failure;
2065 		} else {
2066 			struct timespec ts;
2067 
2068 			if (sig == SIGHUP || sig == SIGUSR1)
2069 				goto exit_success;
2070 			/* Spin until it exits */
2071 			loginfox("waiting for pid %d to exit", pid);
2072 			ts.tv_sec = 0;
2073 			ts.tv_nsec = 100000000; /* 10th of a second */
2074 			for(i = 0; i < 100; i++) {
2075 				nanosleep(&ts, NULL);
2076 				if (pidfile_read(ctx.pidfile) == -1)
2077 					goto exit_success;
2078 			}
2079 			logerrx("pid %d failed to exit", pid);
2080 			goto exit_failure;
2081 		}
2082 	}
2083 #endif
2084 
2085 #ifndef SMALL
2086 	if (ctx.options & DHCPCD_DUMPLEASE &&
2087 	    ioctl(fileno(stdin), FIONREAD, &i, sizeof(i)) == 0 &&
2088 	    i > 0)
2089 	{
2090 		ifp = calloc(1, sizeof(*ifp));
2091 		if (ifp == NULL) {
2092 			logerr(__func__);
2093 			goto exit_failure;
2094 		}
2095 		ifp->ctx = &ctx;
2096 		ifp->options = ifo;
2097 		switch (family) {
2098 		case AF_INET:
2099 #ifdef INET
2100 			if (dhcp_dump(ifp) == -1)
2101 				goto exit_failure;
2102 			break;
2103 #else
2104 			logerrx("No DHCP support");
2105 			goto exit_failure
2106 #endif
2107 		case AF_INET6:
2108 #ifdef DHCP6
2109 			if (dhcp6_dump(ifp) == -1)
2110 				goto exit_failure;
2111 			break;
2112 #else
2113 			logerrx("No DHCP6 support");
2114 			goto exit_failure
2115 #endif
2116 		default:
2117 			logerrx("Family not specified. Please use -4 or -6.");
2118 			goto exit_failure;
2119 		}
2120 		goto exit_success;
2121 	}
2122 #endif
2123 
2124 	/* Test against siga instead of sig to avoid gcc
2125 	 * warning about a bogus potential signed overflow.
2126 	 * The end result will be the same. */
2127 	if ((siga == NULL || i == 4 || ctx.ifc != 0) &&
2128 	    !(ctx.options & DHCPCD_TEST))
2129 	{
2130 		ctx.options |= DHCPCD_FORKED; /* avoid socket unlink */
2131 		if (!(ctx.options & DHCPCD_MASTER))
2132 			ctx.control_fd = control_open(argv[optind], family,
2133 			    ctx.options & DHCPCD_DUMPLEASE);
2134 		if (ctx.control_fd == -1)
2135 			ctx.control_fd = control_open(NULL, AF_UNSPEC,
2136 			    ctx.options & DHCPCD_DUMPLEASE);
2137 		if (ctx.control_fd != -1) {
2138 			if (!(ctx.options & DHCPCD_DUMPLEASE))
2139 				loginfox("sending commands to dhcpcd process");
2140 			len = control_send(&ctx, argc, argv);
2141 			if (len > 0)
2142 				logdebugx("send OK");
2143 			else {
2144 				logerr("%s: control_send", __func__);
2145 				goto exit_failure;
2146 			}
2147 			if (ctx.options & DHCPCD_DUMPLEASE) {
2148 				if (dhcpcd_readdump(&ctx) == -1) {
2149 					logerr("%s: dhcpcd_readdump", __func__);
2150 					goto exit_failure;
2151 				}
2152 			}
2153 			goto exit_success;
2154 		} else {
2155 			if (errno != ENOENT)
2156 				logerr("%s: control_open", __func__);
2157 			if (ctx.options & DHCPCD_DUMPLEASE) {
2158 				if (errno == ENOENT)
2159 					logerrx("dhcpcd is not running");
2160 				goto exit_failure;
2161 			}
2162 		}
2163 		ctx.options &= ~DHCPCD_FORKED;
2164 	}
2165 
2166 	if (!(ctx.options & DHCPCD_TEST)) {
2167 		/* Ensure we have the needed directories */
2168 		if (mkdir(RUNDIR, 0755) == -1 && errno != EEXIST)
2169 			logerr("%s: mkdir `%s'", __func__, RUNDIR);
2170 		if ((pid = pidfile_lock(ctx.pidfile)) != 0) {
2171 			if (pid == -1)
2172 				logerr("%s: pidfile_lock: %s",
2173 				    __func__, ctx.pidfile);
2174 			else
2175 				logerrx(PACKAGE
2176 				    " already running on pid %d (%s)",
2177 				    pid, ctx.pidfile);
2178 			goto exit_failure;
2179 		}
2180 	}
2181 
2182 	loginfox(PACKAGE "-" VERSION " starting");
2183 	freopen(_PATH_DEVNULL, "r", stdin);
2184 
2185 #ifdef PRIVSEP
2186 	ps_init(&ctx);
2187 #endif
2188 
2189 #ifdef USE_SIGNALS
2190 	if (pipe(sigpipe) == -1) {
2191 		logerr("pipe");
2192 		goto exit_failure;
2193 	}
2194 	switch (pid = fork()) {
2195 	case -1:
2196 		logerr("fork");
2197 		goto exit_failure;
2198 	case 0:
2199 		ctx.fork_fd = sigpipe[1];
2200 		close(sigpipe[0]);
2201 		if (setsid() == -1) {
2202 			logerr("%s: setsid", __func__);
2203 			goto exit_failure;
2204 		}
2205 		/* Ensure we can never get a controlling terminal */
2206 		switch (pid = fork()) {
2207 		case -1:
2208 			logerr("fork");
2209 			goto exit_failure;
2210 		case 0:
2211 			eloop_requeue(ctx.eloop);
2212 			break;
2213 		default:
2214 			ctx.options |= DHCPCD_FORKED; /* A lie */
2215 			i = EXIT_SUCCESS;
2216 			goto exit1;
2217 		}
2218 		break;
2219 	default:
2220 		waitpid(pid, &i, 0);
2221 		ctx.options |= DHCPCD_FORKED; /* A lie */
2222 		ctx.fork_fd = sigpipe[0];
2223 		close(sigpipe[1]);
2224 		setproctitle("[launcher]");
2225 		eloop_event_add(ctx.eloop, ctx.fork_fd, dhcpcd_fork_cb, &ctx);
2226 		goto run_loop;
2227 	}
2228 
2229 	/* We have now forked, setsid, forked once more.
2230 	 * From this point on, we are the controlling daemon. */
2231 	ctx.options |= DHCPCD_STARTED;
2232 	if ((pid = pidfile_lock(ctx.pidfile)) != 0) {
2233 		logerr("%s: pidfile_lock %d", __func__, pid);
2234 		goto exit_failure;
2235 	}
2236 #endif
2237 
2238 #if defined(BSD) && defined(INET6)
2239 	/* Disable the kernel RTADV sysctl as early as possible. */
2240 	if (ctx.options & DHCPCD_IPV6 && ctx.options & DHCPCD_IPV6RS)
2241 		if_disable_rtadv();
2242 #endif
2243 
2244 	/* If we're not running in privsep, we need to create the DB
2245 	 * directory here. */
2246 	if (!(ctx.options & DHCPCD_PRIVSEP)) {
2247 		if (mkdir(DBDIR, 0755) == -1 && errno != EEXIST)
2248 			logerr("%s: mkdir `%s'", __func__, DBDIR);
2249 	}
2250 
2251 #ifdef PRIVSEP
2252 	if (ctx.options & DHCPCD_PRIVSEP && ps_start(&ctx) == -1) {
2253 		logerr("ps_start");
2254 		goto exit_failure;
2255 	}
2256 	if (ctx.options & DHCPCD_FORKED)
2257 		goto run_loop;
2258 #endif
2259 
2260 	if (!(ctx.options & DHCPCD_TEST) &&
2261 	    control_start(&ctx,
2262 	    ctx.options & DHCPCD_MASTER ? NULL : argv[optind], family) == -1)
2263 	{
2264 		logerr("%s: control_start", __func__);
2265 		goto exit_failure;
2266 	}
2267 
2268 #ifdef PLUGIN_DEV
2269 	/* Start any dev listening plugin which may want to
2270 	 * change the interface name provided by the kernel */
2271 	if (!IN_PRIVSEP(&ctx) &&
2272 	    (ctx.options & (DHCPCD_MASTER | DHCPCD_DEV)) ==
2273 	    (DHCPCD_MASTER | DHCPCD_DEV))
2274 		dev_start(&ctx, dhcpcd_handleinterface);
2275 #endif
2276 
2277 	setproctitle("%s%s%s",
2278 	    ctx.options & DHCPCD_MASTER ? "[master]" : argv[optind],
2279 	    ctx.options & DHCPCD_IPV4 ? " [ip4]" : "",
2280 	    ctx.options & DHCPCD_IPV6 ? " [ip6]" : "");
2281 
2282 	if (if_opensockets(&ctx) == -1) {
2283 		logerr("%s: if_opensockets", __func__);
2284 		goto exit_failure;
2285 	}
2286 #ifndef SMALL
2287 	dhcpcd_setlinkrcvbuf(&ctx);
2288 #endif
2289 
2290 	/* Try and create DUID from the machine UUID. */
2291 	dhcpcd_initduid(&ctx, NULL);
2292 
2293 	/* Cache the default vendor option. */
2294 	if (dhcp_vendor(ctx.vendor, sizeof(ctx.vendor)) == -1)
2295 		logerrx("dhcp_vendor");
2296 
2297 #ifdef PRIVSEP
2298 	if (ctx.options & DHCPCD_PRIVSEP) {
2299 		if (ps_dropprivs(&ctx) == -1) {
2300 			logerr("ps_dropprivs");
2301 			goto exit_failure;
2302 		}
2303 #ifdef HAVE_CAPSICUM
2304 		if (cap_enter() == -1 && errno != ENOSYS) {
2305 			logerr("%s: cap_enter", __func__);
2306 			goto exit_failure;
2307 		}
2308 #endif
2309 #ifdef HAVE_PLEDGE
2310 		if (pledge("stdio inet route dns", NULL) == -1) {
2311 			logerr("%s: pledge", __func__);
2312 			goto exit_failure;
2313 		}
2314 #endif
2315 	}
2316 #endif
2317 
2318 	/* When running dhcpcd against a single interface, we need to retain
2319 	 * the old behaviour of waiting for an IP address */
2320 	if (ctx.ifc == 1 && !(ctx.options & DHCPCD_BACKGROUND))
2321 		ctx.options |= DHCPCD_WAITIP;
2322 
2323 	/* Start handling kernel messages for interfaces, addresses and
2324 	 * routes. */
2325 	eloop_event_add(ctx.eloop, ctx.link_fd, dhcpcd_handlelink, &ctx);
2326 
2327 	ctx.ifaces = if_discover(&ctx, &ifaddrs, ctx.ifc, ctx.ifv);
2328 	if (ctx.ifaces == NULL) {
2329 		logerr("%s: if_discover", __func__);
2330 		goto exit_failure;
2331 	}
2332 	for (i = 0; i < ctx.ifc; i++) {
2333 		if ((ifp = if_find(ctx.ifaces, ctx.ifv[i])) == NULL)
2334 			logerrx("%s: interface not found",
2335 			    ctx.ifv[i]);
2336 		else if (!ifp->active)
2337 			logerrx("%s: interface has an invalid configuration",
2338 			    ctx.ifv[i]);
2339 	}
2340 	TAILQ_FOREACH(ifp, ctx.ifaces, next) {
2341 		if (ifp->active == IF_ACTIVE_USER)
2342 			break;
2343 	}
2344 	if (ifp == NULL) {
2345 		if (ctx.ifc == 0) {
2346 			int loglevel;
2347 
2348 			loglevel = ctx.options & DHCPCD_INACTIVE ?
2349 			    LOG_DEBUG : LOG_ERR;
2350 			logmessage(loglevel, "no valid interfaces found");
2351 			dhcpcd_daemonise(&ctx);
2352 		} else
2353 			goto exit_failure;
2354 		if (!(ctx.options & DHCPCD_LINK)) {
2355 			logerrx("aborting as link detection is disabled");
2356 			goto exit_failure;
2357 		}
2358 	}
2359 
2360 	TAILQ_FOREACH(ifp, ctx.ifaces, next) {
2361 		if (ifp->active)
2362 			dhcpcd_initstate1(ifp, argc, argv, 0);
2363 	}
2364 	if_learnaddrs(&ctx, ctx.ifaces, &ifaddrs);
2365 
2366 	if (ctx.options & DHCPCD_BACKGROUND)
2367 		dhcpcd_daemonise(&ctx);
2368 
2369 	opt = 0;
2370 	TAILQ_FOREACH(ifp, ctx.ifaces, next) {
2371 		if (ifp->active) {
2372 			run_preinit(ifp);
2373 			if (!(ifp->options->options & DHCPCD_LINK) ||
2374 			    ifp->carrier != LINK_DOWN)
2375 				opt = 1;
2376 		}
2377 	}
2378 
2379 	if (!(ctx.options & DHCPCD_BACKGROUND)) {
2380 		if (ctx.options & DHCPCD_MASTER)
2381 			t = ifo->timeout;
2382 		else {
2383 			t = 0;
2384 			TAILQ_FOREACH(ifp, ctx.ifaces, next) {
2385 				if (ifp->active) {
2386 					t = ifp->options->timeout;
2387 					break;
2388 				}
2389 			}
2390 		}
2391 		if (opt == 0 &&
2392 		    ctx.options & DHCPCD_LINK &&
2393 		    !(ctx.options & DHCPCD_WAITIP))
2394 		{
2395 			int loglevel;
2396 
2397 			loglevel = ctx.options & DHCPCD_INACTIVE ?
2398 			    LOG_DEBUG : LOG_WARNING;
2399 			logmessage(loglevel, "no interfaces have a carrier");
2400 			dhcpcd_daemonise(&ctx);
2401 		} else if (t > 0 &&
2402 		    /* Test mode removes the daemonise bit, so check for both */
2403 		    ctx.options & (DHCPCD_DAEMONISE | DHCPCD_TEST))
2404 		{
2405 			eloop_timeout_add_sec(ctx.eloop, t,
2406 			    handle_exit_timeout, &ctx);
2407 		}
2408 	}
2409 	free_options(&ctx, ifo);
2410 	ifo = NULL;
2411 
2412 	TAILQ_FOREACH(ifp, ctx.ifaces, next) {
2413 		if (ifp->active)
2414 			eloop_timeout_add_sec(ctx.eloop, 0,
2415 			    dhcpcd_prestartinterface, ifp);
2416 	}
2417 
2418 run_loop:
2419 	i = eloop_start(ctx.eloop, &ctx.sigset);
2420 	if (i < 0) {
2421 		logerr("%s: eloop_start", __func__);
2422 		goto exit_failure;
2423 	}
2424 	goto exit1;
2425 
2426 exit_success:
2427 	i = EXIT_SUCCESS;
2428 	goto exit1;
2429 
2430 exit_failure:
2431 	i = EXIT_FAILURE;
2432 
2433 exit1:
2434 	if (control_stop(&ctx) == -1)
2435 		logerr("%s: control_stop", __func__);
2436 #ifdef PRIVSEP
2437 	ps_stop(&ctx);
2438 #endif
2439 	if (ifaddrs != NULL)
2440 		freeifaddrs(ifaddrs);
2441 	/* Free memory and close fd's */
2442 	if (ctx.ifaces) {
2443 		while ((ifp = TAILQ_FIRST(ctx.ifaces))) {
2444 			TAILQ_REMOVE(ctx.ifaces, ifp, next);
2445 			if_free(ifp);
2446 		}
2447 		free(ctx.ifaces);
2448 		ctx.ifaces = NULL;
2449 	}
2450 	free_options(&ctx, ifo);
2451 #ifdef HAVE_OPEN_MEMSTREAM
2452 	if (ctx.script_fp)
2453 		fclose(ctx.script_fp);
2454 #endif
2455 	free(ctx.script_buf);
2456 	free(ctx.script_env);
2457 	rt_dispose(&ctx);
2458 	free(ctx.duid);
2459 	if (ctx.link_fd != -1) {
2460 		eloop_event_delete(ctx.eloop, ctx.link_fd);
2461 		close(ctx.link_fd);
2462 	}
2463 	if_closesockets(&ctx);
2464 	free_globals(&ctx);
2465 #ifdef INET6
2466 	ipv6_ctxfree(&ctx);
2467 #endif
2468 #ifdef PLUGIN_DEV
2469 	dev_stop(&ctx);
2470 #endif
2471 #ifdef PRIVSEP
2472 	eloop_free(ctx.ps_eloop);
2473 #endif
2474 	eloop_free(ctx.eloop);
2475 	if (ctx.script != dhcpcd_default_script)
2476 		free(ctx.script);
2477 	if (ctx.options & DHCPCD_STARTED && !(ctx.options & DHCPCD_FORKED))
2478 		loginfox(PACKAGE " exited");
2479 	logclose();
2480 	free(ctx.logfile);
2481 #ifdef SETPROCTITLE_H
2482 	setproctitle_free();
2483 #endif
2484 #ifdef USE_SIGNALS
2485 	if (ctx.options & DHCPCD_FORKED)
2486 		_exit(i); /* so atexit won't remove our pidfile */
2487 	else if (ctx.options & DHCPCD_STARTED) {
2488 		/* Try to detach from the launch process. */
2489 		if (ctx.fork_fd != -1 &&
2490 		    write(ctx.fork_fd, &i, sizeof(i)) == -1)
2491 			logerr("%s: write", __func__);
2492 	}
2493 #endif
2494 	return i;
2495 }
2496