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