etc/protocols - sync with NetBSD-8
[minix.git] / external / bsd / dhcpcd / dist / dhcpcd.c
blob83085d520bc91160665122b77b8bc0adf9923409
1 #include <sys/cdefs.h>
2 __RCSID("$NetBSD: dhcpcd.c,v 1.28 2015/09/04 12:25:01 roy Exp $");
4 /*
5 * dhcpcd - DHCP client daemon
6 * Copyright (c) 2006-2015 Roy Marples <roy@marples.name>
7 * All rights reserved
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
18 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
19 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
22 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28 * SUCH DAMAGE.
31 const char dhcpcd_copyright[] = "Copyright (c) 2006-2015 Roy Marples";
33 #define _WITH_DPRINTF /* Stop FreeBSD bitching */
35 #include <sys/file.h>
36 #include <sys/socket.h>
37 #include <sys/stat.h>
38 #include <sys/time.h>
39 #include <sys/types.h>
40 #include <sys/uio.h>
42 #include <ctype.h>
43 #include <errno.h>
44 #include <fcntl.h>
45 #include <getopt.h>
46 #include <limits.h>
47 #include <paths.h>
48 #include <signal.h>
49 #include <stdio.h>
50 #include <stdlib.h>
51 #include <string.h>
52 #include <unistd.h>
53 #include <time.h>
55 #include "config.h"
56 #include "arp.h"
57 #include "common.h"
58 #include "control.h"
59 #include "dev.h"
60 #include "dhcpcd.h"
61 #include "dhcp6.h"
62 #include "duid.h"
63 #include "eloop.h"
64 #include "if.h"
65 #include "if-options.h"
66 #include "ipv4.h"
67 #include "ipv4ll.h"
68 #include "ipv6.h"
69 #include "ipv6nd.h"
70 #include "script.h"
72 #ifdef USE_SIGNALS
73 const int dhcpcd_signals[] = {
74 SIGTERM,
75 SIGINT,
76 SIGALRM,
77 SIGHUP,
78 SIGUSR1,
79 SIGUSR2,
80 SIGPIPE
82 const size_t dhcpcd_signals_len = __arraycount(dhcpcd_signals);
83 #endif
85 #if defined(USE_SIGNALS) || !defined(THERE_IS_NO_FORK)
86 static pid_t
87 read_pid(const char *pidfile)
89 FILE *fp;
90 pid_t pid;
92 if ((fp = fopen(pidfile, "r")) == NULL) {
93 errno = ENOENT;
94 return 0;
96 if (fscanf(fp, "%d", &pid) != 1)
97 pid = 0;
98 fclose(fp);
99 return pid;
102 static int
103 write_pid(int fd, pid_t pid)
106 if (ftruncate(fd, (off_t)0) == -1)
107 return -1;
108 lseek(fd, (off_t)0, SEEK_SET);
109 return dprintf(fd, "%d\n", (int)pid);
111 #endif
113 static void
114 usage(void)
117 printf("usage: "PACKAGE"\t[-46ABbDdEGgHJKkLnpqTVw]\n"
118 "\t\t[-C, --nohook hook] [-c, --script script]\n"
119 "\t\t[-e, --env value] [-F, --fqdn FQDN] [-f, --config file]\n"
120 "\t\t[-h, --hostname hostname] [-I, --clientid clientid]\n"
121 "\t\t[-i, --vendorclassid vendorclassid] [-l, --leasetime seconds]\n"
122 "\t\t[-m, --metric metric] [-O, --nooption option]\n"
123 "\t\t[-o, --option option] [-Q, --require option]\n"
124 "\t\t[-r, --request address] [-S, --static value]\n"
125 "\t\t[-s, --inform address[/cidr]] [-t, --timeout seconds]\n"
126 "\t\t[-u, --userclass class] [-v, --vendor code, value]\n"
127 "\t\t[-W, --whitelist address[/cidr]] [-y, --reboot seconds]\n"
128 "\t\t[-X, --blacklist address[/cidr]] [-Z, --denyinterfaces pattern]\n"
129 "\t\t[-z, --allowinterfaces pattern] [interface] [...]\n"
130 " "PACKAGE"\t-k, --release [interface]\n"
131 " "PACKAGE"\t-U, --dumplease interface\n"
132 " "PACKAGE"\t--version\n"
133 " "PACKAGE"\t-x, --exit [interface]\n");
136 static void
137 free_globals(struct dhcpcd_ctx *ctx)
139 struct dhcp_opt *opt;
141 if (ctx->ifac) {
142 for (; ctx->ifac > 0; ctx->ifac--)
143 free(ctx->ifav[ctx->ifac - 1]);
144 free(ctx->ifav);
145 ctx->ifav = NULL;
147 if (ctx->ifdc) {
148 for (; ctx->ifdc > 0; ctx->ifdc--)
149 free(ctx->ifdv[ctx->ifdc - 1]);
150 free(ctx->ifdv);
151 ctx->ifdv = NULL;
153 if (ctx->ifcc) {
154 for (; ctx->ifcc > 0; ctx->ifcc--)
155 free(ctx->ifcv[ctx->ifcc - 1]);
156 free(ctx->ifcv);
157 ctx->ifcv = NULL;
160 #ifdef INET
161 if (ctx->dhcp_opts) {
162 for (opt = ctx->dhcp_opts;
163 ctx->dhcp_opts_len > 0;
164 opt++, ctx->dhcp_opts_len--)
165 free_dhcp_opt_embenc(opt);
166 free(ctx->dhcp_opts);
167 ctx->dhcp_opts = NULL;
169 #endif
170 #ifdef INET6
171 if (ctx->nd_opts) {
172 for (opt = ctx->nd_opts;
173 ctx->nd_opts_len > 0;
174 opt++, ctx->nd_opts_len--)
175 free_dhcp_opt_embenc(opt);
176 free(ctx->nd_opts);
177 ctx->nd_opts = NULL;
179 if (ctx->dhcp6_opts) {
180 for (opt = ctx->dhcp6_opts;
181 ctx->dhcp6_opts_len > 0;
182 opt++, ctx->dhcp6_opts_len--)
183 free_dhcp_opt_embenc(opt);
184 free(ctx->dhcp6_opts);
185 ctx->dhcp6_opts = NULL;
187 #endif
188 if (ctx->vivso) {
189 for (opt = ctx->vivso;
190 ctx->vivso_len > 0;
191 opt++, ctx->vivso_len--)
192 free_dhcp_opt_embenc(opt);
193 free(ctx->vivso);
194 ctx->vivso = NULL;
198 static void
199 handle_exit_timeout(void *arg)
201 struct dhcpcd_ctx *ctx;
203 ctx = arg;
204 logger(ctx, LOG_ERR, "timed out");
205 if (!(ctx->options & DHCPCD_MASTER)) {
206 eloop_exit(ctx->eloop, EXIT_FAILURE);
207 return;
209 ctx->options |= DHCPCD_NOWAITIP;
210 dhcpcd_daemonise(ctx);
213 static const char *
214 dhcpcd_af(int af)
217 switch (af) {
218 case AF_UNSPEC:
219 return "IP";
220 case AF_INET:
221 return "IPv4";
222 case AF_INET6:
223 return "IPv6";
224 default:
225 return NULL;
230 dhcpcd_ifafwaiting(const struct interface *ifp)
232 unsigned long long opts;
234 opts = ifp->options->options;
235 if (opts & DHCPCD_WAITIP4 && !ipv4_hasaddr(ifp))
236 return AF_INET;
237 if (opts & DHCPCD_WAITIP6 && !ipv6_hasaddr(ifp))
238 return AF_INET6;
239 if (opts & DHCPCD_WAITIP &&
240 !(opts & (DHCPCD_WAITIP4 | DHCPCD_WAITIP6)) &&
241 !ipv4_hasaddr(ifp) && !ipv6_hasaddr(ifp))
242 return AF_UNSPEC;
243 return AF_MAX;
247 dhcpcd_afwaiting(const struct dhcpcd_ctx *ctx)
249 unsigned long long opts;
250 const struct interface *ifp;
251 int af;
253 if (!(ctx->options & DHCPCD_WAITOPTS))
254 return AF_MAX;
256 opts = ctx->options;
257 TAILQ_FOREACH(ifp, ctx->ifaces, next) {
258 if (opts & (DHCPCD_WAITIP | DHCPCD_WAITIP4) &&
259 ipv4_hasaddr(ifp))
260 opts &= ~(DHCPCD_WAITIP | DHCPCD_WAITIP4);
261 if (opts & (DHCPCD_WAITIP | DHCPCD_WAITIP6) &&
262 ipv6_hasaddr(ifp))
263 opts &= ~(DHCPCD_WAITIP | DHCPCD_WAITIP6);
264 if (!(opts & DHCPCD_WAITOPTS))
265 break;
267 if (opts & DHCPCD_WAITIP)
268 af = AF_UNSPEC;
269 else if (opts & DHCPCD_WAITIP4)
270 af = AF_INET;
271 else if (opts & DHCPCD_WAITIP6)
272 af = AF_INET6;
273 else
274 return AF_MAX;
275 return af;
278 static int
279 dhcpcd_ipwaited(struct dhcpcd_ctx *ctx)
281 struct interface *ifp;
282 int af;
284 TAILQ_FOREACH(ifp, ctx->ifaces, next) {
285 if ((af = dhcpcd_ifafwaiting(ifp)) != AF_MAX) {
286 logger(ctx, LOG_DEBUG,
287 "%s: waiting for an %s address",
288 ifp->name, dhcpcd_af(af));
289 return 0;
293 if ((af = dhcpcd_afwaiting(ctx)) != AF_MAX) {
294 logger(ctx, LOG_DEBUG,
295 "waiting for an %s address",
296 dhcpcd_af(af));
297 return 0;
300 return 1;
303 /* Returns the pid of the child, otherwise 0. */
304 pid_t
305 dhcpcd_daemonise(struct dhcpcd_ctx *ctx)
307 #ifdef THERE_IS_NO_FORK
308 eloop_timeout_delete(ctx->eloop, handle_exit_timeout, ctx);
309 errno = ENOSYS;
310 return 0;
311 #else
312 pid_t pid;
313 char buf = '\0';
314 int sidpipe[2], fd;
316 if (ctx->options & DHCPCD_DAEMONISE &&
317 !(ctx->options & (DHCPCD_DAEMONISED | DHCPCD_NOWAITIP)))
319 if (!dhcpcd_ipwaited(ctx))
320 return 0;
323 eloop_timeout_delete(ctx->eloop, handle_exit_timeout, ctx);
324 if (ctx->options & DHCPCD_DAEMONISED ||
325 !(ctx->options & DHCPCD_DAEMONISE))
326 return 0;
327 /* Setup a signal pipe so parent knows when to exit. */
328 if (pipe(sidpipe) == -1) {
329 logger(ctx, LOG_ERR, "pipe: %m");
330 return 0;
332 logger(ctx, LOG_DEBUG, "forking to background");
333 switch (pid = fork()) {
334 case -1:
335 logger(ctx, LOG_ERR, "fork: %m");
336 return 0;
337 case 0:
338 setsid();
339 /* Some polling methods don't survive after forking,
340 * so ensure we can requeue all our events. */
341 if (eloop_requeue(ctx->eloop) == -1) {
342 logger(ctx, LOG_ERR, "eloop_requeue: %m");
343 eloop_exit(ctx->eloop, EXIT_FAILURE);
345 /* Notify parent it's safe to exit as we've detached. */
346 close(sidpipe[0]);
347 if (write(sidpipe[1], &buf, 1) == -1)
348 logger(ctx, LOG_ERR, "failed to notify parent: %m");
349 close(sidpipe[1]);
350 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
351 dup2(fd, STDIN_FILENO);
352 dup2(fd, STDOUT_FILENO);
353 dup2(fd, STDERR_FILENO);
354 close(fd);
356 break;
357 default:
358 /* Wait for child to detach */
359 close(sidpipe[1]);
360 if (read(sidpipe[0], &buf, 1) == -1)
361 logger(ctx, LOG_ERR, "failed to read child: %m");
362 close(sidpipe[0]);
363 break;
365 /* Done with the fd now */
366 if (pid != 0) {
367 logger(ctx, LOG_INFO, "forked to background, child pid %d", pid);
368 write_pid(ctx->pid_fd, pid);
369 close(ctx->pid_fd);
370 ctx->pid_fd = -1;
371 ctx->options |= DHCPCD_FORKED;
372 eloop_exit(ctx->eloop, EXIT_SUCCESS);
373 return pid;
375 ctx->options |= DHCPCD_DAEMONISED;
376 return pid;
377 #endif
380 static void
381 dhcpcd_drop(struct interface *ifp, int stop)
384 dhcp6_drop(ifp, stop ? NULL : "EXPIRE6");
385 ipv6nd_drop(ifp);
386 ipv6_drop(ifp);
387 ipv4ll_drop(ifp);
388 dhcp_drop(ifp, stop ? "STOP" : "EXPIRE");
389 arp_close(ifp);
392 static void
393 stop_interface(struct interface *ifp)
395 struct dhcpcd_ctx *ctx;
397 ctx = ifp->ctx;
398 logger(ctx, LOG_INFO, "%s: removing interface", ifp->name);
399 ifp->options->options |= DHCPCD_STOPPING;
401 dhcpcd_drop(ifp, 1);
402 if (ifp->options->options & DHCPCD_DEPARTED)
403 script_runreason(ifp, "DEPARTED");
404 else
405 script_runreason(ifp, "STOPPED");
407 /* Delete all timeouts for the interfaces */
408 eloop_q_timeout_delete(ctx->eloop, 0, NULL, ifp);
410 /* Remove the interface from our list */
411 TAILQ_REMOVE(ifp->ctx->ifaces, ifp, next);
412 if_free(ifp);
414 if (!(ctx->options & (DHCPCD_MASTER | DHCPCD_TEST)))
415 eloop_exit(ctx->eloop, EXIT_FAILURE);
418 static void
419 configure_interface1(struct interface *ifp)
421 struct if_options *ifo = ifp->options;
422 int ra_global, ra_iface;
423 #ifdef INET6
424 size_t i;
425 #endif
427 /* Do any platform specific configuration */
428 if_conf(ifp);
430 /* If we want to release a lease, we can't really persist the
431 * address either. */
432 if (ifo->options & DHCPCD_RELEASE)
433 ifo->options &= ~DHCPCD_PERSISTENT;
435 if (ifp->flags & IFF_POINTOPOINT && !(ifo->options & DHCPCD_INFORM))
436 ifo->options |= DHCPCD_STATIC;
437 if (ifp->flags & IFF_NOARP ||
438 ifo->options & (DHCPCD_INFORM | DHCPCD_STATIC))
439 ifo->options &= ~DHCPCD_IPV4LL;
440 if (ifp->flags & (IFF_POINTOPOINT | IFF_LOOPBACK) ||
441 !(ifp->flags & IFF_MULTICAST))
442 ifo->options &= ~DHCPCD_IPV6RS;
444 if (ifo->metric != -1)
445 ifp->metric = (unsigned int)ifo->metric;
447 if (!(ifo->options & DHCPCD_IPV4))
448 ifo->options &= ~(DHCPCD_DHCP | DHCPCD_IPV4LL | DHCPCD_WAITIP4);
450 if (!(ifo->options & DHCPCD_IPV6))
451 ifo->options &=
452 ~(DHCPCD_IPV6RS | DHCPCD_DHCP6 | DHCPCD_WAITIP6);
454 if (ifo->options & DHCPCD_SLAACPRIVATE &&
455 !(ifp->ctx->options & (DHCPCD_DUMPLEASE | DHCPCD_TEST)))
456 ifo->options |= DHCPCD_IPV6RA_OWN;
458 /* We want to disable kernel interface RA as early as possible. */
459 if (ifo->options & DHCPCD_IPV6RS &&
460 !(ifp->ctx->options & DHCPCD_DUMPLEASE))
462 /* If not doing any DHCP, disable the RDNSS requirement. */
463 if (!(ifo->options & (DHCPCD_DHCP | DHCPCD_DHCP6)))
464 ifo->options &= ~DHCPCD_IPV6RA_REQRDNSS;
465 ra_global = if_checkipv6(ifp->ctx, NULL,
466 ifp->ctx->options & DHCPCD_IPV6RA_OWN ? 1 : 0);
467 ra_iface = if_checkipv6(ifp->ctx, ifp,
468 ifp->options->options & DHCPCD_IPV6RA_OWN ? 1 : 0);
469 if (ra_global == -1 || ra_iface == -1)
470 ifo->options &= ~DHCPCD_IPV6RS;
471 else if (ra_iface == 0 &&
472 !(ifp->ctx->options & DHCPCD_TEST))
473 ifo->options |= DHCPCD_IPV6RA_OWN;
476 /* If we haven't specified a ClientID and our hardware address
477 * length is greater than DHCP_CHADDR_LEN then we enforce a ClientID
478 * of the hardware address family and the hardware address.
479 * If there is no hardware address and no ClientID set,
480 * force a DUID based ClientID. */
481 if (ifp->hwlen > DHCP_CHADDR_LEN)
482 ifo->options |= DHCPCD_CLIENTID;
483 else if (ifp->hwlen == 0 && !(ifo->options & DHCPCD_CLIENTID))
484 ifo->options |= DHCPCD_CLIENTID | DHCPCD_DUID;
486 /* Firewire and InfiniBand interfaces require ClientID and
487 * the broadcast option being set. */
488 switch (ifp->family) {
489 case ARPHRD_IEEE1394: /* FALLTHROUGH */
490 case ARPHRD_INFINIBAND:
491 ifo->options |= DHCPCD_CLIENTID | DHCPCD_BROADCAST;
492 break;
495 if (!(ifo->options & DHCPCD_IAID)) {
497 * An IAID is for identifying a unqiue interface within
498 * the client. It is 4 bytes long. Working out a default
499 * value is problematic.
501 * Interface name and number are not stable
502 * between different OS's. Some OS's also cannot make
503 * up their mind what the interface should be called
504 * (yes, udev, I'm looking at you).
505 * Also, the name could be longer than 4 bytes.
506 * Also, with pluggable interfaces the name and index
507 * could easily get swapped per actual interface.
509 * The MAC address is 6 bytes long, the final 3
510 * being unique to the manufacturer and the initial 3
511 * being unique to the organisation which makes it.
512 * We could use the last 4 bytes of the MAC address
513 * as the IAID as it's the most stable part given the
514 * above, but equally it's not guaranteed to be
515 * unique.
517 * Given the above, and our need to reliably work
518 * between reboots without persitent storage,
519 * generating the IAID from the MAC address is the only
520 * logical default.
522 * dhclient uses the last 4 bytes of the MAC address.
523 * dibbler uses an increamenting counter.
524 * wide-dhcpv6 uses 0 or a configured value.
525 * odhcp6c uses 1.
526 * Windows 7 uses the first 3 bytes of the MAC address
527 * and an unknown byte.
528 * dhcpcd-6.1.0 and earlier used the interface name,
529 * falling back to interface index if name > 4.
531 if (ifp->hwlen >= sizeof(ifo->iaid))
532 memcpy(ifo->iaid,
533 ifp->hwaddr + ifp->hwlen - sizeof(ifo->iaid),
534 sizeof(ifo->iaid));
535 else {
536 uint32_t len;
538 len = (uint32_t)strlen(ifp->name);
539 if (len <= sizeof(ifo->iaid)) {
540 memcpy(ifo->iaid, ifp->name, len);
541 if (len < sizeof(ifo->iaid))
542 memset(ifo->iaid + len, 0,
543 sizeof(ifo->iaid) - len);
544 } else {
545 /* IAID is the same size as a uint32_t */
546 len = htonl(ifp->index);
547 memcpy(ifo->iaid, &len, sizeof(len));
550 ifo->options |= DHCPCD_IAID;
553 #ifdef INET6
554 if (ifo->ia_len == 0 && ifo->options & DHCPCD_IPV6 &&
555 ifp->name[0] != '\0')
557 ifo->ia = malloc(sizeof(*ifo->ia));
558 if (ifo->ia == NULL)
559 logger(ifp->ctx, LOG_ERR, "%s: %m", __func__);
560 else {
561 ifo->ia_len = 1;
562 ifo->ia->ia_type = D6_OPTION_IA_NA;
563 memcpy(ifo->ia->iaid, ifo->iaid, sizeof(ifo->iaid));
564 memset(&ifo->ia->addr, 0, sizeof(ifo->ia->addr));
565 ifo->ia->sla = NULL;
566 ifo->ia->sla_len = 0;
568 } else {
569 for (i = 0; i < ifo->ia_len; i++) {
570 if (!ifo->ia[i].iaid_set) {
571 memcpy(&ifo->ia[i].iaid, ifo->iaid,
572 sizeof(ifo->ia[i].iaid));
573 ifo->ia[i].iaid_set = 1;
577 #endif
581 dhcpcd_selectprofile(struct interface *ifp, const char *profile)
583 struct if_options *ifo;
584 char pssid[PROFILE_LEN];
586 if (ifp->ssid_len) {
587 ssize_t r;
589 r = print_string(pssid, sizeof(pssid), ESCSTRING,
590 ifp->ssid, ifp->ssid_len);
591 if (r == -1) {
592 logger(ifp->ctx, LOG_ERR,
593 "%s: %s: %m", ifp->name, __func__);
594 pssid[0] = '\0';
596 } else
597 pssid[0] = '\0';
598 ifo = read_config(ifp->ctx, ifp->name, pssid, profile);
599 if (ifo == NULL) {
600 logger(ifp->ctx, LOG_DEBUG, "%s: no profile %s",
601 ifp->name, profile);
602 return -1;
604 if (profile != NULL) {
605 strlcpy(ifp->profile, profile, sizeof(ifp->profile));
606 logger(ifp->ctx, LOG_INFO, "%s: selected profile %s",
607 ifp->name, profile);
608 } else
609 *ifp->profile = '\0';
611 free_options(ifp->options);
612 ifp->options = ifo;
613 if (profile)
614 configure_interface1(ifp);
615 return 1;
618 static void
619 configure_interface(struct interface *ifp, int argc, char **argv,
620 unsigned long long options)
622 time_t old;
624 old = ifp->options ? ifp->options->mtime : 0;
625 dhcpcd_selectprofile(ifp, NULL);
626 add_options(ifp->ctx, ifp->name, ifp->options, argc, argv);
627 ifp->options->options |= options;
628 configure_interface1(ifp);
630 /* If the mtime has changed drop any old lease */
631 if (ifp->options && old != 0 && ifp->options->mtime != old) {
632 logger(ifp->ctx, LOG_WARNING,
633 "%s: confile file changed, expiring leases", ifp->name);
634 dhcpcd_drop(ifp, 0);
638 static void
639 dhcpcd_pollup(void *arg)
641 struct interface *ifp = arg;
642 int carrier;
644 carrier = if_carrier(ifp); /* will set ifp->flags */
645 if (carrier == LINK_UP && !(ifp->flags & IFF_UP)) {
646 struct timespec tv;
648 tv.tv_sec = 0;
649 tv.tv_nsec = IF_POLL_UP * NSEC_PER_MSEC;
650 eloop_timeout_add_tv(ifp->ctx->eloop, &tv, dhcpcd_pollup, ifp);
651 return;
654 dhcpcd_handlecarrier(ifp->ctx, carrier, ifp->flags, ifp->name);
657 void
658 dhcpcd_handlecarrier(struct dhcpcd_ctx *ctx, int carrier, unsigned int flags,
659 const char *ifname)
661 struct interface *ifp;
663 ifp = if_find(ctx->ifaces, ifname);
664 if (ifp == NULL || !(ifp->options->options & DHCPCD_LINK))
665 return;
667 switch(carrier) {
668 case LINK_UNKNOWN:
669 carrier = if_carrier(ifp); /* will set ifp->flags */
670 break;
671 case LINK_UP:
672 /* we have a carrier! Still need to check for IFF_UP */
673 if (flags & IFF_UP)
674 ifp->flags = flags;
675 else {
676 /* So we need to poll for IFF_UP as there is no
677 * kernel notification when it's set. */
678 dhcpcd_pollup(ifp);
679 return;
681 break;
682 default:
683 ifp->flags = flags;
686 /* If we here, we don't need to poll for IFF_UP any longer
687 * if generated by a kernel event. */
688 eloop_timeout_delete(ifp->ctx->eloop, dhcpcd_pollup, ifp);
690 if (carrier == LINK_UNKNOWN) {
691 if (errno != ENOTTY) /* For example a PPP link on BSD */
692 logger(ctx, LOG_ERR, "%s: carrier_status: %m", ifname);
693 } else if (carrier == LINK_DOWN || (ifp->flags & IFF_UP) == 0) {
694 if (ifp->carrier != LINK_DOWN) {
695 if (ifp->carrier == LINK_UP)
696 logger(ctx, LOG_INFO, "%s: carrier lost",
697 ifp->name);
698 ifp->carrier = LINK_DOWN;
699 script_runreason(ifp, "NOCARRIER");
700 #ifdef NOCARRIER_PRESERVE_IP
701 arp_close(ifp);
702 dhcp_abort(ifp);
703 if_sortinterfaces(ctx);
704 ipv4_preferanother(ifp);
705 ipv6nd_expire(ifp, 0);
706 #else
707 dhcpcd_drop(ifp, 0);
708 #endif
710 } else if (carrier == LINK_UP && ifp->flags & IFF_UP) {
711 if (ifp->carrier != LINK_UP) {
712 logger(ctx, LOG_INFO, "%s: carrier acquired",
713 ifp->name);
714 ifp->carrier = LINK_UP;
715 #if !defined(__linux__) && !defined(__NetBSD__)
716 /* BSD does not emit RTM_NEWADDR or RTM_CHGADDR when the
717 * hardware address changes so we have to go
718 * through the disovery process to work it out. */
719 dhcpcd_handleinterface(ctx, 0, ifp->name);
720 #endif
721 if (ifp->wireless) {
722 uint8_t ossid[IF_SSIDSIZE];
723 #ifdef NOCARRIER_PRESERVE_IP
724 size_t olen;
726 olen = ifp->ssid_len;
727 #endif
728 memcpy(ossid, ifp->ssid, ifp->ssid_len);
729 if_getssid(ifp);
730 #ifdef NOCARRIER_PRESERVE_IP
731 /* If we changed SSID network, drop leases */
732 if (ifp->ssid_len != olen ||
733 memcmp(ifp->ssid, ossid, ifp->ssid_len))
734 dhcpcd_drop(ifp, 0);
735 #endif
737 dhcpcd_initstate(ifp, 0);
738 script_runreason(ifp, "CARRIER");
739 #ifdef NOCARRIER_PRESERVE_IP
740 /* Set any IPv6 Routers we remembered to expire
741 * faster than they would normally as we
742 * maybe on a new network. */
743 ipv6nd_expire(ifp, RTR_CARRIER_EXPIRE);
744 #endif
745 /* RFC4941 Section 3.5 */
746 if (ifp->options->options & DHCPCD_IPV6RA_OWN)
747 ipv6_gentempifid(ifp);
748 dhcpcd_startinterface(ifp);
753 static void
754 warn_iaid_conflict(struct interface *ifp, uint8_t *iaid)
756 struct interface *ifn;
757 size_t i;
759 TAILQ_FOREACH(ifn, ifp->ctx->ifaces, next) {
760 if (ifn == ifp)
761 continue;
762 if (memcmp(ifn->options->iaid, iaid,
763 sizeof(ifn->options->iaid)) == 0)
764 break;
765 for (i = 0; i < ifn->options->ia_len; i++) {
766 if (memcmp(&ifn->options->ia[i].iaid, iaid,
767 sizeof(ifn->options->ia[i].iaid)) == 0)
768 break;
772 /* This is only a problem if the interfaces are on the same network. */
773 if (ifn)
774 logger(ifp->ctx, LOG_ERR,
775 "%s: IAID conflicts with one assigned to %s",
776 ifp->name, ifn->name);
779 static void
780 pre_start(struct interface *ifp)
783 /* Add our link-local address before upping the interface
784 * so our RFC7217 address beats the hwaddr based one.
785 * This is also a safety check incase it was ripped out
786 * from under us. */
787 if (ifp->options->options & DHCPCD_IPV6 && ipv6_start(ifp) == -1) {
788 logger(ifp->ctx, LOG_ERR, "%s: ipv6_start: %m", ifp->name);
789 ifp->options->options &= ~DHCPCD_IPV6;
793 void
794 dhcpcd_startinterface(void *arg)
796 struct interface *ifp = arg;
797 struct if_options *ifo = ifp->options;
798 size_t i;
799 char buf[DUID_LEN * 3];
800 int carrier;
801 struct timespec tv;
803 if (ifo->options & DHCPCD_LINK) {
804 switch (ifp->carrier) {
805 case LINK_UP:
806 break;
807 case LINK_DOWN:
808 logger(ifp->ctx, LOG_INFO, "%s: waiting for carrier",
809 ifp->name);
810 return;
811 case LINK_UNKNOWN:
812 /* No media state available.
813 * Loop until both IFF_UP and IFF_RUNNING are set */
814 if ((carrier = if_carrier(ifp)) == LINK_UNKNOWN) {
815 tv.tv_sec = 0;
816 tv.tv_nsec = IF_POLL_UP * NSEC_PER_MSEC;
817 eloop_timeout_add_tv(ifp->ctx->eloop,
818 &tv, dhcpcd_startinterface, ifp);
819 } else
820 dhcpcd_handlecarrier(ifp->ctx, carrier,
821 ifp->flags, ifp->name);
822 return;
826 if (ifo->options & (DHCPCD_DUID | DHCPCD_IPV6)) {
827 /* Report client DUID */
828 if (ifp->ctx->duid == NULL) {
829 if (duid_init(ifp) == 0)
830 return;
831 logger(ifp->ctx, LOG_INFO, "DUID %s",
832 hwaddr_ntoa(ifp->ctx->duid,
833 ifp->ctx->duid_len,
834 buf, sizeof(buf)));
838 if (ifo->options & (DHCPCD_DUID | DHCPCD_IPV6)) {
839 /* Report IAIDs */
840 logger(ifp->ctx, LOG_INFO, "%s: IAID %s", ifp->name,
841 hwaddr_ntoa(ifo->iaid, sizeof(ifo->iaid),
842 buf, sizeof(buf)));
843 warn_iaid_conflict(ifp, ifo->iaid);
844 for (i = 0; i < ifo->ia_len; i++) {
845 if (memcmp(ifo->iaid, ifo->ia[i].iaid,
846 sizeof(ifo->iaid)))
848 logger(ifp->ctx, LOG_INFO, "%s: IAID %s",
849 ifp->name, hwaddr_ntoa(ifo->ia[i].iaid,
850 sizeof(ifo->ia[i].iaid),
851 buf, sizeof(buf)));
852 warn_iaid_conflict(ifp, ifo->ia[i].iaid);
857 if (ifo->options & DHCPCD_IPV6) {
858 if (ifo->options & DHCPCD_IPV6RS &&
859 !(ifo->options & DHCPCD_INFORM))
860 ipv6nd_startrs(ifp);
862 if (ifo->options & DHCPCD_DHCP6)
863 dhcp6_find_delegates(ifp);
865 if (!(ifo->options & DHCPCD_IPV6RS) ||
866 ifo->options & DHCPCD_IA_FORCED)
868 ssize_t nolease;
870 if (ifo->options & DHCPCD_IA_FORCED)
871 nolease = dhcp6_start(ifp, DH6S_INIT);
872 else {
873 nolease = 0;
874 /* Enabling the below doesn't really make
875 * sense as there is currently no standard
876 * to push routes via DHCPv6.
877 * (There is an expired working draft,
878 * maybe abandoned?)
879 * You can also get it to work by forcing
880 * an IA as shown above. */
881 #if 0
882 /* With no RS or delegates we might
883 * as well try and solicit a DHCPv6 address */
884 if (nolease == 0)
885 nolease = dhcp6_start(ifp, DH6S_INIT);
886 #endif
888 if (nolease == -1)
889 logger(ifp->ctx, LOG_ERR,
890 "%s: dhcp6_start: %m", ifp->name);
894 if (ifo->options & DHCPCD_IPV4) {
895 /* Ensure we have an IPv4 state before starting DHCP */
896 if (ipv4_getstate(ifp) != NULL)
897 dhcp_start(ifp);
901 static void
902 dhcpcd_prestartinterface(void *arg)
904 struct interface *ifp = arg;
906 pre_start(ifp);
907 if ((!(ifp->ctx->options & DHCPCD_MASTER) ||
908 ifp->options->options & DHCPCD_IF_UP) &&
909 if_up(ifp) == -1)
910 logger(ifp->ctx, LOG_ERR, "%s: if_up: %m", ifp->name);
912 if (ifp->options->options & DHCPCD_LINK &&
913 ifp->carrier == LINK_UNKNOWN)
915 int carrier;
917 if ((carrier = if_carrier(ifp)) != LINK_UNKNOWN) {
918 dhcpcd_handlecarrier(ifp->ctx, carrier,
919 ifp->flags, ifp->name);
920 return;
922 logger(ifp->ctx, LOG_INFO,
923 "%s: unknown carrier, waiting for interface flags",
924 ifp->name);
927 dhcpcd_startinterface(ifp);
930 static void
931 handle_link(void *arg)
933 struct dhcpcd_ctx *ctx;
935 ctx = arg;
936 if (if_managelink(ctx) == -1) {
937 logger(ctx, LOG_ERR, "if_managelink: %m");
938 eloop_event_delete(ctx->eloop, ctx->link_fd);
939 close(ctx->link_fd);
940 ctx->link_fd = -1;
944 static void
945 dhcpcd_initstate1(struct interface *ifp, int argc, char **argv,
946 unsigned long long options)
948 struct if_options *ifo;
950 configure_interface(ifp, argc, argv, options);
951 ifo = ifp->options;
953 if (ifo->options & DHCPCD_IPV4 && ipv4_init(ifp->ctx) == -1) {
954 logger(ifp->ctx, LOG_ERR, "ipv4_init: %m");
955 ifo->options &= ~DHCPCD_IPV4;
957 if (ifo->options & DHCPCD_IPV6 && ipv6_init(ifp->ctx) == NULL) {
958 logger(ifp->ctx, LOG_ERR, "ipv6_init: %m");
959 ifo->options &= ~DHCPCD_IPV6RS;
962 /* Add our link-local address before upping the interface
963 * so our RFC7217 address beats the hwaddr based one.
964 * This needs to happen before PREINIT incase a hook script
965 * inadvertently ups the interface. */
966 if (ifo->options & DHCPCD_IPV6 && ipv6_start(ifp) == -1) {
967 logger(ifp->ctx, LOG_ERR, "%s: ipv6_start: %m", ifp->name);
968 ifo->options &= ~DHCPCD_IPV6;
972 void
973 dhcpcd_initstate(struct interface *ifp, unsigned long long options)
976 dhcpcd_initstate1(ifp, ifp->ctx->argc, ifp->ctx->argv, options);
979 static void
980 run_preinit(struct interface *ifp)
983 pre_start(ifp);
984 if (ifp->ctx->options & DHCPCD_TEST)
985 return;
987 script_runreason(ifp, "PREINIT");
989 if (ifp->options->options & DHCPCD_LINK && ifp->carrier != LINK_UNKNOWN)
990 script_runreason(ifp,
991 ifp->carrier == LINK_UP ? "CARRIER" : "NOCARRIER");
995 dhcpcd_handleinterface(void *arg, int action, const char *ifname)
997 struct dhcpcd_ctx *ctx;
998 struct if_head *ifs;
999 struct interface *ifp, *iff, *ifn;
1000 const char * const argv[] = { ifname };
1001 int i;
1003 ctx = arg;
1004 if (action == -1) {
1005 ifp = if_find(ctx->ifaces, ifname);
1006 if (ifp == NULL) {
1007 errno = ESRCH;
1008 return -1;
1010 logger(ctx, LOG_DEBUG, "%s: interface departed", ifp->name);
1011 ifp->options->options |= DHCPCD_DEPARTED;
1012 stop_interface(ifp);
1013 return 0;
1016 /* If running off an interface list, check it's in it. */
1017 if (ctx->ifc && action != 2) {
1018 for (i = 0; i < ctx->ifc; i++)
1019 if (strcmp(ctx->ifv[i], ifname) == 0)
1020 break;
1021 if (i >= ctx->ifc)
1022 return 0;
1025 i = -1;
1026 ifs = if_discover(ctx, -1, UNCONST(argv));
1027 if (ifs == NULL) {
1028 logger(ctx, LOG_ERR, "%s: if_discover: %m", __func__);
1029 return -1;
1031 TAILQ_FOREACH_SAFE(ifp, ifs, next, ifn) {
1032 if (strcmp(ifp->name, ifname) != 0)
1033 continue;
1034 i = 0;
1035 /* Check if we already have the interface */
1036 iff = if_find(ctx->ifaces, ifp->name);
1037 if (iff) {
1038 logger(ctx, LOG_DEBUG, "%s: interface updated", iff->name);
1039 /* The flags and hwaddr could have changed */
1040 iff->flags = ifp->flags;
1041 iff->hwlen = ifp->hwlen;
1042 if (ifp->hwlen != 0)
1043 memcpy(iff->hwaddr, ifp->hwaddr, iff->hwlen);
1044 } else {
1045 logger(ctx, LOG_DEBUG, "%s: interface added", ifp->name);
1046 TAILQ_REMOVE(ifs, ifp, next);
1047 TAILQ_INSERT_TAIL(ctx->ifaces, ifp, next);
1048 dhcpcd_initstate(ifp, 0);
1049 run_preinit(ifp);
1050 iff = ifp;
1052 if (action > 0)
1053 dhcpcd_prestartinterface(iff);
1056 /* Free our discovered list */
1057 while ((ifp = TAILQ_FIRST(ifs))) {
1058 TAILQ_REMOVE(ifs, ifp, next);
1059 if_free(ifp);
1061 free(ifs);
1063 if (i == -1)
1064 errno = ENOENT;
1065 return i;
1068 void
1069 dhcpcd_handlehwaddr(struct dhcpcd_ctx *ctx, const char *ifname,
1070 const uint8_t *hwaddr, uint8_t hwlen)
1072 struct interface *ifp;
1073 char buf[sizeof(ifp->hwaddr) * 3];
1075 ifp = if_find(ctx->ifaces, ifname);
1076 if (ifp == NULL)
1077 return;
1079 if (hwlen > sizeof(ifp->hwaddr)) {
1080 errno = ENOBUFS;
1081 logger(ctx, LOG_ERR, "%s: %s: %m", ifp->name, __func__);
1082 return;
1085 if (ifp->hwlen == hwlen && memcmp(ifp->hwaddr, hwaddr, hwlen) == 0)
1086 return;
1088 logger(ctx, LOG_INFO, "%s: new hardware address: %s", ifp->name,
1089 hwaddr_ntoa(hwaddr, hwlen, buf, sizeof(buf)));
1090 ifp->hwlen = hwlen;
1091 memcpy(ifp->hwaddr, hwaddr, hwlen);
1094 static void
1095 if_reboot(struct interface *ifp, int argc, char **argv)
1097 unsigned long long oldopts;
1099 oldopts = ifp->options->options;
1100 script_runreason(ifp, "RECONFIGURE");
1101 dhcpcd_initstate1(ifp, argc, argv, 0);
1102 dhcp_reboot_newopts(ifp, oldopts);
1103 dhcp6_reboot(ifp);
1104 dhcpcd_prestartinterface(ifp);
1107 static void
1108 reload_config(struct dhcpcd_ctx *ctx)
1110 struct if_options *ifo;
1112 free_globals(ctx);
1113 ifo = read_config(ctx, NULL, NULL, NULL);
1114 add_options(ctx, NULL, ifo, ctx->argc, ctx->argv);
1115 /* We need to preserve these two options. */
1116 if (ctx->options & DHCPCD_MASTER)
1117 ifo->options |= DHCPCD_MASTER;
1118 if (ctx->options & DHCPCD_DAEMONISED)
1119 ifo->options |= DHCPCD_DAEMONISED;
1120 ctx->options = ifo->options;
1121 free_options(ifo);
1124 static void
1125 reconf_reboot(struct dhcpcd_ctx *ctx, int action, int argc, char **argv, int oi)
1127 struct if_head *ifs;
1128 struct interface *ifn, *ifp;
1130 ifs = if_discover(ctx, argc - oi, argv + oi);
1131 if (ifs == NULL) {
1132 logger(ctx, LOG_ERR, "%s: if_discover: %m", __func__);
1133 return;
1136 while ((ifp = TAILQ_FIRST(ifs))) {
1137 TAILQ_REMOVE(ifs, ifp, next);
1138 ifn = if_find(ctx->ifaces, ifp->name);
1139 if (ifn) {
1140 if (action)
1141 if_reboot(ifn, argc, argv);
1142 else
1143 ipv4_applyaddr(ifn);
1144 if_free(ifp);
1145 } else {
1146 TAILQ_INSERT_TAIL(ctx->ifaces, ifp, next);
1147 dhcpcd_initstate1(ifp, argc, argv, 0);
1148 run_preinit(ifp);
1149 dhcpcd_prestartinterface(ifp);
1152 free(ifs);
1155 static void
1156 stop_all_interfaces(struct dhcpcd_ctx *ctx, int do_release)
1158 struct interface *ifp;
1160 /* Drop the last interface first */
1161 while ((ifp = TAILQ_LAST(ctx->ifaces, if_head)) != NULL) {
1162 if (do_release) {
1163 ifp->options->options |= DHCPCD_RELEASE;
1164 ifp->options->options &= ~DHCPCD_PERSISTENT;
1166 ifp->options->options |= DHCPCD_EXITING;
1167 stop_interface(ifp);
1171 #ifdef USE_SIGNALS
1172 #define sigmsg "received %s, %s"
1173 static void
1174 signal_cb(int sig, void *arg)
1176 struct dhcpcd_ctx *ctx = arg;
1177 struct interface *ifp;
1178 int do_release, exit_code;
1180 do_release = 0;
1181 exit_code = EXIT_FAILURE;
1182 switch (sig) {
1183 case SIGINT:
1184 logger(ctx, LOG_INFO, sigmsg, "SIGINT", "stopping");
1185 break;
1186 case SIGTERM:
1187 logger(ctx, LOG_INFO, sigmsg, "SIGTERM", "stopping");
1188 exit_code = EXIT_SUCCESS;
1189 break;
1190 case SIGALRM:
1191 logger(ctx, LOG_INFO, sigmsg, "SIGALRM", "releasing");
1192 do_release = 1;
1193 exit_code = EXIT_SUCCESS;
1194 break;
1195 case SIGHUP:
1196 logger(ctx, LOG_INFO, sigmsg, "SIGHUP", "rebinding");
1197 reload_config(ctx);
1198 /* Preserve any options passed on the commandline
1199 * when we were started. */
1200 reconf_reboot(ctx, 1, ctx->argc, ctx->argv,
1201 ctx->argc - ctx->ifc);
1202 return;
1203 case SIGUSR1:
1204 logger(ctx, LOG_INFO, sigmsg, "SIGUSR1", "reconfiguring");
1205 TAILQ_FOREACH(ifp, ctx->ifaces, next) {
1206 ipv4_applyaddr(ifp);
1208 return;
1209 case SIGUSR2:
1210 logger_close(ctx);
1211 logger_open(ctx);
1212 logger(ctx, LOG_INFO, sigmsg, "SIGUSR2", "reopened logfile");
1213 return;
1214 case SIGPIPE:
1215 logger(ctx, LOG_WARNING, "received SIGPIPE");
1216 return;
1217 default:
1218 logger(ctx, LOG_ERR,
1219 "received signal %d, "
1220 "but don't know what to do with it",
1221 sig);
1222 return;
1225 if (!(ctx->options & DHCPCD_TEST))
1226 stop_all_interfaces(ctx, do_release);
1227 eloop_exit(ctx->eloop, exit_code);
1229 #endif
1231 static void
1232 dhcpcd_getinterfaces(void *arg)
1234 struct fd_list *fd = arg;
1235 struct interface *ifp;
1236 size_t len;
1238 len = 0;
1239 TAILQ_FOREACH(ifp, fd->ctx->ifaces, next) {
1240 len++;
1241 if (D_STATE_RUNNING(ifp))
1242 len++;
1243 if (IPV4LL_STATE_RUNNING(ifp))
1244 len++;
1245 if (RS_STATE_RUNNING(ifp))
1246 len++;
1247 if (D6_STATE_RUNNING(ifp))
1248 len++;
1250 if (write(fd->fd, &len, sizeof(len)) != sizeof(len))
1251 return;
1252 eloop_event_remove_writecb(fd->ctx->eloop, fd->fd);
1253 TAILQ_FOREACH(ifp, fd->ctx->ifaces, next) {
1254 if (send_interface(fd, ifp) == -1)
1255 logger(ifp->ctx, LOG_ERR,
1256 "send_interface %d: %m", fd->fd);
1261 dhcpcd_handleargs(struct dhcpcd_ctx *ctx, struct fd_list *fd,
1262 int argc, char **argv)
1264 struct interface *ifp;
1265 int do_exit = 0, do_release = 0, do_reboot = 0;
1266 int opt, oi = 0;
1267 size_t len, l;
1268 char *tmp, *p;
1270 /* Special commands for our control socket
1271 * as the other end should be blocking until it gets the
1272 * expected reply we should be safely able just to change the
1273 * write callback on the fd */
1274 if (strcmp(*argv, "--version") == 0) {
1275 return control_queue(fd, UNCONST(VERSION),
1276 strlen(VERSION) + 1, 0);
1277 } else if (strcmp(*argv, "--getconfigfile") == 0) {
1278 return control_queue(fd, UNCONST(fd->ctx->cffile),
1279 strlen(fd->ctx->cffile) + 1, 0);
1280 } else if (strcmp(*argv, "--getinterfaces") == 0) {
1281 eloop_event_add(fd->ctx->eloop, fd->fd, NULL, NULL,
1282 dhcpcd_getinterfaces, fd);
1283 return 0;
1284 } else if (strcmp(*argv, "--listen") == 0) {
1285 fd->flags |= FD_LISTEN;
1286 return 0;
1289 /* Only priviledged users can control dhcpcd via the socket. */
1290 if (fd->flags & FD_UNPRIV) {
1291 errno = EPERM;
1292 return -1;
1295 /* Log the command */
1296 len = 1;
1297 for (opt = 0; opt < argc; opt++)
1298 len += strlen(argv[opt]) + 1;
1299 tmp = malloc(len);
1300 if (tmp == NULL)
1301 return -1;
1302 p = tmp;
1303 for (opt = 0; opt < argc; opt++) {
1304 l = strlen(argv[opt]);
1305 strlcpy(p, argv[opt], len);
1306 len -= l + 1;
1307 p += l;
1308 *p++ = ' ';
1310 *--p = '\0';
1311 logger(ctx, LOG_INFO, "control command: %s", tmp);
1312 free(tmp);
1314 optind = 0;
1315 while ((opt = getopt_long(argc, argv, IF_OPTS, cf_options, &oi)) != -1)
1317 switch (opt) {
1318 case 'g':
1319 /* Assumed if below not set */
1320 break;
1321 case 'k':
1322 do_release = 1;
1323 break;
1324 case 'n':
1325 do_reboot = 1;
1326 break;
1327 case 'x':
1328 do_exit = 1;
1329 break;
1333 if (do_release || do_exit) {
1334 if (optind == argc) {
1335 stop_all_interfaces(ctx, do_release);
1336 eloop_exit(ctx->eloop, EXIT_SUCCESS);
1337 return 0;
1339 for (oi = optind; oi < argc; oi++) {
1340 if ((ifp = if_find(ctx->ifaces, argv[oi])) == NULL)
1341 continue;
1342 if (do_release) {
1343 ifp->options->options |= DHCPCD_RELEASE;
1344 ifp->options->options &= ~DHCPCD_PERSISTENT;
1346 ifp->options->options |= DHCPCD_EXITING;
1347 stop_interface(ifp);
1349 return 0;
1352 reload_config(ctx);
1353 /* XXX: Respect initial commandline options? */
1354 reconf_reboot(ctx, do_reboot, argc, argv, optind - 1);
1355 return 0;
1359 main(int argc, char **argv)
1361 struct dhcpcd_ctx ctx;
1362 struct if_options *ifo;
1363 struct interface *ifp;
1364 uint16_t family = 0;
1365 int opt, oi = 0, i;
1366 time_t t;
1367 ssize_t len;
1368 #if defined(USE_SIGNALS) || !defined(THERE_IS_NO_FORK)
1369 pid_t pid;
1370 #endif
1371 #ifdef USE_SIGNALS
1372 int sig = 0;
1373 const char *siga = NULL;
1374 #endif
1376 /* Test for --help and --version */
1377 if (argc > 1) {
1378 if (strcmp(argv[1], "--help") == 0) {
1379 usage();
1380 return EXIT_SUCCESS;
1381 } else if (strcmp(argv[1], "--version") == 0) {
1382 printf(""PACKAGE" "VERSION"\n%s\n", dhcpcd_copyright);
1383 return EXIT_SUCCESS;
1387 memset(&ctx, 0, sizeof(ctx));
1388 closefrom(3);
1390 ctx.log_fd = -1;
1391 logger_open(&ctx);
1392 logger_mask(&ctx, LOG_UPTO(LOG_INFO));
1394 ifo = NULL;
1395 ctx.cffile = CONFIG;
1396 ctx.pid_fd = ctx.control_fd = ctx.control_unpriv_fd = ctx.link_fd = -1;
1397 ctx.pf_inet_fd = -1;
1398 #if defined(INET6) && defined(BSD)
1399 ctx.pf_inet6_fd = -1;
1400 #endif
1401 #ifdef IFLR_ACTIVE
1402 ctx.pf_link_fd = -1;
1403 #endif
1405 TAILQ_INIT(&ctx.control_fds);
1406 #ifdef PLUGIN_DEV
1407 ctx.dev_fd = -1;
1408 #endif
1409 #ifdef INET
1410 ctx.udp_fd = -1;
1411 #endif
1412 i = 0;
1413 while ((opt = getopt_long(argc, argv, IF_OPTS, cf_options, &oi)) != -1)
1415 switch (opt) {
1416 case '4':
1417 family = AF_INET;
1418 break;
1419 case '6':
1420 family = AF_INET6;
1421 break;
1422 case 'f':
1423 ctx.cffile = optarg;
1424 break;
1425 #ifdef USE_SIGNALS
1426 case 'g':
1427 sig = SIGUSR1;
1428 siga = "USR1";
1429 break;
1430 case 'j':
1431 ctx.logfile = strdup(optarg);
1432 logger_close(&ctx);
1433 logger_open(&ctx);
1434 break;
1435 case 'k':
1436 sig = SIGALRM;
1437 siga = "ARLM";
1438 break;
1439 case 'n':
1440 sig = SIGHUP;
1441 siga = "HUP";
1442 break;
1443 case 'x':
1444 sig = SIGTERM;
1445 siga = "TERM";;
1446 break;
1447 #endif
1448 case 'T':
1449 i = 1;
1450 break;
1451 case 'U':
1452 i = 3;
1453 break;
1454 case 'V':
1455 i = 2;
1456 break;
1457 case '?':
1458 usage();
1459 goto exit_failure;
1463 ctx.argv = argv;
1464 ctx.argc = argc;
1465 ctx.ifc = argc - optind;
1466 ctx.ifv = argv + optind;
1468 ifo = read_config(&ctx, NULL, NULL, NULL);
1469 if (ifo == NULL)
1470 goto exit_failure;
1471 opt = add_options(&ctx, NULL, ifo, argc, argv);
1472 if (opt != 1) {
1473 if (opt == 0)
1474 usage();
1475 goto exit_failure;
1477 if (i == 2) {
1478 printf("Interface options:\n");
1479 if (optind == argc - 1) {
1480 free_options(ifo);
1481 ifo = read_config(&ctx, argv[optind], NULL, NULL);
1482 if (ifo == NULL)
1483 goto exit_failure;
1484 add_options(&ctx, NULL, ifo, argc, argv);
1486 if_printoptions();
1487 #ifdef INET
1488 if (family == 0 || family == AF_INET) {
1489 printf("\nDHCPv4 options:\n");
1490 dhcp_printoptions(&ctx,
1491 ifo->dhcp_override, ifo->dhcp_override_len);
1493 #endif
1494 #ifdef INET6
1495 if (family == 0 || family == AF_INET6) {
1496 printf("\nND options:\n");
1497 ipv6nd_printoptions(&ctx,
1498 ifo->nd_override, ifo->nd_override_len);
1499 printf("\nDHCPv6 options:\n");
1500 dhcp6_printoptions(&ctx,
1501 ifo->dhcp6_override, ifo->dhcp6_override_len);
1503 #endif
1504 goto exit_success;
1506 ctx.options = ifo->options;
1507 if (i != 0) {
1508 if (i == 1)
1509 ctx.options |= DHCPCD_TEST;
1510 else
1511 ctx.options |= DHCPCD_DUMPLEASE;
1512 ctx.options |= DHCPCD_PERSISTENT;
1513 ctx.options &= ~DHCPCD_DAEMONISE;
1516 #ifdef THERE_IS_NO_FORK
1517 ctx.options &= ~DHCPCD_DAEMONISE;
1518 #endif
1520 if (ctx.options & DHCPCD_DEBUG)
1521 logger_mask(&ctx, LOG_UPTO(LOG_DEBUG));
1522 if (ctx.options & DHCPCD_QUIET) {
1523 i = open(_PATH_DEVNULL, O_RDWR);
1524 if (i == -1)
1525 logger(&ctx, LOG_ERR, "%s: open: %m", __func__);
1526 else {
1527 dup2(i, STDERR_FILENO);
1528 close(i);
1532 if (!(ctx.options & (DHCPCD_TEST | DHCPCD_DUMPLEASE))) {
1533 /* If we have any other args, we should run as a single dhcpcd
1534 * instance for that interface. */
1535 if (optind == argc - 1 && !(ctx.options & DHCPCD_MASTER)) {
1536 const char *per;
1538 if (strlen(argv[optind]) > IF_NAMESIZE) {
1539 logger(&ctx, LOG_ERR,
1540 "%s: interface name too long",
1541 argv[optind]);
1542 goto exit_failure;
1544 /* Allow a dhcpcd interface per address family */
1545 switch(family) {
1546 case AF_INET:
1547 per = "-4";
1548 break;
1549 case AF_INET6:
1550 per = "-6";
1551 break;
1552 default:
1553 per = "";
1555 snprintf(ctx.pidfile, sizeof(ctx.pidfile),
1556 PIDFILE, "-", argv[optind], per);
1557 } else {
1558 snprintf(ctx.pidfile, sizeof(ctx.pidfile),
1559 PIDFILE, "", "", "");
1560 ctx.options |= DHCPCD_MASTER;
1564 if (chdir("/") == -1)
1565 logger(&ctx, LOG_ERR, "chdir `/': %m");
1567 /* Freeing allocated addresses from dumping leases can trigger
1568 * eloop removals as well, so init here. */
1569 if ((ctx.eloop = eloop_new()) == NULL) {
1570 logger(&ctx, LOG_ERR, "%s: eloop_init: %m", __func__);
1571 goto exit_failure;
1574 if (ctx.options & DHCPCD_DUMPLEASE) {
1575 if (optind != argc - 1) {
1576 logger(&ctx, LOG_ERR,
1577 "dumplease requires an interface");
1578 goto exit_failure;
1580 i = 0;
1581 /* We need to try and find the interface so we can
1582 * load the hardware address to compare automated IAID */
1583 ctx.ifaces = if_discover(&ctx, 1, argv + optind);
1584 if (ctx.ifaces == NULL) {
1585 logger(&ctx, LOG_ERR, "if_discover: %m");
1586 goto exit_failure;
1588 ifp = TAILQ_FIRST(ctx.ifaces);
1589 if (ifp == NULL) {
1590 ifp = calloc(1, sizeof(*ifp));
1591 if (ifp == NULL) {
1592 logger(&ctx, LOG_ERR, "%s: %m", __func__);
1593 goto exit_failure;
1595 strlcpy(ctx.pidfile, argv[optind], sizeof(ctx.pidfile));
1596 ifp->ctx = &ctx;
1597 TAILQ_INSERT_HEAD(ctx.ifaces, ifp, next);
1598 if (family == 0) {
1599 if (ctx.pidfile[strlen(ctx.pidfile) - 1] == '6')
1600 family = AF_INET6;
1601 else
1602 family = AF_INET;
1605 configure_interface(ifp, ctx.argc, ctx.argv, 0);
1606 if (family == 0 || family == AF_INET) {
1607 if (dhcp_dump(ifp) == -1)
1608 i = 1;
1610 if (family == 0 || family == AF_INET6) {
1611 if (dhcp6_dump(ifp) == -1)
1612 i = 1;
1614 if (i == -1)
1615 goto exit_failure;
1616 goto exit_success;
1619 #ifdef USE_SIGNALS
1620 if (!(ctx.options & DHCPCD_TEST) &&
1621 (sig == 0 || ctx.ifc != 0))
1623 #endif
1624 if (ctx.options & DHCPCD_MASTER)
1625 i = -1;
1626 else
1627 i = control_open(&ctx, argv[optind]);
1628 if (i == -1)
1629 i = control_open(&ctx, NULL);
1630 if (i != -1) {
1631 logger(&ctx, LOG_INFO,
1632 "sending commands to master dhcpcd process");
1633 len = control_send(&ctx, argc, argv);
1634 control_close(&ctx);
1635 if (len > 0) {
1636 logger(&ctx, LOG_DEBUG, "send OK");
1637 goto exit_success;
1638 } else {
1639 logger(&ctx, LOG_ERR,
1640 "failed to send commands");
1641 goto exit_failure;
1643 } else {
1644 if (errno != ENOENT)
1645 logger(&ctx, LOG_ERR, "control_open: %m");
1647 #ifdef USE_SIGNALS
1649 #endif
1651 #ifdef USE_SIGNALS
1652 if (sig != 0) {
1653 pid = read_pid(ctx.pidfile);
1654 if (pid != 0)
1655 logger(&ctx, LOG_INFO, "sending signal %s to pid %d",
1656 siga, pid);
1657 if (pid == 0 || kill(pid, sig) != 0) {
1658 if (sig != SIGHUP && errno != EPERM)
1659 logger(&ctx, LOG_ERR, ""PACKAGE" not running");
1660 if (pid != 0 && errno != ESRCH) {
1661 logger(&ctx, LOG_ERR, "kill: %m");
1662 goto exit_failure;
1664 unlink(ctx.pidfile);
1665 if (sig != SIGHUP)
1666 goto exit_failure;
1667 } else {
1668 struct timespec ts;
1670 if (sig == SIGHUP || sig == SIGUSR1)
1671 goto exit_success;
1672 /* Spin until it exits */
1673 logger(&ctx, LOG_INFO,
1674 "waiting for pid %d to exit", pid);
1675 ts.tv_sec = 0;
1676 ts.tv_nsec = 100000000; /* 10th of a second */
1677 for(i = 0; i < 100; i++) {
1678 nanosleep(&ts, NULL);
1679 if (read_pid(ctx.pidfile) == 0)
1680 goto exit_success;
1682 logger(&ctx, LOG_ERR, "pid %d failed to exit", pid);
1683 goto exit_failure;
1687 if (!(ctx.options & DHCPCD_TEST)) {
1688 if ((pid = read_pid(ctx.pidfile)) > 0 &&
1689 kill(pid, 0) == 0)
1691 logger(&ctx, LOG_ERR, ""PACKAGE
1692 " already running on pid %d (%s)",
1693 pid, ctx.pidfile);
1694 goto exit_failure;
1697 /* Ensure we have the needed directories */
1698 if (mkdir(RUNDIR, 0755) == -1 && errno != EEXIST)
1699 logger(&ctx, LOG_ERR, "mkdir `%s': %m", RUNDIR);
1700 if (mkdir(DBDIR, 0755) == -1 && errno != EEXIST)
1701 logger(&ctx, LOG_ERR, "mkdir `%s': %m", DBDIR);
1703 opt = O_WRONLY | O_CREAT | O_NONBLOCK;
1704 #ifdef O_CLOEXEC
1705 opt |= O_CLOEXEC;
1706 #endif
1707 ctx.pid_fd = open(ctx.pidfile, opt, 0664);
1708 if (ctx.pid_fd == -1)
1709 logger(&ctx, LOG_ERR, "open `%s': %m", ctx.pidfile);
1710 else {
1711 #ifdef LOCK_EX
1712 /* Lock the file so that only one instance of dhcpcd
1713 * runs on an interface */
1714 if (flock(ctx.pid_fd, LOCK_EX | LOCK_NB) == -1) {
1715 logger(&ctx, LOG_ERR, "flock `%s': %m", ctx.pidfile);
1716 close(ctx.pid_fd);
1717 ctx.pid_fd = -1;
1718 goto exit_failure;
1720 #endif
1721 #ifndef O_CLOEXEC
1722 if (fcntl(ctx.pid_fd, F_GETFD, &opt) == -1 ||
1723 fcntl(ctx.pid_fd, F_SETFD, opt | FD_CLOEXEC) == -1)
1725 logger(&ctx, LOG_ERR, "fcntl: %m");
1726 close(ctx.pid_fd);
1727 ctx.pid_fd = -1;
1728 goto exit_failure;
1730 #endif
1731 write_pid(ctx.pid_fd, getpid());
1735 if (ctx.options & DHCPCD_MASTER) {
1736 if (control_start(&ctx, NULL) == -1)
1737 logger(&ctx, LOG_ERR, "control_start: %m");
1739 #else
1740 if (control_start(&ctx,
1741 ctx.options & DHCPCD_MASTER ? NULL : argv[optind]) == -1)
1743 logger(&ctx, LOG_ERR, "control_start: %m");
1744 goto exit_failure;
1746 #endif
1748 logger(&ctx, LOG_DEBUG, PACKAGE "-" VERSION " starting");
1749 ctx.options |= DHCPCD_STARTED;
1750 #ifdef USE_SIGNALS
1751 if (eloop_signal_set_cb(ctx.eloop,
1752 dhcpcd_signals, dhcpcd_signals_len,
1753 signal_cb, &ctx) == -1)
1755 logger(&ctx, LOG_ERR, "eloop_signal_mask: %m");
1756 goto exit_failure;
1758 /* Save signal mask, block and redirect signals to our handler */
1759 if (eloop_signal_mask(ctx.eloop, &ctx.sigset) == -1) {
1760 logger(&ctx, LOG_ERR, "eloop_signal_mask: %m");
1761 goto exit_failure;
1763 #endif
1765 /* When running dhcpcd against a single interface, we need to retain
1766 * the old behaviour of waiting for an IP address */
1767 if (ctx.ifc == 1 && !(ctx.options & DHCPCD_BACKGROUND))
1768 ctx.options |= DHCPCD_WAITIP;
1770 /* Open our persistent sockets. */
1771 if (if_opensockets(&ctx) == -1) {
1772 logger(&ctx, LOG_ERR, "if_opensockets: %m");
1773 goto exit_failure;
1775 eloop_event_add(ctx.eloop, ctx.link_fd, handle_link, &ctx, NULL, NULL);
1777 /* Start any dev listening plugin which may want to
1778 * change the interface name provided by the kernel */
1779 if ((ctx.options & (DHCPCD_MASTER | DHCPCD_DEV)) ==
1780 (DHCPCD_MASTER | DHCPCD_DEV))
1781 dev_start(&ctx);
1783 ctx.ifaces = if_discover(&ctx, ctx.ifc, ctx.ifv);
1784 if (ctx.ifaces == NULL) {
1785 logger(&ctx, LOG_ERR, "if_discover: %m");
1786 goto exit_failure;
1788 for (i = 0; i < ctx.ifc; i++) {
1789 if (if_find(ctx.ifaces, ctx.ifv[i]) == NULL)
1790 logger(&ctx, LOG_ERR,
1791 "%s: interface not found or invalid",
1792 ctx.ifv[i]);
1794 if (TAILQ_FIRST(ctx.ifaces) == NULL) {
1795 if (ctx.ifc == 0)
1796 logger(&ctx, LOG_ERR, "no valid interfaces found");
1797 else
1798 goto exit_failure;
1799 if (!(ctx.options & DHCPCD_LINK)) {
1800 logger(&ctx, LOG_ERR,
1801 "aborting as link detection is disabled");
1802 goto exit_failure;
1806 TAILQ_FOREACH(ifp, ctx.ifaces, next) {
1807 dhcpcd_initstate1(ifp, argc, argv, 0);
1810 if (ctx.options & DHCPCD_BACKGROUND && dhcpcd_daemonise(&ctx))
1811 goto exit_success;
1813 opt = 0;
1814 TAILQ_FOREACH(ifp, ctx.ifaces, next) {
1815 run_preinit(ifp);
1816 if (ifp->carrier != LINK_DOWN)
1817 opt = 1;
1820 if (!(ctx.options & DHCPCD_BACKGROUND)) {
1821 if (ctx.options & DHCPCD_MASTER)
1822 t = ifo->timeout;
1823 else if ((ifp = TAILQ_FIRST(ctx.ifaces)))
1824 t = ifp->options->timeout;
1825 else
1826 t = 0;
1827 if (opt == 0 &&
1828 ctx.options & DHCPCD_LINK &&
1829 !(ctx.options & DHCPCD_WAITIP))
1831 logger(&ctx, LOG_WARNING,
1832 "no interfaces have a carrier");
1833 if (dhcpcd_daemonise(&ctx))
1834 goto exit_success;
1835 } else if (t > 0 &&
1836 /* Test mode removes the daemonise bit, so check for both */
1837 ctx.options & (DHCPCD_DAEMONISE | DHCPCD_TEST))
1839 eloop_timeout_add_sec(ctx.eloop, t,
1840 handle_exit_timeout, &ctx);
1843 free_options(ifo);
1844 ifo = NULL;
1846 if_sortinterfaces(&ctx);
1847 TAILQ_FOREACH(ifp, ctx.ifaces, next) {
1848 eloop_timeout_add_sec(ctx.eloop, 0,
1849 dhcpcd_prestartinterface, ifp);
1852 i = eloop_start(ctx.eloop, &ctx.sigset);
1853 if (i < 0) {
1854 syslog(LOG_ERR, "eloop_start: %m");
1855 goto exit_failure;
1857 goto exit1;
1859 exit_success:
1860 i = EXIT_SUCCESS;
1861 goto exit1;
1863 exit_failure:
1864 i = EXIT_FAILURE;
1866 exit1:
1867 /* Free memory and close fd's */
1868 if (ctx.ifaces) {
1869 while ((ifp = TAILQ_FIRST(ctx.ifaces))) {
1870 TAILQ_REMOVE(ctx.ifaces, ifp, next);
1871 if_free(ifp);
1873 free(ctx.ifaces);
1875 free(ctx.duid);
1876 if (ctx.link_fd != -1) {
1877 eloop_event_delete(ctx.eloop, ctx.link_fd);
1878 close(ctx.link_fd);
1880 if (ctx.pf_inet_fd != -1)
1881 close(ctx.pf_inet_fd);
1882 #if defined(INET6) && defined(BSD)
1883 if (ctx.pf_inet6_fd != -1)
1884 close(ctx.pf_inet6_fd);
1885 #endif
1886 #ifdef IFLR_ACTIVE
1887 if (ctx.pf_link_fd != -1)
1888 close(ctx.pf_link_fd);
1889 #endif
1892 free_options(ifo);
1893 free_globals(&ctx);
1894 ipv4_ctxfree(&ctx);
1895 ipv6_ctxfree(&ctx);
1896 dev_stop(&ctx);
1897 if (control_stop(&ctx) == -1)
1898 logger(&ctx, LOG_ERR, "control_stop: %m:");
1899 if (ctx.pid_fd != -1) {
1900 close(ctx.pid_fd);
1901 unlink(ctx.pidfile);
1903 eloop_free(ctx.eloop);
1905 if (ctx.options & DHCPCD_STARTED && !(ctx.options & DHCPCD_FORKED))
1906 logger(&ctx, LOG_INFO, PACKAGE " exited");
1907 logger_close(&ctx);
1908 free(ctx.logfile);
1909 return i;