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