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