1 /*
2  * dhcpcd - DHCP client daemon
3  * Copyright (c) 2006-2015 Roy Marples <roy@marples.name>
4  * All rights reserved
5 
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  */
27 
28 const char dhcpcd_copyright[] = "Copyright (c) 2006-2015 Roy Marples";
29 
30 #define _WITH_DPRINTF /* Stop FreeBSD bitching */
31 
32 #include <sys/file.h>
33 #include <sys/socket.h>
34 #include <sys/stat.h>
35 #include <sys/time.h>
36 #include <sys/types.h>
37 #include <sys/uio.h>
38 
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 <unistd.h>
50 #include <time.h>
51 
52 #if defined(__ANDROID__)
53 #include <sys/capability.h>
54 #include <sys/prctl.h>
55 #include <private/android_filesystem_config.h>
56 #endif  /* __ANDROID__ */
57 
58 #include "config.h"
59 #include "arp.h"
60 #include "common.h"
61 #include "control.h"
62 #include "dev.h"
63 #include "dhcpcd.h"
64 #include "dhcp6.h"
65 #include "duid.h"
66 #include "eloop.h"
67 #include "if.h"
68 #include "if-options.h"
69 #include "ipv4.h"
70 #include "ipv6.h"
71 #include "ipv6nd.h"
72 #include "rpc-interface.h"
73 #include "script.h"
74 
75 #ifdef USE_SIGNALS
76 const int dhcpcd_handlesigs[] = {
77 	SIGTERM,
78 	SIGINT,
79 	SIGALRM,
80 	SIGHUP,
81 	SIGUSR1,
82 	SIGUSR2,
83 	SIGPIPE,
84 	0
85 };
86 
87 /* Handling signals needs *some* context */
88 static struct dhcpcd_ctx *dhcpcd_ctx;
89 #endif
90 
91 #if defined(USE_SIGNALS) || !defined(THERE_IS_NO_FORK)
92 static pid_t
read_pid(const char * pidfile)93 read_pid(const char *pidfile)
94 {
95 	FILE *fp;
96 	pid_t pid;
97 
98 	if ((fp = fopen(pidfile, "r")) == NULL) {
99 		errno = ENOENT;
100 		return 0;
101 	}
102 	if (fscanf(fp, "%d", &pid) != 1)
103 		pid = 0;
104 	fclose(fp);
105 	return pid;
106 }
107 
108 static int
write_pid(int fd,pid_t pid)109 write_pid(int fd, pid_t pid)
110 {
111 
112 	if (ftruncate(fd, (off_t)0) == -1)
113 		return -1;
114 	lseek(fd, (off_t)0, SEEK_SET);
115 	return dprintf(fd, "%d\n", (int)pid);
116 }
117 #endif
118 
119 static void
usage(void)120 usage(void)
121 {
122 
123 printf("usage: "PACKAGE"\t[-46ABbDdEGgHJKkLnpqTVw]\n"
124 	"\t\t[-C, --nohook hook] [-c, --script script]\n"
125 	"\t\t[-e, --env value] [-F, --fqdn FQDN] [-f, --config file]\n"
126 	"\t\t[-h, --hostname hostname] [-I, --clientid clientid]\n"
127 	"\t\t[-i, --vendorclassid vendorclassid] [-l, --leasetime seconds]\n"
128 	"\t\t[-m, --metric metric] [-O, --nooption option]\n"
129 	"\t\t[-o, --option option] [-Q, --require option]\n"
130 	"\t\t[-r, --request address] [-S, --static value]\n"
131 	"\t\t[-s, --inform address[/cidr]] [-t, --timeout seconds]\n"
132 	"\t\t[-u, --userclass class] [-v, --vendor code, value]\n"
133 	"\t\t[-W, --whitelist address[/cidr]] [-y, --reboot seconds]\n"
134 	"\t\t[-X, --blacklist address[/cidr]] [-Z, --denyinterfaces pattern]\n"
135 	"\t\t[-z, --allowinterfaces pattern] [interface] [...]\n"
136 	"       "PACKAGE"\t-k, --release [interface]\n"
137 	"       "PACKAGE"\t-U, --dumplease interface\n"
138 	"       "PACKAGE"\t--version\n"
139 	"       "PACKAGE"\t-x, --exit [interface]\n");
140 }
141 
142 static void
free_globals(struct dhcpcd_ctx * ctx)143 free_globals(struct dhcpcd_ctx *ctx)
144 {
145 	struct dhcp_opt *opt;
146 
147 	if (ctx->ifac) {
148 		for (; ctx->ifac > 0; ctx->ifac--)
149 			free(ctx->ifav[ctx->ifac - 1]);
150 		free(ctx->ifav);
151 		ctx->ifav = NULL;
152 	}
153 	if (ctx->ifdc) {
154 		for (; ctx->ifdc > 0; ctx->ifdc--)
155 			free(ctx->ifdv[ctx->ifdc - 1]);
156 		free(ctx->ifdv);
157 		ctx->ifdv = NULL;
158 	}
159 	if (ctx->ifcc) {
160 		for (; ctx->ifcc > 0; ctx->ifcc--)
161 			free(ctx->ifcv[ctx->ifcc - 1]);
162 		free(ctx->ifcv);
163 		ctx->ifcv = NULL;
164 	}
165 
166 #ifdef INET
167 	if (ctx->dhcp_opts) {
168 		for (opt = ctx->dhcp_opts;
169 		    ctx->dhcp_opts_len > 0;
170 		    opt++, ctx->dhcp_opts_len--)
171 			free_dhcp_opt_embenc(opt);
172 		free(ctx->dhcp_opts);
173 		ctx->dhcp_opts = NULL;
174 	}
175 #endif
176 #ifdef INET6
177 	if (ctx->dhcp6_opts) {
178 		for (opt = ctx->dhcp6_opts;
179 		    ctx->dhcp6_opts_len > 0;
180 		    opt++, ctx->dhcp6_opts_len--)
181 			free_dhcp_opt_embenc(opt);
182 		free(ctx->dhcp6_opts);
183 		ctx->dhcp6_opts = NULL;
184 	}
185 #endif
186 	if (ctx->vivso) {
187 		for (opt = ctx->vivso;
188 		    ctx->vivso_len > 0;
189 		    opt++, ctx->vivso_len--)
190 			free_dhcp_opt_embenc(opt);
191 		free(ctx->vivso);
192 		ctx->vivso = NULL;
193 	}
194 }
195 
196 static void
handle_exit_timeout(void * arg)197 handle_exit_timeout(void *arg)
198 {
199 	struct dhcpcd_ctx *ctx;
200 
201 	ctx = arg;
202 	logger(ctx, LOG_ERR, "timed out");
203 	if (!(ctx->options & DHCPCD_MASTER)) {
204 		eloop_exit(ctx->eloop, EXIT_FAILURE);
205 		return;
206 	}
207 	ctx->options |= DHCPCD_NOWAITIP;
208 	dhcpcd_daemonise(ctx);
209 }
210 
211 int
dhcpcd_oneup(struct dhcpcd_ctx * ctx)212 dhcpcd_oneup(struct dhcpcd_ctx *ctx)
213 {
214 	const struct interface *ifp;
215 
216 	TAILQ_FOREACH(ifp, ctx->ifaces, next) {
217 		if (D_STATE_RUNNING(ifp) ||
218 		    RS_STATE_RUNNING(ifp) ||
219 		    D6_STATE_RUNNING(ifp))
220 			return 1;
221 	}
222 	return 0;
223 }
224 
225 int
dhcpcd_ipwaited(struct dhcpcd_ctx * ctx)226 dhcpcd_ipwaited(struct dhcpcd_ctx *ctx)
227 {
228 
229 	if (ctx->options & DHCPCD_WAITIP4 &&
230 	    !ipv4_addrexists(ctx, NULL))
231 		return 0;
232 	if (ctx->options & DHCPCD_WAITIP6 &&
233 	    !ipv6nd_findaddr(ctx, NULL, 0) &&
234 	    !dhcp6_findaddr(ctx, NULL, 0))
235 		return 0;
236 	if (ctx->options & DHCPCD_WAITIP &&
237 	    !(ctx->options & (DHCPCD_WAITIP4 | DHCPCD_WAITIP6)) &&
238 	    !ipv4_addrexists(ctx, NULL) &&
239 	    !ipv6nd_findaddr(ctx, NULL, 0) &&
240 	    !dhcp6_findaddr(ctx, NULL, 0))
241 		return 0;
242 	return 1;
243 }
244 
245 /* Returns the pid of the child, otherwise 0. */
246 pid_t
dhcpcd_daemonise(struct dhcpcd_ctx * ctx)247 dhcpcd_daemonise(struct dhcpcd_ctx *ctx)
248 {
249 #ifdef THERE_IS_NO_FORK
250 	eloop_timeout_delete(ctx->eloop, handle_exit_timeout, ctx);
251 	errno = ENOSYS;
252 	return 0;
253 #else
254 	pid_t pid;
255 	char buf = '\0';
256 	int sidpipe[2], fd;
257 
258 	if (ctx->options & DHCPCD_DAEMONISE &&
259 	    !(ctx->options & (DHCPCD_DAEMONISED | DHCPCD_NOWAITIP)))
260 	{
261 		if (!dhcpcd_ipwaited(ctx))
262 			return 0;
263 	}
264 
265 	eloop_timeout_delete(ctx->eloop, handle_exit_timeout, ctx);
266 	if (ctx->options & DHCPCD_DAEMONISED ||
267 	    !(ctx->options & DHCPCD_DAEMONISE))
268 		return 0;
269 	/* Setup a signal pipe so parent knows when to exit. */
270 	if (pipe(sidpipe) == -1) {
271 		logger(ctx, LOG_ERR, "pipe: %m");
272 		return 0;
273 	}
274 	logger(ctx, LOG_DEBUG, "forking to background");
275 	switch (pid = fork()) {
276 	case -1:
277 		logger(ctx, LOG_ERR, "fork: %m");
278 		return 0;
279 	case 0:
280 		setsid();
281 		/* Some polling methods don't survive after forking,
282 		 * so ensure we can requeue all our events. */
283 		if (eloop_requeue(ctx->eloop) == -1) {
284 			logger(ctx, LOG_ERR, "eloop_requeue: %m");
285 			eloop_exit(ctx->eloop, EXIT_FAILURE);
286 		}
287 		/* Notify parent it's safe to exit as we've detached. */
288 		close(sidpipe[0]);
289 		if (write(sidpipe[1], &buf, 1) == -1)
290 			logger(ctx, LOG_ERR, "failed to notify parent: %m");
291 		close(sidpipe[1]);
292 		if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
293 			dup2(fd, STDIN_FILENO);
294 			dup2(fd, STDOUT_FILENO);
295 			dup2(fd, STDERR_FILENO);
296 			close(fd);
297 		}
298 		break;
299 	default:
300 		/* Wait for child to detach */
301 		close(sidpipe[1]);
302 		if (read(sidpipe[0], &buf, 1) == -1)
303 			logger(ctx, LOG_ERR, "failed to read child: %m");
304 		close(sidpipe[0]);
305 		break;
306 	}
307 	/* Done with the fd now */
308 	if (pid != 0) {
309 		logger(ctx, LOG_INFO, "forked to background, child pid %d", pid);
310 		write_pid(ctx->pid_fd, pid);
311 		close(ctx->pid_fd);
312 		ctx->pid_fd = -1;
313 		ctx->options |= DHCPCD_FORKED;
314 		eloop_exit(ctx->eloop, EXIT_SUCCESS);
315 		return pid;
316 	}
317 	ctx->options |= DHCPCD_DAEMONISED;
318 	return pid;
319 #endif
320 }
321 
322 static void
dhcpcd_drop(struct interface * ifp,int stop)323 dhcpcd_drop(struct interface *ifp, int stop)
324 {
325 
326 	dhcp6_drop(ifp, stop ? NULL : "EXPIRE6");
327 	ipv6nd_drop(ifp);
328 	ipv6_drop(ifp);
329 	dhcp_drop(ifp, stop ? "STOP" : "EXPIRE");
330 	arp_close(ifp);
331 }
332 
333 static void
stop_interface(struct interface * ifp)334 stop_interface(struct interface *ifp)
335 {
336 	struct dhcpcd_ctx *ctx;
337 
338 	ctx = ifp->ctx;
339 	logger(ctx, LOG_INFO, "%s: removing interface", ifp->name);
340 	ifp->options->options |= DHCPCD_STOPPING;
341 
342 	dhcpcd_drop(ifp, 1);
343 	if (ifp->options->options & DHCPCD_DEPARTED)
344 		script_runreason(ifp, "DEPARTED");
345 	else
346 		script_runreason(ifp, "STOPPED");
347 
348 	/* Delete all timeouts for the interfaces */
349 	eloop_q_timeout_delete(ctx->eloop, 0, NULL, ifp);
350 
351 	/* Remove the interface from our list */
352 	TAILQ_REMOVE(ifp->ctx->ifaces, ifp, next);
353 	if_free(ifp);
354 
355 	if (!(ctx->options & (DHCPCD_MASTER | DHCPCD_TEST)))
356 		eloop_exit(ctx->eloop, EXIT_FAILURE);
357 }
358 
359 static void
configure_interface1(struct interface * ifp)360 configure_interface1(struct interface *ifp)
361 {
362 	struct if_options *ifo = ifp->options;
363 	int ra_global, ra_iface;
364 #ifdef INET6
365 	size_t i;
366 #endif
367 
368 	/* Do any platform specific configuration */
369 	if_conf(ifp);
370 
371 	/* If we want to release a lease, we can't really persist the
372 	 * address either. */
373 	if (ifo->options & DHCPCD_RELEASE)
374 		ifo->options &= ~DHCPCD_PERSISTENT;
375 
376 	if (ifp->flags & IFF_POINTOPOINT && !(ifo->options & DHCPCD_INFORM))
377 		ifo->options |= DHCPCD_STATIC;
378 	if (ifp->flags & IFF_NOARP ||
379 	    ifo->options & (DHCPCD_INFORM | DHCPCD_STATIC))
380 		ifo->options &= ~(DHCPCD_ARP | DHCPCD_IPV4LL);
381 	if (ifp->flags & (IFF_POINTOPOINT | IFF_LOOPBACK) ||
382 	    !(ifp->flags & IFF_MULTICAST))
383 		ifo->options &= ~DHCPCD_IPV6RS;
384 
385 	if (ifo->metric != -1)
386 		ifp->metric = (unsigned int)ifo->metric;
387 
388 	if (!(ifo->options & DHCPCD_IPV4))
389 		ifo->options &= ~(DHCPCD_DHCP | DHCPCD_IPV4LL);
390 
391 	if (!(ifo->options & DHCPCD_IPV6))
392 		ifo->options &= ~(DHCPCD_IPV6RS | DHCPCD_DHCP6);
393 
394 	if (ifo->options & DHCPCD_SLAACPRIVATE &&
395 	    !(ifp->ctx->options & (DHCPCD_DUMPLEASE | DHCPCD_TEST)))
396 		ifo->options |= DHCPCD_IPV6RA_OWN;
397 
398 	/* If we're a psuedo interface, ensure we disable as much as we can */
399 	if (ifp->options->options & DHCPCD_PFXDLGONLY)
400 		ifp->options->options &= ~(DHCPCD_IPV4 | DHCPCD_IPV6RS);
401 
402 	/* We want to disable kernel interface RA as early as possible. */
403 	if (ifo->options & DHCPCD_IPV6RS &&
404 	    !(ifp->ctx->options & DHCPCD_DUMPLEASE))
405 	{
406 		/* If not doing any DHCP, disable the RDNSS requirement. */
407 		if (!(ifo->options & (DHCPCD_DHCP | DHCPCD_DHCP6)))
408 			ifo->options &= ~DHCPCD_IPV6RA_REQRDNSS;
409 		ra_global = if_checkipv6(ifp->ctx, NULL,
410 		    ifp->ctx->options & DHCPCD_IPV6RA_OWN ? 1 : 0);
411 		ra_iface = if_checkipv6(ifp->ctx, ifp,
412 		    ifp->options->options & DHCPCD_IPV6RA_OWN ? 1 : 0);
413 		if (ra_global == -1 || ra_iface == -1)
414 			ifo->options &= ~DHCPCD_IPV6RS;
415 		else if (ra_iface == 0 &&
416 		    !(ifp->ctx->options & DHCPCD_TEST))
417 			ifo->options |= DHCPCD_IPV6RA_OWN;
418 	}
419 
420 	/* If we haven't specified a ClientID and our hardware address
421 	 * length is greater than DHCP_CHADDR_LEN then we enforce a ClientID
422 	 * of the hardware address family and the hardware address.
423 	 * If there is no hardware address and no ClientID set,
424 	 * force a DUID based ClientID. */
425 	if (ifp->hwlen > DHCP_CHADDR_LEN)
426 		ifo->options |= DHCPCD_CLIENTID;
427 	else if (ifp->hwlen == 0 && !(ifo->options & DHCPCD_CLIENTID))
428 		ifo->options |= DHCPCD_CLIENTID | DHCPCD_DUID;
429 
430 	/* Firewire and InfiniBand interfaces require ClientID and
431 	 * the broadcast option being set. */
432 	switch (ifp->family) {
433 	case ARPHRD_IEEE1394:	/* FALLTHROUGH */
434 	case ARPHRD_INFINIBAND:
435 		ifo->options |= DHCPCD_CLIENTID | DHCPCD_BROADCAST;
436 		break;
437 	}
438 
439 	if (!(ifo->options & DHCPCD_IAID)) {
440 		/*
441 		 * An IAID is for identifying a unqiue interface within
442 		 * the client. It is 4 bytes long. Working out a default
443 		 * value is problematic.
444 		 *
445 		 * Interface name and number are not stable
446 		 * between different OS's. Some OS's also cannot make
447 		 * up their mind what the interface should be called
448 		 * (yes, udev, I'm looking at you).
449 		 * Also, the name could be longer than 4 bytes.
450 		 * Also, with pluggable interfaces the name and index
451 		 * could easily get swapped per actual interface.
452 		 *
453 		 * The MAC address is 6 bytes long, the final 3
454 		 * being unique to the manufacturer and the initial 3
455 		 * being unique to the organisation which makes it.
456 		 * We could use the last 4 bytes of the MAC address
457 		 * as the IAID as it's the most stable part given the
458 		 * above, but equally it's not guaranteed to be
459 		 * unique.
460 		 *
461 		 * Given the above, and our need to reliably work
462 		 * between reboots without persitent storage,
463 		 * generating the IAID from the MAC address is the only
464 		 * logical default.
465 		 *
466 		 * dhclient uses the last 4 bytes of the MAC address.
467 		 * dibbler uses an increamenting counter.
468 		 * wide-dhcpv6 uses 0 or a configured value.
469 		 * odhcp6c uses 1.
470 		 * Windows 7 uses the first 3 bytes of the MAC address
471 		 * and an unknown byte.
472 		 * dhcpcd-6.1.0 and earlier used the interface name,
473 		 * falling back to interface index if name > 4.
474 		 */
475 		if (ifp->hwlen >= sizeof(ifo->iaid))
476 			memcpy(ifo->iaid,
477 			    ifp->hwaddr + ifp->hwlen - sizeof(ifo->iaid),
478 			    sizeof(ifo->iaid));
479 		else {
480 			uint32_t len;
481 
482 			len = (uint32_t)strlen(ifp->name);
483 			if (len <= sizeof(ifo->iaid)) {
484 				memcpy(ifo->iaid, ifp->name, len);
485 				if (len < sizeof(ifo->iaid))
486 					memset(ifo->iaid + len, 0,
487 					    sizeof(ifo->iaid) - len);
488 			} else {
489 				/* IAID is the same size as a uint32_t */
490 				len = htonl(ifp->index);
491 				memcpy(ifo->iaid, &len, sizeof(len));
492 			}
493 		}
494 		ifo->options |= DHCPCD_IAID;
495 	}
496 
497 #ifdef INET6
498 	if (ifo->ia_len == 0 && ifo->options & DHCPCD_IPV6 &&
499 	    ifp->name[0] != '\0')
500 	{
501 		ifo->ia = malloc(sizeof(*ifo->ia));
502 		if (ifo->ia == NULL)
503 			logger(ifp->ctx, LOG_ERR, "%s: %m", __func__);
504 		else {
505 			ifo->ia_len = 1;
506 			ifo->ia->ia_type = D6_OPTION_IA_NA;
507 			memcpy(ifo->ia->iaid, ifo->iaid, sizeof(ifo->iaid));
508 			memset(&ifo->ia->addr, 0, sizeof(ifo->ia->addr));
509 			ifo->ia->sla = NULL;
510 			ifo->ia->sla_len = 0;
511 		}
512 	} else {
513 		for (i = 0; i < ifo->ia_len; i++) {
514 			if (!ifo->ia[i].iaid_set) {
515 				memcpy(&ifo->ia[i].iaid, ifo->iaid,
516 				    sizeof(ifo->ia[i].iaid));
517 				ifo->ia[i].iaid_set = 1;
518 			}
519 		}
520 	}
521 #endif
522 
523 	/* If we are not sending an authentication option, don't require it */
524 	if (!(ifo->auth.options & DHCPCD_AUTH_SEND))
525 		ifo->auth.options &= ~DHCPCD_AUTH_REQUIRE;
526 }
527 
528 int
dhcpcd_selectprofile(struct interface * ifp,const char * profile)529 dhcpcd_selectprofile(struct interface *ifp, const char *profile)
530 {
531 	struct if_options *ifo;
532 	char pssid[PROFILE_LEN];
533 
534 	if (ifp->ssid_len) {
535 		ssize_t r;
536 
537 		r = print_string(pssid, sizeof(pssid), ESCSTRING,
538 		    ifp->ssid, ifp->ssid_len);
539 		if (r == -1) {
540 			logger(ifp->ctx, LOG_ERR,
541 			    "%s: %s: %m", ifp->name, __func__);
542 			pssid[0] = '\0';
543 		}
544 	} else
545 		pssid[0] = '\0';
546 	ifo = read_config(ifp->ctx, ifp->name, pssid, profile);
547 	if (ifo == NULL) {
548 		logger(ifp->ctx, LOG_DEBUG, "%s: no profile %s",
549 		    ifp->name, profile);
550 		return -1;
551 	}
552 	if (profile != NULL) {
553 		strlcpy(ifp->profile, profile, sizeof(ifp->profile));
554 		logger(ifp->ctx, LOG_INFO, "%s: selected profile %s",
555 		    ifp->name, profile);
556 	} else
557 		*ifp->profile = '\0';
558 
559 	free_options(ifp->options);
560 	ifp->options = ifo;
561 	if (profile)
562 		configure_interface1(ifp);
563 	return 1;
564 }
565 
566 static void
configure_interface(struct interface * ifp,int argc,char ** argv,unsigned long long options)567 configure_interface(struct interface *ifp, int argc, char **argv,
568     unsigned long long options)
569 {
570 	time_t old;
571 
572 	old = ifp->options ? ifp->options->mtime : 0;
573 	dhcpcd_selectprofile(ifp, NULL);
574 	add_options(ifp->ctx, ifp->name, ifp->options, argc, argv);
575 	ifp->options->options |= options;
576 	configure_interface1(ifp);
577 
578 	/* If the mtime has changed drop any old lease */
579 	if (ifp->options && old != 0 && ifp->options->mtime != old) {
580 		logger(ifp->ctx, LOG_WARNING,
581 		    "%s: confile file changed, expiring leases", ifp->name);
582 		dhcpcd_drop(ifp, 0);
583 	}
584 }
585 
586 static void
dhcpcd_pollup(void * arg)587 dhcpcd_pollup(void *arg)
588 {
589 	struct interface *ifp = arg;
590 	int carrier;
591 
592 	carrier = if_carrier(ifp); /* will set ifp->flags */
593 	if (carrier == LINK_UP && !(ifp->flags & IFF_UP)) {
594 		struct timespec tv;
595 
596 		tv.tv_sec = 0;
597 		tv.tv_nsec = IF_POLL_UP * MSEC_PER_NSEC;
598 		eloop_timeout_add_tv(ifp->ctx->eloop, &tv, dhcpcd_pollup, ifp);
599 		return;
600 	}
601 
602 	dhcpcd_handlecarrier(ifp->ctx, carrier, ifp->flags, ifp->name);
603 }
604 
605 void
dhcpcd_handlecarrier(struct dhcpcd_ctx * ctx,int carrier,unsigned int flags,const char * ifname)606 dhcpcd_handlecarrier(struct dhcpcd_ctx *ctx, int carrier, unsigned int flags,
607     const char *ifname)
608 {
609 	struct interface *ifp;
610 
611 	ifp = if_find(ctx->ifaces, ifname);
612 	if (ifp == NULL || !(ifp->options->options & DHCPCD_LINK))
613 		return;
614 
615 	switch(carrier) {
616 	case LINK_UNKNOWN:
617 		carrier = if_carrier(ifp); /* will set ifp->flags */
618 		break;
619 	case LINK_UP:
620 		/* we have a carrier! Still need to check for IFF_UP */
621 		if (flags & IFF_UP)
622 			ifp->flags = flags;
623 		else {
624 			/* So we need to poll for IFF_UP as there is no
625 			 * kernel notification when it's set. */
626 			dhcpcd_pollup(ifp);
627 			return;
628 		}
629 		break;
630 	default:
631 		ifp->flags = flags;
632 	}
633 
634 	/* If we here, we don't need to poll for IFF_UP any longer
635 	 * if generated by a kernel event. */
636 	eloop_timeout_delete(ifp->ctx->eloop, dhcpcd_pollup, ifp);
637 
638 	if (carrier == LINK_UNKNOWN) {
639 		if (errno != ENOTTY) /* For example a PPP link on BSD */
640 			logger(ctx, LOG_ERR, "%s: carrier_status: %m", ifname);
641 	} else if (carrier == LINK_DOWN || (ifp->flags & IFF_UP) == 0) {
642 		if (ifp->carrier != LINK_DOWN) {
643 			if (ifp->carrier == LINK_UP)
644 				logger(ctx, LOG_INFO, "%s: carrier lost",
645 				    ifp->name);
646 			ifp->carrier = LINK_DOWN;
647 			script_runreason(ifp, "NOCARRIER");
648 #ifdef NOCARRIER_PRESERVE_IP
649 			arp_close(ifp);
650 			ipv4_buildroutes(ifp->ctx);
651 			ipv6nd_expire(ifp, 0);
652 #else
653 			dhcpcd_drop(ifp, 0);
654 #endif
655 		}
656 	} else if (carrier == LINK_UP && ifp->flags & IFF_UP) {
657 		if (ifp->carrier != LINK_UP) {
658 			logger(ctx, LOG_INFO, "%s: carrier acquired",
659 			    ifp->name);
660 			ifp->carrier = LINK_UP;
661 #if !defined(__linux__) && !defined(__NetBSD__)
662 			/* BSD does not emit RTM_NEWADDR or RTM_CHGADDR when the
663 			 * hardware address changes so we have to go
664 			 * through the disovery process to work it out. */
665 			dhcpcd_handleinterface(ctx, 0, ifp->name);
666 #endif
667 			if (ifp->wireless) {
668 				uint8_t ossid[IF_SSIDSIZE];
669 #ifdef NOCARRIER_PRESERVE_IP
670 				size_t olen;
671 
672 				olen = ifp->ssid_len;
673 #endif
674 				memcpy(ossid, ifp->ssid, ifp->ssid_len);
675 				if_getssid(ifp);
676 #ifdef NOCARRIER_PRESERVE_IP
677 				/* If we changed SSID network, drop leases */
678 				if (ifp->ssid_len != olen ||
679 				    memcmp(ifp->ssid, ossid, ifp->ssid_len))
680 					dhcpcd_drop(ifp, 0);
681 #endif
682 			}
683 			dhcpcd_initstate(ifp, 0);
684 			script_runreason(ifp, "CARRIER");
685 #ifdef NOCARRIER_PRESERVE_IP
686 			/* Set any IPv6 Routers we remembered to expire
687 			 * faster than they would normally as we
688 			 * maybe on a new network. */
689 			ipv6nd_expire(ifp, RTR_CARRIER_EXPIRE);
690 #endif
691 			/* RFC4941 Section 3.5 */
692 			if (ifp->options->options & DHCPCD_IPV6RA_OWN)
693 				ipv6_gentempifid(ifp);
694 			dhcpcd_startinterface(ifp);
695 		}
696 	}
697 }
698 
699 static void
warn_iaid_conflict(struct interface * ifp,uint8_t * iaid)700 warn_iaid_conflict(struct interface *ifp, uint8_t *iaid)
701 {
702 	struct interface *ifn;
703 	size_t i;
704 
705 	TAILQ_FOREACH(ifn, ifp->ctx->ifaces, next) {
706 		if (ifn == ifp)
707 			continue;
708 		if (ifn->options->options & DHCPCD_PFXDLGONLY)
709 			continue;
710 		if (memcmp(ifn->options->iaid, iaid,
711 		    sizeof(ifn->options->iaid)) == 0)
712 			break;
713 		for (i = 0; i < ifn->options->ia_len; i++) {
714 			if (memcmp(&ifn->options->ia[i].iaid, iaid,
715 			    sizeof(ifn->options->ia[i].iaid)) == 0)
716 				break;
717 		}
718 	}
719 
720 	/* This is only a problem if the interfaces are on the same network. */
721 	if (ifn && strcmp(ifp->name, ifn->name))
722 		logger(ifp->ctx, LOG_ERR,
723 		    "%s: IAID conflicts with one assigned to %s",
724 		    ifp->name, ifn->name);
725 }
726 
727 static void
pre_start(struct interface * ifp)728 pre_start(struct interface *ifp)
729 {
730 
731 	/* Add our link-local address before upping the interface
732 	 * so our RFC7217 address beats the hwaddr based one.
733 	 * This is also a safety check incase it was ripped out
734 	 * from under us. */
735 	if (ifp->options->options & DHCPCD_IPV6 && ipv6_start(ifp) == -1) {
736 		logger(ifp->ctx, LOG_ERR, "%s: ipv6_start: %m", ifp->name);
737 		ifp->options->options &= ~DHCPCD_IPV6;
738 	}
739 }
740 
741 void
dhcpcd_startinterface(void * arg)742 dhcpcd_startinterface(void *arg)
743 {
744 	struct interface *ifp = arg;
745 	struct if_options *ifo = ifp->options;
746 	size_t i;
747 	char buf[DUID_LEN * 3];
748 	int carrier;
749 	struct timespec tv;
750 
751 	if (ifo->options & DHCPCD_LINK) {
752 		switch (ifp->carrier) {
753 		case LINK_UP:
754 			break;
755 		case LINK_DOWN:
756 			logger(ifp->ctx, LOG_INFO, "%s: waiting for carrier",
757 			    ifp->name);
758 			return;
759 		case LINK_UNKNOWN:
760 			/* No media state available.
761 			 * Loop until both IFF_UP and IFF_RUNNING are set */
762 			if ((carrier = if_carrier(ifp)) == LINK_UNKNOWN) {
763 				tv.tv_sec = 0;
764 				tv.tv_nsec = IF_POLL_UP * MSEC_PER_NSEC;
765 				eloop_timeout_add_tv(ifp->ctx->eloop,
766 				    &tv, dhcpcd_startinterface, ifp);
767 			} else
768 				dhcpcd_handlecarrier(ifp->ctx, carrier,
769 				    ifp->flags, ifp->name);
770 			return;
771 		}
772 	}
773 
774 	if (ifo->options & (DHCPCD_DUID | DHCPCD_IPV6)) {
775 		/* Report client DUID */
776 		if (ifp->ctx->duid == NULL) {
777 			if (duid_init(ifp) == 0)
778 				return;
779 			if (!(ifo->options & DHCPCD_PFXDLGONLY))
780 				logger(ifp->ctx, LOG_INFO, "DUID %s",
781 				    hwaddr_ntoa(ifp->ctx->duid,
782 				    ifp->ctx->duid_len,
783 				    buf, sizeof(buf)));
784 		}
785 	}
786 
787 	if (ifo->options & (DHCPCD_DUID | DHCPCD_IPV6) &&
788 	    !(ifo->options & DHCPCD_PFXDLGONLY))
789 	{
790 		/* Report IAIDs */
791 		logger(ifp->ctx, LOG_INFO, "%s: IAID %s", ifp->name,
792 		    hwaddr_ntoa(ifo->iaid, sizeof(ifo->iaid),
793 		    buf, sizeof(buf)));
794 		warn_iaid_conflict(ifp, ifo->iaid);
795 		for (i = 0; i < ifo->ia_len; i++) {
796 			if (memcmp(ifo->iaid, ifo->ia[i].iaid,
797 			    sizeof(ifo->iaid)))
798 			{
799 				logger(ifp->ctx, LOG_INFO, "%s: IAID %s",
800 				    ifp->name, hwaddr_ntoa(ifo->ia[i].iaid,
801 				    sizeof(ifo->ia[i].iaid),
802 				    buf, sizeof(buf)));
803 				warn_iaid_conflict(ifp, ifo->ia[i].iaid);
804 			}
805 		}
806 	}
807 
808 	if (ifo->options & DHCPCD_IPV6) {
809 		if (ifo->options & DHCPCD_IPV6RS &&
810 		    !(ifo->options & DHCPCD_INFORM))
811 			ipv6nd_startrs(ifp);
812 
813 		if (ifo->options & DHCPCD_DHCP6)
814 			dhcp6_find_delegates(ifp);
815 
816 		if (!(ifo->options & DHCPCD_IPV6RS) ||
817 		    ifo->options & DHCPCD_IA_FORCED)
818 		{
819 			ssize_t nolease;
820 
821 			if (ifo->options & DHCPCD_IA_FORCED)
822 				nolease = dhcp6_start(ifp, DH6S_INIT);
823 			else {
824 				nolease = 0;
825 				/* Enabling the below doesn't really make
826 				 * sense as there is currently no standard
827 				 * to push routes via DHCPv6.
828 				 * (There is an expired working draft,
829 				 * maybe abandoned?)
830 				 * You can also get it to work by forcing
831 				 * an IA as shown above. */
832 #if 0
833 				/* With no RS or delegates we might
834 				 * as well try and solicit a DHCPv6 address */
835 				if (nolease == 0)
836 					nolease = dhcp6_start(ifp, DH6S_INIT);
837 #endif
838 			}
839 			if (nolease == -1)
840 			        logger(ifp->ctx, LOG_ERR,
841 				    "%s: dhcp6_start: %m", ifp->name);
842 		}
843 	}
844 
845 	if (ifo->options & DHCPCD_IPV4)
846 		dhcp_start(ifp);
847 }
848 
849 static void
dhcpcd_prestartinterface(void * arg)850 dhcpcd_prestartinterface(void *arg)
851 {
852 	struct interface *ifp = arg;
853 
854 	pre_start(ifp);
855 	if (if_up(ifp) == -1)
856 		logger(ifp->ctx, LOG_ERR, "%s: if_up: %m", ifp->name);
857 
858 	if (ifp->options->options & DHCPCD_LINK &&
859 	    ifp->carrier == LINK_UNKNOWN)
860 	{
861 		int carrier;
862 
863 		if ((carrier = if_carrier(ifp)) != LINK_UNKNOWN) {
864 			dhcpcd_handlecarrier(ifp->ctx, carrier,
865 			    ifp->flags, ifp->name);
866 			return;
867 		}
868 		logger(ifp->ctx, LOG_INFO,
869 		    "%s: unknown carrier, waiting for interface flags",
870 		    ifp->name);
871 	}
872 
873 	dhcpcd_startinterface(ifp);
874 }
875 
876 static void
handle_link(void * arg)877 handle_link(void *arg)
878 {
879 	struct dhcpcd_ctx *ctx;
880 
881 	ctx = arg;
882 	if (if_managelink(ctx) == -1) {
883 		logger(ctx, LOG_ERR, "if_managelink: %m");
884 		eloop_event_delete(ctx->eloop, ctx->link_fd, 0);
885 		close(ctx->link_fd);
886 		ctx->link_fd = -1;
887 	}
888 }
889 
890 static void
dhcpcd_initstate1(struct interface * ifp,int argc,char ** argv,unsigned long long options)891 dhcpcd_initstate1(struct interface *ifp, int argc, char **argv,
892     unsigned long long options)
893 {
894 	struct if_options *ifo;
895 
896 	configure_interface(ifp, argc, argv, options);
897 	ifo = ifp->options;
898 
899 	if (ifo->options & DHCPCD_IPV4 && ipv4_init(ifp->ctx) == -1) {
900 		logger(ifp->ctx, LOG_ERR, "ipv4_init: %m");
901 		ifo->options &= ~DHCPCD_IPV4;
902 	}
903 	if (ifo->options & DHCPCD_IPV6 && ipv6_init(ifp->ctx) == NULL) {
904 		logger(ifp->ctx, LOG_ERR, "ipv6_init: %m");
905 		ifo->options &= ~DHCPCD_IPV6RS;
906 	}
907 
908 	/* Add our link-local address before upping the interface
909 	 * so our RFC7217 address beats the hwaddr based one.
910 	 * This needs to happen before PREINIT incase a hook script
911 	 * inadvertently ups the interface. */
912 	if (ifo->options & DHCPCD_IPV6 && ipv6_start(ifp) == -1) {
913 		logger(ifp->ctx, LOG_ERR, "%s: ipv6_start: %m", ifp->name);
914 		ifo->options &= ~DHCPCD_IPV6;
915 	}
916 }
917 
918 void
dhcpcd_initstate(struct interface * ifp,unsigned long long options)919 dhcpcd_initstate(struct interface *ifp, unsigned long long options)
920 {
921 
922 	dhcpcd_initstate1(ifp, ifp->ctx->argc, ifp->ctx->argv, options);
923 }
924 
925 static void
run_preinit(struct interface * ifp)926 run_preinit(struct interface *ifp)
927 {
928 
929 	pre_start(ifp);
930 	if (ifp->ctx->options & DHCPCD_TEST)
931 		return;
932 
933 	script_runreason(ifp, "PREINIT");
934 
935 	if (ifp->options->options & DHCPCD_LINK && ifp->carrier != LINK_UNKNOWN)
936 		script_runreason(ifp,
937 		    ifp->carrier == LINK_UP ? "CARRIER" : "NOCARRIER");
938 }
939 
940 int
dhcpcd_handleinterface(void * arg,int action,const char * ifname)941 dhcpcd_handleinterface(void *arg, int action, const char *ifname)
942 {
943 	struct dhcpcd_ctx *ctx;
944 	struct if_head *ifs;
945 	struct interface *ifp, *iff, *ifn;
946 	const char * const argv[] = { ifname };
947 	int i;
948 
949 	ctx = arg;
950 	if (action == -1) {
951 		ifp = if_find(ctx->ifaces, ifname);
952 		if (ifp == NULL) {
953 			errno = ESRCH;
954 			return -1;
955 		}
956 		logger(ctx, LOG_DEBUG, "%s: interface departed", ifp->name);
957 		ifp->options->options |= DHCPCD_DEPARTED;
958 		stop_interface(ifp);
959 		return 0;
960 	}
961 
962 	/* If running off an interface list, check it's in it. */
963 	if (ctx->ifc && action != 2) {
964 		for (i = 0; i < ctx->ifc; i++)
965 			if (strcmp(ctx->ifv[i], ifname) == 0)
966 				break;
967 		if (i >= ctx->ifc)
968 			return 0;
969 	}
970 
971 	i = -1;
972 	ifs = if_discover(ctx, -1, UNCONST(argv));
973 	if (ifs == NULL) {
974 		logger(ctx, LOG_ERR, "%s: if_discover: %m", __func__);
975 		return -1;
976 	}
977 	TAILQ_FOREACH_SAFE(ifp, ifs, next, ifn) {
978 		if (strcmp(ifp->name, ifname) != 0)
979 			continue;
980 		i = 0;
981 		/* Check if we already have the interface */
982 		iff = if_find(ctx->ifaces, ifp->name);
983 		if (iff) {
984 			logger(ctx, LOG_DEBUG, "%s: interface updated", iff->name);
985 			/* The flags and hwaddr could have changed */
986 			iff->flags = ifp->flags;
987 			iff->hwlen = ifp->hwlen;
988 			if (ifp->hwlen != 0)
989 				memcpy(iff->hwaddr, ifp->hwaddr, iff->hwlen);
990 		} else {
991 			logger(ctx, LOG_DEBUG, "%s: interface added", ifp->name);
992 			TAILQ_REMOVE(ifs, ifp, next);
993 			TAILQ_INSERT_TAIL(ctx->ifaces, ifp, next);
994 			dhcpcd_initstate(ifp, 0);
995 			run_preinit(ifp);
996 			iff = ifp;
997 		}
998 		if (action > 0)
999 			dhcpcd_prestartinterface(iff);
1000 	}
1001 
1002 	/* Free our discovered list */
1003 	while ((ifp = TAILQ_FIRST(ifs))) {
1004 		TAILQ_REMOVE(ifs, ifp, next);
1005 		if_free(ifp);
1006 	}
1007 	free(ifs);
1008 
1009 	if (i == -1)
1010 		errno = ENOENT;
1011 	return i;
1012 }
1013 
1014 void
dhcpcd_handlehwaddr(struct dhcpcd_ctx * ctx,const char * ifname,const uint8_t * hwaddr,uint8_t hwlen)1015 dhcpcd_handlehwaddr(struct dhcpcd_ctx *ctx, const char *ifname,
1016     const uint8_t *hwaddr, uint8_t hwlen)
1017 {
1018 	struct interface *ifp;
1019 	char buf[sizeof(ifp->hwaddr) * 3];
1020 
1021 	ifp = if_find(ctx->ifaces, ifname);
1022 	if (ifp == NULL)
1023 		return;
1024 
1025 	if (hwlen > sizeof(ifp->hwaddr)) {
1026 		errno = ENOBUFS;
1027 		logger(ctx, LOG_ERR, "%s: %s: %m", ifp->name, __func__);
1028 		return;
1029 	}
1030 
1031 	if (ifp->hwlen == hwlen && memcmp(ifp->hwaddr, hwaddr, hwlen) == 0)
1032 		return;
1033 
1034 	logger(ctx, LOG_INFO, "%s: new hardware address: %s", ifp->name,
1035 	    hwaddr_ntoa(hwaddr, hwlen, buf, sizeof(buf)));
1036 	ifp->hwlen = hwlen;
1037 	memcpy(ifp->hwaddr, hwaddr, hwlen);
1038 }
1039 
1040 void
dhcpcd_start_interface(struct dhcpcd_ctx * ctx,const char * ifname)1041 dhcpcd_start_interface(struct dhcpcd_ctx *ctx, const char *ifname)
1042 {
1043 	struct interface *ifp;
1044 	ifp = if_find(ctx->ifaces, ifname);
1045 	if (ifp == NULL)
1046 	{
1047 		logger(ctx, LOG_ERR, "start_interface: %s not found",
1048 		       ifname);
1049 		return;
1050 	}
1051 	dhcpcd_startinterface(ifp);
1052 }
1053 
1054 void
dhcpcd_stop_interface(struct dhcpcd_ctx * ctx,const char * ifname)1055 dhcpcd_stop_interface(struct dhcpcd_ctx *ctx, const char *ifname)
1056 {
1057 	struct interface *ifp;
1058 	ifp = if_find(ctx->ifaces, ifname);
1059 	if (ifp == NULL)
1060 	{
1061 		logger(ctx, LOG_ERR, "stop_interface: %s not found",
1062 		       ifname);
1063 		return;
1064 	}
1065 	stop_interface(ifp);
1066 }
1067 
1068 void
dhcpcd_stop_interfaces(struct dhcpcd_ctx * ctx)1069 dhcpcd_stop_interfaces(struct dhcpcd_ctx *ctx)
1070 {
1071 	struct interface *ifp;
1072 	TAILQ_FOREACH(ifp, ctx->ifaces, next) {
1073 		stop_interface(ifp);
1074 	}
1075 }
1076 
1077 void
dhcpcd_release_ipv4(struct dhcpcd_ctx * ctx,const char * ifname)1078 dhcpcd_release_ipv4(struct dhcpcd_ctx *ctx, const char *ifname)
1079 {
1080 	struct interface *ifp;
1081 
1082 	ifp = if_find(ctx->ifaces, ifname);
1083 	if (ifp == NULL)
1084 	{
1085 		logger(ctx, LOG_ERR, "IPv4 release: %s not found",
1086 		       ifname);
1087 		return;
1088 	}
1089 	dhcp_drop(ifp, "RELEASE");
1090 }
1091 
1092 static void
if_reboot(struct interface * ifp,int argc,char ** argv)1093 if_reboot(struct interface *ifp, int argc, char **argv)
1094 {
1095 	unsigned long long oldopts;
1096 
1097 	oldopts = ifp->options->options;
1098 	script_runreason(ifp, "RECONFIGURE");
1099 	dhcpcd_initstate1(ifp, argc, argv, 0);
1100 	dhcp_reboot_newopts(ifp, oldopts);
1101 	dhcp6_reboot(ifp);
1102 	dhcpcd_prestartinterface(ifp);
1103 }
1104 
1105 static void
reload_config(struct dhcpcd_ctx * ctx)1106 reload_config(struct dhcpcd_ctx *ctx)
1107 {
1108 	struct if_options *ifo;
1109 
1110 	free_globals(ctx);
1111 	ifo = read_config(ctx, NULL, NULL, NULL);
1112 	add_options(ctx, NULL, ifo, ctx->argc, ctx->argv);
1113 	/* We need to preserve these two options. */
1114 	if (ctx->options & DHCPCD_MASTER)
1115 		ifo->options |= DHCPCD_MASTER;
1116 	if (ctx->options & DHCPCD_DAEMONISED)
1117 		ifo->options |= DHCPCD_DAEMONISED;
1118 	ctx->options = ifo->options;
1119 	free_options(ifo);
1120 }
1121 
1122 static void
reconf_reboot(struct dhcpcd_ctx * ctx,int action,int argc,char ** argv,int oi)1123 reconf_reboot(struct dhcpcd_ctx *ctx, int action, int argc, char **argv, int oi)
1124 {
1125 	struct if_head *ifs;
1126 	struct interface *ifn, *ifp;
1127 
1128 	ifs = if_discover(ctx, argc - oi, argv + oi);
1129 	if (ifs == NULL) {
1130 		logger(ctx, LOG_ERR, "%s: if_discover: %m", __func__);
1131 		return;
1132 	}
1133 
1134 	while ((ifp = TAILQ_FIRST(ifs))) {
1135 		TAILQ_REMOVE(ifs, ifp, next);
1136 		ifn = if_find(ctx->ifaces, ifp->name);
1137 		if (ifn) {
1138 			if (action)
1139 				if_reboot(ifn, argc, argv);
1140 			else
1141 				ipv4_applyaddr(ifn);
1142 			if_free(ifp);
1143 		} else {
1144 			TAILQ_INSERT_TAIL(ctx->ifaces, ifp, next);
1145 			dhcpcd_initstate1(ifp, argc, argv, 0);
1146 			run_preinit(ifp);
1147 			dhcpcd_prestartinterface(ifp);
1148 		}
1149 	}
1150 	free(ifs);
1151 }
1152 
1153 static void
stop_all_interfaces(struct dhcpcd_ctx * ctx,int do_release)1154 stop_all_interfaces(struct dhcpcd_ctx *ctx, int do_release)
1155 {
1156 	struct interface *ifp;
1157 
1158 	/* drop_dhcp could change the order, so we do it like this. */
1159 	for (;;) {
1160 		/* Be sane and drop the last config first,
1161 		 * skipping any pseudo interfaces */
1162 		TAILQ_FOREACH_REVERSE(ifp, ctx->ifaces, if_head, next) {
1163 			if (!(ifp->options->options & DHCPCD_PFXDLGONLY))
1164 				break;
1165 		}
1166 		if (ifp == NULL)
1167 			break;
1168 		if (do_release) {
1169 			ifp->options->options |= DHCPCD_RELEASE;
1170 			ifp->options->options &= ~DHCPCD_PERSISTENT;
1171 		}
1172 		ifp->options->options |= DHCPCD_EXITING;
1173 		stop_interface(ifp);
1174 	}
1175 }
1176 
1177 #ifdef USE_SIGNALS
1178 struct dhcpcd_siginfo dhcpcd_siginfo;
1179 #define sigmsg "received %s, %s"
1180 void
dhcpcd_handle_signal(void * arg)1181 dhcpcd_handle_signal(void *arg)
1182 {
1183 	struct dhcpcd_ctx *ctx;
1184 	struct dhcpcd_siginfo *si;
1185 	struct interface *ifp;
1186 	int do_release, exit_code;;
1187 
1188 	ctx = dhcpcd_ctx;
1189 	si = arg;
1190 	do_release = 0;
1191 	exit_code = EXIT_FAILURE;
1192 	switch (si->signo) {
1193 	case SIGINT:
1194 		logger(ctx, LOG_INFO, sigmsg, "SIGINT", "stopping");
1195 		break;
1196 	case SIGTERM:
1197 		logger(ctx, LOG_INFO, sigmsg, "SIGTERM", "stopping");
1198 		exit_code = EXIT_SUCCESS;
1199 		break;
1200 	case SIGALRM:
1201 		logger(ctx, LOG_INFO, sigmsg, "SIGALRM", "releasing");
1202 		do_release = 1;
1203 		exit_code = EXIT_SUCCESS;
1204 		break;
1205 	case SIGHUP:
1206 		logger(ctx, LOG_INFO, sigmsg, "SIGHUP", "rebinding");
1207 		reload_config(ctx);
1208 		/* Preserve any options passed on the commandline
1209 		 * when we were started. */
1210 		reconf_reboot(ctx, 1, ctx->argc, ctx->argv,
1211 		    ctx->argc - ctx->ifc);
1212 		return;
1213 	case SIGUSR1:
1214 		logger(ctx, LOG_INFO, sigmsg, "SIGUSR1", "reconfiguring");
1215 		TAILQ_FOREACH(ifp, ctx->ifaces, next) {
1216 			ipv4_applyaddr(ifp);
1217 		}
1218 		return;
1219 	case SIGUSR2:
1220 		logger_close(ctx);
1221 		logger_open(ctx);
1222 		logger(ctx, LOG_INFO, sigmsg, "SIGUSR2", "reopened logfile");
1223 		return;
1224 	case SIGPIPE:
1225 		logger(ctx, LOG_WARNING, "received SIGPIPE");
1226 		return;
1227 	default:
1228 		logger(ctx, LOG_ERR,
1229 		    "received signal %d, "
1230 		    "but don't know what to do with it",
1231 		    si->signo);
1232 		return;
1233 	}
1234 
1235 	if (!(ctx->options & DHCPCD_TEST))
1236 		stop_all_interfaces(ctx, do_release);
1237 	eloop_exit(ctx->eloop, exit_code);
1238 }
1239 
1240 #ifndef HAVE_KQUEUE
1241 static void
handle_signal(int sig,__unused siginfo_t * siginfo,__unused void * context)1242 handle_signal(int sig, __unused siginfo_t *siginfo, __unused void *context)
1243 {
1244 
1245 	/* So that we can operate safely under a signal we instruct
1246 	 * eloop to pass a copy of the siginfo structure to handle_signal1
1247 	 * as the very first thing to do. */
1248 	dhcpcd_siginfo.signo = sig;
1249 	eloop_timeout_add_now(dhcpcd_ctx->eloop,
1250 	    dhcpcd_handle_signal, &dhcpcd_siginfo);
1251 }
1252 #endif
1253 
1254 static int
signal_init(sigset_t * oldset)1255 signal_init(sigset_t *oldset)
1256 {
1257 	sigset_t newset;
1258 #ifndef HAVE_KQUEUE
1259 	int i;
1260 	struct sigaction sa;
1261 #endif
1262 
1263 	sigfillset(&newset);
1264 	if (sigprocmask(SIG_SETMASK, &newset, oldset) == -1)
1265 		return -1;
1266 
1267 #ifndef HAVE_KQUEUE
1268 	memset(&sa, 0, sizeof(sa));
1269 	sa.sa_sigaction = handle_signal;
1270 	sa.sa_flags = SA_SIGINFO;
1271 	sigemptyset(&sa.sa_mask);
1272 
1273 	for (i = 0; dhcpcd_handlesigs[i]; i++) {
1274 		if (sigaction(dhcpcd_handlesigs[i], &sa, NULL) == -1)
1275 			return -1;
1276 	}
1277 #endif
1278 	return 0;
1279 }
1280 #endif
1281 
1282 static void
dhcpcd_getinterfaces(void * arg)1283 dhcpcd_getinterfaces(void *arg)
1284 {
1285 	struct fd_list *fd = arg;
1286 	struct interface *ifp;
1287 	size_t len;
1288 
1289 	len = 0;
1290 	TAILQ_FOREACH(ifp, fd->ctx->ifaces, next) {
1291 		len++;
1292 		if (D_STATE_RUNNING(ifp))
1293 			len++;
1294 		if (RS_STATE_RUNNING(ifp))
1295 			len++;
1296 		if (D6_STATE_RUNNING(ifp))
1297 			len++;
1298 	}
1299 	if (write(fd->fd, &len, sizeof(len)) != sizeof(len))
1300 		return;
1301 	eloop_event_delete(fd->ctx->eloop, fd->fd, 1);
1302 	TAILQ_FOREACH(ifp, fd->ctx->ifaces, next) {
1303 		if (send_interface(fd, ifp) == -1)
1304 			logger(ifp->ctx, LOG_ERR,
1305 			    "send_interface %d: %m", fd->fd);
1306 	}
1307 }
1308 
1309 int
dhcpcd_handleargs(struct dhcpcd_ctx * ctx,struct fd_list * fd,int argc,char ** argv)1310 dhcpcd_handleargs(struct dhcpcd_ctx *ctx, struct fd_list *fd,
1311     int argc, char **argv)
1312 {
1313 	struct interface *ifp;
1314 	int do_exit = 0, do_release = 0, do_reboot = 0;
1315 	int opt, oi = 0;
1316 	size_t len, l;
1317 	char *tmp, *p;
1318 
1319 	/* Special commands for our control socket
1320 	 * as the other end should be blocking until it gets the
1321 	 * expected reply we should be safely able just to change the
1322 	 * write callback on the fd */
1323 	if (strcmp(*argv, "--version") == 0) {
1324 		return control_queue(fd, UNCONST(VERSION),
1325 			strlen(VERSION) + 1, 0);
1326 	} else if (strcmp(*argv, "--getconfigfile") == 0) {
1327 		return control_queue(fd, UNCONST(fd->ctx->cffile),
1328 			strlen(fd->ctx->cffile) + 1, 0);
1329 	} else if (strcmp(*argv, "--getinterfaces") == 0) {
1330 		eloop_event_add(fd->ctx->eloop, fd->fd, NULL, NULL,
1331 			dhcpcd_getinterfaces, fd);
1332 		return 0;
1333 	} else if (strcmp(*argv, "--listen") == 0) {
1334 		fd->flags |= FD_LISTEN;
1335 		return 0;
1336 	}
1337 
1338 	/* Only priviledged users can control dhcpcd via the socket. */
1339 	if (fd->flags & FD_UNPRIV) {
1340 		errno = EPERM;
1341 		return -1;
1342 	}
1343 
1344 	/* Log the command */
1345 	len = 1;
1346 	for (opt = 0; opt < argc; opt++)
1347 		len += strlen(argv[opt]) + 1;
1348 	tmp = malloc(len);
1349 	if (tmp == NULL)
1350 		return -1;
1351 	p = tmp;
1352 	for (opt = 0; opt < argc; opt++) {
1353 		l = strlen(argv[opt]);
1354 		strlcpy(p, argv[opt], len);
1355 		len -= l + 1;
1356 		p += l;
1357 		*p++ = ' ';
1358 	}
1359 	*--p = '\0';
1360 	logger(ctx, LOG_INFO, "control command: %s", tmp);
1361 	free(tmp);
1362 
1363 	optind = 0;
1364 	while ((opt = getopt_long(argc, argv, IF_OPTS, cf_options, &oi)) != -1)
1365 	{
1366 		switch (opt) {
1367 		case 'g':
1368 			/* Assumed if below not set */
1369 			break;
1370 		case 'k':
1371 			do_release = 1;
1372 			break;
1373 		case 'n':
1374 			do_reboot = 1;
1375 			break;
1376 		case 'x':
1377 			do_exit = 1;
1378 			break;
1379 		}
1380 	}
1381 
1382 	if (do_release || do_exit) {
1383 		if (optind == argc) {
1384 			stop_all_interfaces(ctx, do_release);
1385 			eloop_exit(ctx->eloop, EXIT_SUCCESS);
1386 			return 0;
1387 		}
1388 		for (oi = optind; oi < argc; oi++) {
1389 			if ((ifp = if_find(ctx->ifaces, argv[oi])) == NULL)
1390 				continue;
1391 			if (do_release) {
1392 				ifp->options->options |= DHCPCD_RELEASE;
1393 				ifp->options->options &= ~DHCPCD_PERSISTENT;
1394 			}
1395 			ifp->options->options |= DHCPCD_EXITING;
1396 			stop_interface(ifp);
1397 		}
1398 		return 0;
1399 	}
1400 
1401 	reload_config(ctx);
1402 	/* XXX: Respect initial commandline options? */
1403 	reconf_reboot(ctx, do_reboot, argc, argv, optind);
1404 	return 0;
1405 }
1406 
1407 #if defined(__ANDROID__)
1408 static void
switch_user(void)1409 switch_user(void)
1410 {
1411 	gid_t groups[] = { AID_DBUS, AID_INET, AID_SHELL };
1412 	struct __user_cap_header_struct header;
1413 	struct __user_cap_data_struct cap;
1414 
1415 	setgroups(sizeof(groups)/sizeof(groups[0]), groups);
1416 
1417 	prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0);
1418 
1419 	setgid(AID_DHCP);
1420 	setuid(AID_DHCP);
1421 	header.version = _LINUX_CAPABILITY_VERSION;
1422 	header.pid = 0;
1423 	cap.effective = cap.permitted =
1424 		(1 << CAP_NET_ADMIN) | (1 << CAP_NET_RAW) |
1425 		(1 << CAP_NET_BROADCAST) | (1 << CAP_NET_BIND_SERVICE);
1426 	cap.inheritable = 0;
1427 	capset(&header, &cap);
1428 }
1429 #endif  /* __ANDROID__ */
1430 
1431 int
main(int argc,char ** argv)1432 main(int argc, char **argv)
1433 {
1434 	struct dhcpcd_ctx ctx;
1435 	struct if_options *ifo;
1436 	struct interface *ifp;
1437 	uint16_t family = 0;
1438 	int opt, oi = 0, i;
1439 	time_t t;
1440 	ssize_t len;
1441 #if defined(USE_SIGNALS) || !defined(THERE_IS_NO_FORK)
1442 	pid_t pid;
1443 #endif
1444 #ifdef USE_SIGNALS
1445 	int sig;
1446 	const char *siga;
1447 #endif
1448 	char ifn[IF_NAMESIZE];
1449 
1450 #if defined(__ANDROID__) && !defined(__BRILLO__)
1451 	switch_user();
1452 #endif  /* __ANDROID__ && !__BRILLO__ */
1453 
1454 	/* Test for --help and --version */
1455 	if (argc > 1) {
1456 		if (strcmp(argv[1], "--help") == 0) {
1457 			usage();
1458 			return EXIT_SUCCESS;
1459 		} else if (strcmp(argv[1], "--version") == 0) {
1460 			printf(""PACKAGE" "VERSION"\n%s\n", dhcpcd_copyright);
1461 			return EXIT_SUCCESS;
1462 		}
1463 	}
1464 
1465 	memset(&ctx, 0, sizeof(ctx));
1466 #ifdef USE_SIGNALS
1467 	dhcpcd_ctx = &ctx;
1468 	sig = 0;
1469 	siga = NULL;
1470 #endif
1471 	closefrom(3);
1472 
1473 	ctx.log_fd = -1;
1474 	logger_open(&ctx);
1475 	logger_mask(&ctx, LOG_UPTO(LOG_INFO));
1476 
1477 	ifo = NULL;
1478 	ctx.cffile = CONFIG;
1479 	ctx.pid_fd = ctx.control_fd = ctx.control_unpriv_fd = ctx.link_fd = -1;
1480 	TAILQ_INIT(&ctx.control_fds);
1481 #ifdef PLUGIN_DEV
1482 	ctx.dev_fd = -1;
1483 #endif
1484 #ifdef INET
1485 	ctx.udp_fd = -1;
1486 #endif
1487 	i = 0;
1488 	while ((opt = getopt_long(argc, argv, IF_OPTS, cf_options, &oi)) != -1)
1489 	{
1490 		switch (opt) {
1491 		case '4':
1492 			family = AF_INET;
1493 			break;
1494 		case '6':
1495 			family = AF_INET6;
1496 			break;
1497 		case 'f':
1498 			ctx.cffile = optarg;
1499 			break;
1500 #ifdef USE_SIGNALS
1501 		case 'g':
1502 			sig = SIGUSR1;
1503 			siga = "USR1";
1504 			break;
1505 		case 'j':
1506 			ctx.logfile = strdup(optarg);
1507 			logger_close(&ctx);
1508 			logger_open(&ctx);
1509 			break;
1510 		case 'k':
1511 			sig = SIGALRM;
1512 			siga = "ARLM";
1513 			break;
1514 		case 'n':
1515 			sig = SIGHUP;
1516 			siga = "HUP";
1517 			break;
1518 		case 'x':
1519 			sig = SIGTERM;
1520 			siga = "TERM";;
1521 			break;
1522 #endif
1523 		case 'T':
1524 			i = 1;
1525 			break;
1526 		case 'U':
1527 			if (i == 3)
1528 				i = 4;
1529 			else if (i != 4)
1530 				i = 3;
1531 			break;
1532 		case 'V':
1533 			i = 2;
1534 			break;
1535 		case '?':
1536 			usage();
1537 			goto exit_failure;
1538 		}
1539 	}
1540 
1541 	ctx.argv = argv;
1542 	ctx.argc = argc;
1543 	ctx.ifc = argc - optind;
1544 	ctx.ifv = argv + optind;
1545 
1546 	ifo = read_config(&ctx, NULL, NULL, NULL);
1547 	if (ifo == NULL)
1548 		goto exit_failure;
1549 	opt = add_options(&ctx, NULL, ifo, argc, argv);
1550 	if (opt != 1) {
1551 		if (opt == 0)
1552 			usage();
1553 		goto exit_failure;
1554 	}
1555 	if (i == 2) {
1556 		printf("Interface options:\n");
1557 		if (optind == argc - 1) {
1558 			free_options(ifo);
1559 			ifo = read_config(&ctx, argv[optind], NULL, NULL);
1560 			if (ifo == NULL)
1561 				goto exit_failure;
1562 			add_options(&ctx, NULL, ifo, argc, argv);
1563 		}
1564 		if_printoptions();
1565 #ifdef INET
1566 		if (family == 0 || family == AF_INET) {
1567 			printf("\nDHCPv4 options:\n");
1568 			dhcp_printoptions(&ctx,
1569 			    ifo->dhcp_override, ifo->dhcp_override_len);
1570 		}
1571 #endif
1572 #ifdef INET6
1573 		if (family == 0 || family == AF_INET6) {
1574 			printf("\nDHCPv6 options:\n");
1575 			dhcp6_printoptions(&ctx,
1576 			    ifo->dhcp6_override, ifo->dhcp6_override_len);
1577 		}
1578 #endif
1579 		goto exit_success;
1580 	}
1581 	ctx.options = ifo->options;
1582 	if (i != 0) {
1583 		if (i == 1)
1584 			ctx.options |= DHCPCD_TEST;
1585 		else
1586 			ctx.options |= DHCPCD_DUMPLEASE;
1587 		if (i == 4)
1588 			ctx.options |= DHCPCD_PFXDLGONLY;
1589 		ctx.options |= DHCPCD_PERSISTENT;
1590 		ctx.options &= ~DHCPCD_DAEMONISE;
1591 	}
1592 
1593 #ifdef THERE_IS_NO_FORK
1594 	ctx.options &= ~DHCPCD_DAEMONISE;
1595 #endif
1596 
1597 	if (ctx.options & DHCPCD_DEBUG)
1598 		logger_mask(&ctx, LOG_UPTO(LOG_DEBUG));
1599 	if (ctx.options & DHCPCD_QUIET) {
1600 		i = open(_PATH_DEVNULL, O_RDWR);
1601 		if (i == -1)
1602 			logger(&ctx, LOG_ERR, "%s: open: %m", __func__);
1603 		else {
1604 			dup2(i, STDERR_FILENO);
1605 			close(i);
1606 		}
1607 	}
1608 
1609 	if (!(ctx.options & (DHCPCD_TEST | DHCPCD_DUMPLEASE))) {
1610 		/* If we have any other args, we should run as a single dhcpcd
1611 		 *  instance for that interface. */
1612 		if (optind == argc - 1 && !(ctx.options & DHCPCD_MASTER)) {
1613 			const char *per;
1614 			int intf_len = strlen(argv[optind]);
1615 			split_interface_lease(argv[optind], &intf_len, NULL);
1616 			if (intf_len > IF_NAMESIZE) {
1617 				logger(&ctx, LOG_ERR,
1618 				    "%s: interface name too long",
1619 				    argv[optind]);
1620 				goto exit_failure;
1621 			}
1622 			strlcpy(ifn, argv[optind], intf_len + 1);
1623 			/* Allow a dhcpcd interface per address family */
1624 			switch(family) {
1625 			case AF_INET:
1626 				per = "-4";
1627 				break;
1628 			case AF_INET6:
1629 				per = "-6";
1630 				break;
1631 			default:
1632 				per = "";
1633 			}
1634 			snprintf(ctx.pidfile, sizeof(ctx.pidfile),
1635 			    PIDFILE, "-", ifn, per);
1636 		} else {
1637 			snprintf(ctx.pidfile, sizeof(ctx.pidfile),
1638 			    PIDFILE, "", "", "");
1639 			ctx.options |= DHCPCD_MASTER;
1640 		}
1641 	}
1642 
1643 	if (chdir("/") == -1)
1644 		logger(&ctx, LOG_ERR, "chdir `/': %m");
1645 
1646 	/* Freeing allocated addresses from dumping leases can trigger
1647 	 * eloop removals as well, so init here. */
1648 	ctx.eloop = eloop_init(&ctx);
1649 	if (ctx.eloop == NULL) {
1650 		logger(&ctx, LOG_ERR, "%s: eloop_init: %m", __func__);
1651 		goto exit_failure;
1652 	}
1653 
1654 	if (ctx.options & DHCPCD_DUMPLEASE) {
1655 		if (optind != argc - 1) {
1656 			logger(&ctx, LOG_ERR,
1657 			    "dumplease requires an interface");
1658 			goto exit_failure;
1659 		}
1660 		i = 0;
1661 		/* We need to try and find the interface so we can
1662 		 * load the hardware address to compare automated IAID */
1663 		ctx.ifaces = if_discover(&ctx, 1, argv + optind);
1664 		if (ctx.ifaces == NULL) {
1665 			logger(&ctx, LOG_ERR, "if_discover: %m");
1666 			goto exit_failure;
1667 		}
1668 		ifp = TAILQ_FIRST(ctx.ifaces);
1669 		if (ifp == NULL) {
1670 			ifp = calloc(1, sizeof(*ifp));
1671 			if (ifp == NULL) {
1672 				logger(&ctx, LOG_ERR, "%s: %m", __func__);
1673 				goto exit_failure;
1674 			}
1675 			strlcpy(ctx.pidfile, argv[optind], sizeof(ctx.pidfile));
1676 			ifp->ctx = &ctx;
1677 			TAILQ_INSERT_HEAD(ctx.ifaces, ifp, next);
1678 			if (family == 0) {
1679 				if (ctx.pidfile[strlen(ctx.pidfile) - 1] == '6')
1680 					family = AF_INET6;
1681 				else
1682 					family = AF_INET;
1683 			}
1684 		}
1685 		configure_interface(ifp, ctx.argc, ctx.argv, 0);
1686 		if (ctx.options & DHCPCD_PFXDLGONLY)
1687 			ifp->options->options |= DHCPCD_PFXDLGONLY;
1688 		if (family == 0 || family == AF_INET) {
1689 			if (dhcp_dump(ifp) == -1)
1690 				i = 1;
1691 		}
1692 		if (family == 0 || family == AF_INET6) {
1693 			if (dhcp6_dump(ifp) == -1)
1694 				i = 1;
1695 		}
1696 		if (i == -1)
1697 			goto exit_failure;
1698 		goto exit_success;
1699 	}
1700 
1701 #ifdef USE_SIGNALS
1702 	if (!(ctx.options & DHCPCD_TEST) &&
1703 	    (sig == 0 || ctx.ifc != 0))
1704 	{
1705 #endif
1706 		if (ctx.options & DHCPCD_MASTER)
1707 			i = -1;
1708 		else
1709 			i = control_open(&ctx, argv[optind]);
1710 		if (i == -1)
1711 			i = control_open(&ctx, NULL);
1712 		if (i != -1) {
1713 			logger(&ctx, LOG_INFO,
1714 			    "sending commands to master dhcpcd process");
1715 			len = control_send(&ctx, argc, argv);
1716 			control_close(&ctx);
1717 			if (len > 0) {
1718 				logger(&ctx, LOG_DEBUG, "send OK");
1719 				goto exit_success;
1720 			} else {
1721 				logger(&ctx, LOG_ERR,
1722 				    "failed to send commands");
1723 				goto exit_failure;
1724 			}
1725 		} else {
1726 			if (errno != ENOENT)
1727 				logger(&ctx, LOG_ERR, "control_open: %m");
1728 		}
1729 #ifdef USE_SIGNALS
1730 	}
1731 #endif
1732 
1733 	if (geteuid())
1734 		logger(&ctx, LOG_NOTICE,
1735 		    PACKAGE " is running with reduced privileges");
1736 
1737 #ifdef USE_SIGNALS
1738 	if (sig != 0) {
1739 		pid = read_pid(ctx.pidfile);
1740 		if (pid != 0)
1741 			logger(&ctx, LOG_INFO, "sending signal %s to pid %d",
1742 			    siga, pid);
1743 		if (pid == 0 || kill(pid, sig) != 0) {
1744 			if (sig != SIGHUP && errno != EPERM)
1745 				logger(&ctx, LOG_ERR, ""PACKAGE" not running");
1746 			if (pid != 0 && errno != ESRCH) {
1747 				logger(&ctx, LOG_ERR, "kill: %m");
1748 				goto exit_failure;
1749 			}
1750 			unlink(ctx.pidfile);
1751 			if (sig != SIGHUP)
1752 				goto exit_failure;
1753 		} else {
1754 			struct timespec ts;
1755 
1756 			if (sig == SIGHUP || sig == SIGUSR1)
1757 				goto exit_success;
1758 			/* Spin until it exits */
1759 			logger(&ctx, LOG_INFO,
1760 			    "waiting for pid %d to exit", pid);
1761 			ts.tv_sec = 0;
1762 			ts.tv_nsec = 100000000; /* 10th of a second */
1763 			for(i = 0; i < 100; i++) {
1764 				nanosleep(&ts, NULL);
1765 				if (read_pid(ctx.pidfile) == 0)
1766 					goto exit_success;
1767 			}
1768 			logger(&ctx, LOG_ERR, "pid %d failed to exit", pid);
1769 			goto exit_failure;
1770 		}
1771 	}
1772 
1773 	if (!(ctx.options & DHCPCD_TEST)) {
1774 		if ((pid = read_pid(ctx.pidfile)) > 0 &&
1775 		    kill(pid, 0) == 0)
1776 		{
1777 			logger(&ctx, LOG_ERR, ""PACKAGE
1778 			    " already running on pid %d (%s)",
1779 			    pid, ctx.pidfile);
1780 			goto exit_failure;
1781 		}
1782 
1783 #if !defined(__ANDROID__)
1784 		/* Ensure we have the needed directories
1785 		 * On Android, we assume that these directories have been created
1786 		 * by calls to mkdir in an init.rc file. */
1787 		if (mkdir(RUNDIR, 0755) == -1 && errno != EEXIST)
1788 			logger(&ctx, LOG_ERR, "mkdir `%s': %m", RUNDIR);
1789 		if (mkdir(DBDIR, 0755) == -1 && errno != EEXIST)
1790 			logger(&ctx, LOG_ERR, "mkdir `%s': %m", DBDIR);
1791 #endif /* __ANDROID__ */
1792 
1793 		opt = O_WRONLY | O_CREAT | O_NONBLOCK;
1794 #ifdef O_CLOEXEC
1795 		opt |= O_CLOEXEC;
1796 #endif
1797 		ctx.pid_fd = open(ctx.pidfile, opt, 0664);
1798 		if (ctx.pid_fd == -1)
1799 			logger(&ctx, LOG_ERR, "open `%s': %m", ctx.pidfile);
1800 		else {
1801 #ifdef LOCK_EX
1802 			/* Lock the file so that only one instance of dhcpcd
1803 			 * runs on an interface */
1804 			if (flock(ctx.pid_fd, LOCK_EX | LOCK_NB) == -1) {
1805 				logger(&ctx, LOG_ERR, "flock `%s': %m", ctx.pidfile);
1806 				close(ctx.pid_fd);
1807 				ctx.pid_fd = -1;
1808 				goto exit_failure;
1809 			}
1810 #endif
1811 #ifndef O_CLOEXEC
1812 			if (fcntl(ctx.pid_fd, F_GETFD, &opt) == -1 ||
1813 			    fcntl(ctx.pid_fd, F_SETFD, opt | FD_CLOEXEC) == -1)
1814 			{
1815 				logger(&ctx, LOG_ERR, "fcntl: %m");
1816 				close(ctx.pid_fd);
1817 				ctx.pid_fd = -1;
1818 				goto exit_failure;
1819 			}
1820 #endif
1821 			write_pid(ctx.pid_fd, getpid());
1822 		}
1823 	}
1824 
1825 	if (ctx.options & DHCPCD_MASTER) {
1826 		if (control_start(&ctx, NULL) == -1)
1827 			logger(&ctx, LOG_ERR, "control_start: %m");
1828 	}
1829 #else
1830 	if (control_start(&ctx,
1831 	    ctx.options & DHCPCD_MASTER ? NULL : argv[optind]) == -1)
1832 	{
1833 		logger(&ctx, LOG_ERR, "control_start: %m");
1834 		goto exit_failure;
1835 	}
1836 #endif
1837 
1838 	logger(&ctx, LOG_DEBUG, PACKAGE "-" VERSION " starting");
1839 	ctx.options |= DHCPCD_STARTED;
1840 #ifdef USE_SIGNALS
1841 	/* Save signal mask, block and redirect signals to our handler */
1842 	if (signal_init(&ctx.sigset) == -1) {
1843 		logger(&ctx, LOG_ERR, "signal_setup: %m");
1844 		goto exit_failure;
1845 	}
1846 #endif
1847 
1848 	/* When running dhcpcd against a single interface, we need to retain
1849 	 * the old behaviour of waiting for an IP address */
1850 	if (ctx.ifc == 1 && !(ctx.options & DHCPCD_BACKGROUND))
1851 		ctx.options |= DHCPCD_WAITIP;
1852 
1853 	/* RTM_NEWADDR goes through the link socket as well which we
1854 	 * need for IPv6 DAD, so we check for DHCPCD_LINK in
1855 	 * dhcpcd_handlecarrier instead.
1856 	 * We also need to open this before checking for interfaces below
1857 	 * so that we pickup any new addresses during the discover phase. */
1858 	ctx.link_fd = if_openlinksocket();
1859 	if (ctx.link_fd == -1)
1860 		logger(&ctx, LOG_ERR, "open_link_socket: %m");
1861 	else
1862 		eloop_event_add(ctx.eloop, ctx.link_fd,
1863 		    handle_link, &ctx, NULL, NULL);
1864 
1865 	/* Start any dev listening plugin which may want to
1866 	 * change the interface name provided by the kernel */
1867 	if ((ctx.options & (DHCPCD_MASTER | DHCPCD_DEV)) ==
1868 	    (DHCPCD_MASTER | DHCPCD_DEV))
1869 		dev_start(&ctx);
1870 
1871 	if (rpc_init(&ctx) == -1) {
1872 		/* NB: rpc_init generates a syslog msg */
1873 		exit(EXIT_FAILURE);
1874 	}
1875 	rpc_signal_status("Init");
1876 
1877 	ctx.ifaces = if_discover(&ctx, ctx.ifc, ctx.ifv);
1878 	if (ctx.ifaces == NULL) {
1879 		logger(&ctx, LOG_ERR, "if_discover: %m");
1880 		goto exit_failure;
1881 	}
1882 	for (i = 0; i < ctx.ifc; i++) {
1883 		int intf_len = strlen(ctx.ifv[i]);
1884 		split_interface_lease(ctx.ifv[i], &intf_len, NULL);
1885 		if (intf_len > IF_NAMESIZE) {
1886 			logger(&ctx, LOG_ERR,
1887 			    "%s: interface name too long",
1888 			    ctx.ifv[i]);
1889 			continue;
1890 		}
1891 		strlcpy(ifn, ctx.ifv[i], intf_len + 1);
1892 		if (if_find(ctx.ifaces, ifn) == NULL)
1893 			logger(&ctx, LOG_ERR,
1894 			    "%s: interface not found or invalid",
1895 			    ifn);
1896 	}
1897 	if (TAILQ_FIRST(ctx.ifaces) == NULL) {
1898 		if (ctx.ifc == 0)
1899 			logger(&ctx, LOG_ERR, "no valid interfaces found");
1900 		else
1901 			goto exit_failure;
1902 		if (!(ctx.options & DHCPCD_LINK)) {
1903 			logger(&ctx, LOG_ERR,
1904 			    "aborting as link detection is disabled");
1905 			goto exit_failure;
1906 		}
1907 	}
1908 
1909 	TAILQ_FOREACH(ifp, ctx.ifaces, next) {
1910 		dhcpcd_initstate1(ifp, argc, argv, 0);
1911 	}
1912 
1913 	if (ctx.options & DHCPCD_BACKGROUND && dhcpcd_daemonise(&ctx))
1914 		goto exit_success;
1915 
1916 	opt = 0;
1917 	TAILQ_FOREACH(ifp, ctx.ifaces, next) {
1918 		run_preinit(ifp);
1919 		if (ifp->carrier != LINK_DOWN)
1920 			opt = 1;
1921 	}
1922 
1923 	if (!(ctx.options & DHCPCD_BACKGROUND)) {
1924 		if (ctx.options & DHCPCD_MASTER)
1925 			t = ifo->timeout;
1926 		else if ((ifp = TAILQ_FIRST(ctx.ifaces)))
1927 			t = ifp->options->timeout;
1928 		else
1929 			t = 0;
1930 		if (opt == 0 &&
1931 		    ctx.options & DHCPCD_LINK &&
1932 		    !(ctx.options & DHCPCD_WAITIP))
1933 		{
1934 			logger(&ctx, LOG_WARNING,
1935 			    "no interfaces have a carrier");
1936 			if (dhcpcd_daemonise(&ctx))
1937 				goto exit_success;
1938 		} else if (t > 0 &&
1939 		    /* Test mode removes the daemonise bit, so check for both */
1940 		    ctx.options & (DHCPCD_DAEMONISE | DHCPCD_TEST))
1941 		{
1942 			eloop_timeout_add_sec(ctx.eloop, t,
1943 			    handle_exit_timeout, &ctx);
1944 		}
1945 	}
1946 	free_options(ifo);
1947 	ifo = NULL;
1948 
1949 	if_sortinterfaces(&ctx);
1950 	TAILQ_FOREACH(ifp, ctx.ifaces, next) {
1951 		eloop_timeout_add_sec(ctx.eloop, 0,
1952 		    dhcpcd_prestartinterface, ifp);
1953 	}
1954 
1955 	i = eloop_start(ctx.eloop);
1956 	goto exit1;
1957 
1958 exit_success:
1959 	i = EXIT_SUCCESS;
1960 	goto exit1;
1961 
1962 exit_failure:
1963 	i = EXIT_FAILURE;
1964 
1965 exit1:
1966 	/* Free memory and close fd's */
1967 	if (ctx.ifaces) {
1968 		while ((ifp = TAILQ_FIRST(ctx.ifaces))) {
1969 			TAILQ_REMOVE(ctx.ifaces, ifp, next);
1970 			if_free(ifp);
1971 		}
1972 		free(ctx.ifaces);
1973 	}
1974 	free(ctx.duid);
1975 	if (ctx.link_fd != -1) {
1976 		eloop_event_delete(ctx.eloop, ctx.link_fd, 0);
1977 		close(ctx.link_fd);
1978 	}
1979 
1980 	free_options(ifo);
1981 	free_globals(&ctx);
1982 	ipv4_ctxfree(&ctx);
1983 	ipv6_ctxfree(&ctx);
1984 	dev_stop(&ctx);
1985 	if (control_stop(&ctx) == -1)
1986 		logger(&ctx, LOG_ERR, "control_stop: %m:");
1987 	if (ctx.pid_fd != -1) {
1988 		close(ctx.pid_fd);
1989 		unlink(ctx.pidfile);
1990 	}
1991 	eloop_free(ctx.eloop);
1992 
1993 	if (ctx.options & DHCPCD_STARTED && !(ctx.options & DHCPCD_FORKED))
1994 		logger(&ctx, LOG_INFO, PACKAGE " exited");
1995 	logger_close(&ctx);
1996 	free(ctx.logfile);
1997 	return i;
1998 }
1999