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