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