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