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