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