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