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