Import dhcpcd-8.0.4 to vendor branch.
[dragonfly.git] / contrib / dhcpcd / src / dhcpcd.c
1 /* SPDX-License-Identifier: BSD-2-Clause */
2 /*
3  * dhcpcd - DHCP client daemon
4  * Copyright (c) 2006-2019 Roy Marples <roy@marples.name>
5  * All rights reserved
6
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28
29 const char dhcpcd_copyright[] = "Copyright (c) 2006-2019 Roy Marples";
30
31 #include <sys/file.h>
32 #include <sys/socket.h>
33 #include <sys/stat.h>
34 #include <sys/time.h>
35 #include <sys/types.h>
36 #include <sys/uio.h>
37
38 #include <ctype.h>
39 #include <errno.h>
40 #include <fcntl.h>
41 #include <getopt.h>
42 #include <limits.h>
43 #include <paths.h>
44 #include <signal.h>
45 #include <stdio.h>
46 #include <stdlib.h>
47 #include <string.h>
48 #include <unistd.h>
49 #include <time.h>
50
51 #include "config.h"
52 #include "arp.h"
53 #include "common.h"
54 #include "control.h"
55 #include "dev.h"
56 #include "dhcp-common.h"
57 #include "dhcpcd.h"
58 #include "dhcp.h"
59 #include "dhcp6.h"
60 #include "duid.h"
61 #include "eloop.h"
62 #include "if.h"
63 #include "if-options.h"
64 #include "ipv4.h"
65 #include "ipv4ll.h"
66 #include "ipv6.h"
67 #include "ipv6nd.h"
68 #include "logerr.h"
69 #include "script.h"
70
71 #ifdef HAVE_UTIL_H
72 #include <util.h>
73 #endif
74
75 #ifdef USE_SIGNALS
76 const int dhcpcd_signals[] = {
77         SIGTERM,
78         SIGINT,
79         SIGALRM,
80         SIGHUP,
81         SIGUSR1,
82         SIGUSR2,
83         SIGPIPE
84 };
85 const size_t dhcpcd_signals_len = __arraycount(dhcpcd_signals);
86 #endif
87
88 #define IF_UPANDRUNNING(a) \
89         (((a)->flags & (IFF_UP | IFF_RUNNING)) == (IFF_UP | IFF_RUNNING))
90
91 static void
92 usage(void)
93 {
94
95 printf("usage: "PACKAGE"\t[-146ABbDdEGgHJKLMNPpqTV]\n"
96         "\t\t[-C, --nohook hook] [-c, --script script]\n"
97         "\t\t[-e, --env value] [-F, --fqdn FQDN] [-f, --config file]\n"
98         "\t\t[-h, --hostname hostname] [-I, --clientid clientid]\n"
99         "\t\t[-i, --vendorclassid vendorclassid] [-j, --logfile logfile]\n" 
100         "\t\t[-l, --leasetime seconds] [-m, --metric metric]\n"
101         "\t\t[-O, --nooption option] [-o, --option option]\n"
102         "\t\t[-Q, --require option] [-r, --request address]\n"
103         "\t\t[-S, --static value]\n"
104         "\t\t[-s, --inform address[/cidr[/broadcast_address]]]\n [--inform6]"
105         "\t\t[-t, --timeout seconds] [-u, --userclass class]\n"
106         "\t\t[-v, --vendor code, value] [-W, --whitelist address[/cidr]] [-w]\n"
107         "\t\t[--waitip [4 | 6]] [-y, --reboot seconds]\n"
108         "\t\t[-X, --blacklist address[/cidr]] [-Z, --denyinterfaces pattern]\n"
109         "\t\t[-z, --allowinterfaces pattern] [--inactive] [interface] [...]\n"
110         "       "PACKAGE"\t-n, --rebind [interface]\n"
111         "       "PACKAGE"\t-k, --release [interface]\n"
112         "       "PACKAGE"\t-U, --dumplease interface\n"
113         "       "PACKAGE"\t--version\n"
114         "       "PACKAGE"\t-x, --exit [interface]\n");
115 }
116
117 static void
118 free_globals(struct dhcpcd_ctx *ctx)
119 {
120         struct dhcp_opt *opt;
121
122         if (ctx->ifac) {
123                 for (; ctx->ifac > 0; ctx->ifac--)
124                         free(ctx->ifav[ctx->ifac - 1]);
125                 free(ctx->ifav);
126                 ctx->ifav = NULL;
127         }
128         if (ctx->ifdc) {
129                 for (; ctx->ifdc > 0; ctx->ifdc--)
130                         free(ctx->ifdv[ctx->ifdc - 1]);
131                 free(ctx->ifdv);
132                 ctx->ifdv = NULL;
133         }
134         if (ctx->ifcc) {
135                 for (; ctx->ifcc > 0; ctx->ifcc--)
136                         free(ctx->ifcv[ctx->ifcc - 1]);
137                 free(ctx->ifcv);
138                 ctx->ifcv = NULL;
139         }
140
141 #ifdef INET
142         if (ctx->dhcp_opts) {
143                 for (opt = ctx->dhcp_opts;
144                     ctx->dhcp_opts_len > 0;
145                     opt++, ctx->dhcp_opts_len--)
146                         free_dhcp_opt_embenc(opt);
147                 free(ctx->dhcp_opts);
148                 ctx->dhcp_opts = NULL;
149         }
150 #endif
151 #ifdef INET6
152         if (ctx->nd_opts) {
153                 for (opt = ctx->nd_opts;
154                     ctx->nd_opts_len > 0;
155                     opt++, ctx->nd_opts_len--)
156                         free_dhcp_opt_embenc(opt);
157                 free(ctx->nd_opts);
158                 ctx->nd_opts = NULL;
159         }
160 #ifdef DHCP6
161         if (ctx->dhcp6_opts) {
162                 for (opt = ctx->dhcp6_opts;
163                     ctx->dhcp6_opts_len > 0;
164                     opt++, ctx->dhcp6_opts_len--)
165                         free_dhcp_opt_embenc(opt);
166                 free(ctx->dhcp6_opts);
167                 ctx->dhcp6_opts = NULL;
168         }
169 #endif
170 #endif
171         if (ctx->vivso) {
172                 for (opt = ctx->vivso;
173                     ctx->vivso_len > 0;
174                     opt++, ctx->vivso_len--)
175                         free_dhcp_opt_embenc(opt);
176                 free(ctx->vivso);
177                 ctx->vivso = NULL;
178         }
179 }
180
181 static void
182 handle_exit_timeout(void *arg)
183 {
184         struct dhcpcd_ctx *ctx;
185
186         ctx = arg;
187         logerrx("timed out");
188         if (!(ctx->options & DHCPCD_MASTER)) {
189                 eloop_exit(ctx->eloop, EXIT_FAILURE);
190                 return;
191         }
192         ctx->options |= DHCPCD_NOWAITIP;
193         dhcpcd_daemonise(ctx);
194 }
195
196 static const char *
197 dhcpcd_af(int af)
198 {
199
200         switch (af) {
201         case AF_UNSPEC:
202                 return "IP";
203         case AF_INET:
204                 return "IPv4";
205         case AF_INET6:
206                 return "IPv6";
207         default:
208                 return NULL;
209         }
210 }
211
212 int
213 dhcpcd_ifafwaiting(const struct interface *ifp)
214 {
215         unsigned long long opts;
216         bool foundany = false;
217
218         if (ifp->active != IF_ACTIVE_USER)
219                 return AF_MAX;
220
221 #define DHCPCD_WAITALL  (DHCPCD_WAITIP4 | DHCPCD_WAITIP6)
222         opts = ifp->options->options;
223 #ifdef INET
224         if (opts & DHCPCD_WAITIP4 ||
225             (opts & DHCPCD_WAITIP && !(opts & DHCPCD_WAITALL)))
226         {
227                 bool foundaddr = ipv4_hasaddr(ifp);
228
229                 if (opts & DHCPCD_WAITIP4 && !foundaddr)
230                         return AF_INET;
231                 if (foundaddr)
232                         foundany = true;
233         }
234 #endif
235 #ifdef INET6
236         if (opts & DHCPCD_WAITIP6 ||
237             (opts & DHCPCD_WAITIP && !(opts & DHCPCD_WAITALL)))
238         {
239                 bool foundaddr = ipv6_hasaddr(ifp);
240
241                 if (opts & DHCPCD_WAITIP6 && !foundaddr)
242                         return AF_INET;
243                 if (foundaddr)
244                         foundany = true;
245         }
246 #endif
247
248         if (opts & DHCPCD_WAITIP && !(opts & DHCPCD_WAITALL) && !foundany)
249                 return AF_UNSPEC;
250         return AF_MAX;
251 }
252
253 int
254 dhcpcd_afwaiting(const struct dhcpcd_ctx *ctx)
255 {
256         unsigned long long opts;
257         const struct interface *ifp;
258         int af;
259
260         if (!(ctx->options & DHCPCD_WAITOPTS))
261                 return AF_MAX;
262
263         opts = ctx->options;
264         TAILQ_FOREACH(ifp, ctx->ifaces, next) {
265 #ifdef INET
266                 if (opts & (DHCPCD_WAITIP | DHCPCD_WAITIP4) &&
267                     ipv4_hasaddr(ifp))
268                         opts &= ~(DHCPCD_WAITIP | DHCPCD_WAITIP4);
269 #endif
270 #ifdef INET6
271                 if (opts & (DHCPCD_WAITIP | DHCPCD_WAITIP6) &&
272                     ipv6_hasaddr(ifp))
273                         opts &= ~(DHCPCD_WAITIP | DHCPCD_WAITIP6);
274 #endif
275                 if (!(opts & DHCPCD_WAITOPTS))
276                         break;
277         }
278         if (opts & DHCPCD_WAITIP)
279                 af = AF_UNSPEC;
280         else if (opts & DHCPCD_WAITIP4)
281                 af = AF_INET;
282         else if (opts & DHCPCD_WAITIP6)
283                 af = AF_INET6;
284         else
285                 return AF_MAX;
286         return af;
287 }
288
289 static int
290 dhcpcd_ipwaited(struct dhcpcd_ctx *ctx)
291 {
292         struct interface *ifp;
293         int af;
294
295         TAILQ_FOREACH(ifp, ctx->ifaces, next) {
296                 if ((af = dhcpcd_ifafwaiting(ifp)) != AF_MAX) {
297                         logdebugx("%s: waiting for an %s address",
298                             ifp->name, dhcpcd_af(af));
299                         return 0;
300                 }
301         }
302
303         if ((af = dhcpcd_afwaiting(ctx)) != AF_MAX) {
304                 logdebugx("waiting for an %s address",
305                     dhcpcd_af(af));
306                 return 0;
307         }
308
309         return 1;
310 }
311
312 /* Returns the pid of the child, otherwise 0. */
313 pid_t
314 dhcpcd_daemonise(struct dhcpcd_ctx *ctx)
315 {
316 #ifdef THERE_IS_NO_FORK
317         eloop_timeout_delete(ctx->eloop, handle_exit_timeout, ctx);
318         errno = ENOSYS;
319         return 0;
320 #else
321         pid_t pid, lpid;
322         char buf = '\0';
323         int sidpipe[2], fd;
324
325         if (ctx->options & DHCPCD_DAEMONISE &&
326             !(ctx->options & (DHCPCD_DAEMONISED | DHCPCD_NOWAITIP)))
327         {
328                 if (!dhcpcd_ipwaited(ctx))
329                         return 0;
330         }
331
332         if (ctx->options & DHCPCD_ONESHOT) {
333                 loginfox("exiting due to oneshot");
334                 eloop_exit(ctx->eloop, EXIT_SUCCESS);
335                 return 0;
336         }
337
338         eloop_timeout_delete(ctx->eloop, handle_exit_timeout, ctx);
339         if (ctx->options & DHCPCD_DAEMONISED ||
340             !(ctx->options & DHCPCD_DAEMONISE))
341                 return 0;
342         logdebugx("forking to background");
343
344         /* Setup a signal pipe so parent knows when to exit. */
345         if (pipe(sidpipe) == -1) {
346                 logerr("%s: pipe", __func__);
347                 return 0;
348         }
349
350         switch (pid = fork()) {
351         case -1:
352                 logerr("%s: fork", __func__);
353                 return 0;
354         case 0:
355                 if ((lpid = pidfile_lock(ctx->pidfile)) != 0)
356                         logerr("%s: pidfile_lock %d", __func__, lpid);
357                 setsid();
358                 /* Notify parent it's safe to exit as we've detached. */
359                 close(sidpipe[0]);
360                 if (write(sidpipe[1], &buf, 1) == -1)
361                         logerr("%s: write", __func__);
362                 close(sidpipe[1]);
363                 /* Some polling methods don't survive after forking,
364                  * so ensure we can requeue all our events. */
365                 if (eloop_requeue(ctx->eloop) == -1) {
366                         logerr("%s: eloop_requeue", __func__);
367                         eloop_exit(ctx->eloop, EXIT_FAILURE);
368                 }
369                 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
370                         dup2(fd, STDIN_FILENO);
371                         dup2(fd, STDOUT_FILENO);
372                         dup2(fd, STDERR_FILENO);
373                         close(fd);
374                 }
375                 ctx->options |= DHCPCD_DAEMONISED;
376                 return 0;
377         default:
378                 /* Wait for child to detach */
379                 close(sidpipe[1]);
380                 if (read(sidpipe[0], &buf, 1) == -1)
381                         logerr("%s: read", __func__);
382                 close(sidpipe[0]);
383                 loginfox("forked to background, child pid %d", pid);
384                 ctx->options |= DHCPCD_FORKED;
385                 eloop_exit(ctx->eloop, EXIT_SUCCESS);
386                 return pid;
387         }
388 #endif
389 }
390
391 static void
392 dhcpcd_drop(struct interface *ifp, int stop)
393 {
394
395 #ifdef DHCP6
396         dhcp6_drop(ifp, stop ? NULL : "EXPIRE6");
397 #endif
398 #ifdef INET6
399         ipv6nd_drop(ifp);
400         ipv6_drop(ifp);
401 #endif
402 #ifdef IPV4LL
403         ipv4ll_drop(ifp);
404 #endif
405 #ifdef INET
406         dhcp_drop(ifp, stop ? "STOP" : "EXPIRE");
407 #endif
408 #ifdef ARP
409         arp_drop(ifp);
410 #endif
411 #if !defined(DHCP6) && !defined(DHCP)
412         UNUSED(stop);
413 #endif
414 }
415
416 static void
417 stop_interface(struct interface *ifp)
418 {
419         struct dhcpcd_ctx *ctx;
420
421         ctx = ifp->ctx;
422         loginfox("%s: removing interface", ifp->name);
423         ifp->options->options |= DHCPCD_STOPPING;
424
425         dhcpcd_drop(ifp, 1);
426         if (ifp->options->options & DHCPCD_DEPARTED)
427                 script_runreason(ifp, "DEPARTED");
428         else
429                 script_runreason(ifp, "STOPPED");
430
431         /* Delete all timeouts for the interfaces */
432         eloop_q_timeout_delete(ctx->eloop, 0, NULL, ifp);
433
434         /* De-activate the interface */
435         ifp->active = IF_INACTIVE;
436         ifp->options->options &= ~DHCPCD_STOPPING;
437         /* Set the link state to unknown as we're no longer tracking it. */
438         ifp->carrier = LINK_UNKNOWN;
439
440         if (!(ctx->options & (DHCPCD_MASTER | DHCPCD_TEST)))
441                 eloop_exit(ctx->eloop, EXIT_FAILURE);
442 }
443
444 static void
445 configure_interface1(struct interface *ifp)
446 {
447         struct if_options *ifo = ifp->options;
448
449         /* Do any platform specific configuration */
450         if_conf(ifp);
451
452         /* If we want to release a lease, we can't really persist the
453          * address either. */
454         if (ifo->options & DHCPCD_RELEASE)
455                 ifo->options &= ~DHCPCD_PERSISTENT;
456
457         if (ifp->flags & (IFF_POINTOPOINT | IFF_LOOPBACK)) {
458                 ifo->options &= ~DHCPCD_ARP;
459                 if (!(ifp->flags & IFF_MULTICAST))
460                         ifo->options &= ~DHCPCD_IPV6RS;
461                 if (!(ifo->options & (DHCPCD_INFORM | DHCPCD_WANTDHCP)))
462                         ifo->options |= DHCPCD_STATIC;
463         }
464         if (!(ifo->options & DHCPCD_ARP) ||
465             ifo->options & (DHCPCD_INFORM | DHCPCD_STATIC))
466                 ifo->options &= ~DHCPCD_IPV4LL;
467
468         if (ifo->metric != -1)
469                 ifp->metric = (unsigned int)ifo->metric;
470
471         if (!(ifo->options & DHCPCD_IPV4))
472                 ifo->options &= ~(DHCPCD_DHCP | DHCPCD_IPV4LL | DHCPCD_WAITIP4);
473
474 #ifdef INET6
475         if (!(ifo->options & DHCPCD_IPV6))
476                 ifo->options &=
477                     ~(DHCPCD_IPV6RS | DHCPCD_DHCP6 | DHCPCD_WAITIP6);
478
479         if (!(ifo->options & DHCPCD_IPV6RS))
480                 ifo->options &=
481                     ~(DHCPCD_IPV6RA_AUTOCONF | DHCPCD_IPV6RA_REQRDNSS);
482
483         /* We want to setup INET6 on the interface as soon as possible. */
484         if (ifp->active == IF_ACTIVE_USER &&
485             ifo->options & DHCPCD_IPV6 &&
486             !(ifp->ctx->options & (DHCPCD_DUMPLEASE | DHCPCD_TEST)))
487         {
488                 /* If not doing any DHCP, disable the RDNSS requirement. */
489                 if (!(ifo->options & (DHCPCD_DHCP | DHCPCD_DHCP6)))
490                         ifo->options &= ~DHCPCD_IPV6RA_REQRDNSS;
491                 if_setup_inet6(ifp);
492         }
493 #endif
494
495         if (!(ifo->options & DHCPCD_IAID)) {
496                 /*
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.
500                  *
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.
508                  *
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.
516                  *
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.
521                  * Saying that, if a VLANID has been specified then we
522                  * can use that. It's possible that different interfaces
523                  * can have the same VLANID, but this is no worse than
524                  * generating the IAID from the duplicate MAC address.
525                  *
526                  * dhclient uses the last 4 bytes of the MAC address.
527                  * dibbler uses an increamenting counter.
528                  * wide-dhcpv6 uses 0 or a configured value.
529                  * odhcp6c uses 1.
530                  * Windows 7 uses the first 3 bytes of the MAC address
531                  * and an unknown byte.
532                  * dhcpcd-6.1.0 and earlier used the interface name,
533                  * falling back to interface index if name > 4.
534                  */
535                 if (ifp->vlanid != 0) {
536                         uint32_t vlanid;
537
538                         /* Maximal VLANID is 4095, so prefix with 0xff
539                          * so we don't conflict with an interface index. */
540                         vlanid = htonl(ifp->vlanid | 0xff000000);
541                         memcpy(ifo->iaid, &vlanid, sizeof(vlanid));
542                 } else if (ifp->hwlen >= sizeof(ifo->iaid)) {
543                         memcpy(ifo->iaid,
544                             ifp->hwaddr + ifp->hwlen - sizeof(ifo->iaid),
545                             sizeof(ifo->iaid));
546                 } else {
547                         uint32_t len;
548
549                         len = (uint32_t)strlen(ifp->name);
550                         if (len <= sizeof(ifo->iaid)) {
551                                 memcpy(ifo->iaid, ifp->name, len);
552                                 if (len < sizeof(ifo->iaid))
553                                         memset(ifo->iaid + len, 0,
554                                             sizeof(ifo->iaid) - len);
555                         } else {
556                                 /* IAID is the same size as a uint32_t */
557                                 len = htonl(ifp->index);
558                                 memcpy(ifo->iaid, &len, sizeof(ifo->iaid));
559                         }
560                 }
561                 ifo->options |= DHCPCD_IAID;
562         }
563
564 #ifdef DHCP6
565         if (ifo->ia_len == 0 && ifo->options & DHCPCD_IPV6 &&
566             ifp->name[0] != '\0')
567         {
568                 ifo->ia = malloc(sizeof(*ifo->ia));
569                 if (ifo->ia == NULL)
570                         logerr(__func__);
571                 else {
572                         ifo->ia_len = 1;
573                         ifo->ia->ia_type = D6_OPTION_IA_NA;
574                         memcpy(ifo->ia->iaid, ifo->iaid, sizeof(ifo->iaid));
575                         memset(&ifo->ia->addr, 0, sizeof(ifo->ia->addr));
576 #ifndef SMALL
577                         ifo->ia->sla = NULL;
578                         ifo->ia->sla_len = 0;
579 #endif
580                 }
581         } else {
582                 size_t i;
583
584                 for (i = 0; i < ifo->ia_len; i++) {
585                         if (!ifo->ia[i].iaid_set) {
586                                 memcpy(&ifo->ia[i].iaid, ifo->iaid,
587                                     sizeof(ifo->ia[i].iaid));
588                                 ifo->ia[i].iaid_set = 1;
589                         }
590                 }
591         }
592 #endif
593 }
594
595 int
596 dhcpcd_selectprofile(struct interface *ifp, const char *profile)
597 {
598         struct if_options *ifo;
599         char pssid[PROFILE_LEN];
600
601         if (ifp->ssid_len) {
602                 ssize_t r;
603
604                 r = print_string(pssid, sizeof(pssid), OT_ESCSTRING,
605                     ifp->ssid, ifp->ssid_len);
606                 if (r == -1) {
607                         logerr(__func__);
608                         pssid[0] = '\0';
609                 }
610         } else
611                 pssid[0] = '\0';
612         ifo = read_config(ifp->ctx, ifp->name, pssid, profile);
613         if (ifo == NULL) {
614                 logdebugx("%s: no profile %s", ifp->name, profile);
615                 return -1;
616         }
617         if (profile != NULL) {
618                 strlcpy(ifp->profile, profile, sizeof(ifp->profile));
619                 loginfox("%s: selected profile %s", ifp->name, profile);
620         } else
621                 *ifp->profile = '\0';
622
623         free_options(ifp->ctx, ifp->options);
624         ifp->options = ifo;
625         if (profile) {
626                 add_options(ifp->ctx, ifp->name, ifp->options,
627                     ifp->ctx->argc, ifp->ctx->argv);
628                 configure_interface1(ifp);
629         }
630         return 1;
631 }
632
633 static void
634 configure_interface(struct interface *ifp, int argc, char **argv,
635     unsigned long long options)
636 {
637         time_t old;
638
639         old = ifp->options ? ifp->options->mtime : 0;
640         dhcpcd_selectprofile(ifp, NULL);
641         if (ifp->options == NULL) {
642                 /* dhcpcd cannot continue with this interface. */
643                 ifp->active = IF_INACTIVE;
644                 return;
645         }
646         add_options(ifp->ctx, ifp->name, ifp->options, argc, argv);
647         ifp->options->options |= options;
648         configure_interface1(ifp);
649
650         /* If the mtime has changed drop any old lease */
651         if (old != 0 && ifp->options->mtime != old) {
652                 logwarnx("%s: confile file changed, expiring leases",
653                     ifp->name);
654                 dhcpcd_drop(ifp, 0);
655         }
656 }
657
658 static void
659 dhcpcd_initstate2(struct interface *ifp, unsigned long long options)
660 {
661         struct if_options *ifo;
662
663         if (options) {
664                 if ((ifo = default_config(ifp->ctx)) == NULL) {
665                         logerr(__func__);
666                         return;
667                 }
668                 ifo->options |= options;
669                 free(ifp->options);
670                 ifp->options = ifo;
671         } else
672                 ifo = ifp->options;
673
674 #ifdef INET6
675         if (ifo->options & DHCPCD_IPV6 && ipv6_init(ifp->ctx) == -1) {
676                 logerr(__func__);
677                 ifo->options &= ~DHCPCD_IPV6;
678         }
679 #endif
680 }
681
682 static void
683 dhcpcd_initstate1(struct interface *ifp, int argc, char **argv,
684     unsigned long long options)
685 {
686
687         configure_interface(ifp, argc, argv, options);
688         if (ifp->active)
689                 dhcpcd_initstate2(ifp, 0);
690 }
691
692 static void
693 dhcpcd_initstate(struct interface *ifp, unsigned long long options)
694 {
695
696         dhcpcd_initstate1(ifp, ifp->ctx->argc, ifp->ctx->argv, options);
697 }
698
699 void
700 dhcpcd_handlecarrier(struct dhcpcd_ctx *ctx, int carrier, unsigned int flags,
701     const char *ifname)
702 {
703         struct interface *ifp;
704
705         ifp = if_find(ctx->ifaces, ifname);
706         if (ifp == NULL ||
707             ifp->options == NULL || !(ifp->options->options & DHCPCD_LINK) ||
708             !ifp->active)
709                 return;
710
711         if (carrier == LINK_UNKNOWN) {
712                 if (ifp->wireless) {
713                         carrier = LINK_DOWN;
714                         ifp->flags = flags;
715                 } else
716                         carrier = if_carrier(ifp);
717         } else
718                 ifp->flags = flags;
719         if (carrier == LINK_UNKNOWN)
720                 carrier = IF_UPANDRUNNING(ifp) ? LINK_UP : LINK_DOWN;
721
722         if (carrier == LINK_DOWN || (ifp->flags & IFF_UP) == 0) {
723                 if (ifp->carrier != LINK_DOWN) {
724                         if (ifp->carrier == LINK_UP)
725                                 loginfox("%s: carrier lost", ifp->name);
726 #ifdef NOCARRIER_PRESERVE_IP
727                         if (ifp->flags & IFF_UP)
728                                 ifp->carrier = LINK_DOWN_IFFUP;
729                         else
730 #endif
731                                 ifp->carrier = LINK_DOWN;
732                         script_runreason(ifp, "NOCARRIER");
733 #ifdef NOCARRIER_PRESERVE_IP
734                         if (ifp->flags & IFF_UP) {
735 #ifdef ARP
736                                 arp_drop(ifp);
737 #endif
738 #ifdef INET
739                                 dhcp_abort(ifp);
740 #endif
741 #ifdef DHCP6
742                                 dhcp6_abort(ifp);
743 #endif
744                         } else
745 #endif
746                                 dhcpcd_drop(ifp, 0);
747                 }
748         } else if (carrier == LINK_UP && ifp->flags & IFF_UP) {
749                 if (ifp->carrier != LINK_UP) {
750                         loginfox("%s: carrier acquired", ifp->name);
751                         ifp->carrier = LINK_UP;
752 #if !defined(__linux__) && !defined(__NetBSD__)
753                         /* BSD does not emit RTM_NEWADDR or RTM_CHGADDR when the
754                          * hardware address changes so we have to go
755                          * through the disovery process to work it out. */
756                         dhcpcd_handleinterface(ctx, 0, ifp->name);
757 #endif
758                         if (ifp->wireless) {
759                                 uint8_t ossid[IF_SSIDLEN];
760                                 size_t olen;
761
762                                 olen = ifp->ssid_len;
763                                 memcpy(ossid, ifp->ssid, ifp->ssid_len);
764                                 if_getssid(ifp);
765
766                                 /* If we changed SSID network, drop leases */
767                                 if (ifp->ssid_len != olen ||
768                                     memcmp(ifp->ssid, ossid, ifp->ssid_len))
769                                 {
770 #ifdef NOCARRIER_PRESERVE_IP
771                                         dhcpcd_drop(ifp, 0);
772 #endif
773 #ifdef IPV4LL
774                                         ipv4ll_reset(ifp);
775 #endif
776                                 }
777                         }
778                         dhcpcd_initstate(ifp, 0);
779                         script_runreason(ifp, "CARRIER");
780 #ifdef INET6
781 #ifdef NOCARRIER_PRESERVE_IP
782                         /* Set any IPv6 Routers we remembered to expire
783                          * faster than they would normally as we
784                          * maybe on a new network. */
785                         ipv6nd_startexpire(ifp);
786 #endif
787                         /* RFC4941 Section 3.5 */
788                         ipv6_gentempifid(ifp);
789 #endif
790                         dhcpcd_startinterface(ifp);
791                 }
792         }
793 }
794
795 static void
796 warn_iaid_conflict(struct interface *ifp, uint16_t ia_type, uint8_t *iaid)
797 {
798         struct interface *ifn;
799 #ifdef INET6
800         size_t i;
801         struct if_ia *ia;
802 #endif
803
804         TAILQ_FOREACH(ifn, ifp->ctx->ifaces, next) {
805                 if (ifn == ifp || !ifn->active)
806                         continue;
807                 if (ia_type == 0 &&
808                     memcmp(ifn->options->iaid, iaid,
809                     sizeof(ifn->options->iaid)) == 0)
810                         break;
811 #ifdef INET6
812                 for (i = 0; i < ifn->options->ia_len; i++) {
813                         ia = &ifn->options->ia[i];
814                         if (ia->ia_type == ia_type &&
815                             memcmp(ia->iaid, iaid, sizeof(ia->iaid)) == 0)
816                                 break;
817                 }
818 #endif
819         }
820
821         /* This is only a problem if the interfaces are on the same network. */
822         if (ifn)
823                 logerrx("%s: IAID conflicts with one assigned to %s",
824                     ifp->name, ifn->name);
825 }
826
827 void
828 dhcpcd_startinterface(void *arg)
829 {
830         struct interface *ifp = arg;
831         struct if_options *ifo = ifp->options;
832         char buf[DUID_LEN * 3];
833         int carrier;
834
835         if (ifo->options & DHCPCD_LINK) {
836                 switch (ifp->carrier) {
837                 case LINK_UP:
838                         break;
839                 case LINK_DOWN:
840                         loginfox("%s: waiting for carrier", ifp->name);
841                         return;
842                 case LINK_UNKNOWN:
843                         /* No media state available.
844                          * Loop until both IFF_UP and IFF_RUNNING are set */
845                         carrier = if_carrier(ifp);
846                         if (carrier == LINK_UNKNOWN) {
847                                 if (IF_UPANDRUNNING(ifp))
848                                         carrier = LINK_UP;
849                                 else {
850                                         struct timespec tv;
851
852                                         tv.tv_sec = 0;
853                                         tv.tv_nsec = IF_POLL_UP * NSEC_PER_MSEC;
854                                         eloop_timeout_add_tv(ifp->ctx->eloop,
855                                             &tv, dhcpcd_startinterface, ifp);
856                                         return;
857                                 }
858                         }
859                         dhcpcd_handlecarrier(ifp->ctx, carrier,
860                             ifp->flags, ifp->name);
861                         return;
862                 }
863         }
864
865         if (ifo->options & (DHCPCD_DUID | DHCPCD_IPV6)) {
866                 /* Report client DUID */
867                 if (ifp->ctx->duid == NULL) {
868                         if (duid_init(ifp) == 0)
869                                 return;
870                         loginfox("DUID %s",
871                             hwaddr_ntoa(ifp->ctx->duid,
872                             ifp->ctx->duid_len,
873                             buf, sizeof(buf)));
874                 }
875         }
876
877         if (ifo->options & (DHCPCD_DUID | DHCPCD_IPV6)) {
878 #ifdef INET6
879                 size_t i;
880                 struct if_ia *ia;
881 #endif
882
883                 /* Report IAIDs */
884                 loginfox("%s: IAID %s", ifp->name,
885                     hwaddr_ntoa(ifo->iaid, sizeof(ifo->iaid),
886                     buf, sizeof(buf)));
887                 warn_iaid_conflict(ifp, 0, ifo->iaid);
888 #ifdef INET6
889                 for (i = 0; i < ifo->ia_len; i++) {
890                         ia = &ifo->ia[i];
891                         if (memcmp(ifo->iaid, ia->iaid, sizeof(ifo->iaid))) {
892                                 loginfox("%s: IA type %u IAID %s",
893                                     ifp->name, ia->ia_type,
894                                     hwaddr_ntoa(ia->iaid, sizeof(ia->iaid),
895                                     buf, sizeof(buf)));
896                                 warn_iaid_conflict(ifp, ia->ia_type, ia->iaid);
897                         }
898                 }
899 #endif
900         }
901
902 #ifdef INET6
903         if (ifo->options & DHCPCD_IPV6 && ipv6_start(ifp) == -1) {
904                 logerr("%s: ipv6_start", ifp->name);
905                 ifo->options &= ~DHCPCD_IPV6;
906         }
907
908         if (ifo->options & DHCPCD_IPV6) {
909                 if (ifp->active == IF_ACTIVE_USER) {
910                         ipv6_startstatic(ifp);
911
912                         if (ifo->options & DHCPCD_IPV6RS)
913                                 ipv6nd_startrs(ifp);
914                 }
915
916 #ifdef DHCP6
917                 if (ifo->options & DHCPCD_DHCP6) {
918                         dhcp6_find_delegates(ifp);
919
920                         if (ifp->active == IF_ACTIVE_USER) {
921                                 enum DH6S d6_state;
922
923                                 if (ifo->options & DHCPCD_IA_FORCED)
924                                         d6_state = DH6S_INIT;
925                                 else if (ifo->options & DHCPCD_INFORM6)
926                                         d6_state = DH6S_INFORM;
927                                 else
928                                         d6_state = DH6S_CONFIRM;
929                                 if (dhcp6_start(ifp, d6_state) == -1)
930                                         logerr("%s: dhcp6_start", ifp->name);
931                         }
932                 }
933 #endif
934         }
935 #endif
936
937 #ifdef INET
938         if (ifo->options & DHCPCD_IPV4 && ifp->active == IF_ACTIVE_USER) {
939                 /* Ensure we have an IPv4 state before starting DHCP */
940                 if (ipv4_getstate(ifp) != NULL)
941                         dhcp_start(ifp);
942         }
943 #endif
944 }
945
946 static void
947 dhcpcd_prestartinterface(void *arg)
948 {
949         struct interface *ifp = arg;
950
951         if ((!(ifp->ctx->options & DHCPCD_MASTER) ||
952             ifp->options->options & DHCPCD_IF_UP) &&
953             if_up(ifp) == -1)
954                 logerr("%s: %s", __func__, ifp->name);
955
956         dhcpcd_startinterface(ifp);
957 }
958
959 static void
960 run_preinit(struct interface *ifp)
961 {
962
963         if (ifp->ctx->options & DHCPCD_TEST)
964                 return;
965
966         script_runreason(ifp, "PREINIT");
967
968         if (ifp->options->options & DHCPCD_LINK && ifp->carrier != LINK_UNKNOWN)
969                 script_runreason(ifp,
970                     ifp->carrier == LINK_UP ? "CARRIER" : "NOCARRIER");
971 }
972
973 void
974 dhcpcd_activateinterface(struct interface *ifp, unsigned long long options)
975 {
976
977         if (!ifp->active) {
978                 ifp->active = IF_ACTIVE;
979                 dhcpcd_initstate2(ifp, options);
980                 /* It's possible we might not have been able to load
981                  * a config. */
982                 if (ifp->active) {
983                         configure_interface1(ifp);
984                         run_preinit(ifp);
985                         dhcpcd_prestartinterface(ifp);
986                 }
987         }
988 }
989
990 int
991 dhcpcd_handleinterface(void *arg, int action, const char *ifname)
992 {
993         struct dhcpcd_ctx *ctx;
994         struct ifaddrs *ifaddrs;
995         struct if_head *ifs;
996         struct interface *ifp, *iff;
997         const char * const argv[] = { ifname };
998         int e;
999
1000         ctx = arg;
1001         if (action == -1) {
1002                 ifp = if_find(ctx->ifaces, ifname);
1003                 if (ifp == NULL) {
1004                         errno = ESRCH;
1005                         return -1;
1006                 }
1007                 if (ifp->active) {
1008                         logdebugx("%s: interface departed", ifp->name);
1009                         ifp->options->options |= DHCPCD_DEPARTED;
1010                         stop_interface(ifp);
1011                 }
1012                 TAILQ_REMOVE(ctx->ifaces, ifp, next);
1013                 if_free(ifp);
1014                 return 0;
1015         }
1016
1017         ifs = if_discover(ctx, &ifaddrs, -1, UNCONST(argv));
1018         if (ifs == NULL) {
1019                 logerr(__func__);
1020                 return -1;
1021         }
1022
1023         ifp = if_find(ifs, ifname);
1024         if (ifp == NULL) {
1025                 /* This can happen if an interface is quickly added
1026                  * and then removed. */
1027                 errno = ENOENT;
1028                 e = -1;
1029                 goto out;
1030         }
1031         e = 1;
1032
1033         /* Check if we already have the interface */
1034         iff = if_find(ctx->ifaces, ifp->name);
1035
1036         if (iff != NULL) {
1037                 if (iff->active)
1038                         logdebugx("%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                 TAILQ_REMOVE(ifs, ifp, next);
1046                 TAILQ_INSERT_TAIL(ctx->ifaces, ifp, next);
1047                 if (ifp->active) {
1048                         logdebugx("%s: interface added", ifp->name);
1049                         dhcpcd_initstate(ifp, 0);
1050                         run_preinit(ifp);
1051                 }
1052                 iff = ifp;
1053         }
1054
1055         if (action > 0) {
1056                 if_learnaddrs(ctx, ifs, &ifaddrs);
1057                 if (iff->active)
1058                         dhcpcd_prestartinterface(iff);
1059         }
1060
1061 out:
1062         /* Free our discovered list */
1063         while ((ifp = TAILQ_FIRST(ifs))) {
1064                 TAILQ_REMOVE(ifs, ifp, next);
1065                 if_free(ifp);
1066         }
1067         free(ifs);
1068
1069         return e;
1070 }
1071
1072 static void
1073 dhcpcd_handlelink(void *arg)
1074 {
1075         struct dhcpcd_ctx *ctx = arg;
1076
1077         if (if_handlelink(ctx) == -1) {
1078                 if (errno == ENOBUFS || errno == ENOMEM) {
1079                         dhcpcd_linkoverflow(ctx);
1080                         return;
1081                 }
1082                 if (errno != ENOTSUP)
1083                         logerr(__func__);
1084         }
1085 }
1086
1087 static void
1088 dhcpcd_checkcarrier(void *arg)
1089 {
1090         struct interface *ifp = arg;
1091
1092         dhcpcd_handlecarrier(ifp->ctx, LINK_UNKNOWN, ifp->flags, ifp->name);
1093 }
1094
1095 #ifndef SMALL
1096 static void
1097 dhcpcd_setlinkrcvbuf(struct dhcpcd_ctx *ctx)
1098 {
1099         socklen_t socklen;
1100
1101         if (ctx->link_rcvbuf == 0)
1102                 return;
1103
1104         socklen = sizeof(ctx->link_rcvbuf);
1105         if (setsockopt(ctx->link_fd, SOL_SOCKET,
1106             SO_RCVBUF, &ctx->link_rcvbuf, socklen) == -1)
1107                 logerr(__func__);
1108 }
1109 #endif
1110
1111 void
1112 dhcpcd_linkoverflow(struct dhcpcd_ctx *ctx)
1113 {
1114         struct if_head *ifaces;
1115         struct ifaddrs *ifaddrs;
1116         struct interface *ifp, *ifn, *ifp1;
1117
1118         logerrx("route socket overflowed - learning interface state");
1119
1120         /* Close the existing socket and open a new one.
1121          * This is easier than draining the kernel buffer of an
1122          * in-determinate size. */
1123         eloop_event_delete(ctx->eloop, ctx->link_fd);
1124         close(ctx->link_fd);
1125         if_closesockets_os(ctx);
1126         if (if_opensockets_os(ctx) == -1) {
1127                 logerr("%s: if_opensockets", __func__);
1128                 eloop_exit(ctx->eloop, EXIT_FAILURE);
1129                 return;
1130         }
1131 #ifndef SMALL
1132         dhcpcd_setlinkrcvbuf(ctx);
1133 #endif
1134         eloop_event_add(ctx->eloop, ctx->link_fd, dhcpcd_handlelink, ctx);
1135
1136         /* Work out the current interfaces. */
1137         ifaces = if_discover(ctx, &ifaddrs, ctx->ifc, ctx->ifv);
1138         if (ifaces == NULL) {
1139                 logerr(__func__);
1140                 return;
1141         }
1142
1143         /* Punt departed interfaces */
1144         TAILQ_FOREACH_SAFE(ifp, ctx->ifaces, next, ifn) {
1145                 if (if_find(ifaces, ifp->name) != NULL)
1146                         continue;
1147                 dhcpcd_handleinterface(ctx, -1, ifp->name);
1148         }
1149
1150         /* Add new interfaces */
1151         while ((ifp = TAILQ_FIRST(ifaces)) != NULL ) {
1152                 TAILQ_REMOVE(ifaces, ifp, next);
1153                 ifp1 = if_find(ctx->ifaces, ifp->name);
1154                 if (ifp1 != NULL) {
1155                         /* If the interface already exists,
1156                          * check carrier state. */
1157                         eloop_timeout_add_sec(ctx->eloop, 0,
1158                             dhcpcd_checkcarrier, ifp1);
1159                         if_free(ifp);
1160                         continue;
1161                 }
1162                 TAILQ_INSERT_TAIL(ctx->ifaces, ifp, next);
1163                 if (ifp->active)
1164                         eloop_timeout_add_sec(ctx->eloop, 0,
1165                             dhcpcd_prestartinterface, ifp);
1166         }
1167         free(ifaces);
1168
1169         /* Update address state. */
1170         if_markaddrsstale(ctx->ifaces);
1171         if_learnaddrs(ctx, ctx->ifaces, &ifaddrs);
1172         if_deletestaleaddrs(ctx->ifaces);
1173 }
1174
1175 void
1176 dhcpcd_handlehwaddr(struct dhcpcd_ctx *ctx, const char *ifname,
1177     const void *hwaddr, uint8_t hwlen)
1178 {
1179         struct interface *ifp;
1180         char buf[sizeof(ifp->hwaddr) * 3];
1181
1182         ifp = if_find(ctx->ifaces, ifname);
1183         if (ifp == NULL)
1184                 return;
1185
1186         if (!if_valid_hwaddr(hwaddr, hwlen))
1187                 hwlen = 0;
1188
1189         if (hwlen > sizeof(ifp->hwaddr)) {
1190                 errno = ENOBUFS;
1191                 logerr("%s: %s", __func__, ifp->name);
1192                 return;
1193         }
1194
1195         if (ifp->hwlen == hwlen && memcmp(ifp->hwaddr, hwaddr, hwlen) == 0)
1196                 return;
1197
1198         loginfox("%s: new hardware address: %s", ifp->name,
1199             hwaddr_ntoa(hwaddr, hwlen, buf, sizeof(buf)));
1200         ifp->hwlen = hwlen;
1201         memcpy(ifp->hwaddr, hwaddr, hwlen);
1202 }
1203
1204 static void
1205 if_reboot(struct interface *ifp, int argc, char **argv)
1206 {
1207 #ifdef INET
1208         unsigned long long oldopts;
1209
1210         oldopts = ifp->options->options;
1211 #endif
1212         script_runreason(ifp, "RECONFIGURE");
1213         dhcpcd_initstate1(ifp, argc, argv, 0);
1214 #ifdef INET
1215         dhcp_reboot_newopts(ifp, oldopts);
1216 #endif
1217 #ifdef DHCP6
1218         dhcp6_reboot(ifp);
1219 #endif
1220         dhcpcd_prestartinterface(ifp);
1221 }
1222
1223 static void
1224 reload_config(struct dhcpcd_ctx *ctx)
1225 {
1226         struct if_options *ifo;
1227
1228         free_globals(ctx);
1229         if ((ifo = read_config(ctx, NULL, NULL, NULL)) == NULL)
1230                 return;
1231         add_options(ctx, NULL, ifo, ctx->argc, ctx->argv);
1232         /* We need to preserve these two options. */
1233         if (ctx->options & DHCPCD_MASTER)
1234                 ifo->options |= DHCPCD_MASTER;
1235         if (ctx->options & DHCPCD_DAEMONISED)
1236                 ifo->options |= DHCPCD_DAEMONISED;
1237         ctx->options = ifo->options;
1238         free_options(ctx, ifo);
1239 }
1240
1241 static void
1242 reconf_reboot(struct dhcpcd_ctx *ctx, int action, int argc, char **argv, int oi)
1243 {
1244         int i;
1245         struct interface *ifp;
1246
1247         TAILQ_FOREACH(ifp, ctx->ifaces, next) {
1248                 for (i = oi; i < argc; i++) {
1249                         if (strcmp(ifp->name, argv[i]) == 0)
1250                                 break;
1251                 }
1252                 if (oi != argc && i == argc)
1253                         continue;
1254                 if (ifp->active == IF_ACTIVE_USER) {
1255                         if (action)
1256                                 if_reboot(ifp, argc, argv);
1257 #ifdef INET
1258                         else
1259                                 ipv4_applyaddr(ifp);
1260 #endif
1261                 } else if (i != argc) {
1262                         ifp->active = IF_ACTIVE_USER;
1263                         dhcpcd_initstate1(ifp, argc, argv, 0);
1264                         run_preinit(ifp);
1265                         dhcpcd_prestartinterface(ifp);
1266                 }
1267         }
1268 }
1269
1270 static void
1271 stop_all_interfaces(struct dhcpcd_ctx *ctx, unsigned long long opts)
1272 {
1273         struct interface *ifp;
1274
1275         ctx->options |= DHCPCD_EXITING;
1276         /* Drop the last interface first */
1277         TAILQ_FOREACH_REVERSE(ifp, ctx->ifaces, if_head, next) {
1278                 if (ifp->active) {
1279                         ifp->options->options |= opts;
1280                         if (ifp->options->options & DHCPCD_RELEASE)
1281                                 ifp->options->options &= ~DHCPCD_PERSISTENT;
1282                         ifp->options->options |= DHCPCD_EXITING;
1283                         stop_interface(ifp);
1284                 }
1285         }
1286 }
1287
1288 static void
1289 dhcpcd_ifrenew(struct interface *ifp)
1290 {
1291
1292         if (!ifp->active)
1293                 return;
1294
1295         if (ifp->options->options & DHCPCD_LINK &&
1296             ifp->carrier == LINK_DOWN)
1297                 return;
1298
1299 #ifdef INET
1300         dhcp_renew(ifp);
1301 #endif
1302 #ifdef INET6
1303 #define DHCPCD_RARENEW (DHCPCD_IPV6 | DHCPCD_IPV6RS)
1304         if ((ifp->options->options & DHCPCD_RARENEW) == DHCPCD_RARENEW)
1305                 ipv6nd_startrs(ifp);
1306 #endif
1307 #ifdef DHCP6
1308         dhcp6_renew(ifp);
1309 #endif
1310 }
1311
1312 static void
1313 dhcpcd_renew(struct dhcpcd_ctx *ctx)
1314 {
1315         struct interface *ifp;
1316
1317         TAILQ_FOREACH(ifp, ctx->ifaces, next) {
1318                 dhcpcd_ifrenew(ifp);
1319         }
1320 }
1321
1322 #ifdef USE_SIGNALS
1323 #define sigmsg "received %s, %s"
1324 static void
1325 signal_cb(int sig, void *arg)
1326 {
1327         struct dhcpcd_ctx *ctx = arg;
1328         unsigned long long opts;
1329         int exit_code;
1330
1331         opts = 0;
1332         exit_code = EXIT_FAILURE;
1333         switch (sig) {
1334         case SIGINT:
1335                 loginfox(sigmsg, "SIGINT", "stopping");
1336                 break;
1337         case SIGTERM:
1338                 loginfox(sigmsg, "SIGTERM", "stopping");
1339                 exit_code = EXIT_SUCCESS;
1340                 break;
1341         case SIGALRM:
1342                 loginfox(sigmsg, "SIGALRM", "releasing");
1343                 opts |= DHCPCD_RELEASE;
1344                 exit_code = EXIT_SUCCESS;
1345                 break;
1346         case SIGHUP:
1347                 loginfox(sigmsg, "SIGHUP", "rebinding");
1348                 reload_config(ctx);
1349                 /* Preserve any options passed on the commandline
1350                  * when we were started. */
1351                 reconf_reboot(ctx, 1, ctx->argc, ctx->argv,
1352                     ctx->argc - ctx->ifc);
1353                 return;
1354         case SIGUSR1:
1355                 loginfox(sigmsg, "SIGUSR1", "renewing");
1356                 dhcpcd_renew(ctx);
1357                 return;
1358         case SIGUSR2:
1359                 loginfox(sigmsg, "SIGUSR2", "reopening log");
1360                 logclose();
1361                 if (logopen(ctx->logfile) == -1)
1362                         logerr(__func__);
1363                 return;
1364         case SIGPIPE:
1365                 logwarnx("received SIGPIPE");
1366                 return;
1367         default:
1368                 logerrx("received signal %d but don't know what to do with it",
1369                     sig);
1370                 return;
1371         }
1372
1373         if (!(ctx->options & DHCPCD_TEST))
1374                 stop_all_interfaces(ctx, opts);
1375         eloop_exit(ctx->eloop, exit_code);
1376 }
1377 #endif
1378
1379 static void
1380 dhcpcd_getinterfaces(void *arg)
1381 {
1382         struct fd_list *fd = arg;
1383         struct interface *ifp;
1384         size_t len;
1385
1386         len = 0;
1387         TAILQ_FOREACH(ifp, fd->ctx->ifaces, next) {
1388                 if (!ifp->active)
1389                         continue;
1390                 len++;
1391 #ifdef INET
1392                 if (D_STATE_RUNNING(ifp))
1393                         len++;
1394 #endif
1395 #ifdef IPV4LL
1396                 if (IPV4LL_STATE_RUNNING(ifp))
1397                         len++;
1398 #endif
1399 #ifdef INET6
1400                 if (IPV6_STATE_RUNNING(ifp))
1401                         len++;
1402                 if (RS_STATE_RUNNING(ifp))
1403                         len++;
1404 #endif
1405 #ifdef DHCP6
1406                 if (D6_STATE_RUNNING(ifp))
1407                         len++;
1408 #endif
1409         }
1410         if (write(fd->fd, &len, sizeof(len)) != sizeof(len))
1411                 return;
1412         eloop_event_remove_writecb(fd->ctx->eloop, fd->fd);
1413         TAILQ_FOREACH(ifp, fd->ctx->ifaces, next) {
1414                 if (!ifp->active)
1415                         continue;
1416                 if (send_interface(fd, ifp) == -1)
1417                         logerr(__func__);
1418         }
1419 }
1420
1421 int
1422 dhcpcd_handleargs(struct dhcpcd_ctx *ctx, struct fd_list *fd,
1423     int argc, char **argv)
1424 {
1425         struct interface *ifp;
1426         unsigned long long opts;
1427         int opt, oi, do_reboot, do_renew;
1428         size_t len, l;
1429         char *tmp, *p;
1430
1431         /* Special commands for our control socket
1432          * as the other end should be blocking until it gets the
1433          * expected reply we should be safely able just to change the
1434          * write callback on the fd */
1435         if (strcmp(*argv, "--version") == 0) {
1436                 return control_queue(fd, UNCONST(VERSION),
1437                     strlen(VERSION) + 1, false);
1438         } else if (strcmp(*argv, "--getconfigfile") == 0) {
1439                 return control_queue(fd, UNCONST(fd->ctx->cffile),
1440                     strlen(fd->ctx->cffile) + 1, false);
1441         } else if (strcmp(*argv, "--getinterfaces") == 0) {
1442                 eloop_event_add_w(fd->ctx->eloop, fd->fd,
1443                     dhcpcd_getinterfaces, fd);
1444                 return 0;
1445         } else if (strcmp(*argv, "--listen") == 0) {
1446                 fd->flags |= FD_LISTEN;
1447                 return 0;
1448         }
1449
1450         /* Only priviledged users can control dhcpcd via the socket. */
1451         if (fd->flags & FD_UNPRIV) {
1452                 errno = EPERM;
1453                 return -1;
1454         }
1455
1456         /* Log the command */
1457         len = 1;
1458         for (opt = 0; opt < argc; opt++)
1459                 len += strlen(argv[opt]) + 1;
1460         tmp = malloc(len);
1461         if (tmp == NULL)
1462                 return -1;
1463         p = tmp;
1464         for (opt = 0; opt < argc; opt++) {
1465                 l = strlen(argv[opt]);
1466                 strlcpy(p, argv[opt], len);
1467                 len -= l + 1;
1468                 p += l;
1469                 *p++ = ' ';
1470         }
1471         *--p = '\0';
1472         loginfox("control command: %s", tmp);
1473         free(tmp);
1474
1475         optind = 0;
1476         oi = 0;
1477         opts = 0;
1478         do_reboot = do_renew = 0;
1479         while ((opt = getopt_long(argc, argv, IF_OPTS, cf_options, &oi)) != -1)
1480         {
1481                 switch (opt) {
1482                 case 'g':
1483                         /* Assumed if below not set */
1484                         break;
1485                 case 'k':
1486                         opts |= DHCPCD_RELEASE;
1487                         break;
1488                 case 'n':
1489                         do_reboot = 1;
1490                         break;
1491                 case 'p':
1492                         opts |= DHCPCD_PERSISTENT;
1493                         break;
1494                 case 'x':
1495                         opts |= DHCPCD_EXITING;
1496                         break;
1497                 case 'N':
1498                         do_renew = 1;
1499                         break;
1500                 }
1501         }
1502
1503         if (opts & (DHCPCD_EXITING | DHCPCD_RELEASE)) {
1504                 if (optind == argc) {
1505                         stop_all_interfaces(ctx, opts);
1506                         eloop_exit(ctx->eloop, EXIT_SUCCESS);
1507                         return 0;
1508                 }
1509                 for (oi = optind; oi < argc; oi++) {
1510                         if ((ifp = if_find(ctx->ifaces, argv[oi])) == NULL)
1511                                 continue;
1512                         if (!ifp->active)
1513                                 continue;
1514                         ifp->options->options |= opts;
1515                         if (opts & DHCPCD_RELEASE)
1516                                 ifp->options->options &= ~DHCPCD_PERSISTENT;
1517                         stop_interface(ifp);
1518                 }
1519                 return 0;
1520         }
1521
1522         if (do_renew) {
1523                 if (optind == argc) {
1524                         dhcpcd_renew(ctx);
1525                         return 0;
1526                 }
1527                 for (oi = optind; oi < argc; oi++) {
1528                         if ((ifp = if_find(ctx->ifaces, argv[oi])) == NULL)
1529                                 continue;
1530                         dhcpcd_ifrenew(ifp);
1531                 }
1532                 return 0;
1533         }
1534
1535         reload_config(ctx);
1536         /* XXX: Respect initial commandline options? */
1537         reconf_reboot(ctx, do_reboot, argc, argv, optind - 1);
1538         return 0;
1539 }
1540
1541 int
1542 main(int argc, char **argv)
1543 {
1544         struct dhcpcd_ctx ctx;
1545         struct ifaddrs *ifaddrs = NULL;
1546         struct if_options *ifo;
1547         struct interface *ifp;
1548         uint16_t family = 0;
1549         int opt, oi = 0, i;
1550         unsigned int logopts;
1551         time_t t;
1552         ssize_t len;
1553 #if defined(USE_SIGNALS) || !defined(THERE_IS_NO_FORK)
1554         pid_t pid;
1555 #endif
1556 #ifdef USE_SIGNALS
1557         int sig = 0;
1558         const char *siga = NULL;
1559 #endif
1560
1561         /* Test for --help and --version */
1562         if (argc > 1) {
1563                 if (strcmp(argv[1], "--help") == 0) {
1564                         usage();
1565                         return EXIT_SUCCESS;
1566                 } else if (strcmp(argv[1], "--version") == 0) {
1567                         printf(""PACKAGE" "VERSION"\n%s\n", dhcpcd_copyright);
1568                         printf("Compiled in features:"
1569 #ifdef INET
1570                         " INET"
1571 #endif
1572 #ifdef ARP
1573                         " ARP"
1574 #endif
1575 #ifdef ARPING
1576                         " ARPing"
1577 #endif
1578 #ifdef IPV4LL
1579                         " IPv4LL"
1580 #endif
1581 #ifdef INET6
1582                         " INET6"
1583 #endif
1584 #ifdef DHCP6
1585                         " DHCPv6"
1586 #endif
1587 #ifdef AUTH
1588                         " AUTH"
1589 #endif
1590                         "\n");
1591                         return EXIT_SUCCESS;
1592                 }
1593         }
1594
1595         memset(&ctx, 0, sizeof(ctx));
1596
1597         ifo = NULL;
1598         ctx.cffile = CONFIG;
1599         ctx.control_fd = ctx.control_unpriv_fd = ctx.link_fd = -1;
1600         ctx.pf_inet_fd = -1;
1601
1602         TAILQ_INIT(&ctx.control_fds);
1603 #ifdef PLUGIN_DEV
1604         ctx.dev_fd = -1;
1605 #endif
1606 #ifdef INET
1607         ctx.udp_fd = -1;
1608 #endif
1609         rt_init(&ctx);
1610
1611         logopts = LOGERR_ERR|LOGERR_LOG|LOGERR_LOG_DATE|LOGERR_LOG_PID;
1612         i = 0;
1613         while ((opt = getopt_long(argc, argv,
1614             ctx.options & DHCPCD_PRINT_PIDFILE ? NOERR_IF_OPTS : IF_OPTS,
1615             cf_options, &oi)) != -1)
1616         {
1617                 switch (opt) {
1618                 case '4':
1619                         family = AF_INET;
1620                         break;
1621                 case '6':
1622                         family = AF_INET6;
1623                         break;
1624                 case 'f':
1625                         ctx.cffile = optarg;
1626                         break;
1627                 case 'j':
1628                         free(ctx.logfile);
1629                         ctx.logfile = strdup(optarg);
1630                         break;
1631 #ifdef USE_SIGNALS
1632                 case 'k':
1633                         sig = SIGALRM;
1634                         siga = "ALRM";
1635                         break;
1636                 case 'n':
1637                         sig = SIGHUP;
1638                         siga = "HUP";
1639                         break;
1640                 case 'g':
1641                 case 'p':
1642                         /* Force going via command socket as we're
1643                          * out of user definable signals. */
1644                         i = 4;
1645                         break;
1646                 case 'q':
1647                         logopts |= LOGERR_QUIET;
1648                         break;
1649                 case 'x':
1650                         sig = SIGTERM;
1651                         siga = "TERM";
1652                         break;
1653                 case 'N':
1654                         sig = SIGUSR1;
1655                         siga = "USR1";
1656                         break;
1657 #endif
1658                 case 'P':
1659                         ctx.options |= DHCPCD_PRINT_PIDFILE;
1660                         logopts &= ~(LOGERR_LOG | LOGERR_ERR);
1661                         break;
1662                 case 'T':
1663                         i = 1;
1664                         logopts &= ~LOGERR_LOG;
1665                         break;
1666                 case 'U':
1667                         i = 3;
1668                         break;
1669                 case 'V':
1670                         i = 2;
1671                         break;
1672                 case '?':
1673                         if (ctx.options & DHCPCD_PRINT_PIDFILE)
1674                                 continue;
1675                         usage();
1676                         goto exit_failure;
1677                 }
1678         }
1679
1680         logsetopts(logopts);
1681         logopen(ctx.logfile);
1682
1683         ctx.argv = argv;
1684         ctx.argc = argc;
1685         ctx.ifc = argc - optind;
1686         ctx.ifv = argv + optind;
1687
1688         ifo = read_config(&ctx, NULL, NULL, NULL);
1689         if (ifo == NULL) {
1690                 if (ctx.options & DHCPCD_PRINT_PIDFILE)
1691                         goto printpidfile;
1692                 goto exit_failure;
1693         }
1694         opt = add_options(&ctx, NULL, ifo, argc, argv);
1695         if (opt != 1) {
1696                 if (ctx.options & DHCPCD_PRINT_PIDFILE)
1697                         goto printpidfile;
1698                 if (opt == 0)
1699                         usage();
1700                 goto exit_failure;
1701         }
1702         if (i == 2) {
1703                 printf("Interface options:\n");
1704                 if (optind == argc - 1) {
1705                         free_options(&ctx, ifo);
1706                         ifo = read_config(&ctx, argv[optind], NULL, NULL);
1707                         if (ifo == NULL)
1708                                 goto exit_failure;
1709                         add_options(&ctx, NULL, ifo, argc, argv);
1710                 }
1711                 if_printoptions();
1712 #ifdef INET
1713                 if (family == 0 || family == AF_INET) {
1714                         printf("\nDHCPv4 options:\n");
1715                         dhcp_printoptions(&ctx,
1716                             ifo->dhcp_override, ifo->dhcp_override_len);
1717                 }
1718 #endif
1719 #ifdef INET6
1720                 if (family == 0 || family == AF_INET6) {
1721                         printf("\nND options:\n");
1722                         ipv6nd_printoptions(&ctx,
1723                             ifo->nd_override, ifo->nd_override_len);
1724 #ifdef DHCP6
1725                         printf("\nDHCPv6 options:\n");
1726                         dhcp6_printoptions(&ctx,
1727                             ifo->dhcp6_override, ifo->dhcp6_override_len);
1728 #endif
1729                 }
1730 #endif
1731                 goto exit_success;
1732         }
1733         ctx.options |= ifo->options;
1734         if (i == 1 || i == 3) {
1735                 if (i == 1)
1736                         ctx.options |= DHCPCD_TEST;
1737                 else
1738                         ctx.options |= DHCPCD_DUMPLEASE;
1739                 ctx.options |= DHCPCD_PERSISTENT;
1740                 ctx.options &= ~DHCPCD_DAEMONISE;
1741         }
1742
1743 #ifdef THERE_IS_NO_FORK
1744         ctx.options &= ~DHCPCD_DAEMONISE;
1745 #endif
1746
1747         if (ctx.options & DHCPCD_DEBUG)
1748                 logsetopts(logopts | LOGERR_DEBUG);
1749
1750         if (!(ctx.options & (DHCPCD_TEST | DHCPCD_DUMPLEASE))) {
1751 printpidfile:
1752                 /* If we have any other args, we should run as a single dhcpcd
1753                  *  instance for that interface. */
1754                 if (optind == argc - 1 && !(ctx.options & DHCPCD_MASTER)) {
1755                         const char *per;
1756                         const char *ifname;
1757
1758                         ifname = *ctx.ifv;
1759                         if (ifname == NULL || strlen(ifname) > IF_NAMESIZE) {
1760                                 errno = ifname == NULL ? EINVAL : E2BIG;
1761                                 logerr("%s: ", ifname);
1762                                 goto exit_failure;
1763                         }
1764                         /* Allow a dhcpcd interface per address family */
1765                         switch(family) {
1766                         case AF_INET:
1767                                 per = "-4";
1768                                 break;
1769                         case AF_INET6:
1770                                 per = "-6";
1771                                 break;
1772                         default:
1773                                 per = "";
1774                         }
1775                         snprintf(ctx.pidfile, sizeof(ctx.pidfile),
1776                             PIDFILE, "-", ifname, per);
1777                 } else {
1778                         snprintf(ctx.pidfile, sizeof(ctx.pidfile),
1779                             PIDFILE, "", "", "");
1780                         ctx.options |= DHCPCD_MASTER;
1781                 }
1782                 if (ctx.options & DHCPCD_PRINT_PIDFILE) {
1783                         printf("%s\n", ctx.pidfile);
1784                         goto exit_success;
1785                 }
1786         }
1787
1788         if (chdir("/") == -1)
1789                 logerr("%s: chdir `/'", __func__);
1790
1791         /* Freeing allocated addresses from dumping leases can trigger
1792          * eloop removals as well, so init here. */
1793         if ((ctx.eloop = eloop_new()) == NULL) {
1794                 logerr("%s: eloop_init", __func__);
1795                 goto exit_failure;
1796         }
1797 #ifdef USE_SIGNALS
1798         /* Save signal mask, block and redirect signals to our handler */
1799         if (eloop_signal_set_cb(ctx.eloop,
1800             dhcpcd_signals, dhcpcd_signals_len,
1801             signal_cb, &ctx) == -1)
1802         {
1803                 logerr("%s: eloop_signal_set_cb", __func__);
1804                 goto exit_failure;
1805         }
1806         if (eloop_signal_mask(ctx.eloop, &ctx.sigset) == -1) {
1807                 logerr("%s: eloop_signal_mask", __func__);
1808                 goto exit_failure;
1809         }
1810 #endif
1811
1812         if (ctx.options & DHCPCD_DUMPLEASE) {
1813                 /* Open sockets so we can dump something about
1814                  * valid interfaces. */
1815                 if (if_opensockets(&ctx) == -1) {
1816                         logerr("%s: if_opensockets", __func__);
1817                         goto exit_failure;
1818                 }
1819                 if (optind != argc) {
1820                         /* We need to try and find the interface so we can load
1821                          * the hardware address to compare automated IAID */
1822                         ctx.ifaces = if_discover(&ctx, &ifaddrs,
1823                             argc - optind, argv + optind);
1824                 } else {
1825                         if ((ctx.ifaces = malloc(sizeof(*ctx.ifaces))) != NULL)
1826                                 TAILQ_INIT(ctx.ifaces);
1827                 }
1828                 if (ctx.ifaces == NULL) {
1829                         logerr("%s: if_discover", __func__);
1830                         goto exit_failure;
1831                 }
1832                 ifp = if_find(ctx.ifaces, argv[optind]);
1833                 if (ifp == NULL) {
1834                         ifp = calloc(1, sizeof(*ifp));
1835                         if (ifp == NULL) {
1836                                 logerr(__func__);
1837                                 goto exit_failure;
1838                         }
1839                         if (optind != argc)
1840                                 strlcpy(ctx.pidfile, argv[optind],
1841                                     sizeof(ctx.pidfile));
1842                         ifp->ctx = &ctx;
1843                         TAILQ_INSERT_HEAD(ctx.ifaces, ifp, next);
1844                         if (family == 0) {
1845                                 if (ctx.pidfile[0] != '\0' &&
1846                                     ctx.pidfile[strlen(ctx.pidfile) - 1] == '6')
1847                                         family = AF_INET6;
1848                                 else
1849                                         family = AF_INET;
1850                         }
1851                 }
1852                 configure_interface(ifp, ctx.argc, ctx.argv, 0);
1853                 i = 0;
1854                 if (family == 0 || family == AF_INET) {
1855 #ifdef INET
1856                         if (dhcp_dump(ifp) == -1)
1857                                 i = -1;
1858 #else
1859                         if (family == AF_INET)
1860                                 logerrx("No INET support");
1861 #endif
1862                 }
1863                 if (family == 0 || family == AF_INET6) {
1864 #ifdef DHCP6
1865                         if (dhcp6_dump(ifp) == -1)
1866                                 i = -1;
1867 #else
1868                         if (family == AF_INET6)
1869                                 logerrx("No DHCP6 support");
1870 #endif
1871                 }
1872                 if (i == -1)
1873                         goto exit_failure;
1874                 goto exit_success;
1875         }
1876
1877 #ifdef USE_SIGNALS
1878         /* Test against siga instead of sig to avoid gcc
1879          * warning about a bogus potential signed overflow.
1880          * The end result will be the same. */
1881         if ((siga == NULL || i == 4 || ctx.ifc != 0) &&
1882             !(ctx.options & DHCPCD_TEST))
1883         {
1884 #endif
1885                 if (!(ctx.options & DHCPCD_MASTER))
1886                         ctx.control_fd = control_open(argv[optind]);
1887                 if (ctx.control_fd == -1)
1888                         ctx.control_fd = control_open(NULL);
1889                 if (ctx.control_fd != -1) {
1890                         loginfox("sending commands to master dhcpcd process");
1891                         len = control_send(&ctx, argc, argv);
1892                         control_close(&ctx);
1893                         if (len > 0) {
1894                                 logdebugx("send OK");
1895                                 goto exit_success;
1896                         } else {
1897                                 logerr("%s: control_send", __func__);
1898                                 goto exit_failure;
1899                         }
1900                 } else {
1901                         if (errno != ENOENT)
1902                                 logerr("%s: control_open", __func__);
1903                 }
1904 #ifdef USE_SIGNALS
1905         }
1906 #endif
1907
1908 #ifdef USE_SIGNALS
1909         if (sig != 0) {
1910                 pid = pidfile_read(ctx.pidfile);
1911                 if (pid != 0 && pid != -1)
1912                         loginfox("sending signal %s to pid %d", siga, pid);
1913                 if (pid == 0 || pid == -1 || kill(pid, sig) != 0) {
1914                         if (sig != SIGHUP && sig != SIGUSR1 && errno != EPERM)
1915                                 logerrx(PACKAGE" not running");
1916                         if (pid != 0 && pid != -1 && errno != ESRCH) {
1917                                 logerr("kill");
1918                                 goto exit_failure;
1919                         }
1920                         unlink(ctx.pidfile);
1921                         if (sig != SIGHUP && sig != SIGUSR1)
1922                                 goto exit_failure;
1923                 } else {
1924                         struct timespec ts;
1925
1926                         if (sig == SIGHUP || sig == SIGUSR1)
1927                                 goto exit_success;
1928                         /* Spin until it exits */
1929                         loginfox("waiting for pid %d to exit", pid);
1930                         ts.tv_sec = 0;
1931                         ts.tv_nsec = 100000000; /* 10th of a second */
1932                         for(i = 0; i < 100; i++) {
1933                                 nanosleep(&ts, NULL);
1934                                 if (pidfile_read(ctx.pidfile) == -1)
1935                                         goto exit_success;
1936                         }
1937                         logerrx("pid %d failed to exit", pid);
1938                         goto exit_failure;
1939                 }
1940         }
1941
1942         if (!(ctx.options & DHCPCD_TEST)) {
1943                 /* Ensure we have the needed directories */
1944                 if (mkdir(RUNDIR, 0755) == -1 && errno != EEXIST)
1945                         logerr("%s: mkdir `%s'", __func__, RUNDIR);
1946                 if (mkdir(DBDIR, 0755) == -1 && errno != EEXIST)
1947                         logerr("%s: mkdir `%s'", __func__, DBDIR);
1948
1949                 if ((pid = pidfile_lock(ctx.pidfile)) != 0) {
1950                         if (pid == -1)
1951                                 logerr("%s: pidfile_lock", __func__);
1952                         else
1953                                 logerrx(PACKAGE
1954                                     " already running on pid %d (%s)",
1955                                     pid, ctx.pidfile);
1956                         goto exit_failure;
1957                 }
1958         }
1959
1960         if (ctx.options & DHCPCD_MASTER) {
1961                 if (control_start(&ctx, NULL) == -1)
1962                         logerr("%s: control_start", __func__);
1963         }
1964 #else
1965         if (control_start(&ctx,
1966             ctx.options & DHCPCD_MASTER ? NULL : argv[optind]) == -1)
1967         {
1968                 logerr("%s: control_start", __func__);
1969                 goto exit_failure;
1970         }
1971 #endif
1972
1973         logdebugx(PACKAGE "-" VERSION " starting");
1974         ctx.options |= DHCPCD_STARTED;
1975
1976 #ifdef HAVE_SETPROCTITLE
1977         setproctitle("%s%s%s",
1978             ctx.options & DHCPCD_MASTER ? "[master]" : argv[optind],
1979             ctx.options & DHCPCD_IPV4 ? " [ip4]" : "",
1980             ctx.options & DHCPCD_IPV6 ? " [ip6]" : "");
1981 #endif
1982
1983         if (if_opensockets(&ctx) == -1) {
1984                 logerr("%s: if_opensockets", __func__);
1985                 goto exit_failure;
1986         }
1987 #ifndef SMALL
1988         dhcpcd_setlinkrcvbuf(&ctx);
1989 #endif
1990
1991         /* When running dhcpcd against a single interface, we need to retain
1992          * the old behaviour of waiting for an IP address */
1993         if (ctx.ifc == 1 && !(ctx.options & DHCPCD_BACKGROUND))
1994                 ctx.options |= DHCPCD_WAITIP;
1995
1996         /* Start handling kernel messages for interfaces, addresses and
1997          * routes. */
1998         eloop_event_add(ctx.eloop, ctx.link_fd, dhcpcd_handlelink, &ctx);
1999
2000         /* Start any dev listening plugin which may want to
2001          * change the interface name provided by the kernel */
2002         if ((ctx.options & (DHCPCD_MASTER | DHCPCD_DEV)) ==
2003             (DHCPCD_MASTER | DHCPCD_DEV))
2004                 dev_start(&ctx);
2005
2006         ctx.ifaces = if_discover(&ctx, &ifaddrs, ctx.ifc, ctx.ifv);
2007         if (ctx.ifaces == NULL) {
2008                 logerr("%s: if_discover", __func__);
2009                 goto exit_failure;
2010         }
2011         for (i = 0; i < ctx.ifc; i++) {
2012                 if ((ifp = if_find(ctx.ifaces, ctx.ifv[i])) == NULL ||
2013                     !ifp->active)
2014                         logerrx("%s: interface not found or invalid",
2015                             ctx.ifv[i]);
2016         }
2017         TAILQ_FOREACH(ifp, ctx.ifaces, next) {
2018                 if (ifp->active == IF_ACTIVE_USER)
2019                         break;
2020         }
2021         if (ifp == NULL) {
2022                 if (ctx.ifc == 0) {
2023                         logfunc_t *logfunc;
2024
2025                         logfunc = ctx.options & DHCPCD_INACTIVE ?
2026                             logdebugx : logerrx;
2027                         logfunc("no valid interfaces found");
2028                 } else
2029                         goto exit_failure;
2030                 if (!(ctx.options & DHCPCD_LINK)) {
2031                         logerrx("aborting as link detection is disabled");
2032                         goto exit_failure;
2033                 }
2034         }
2035
2036         TAILQ_FOREACH(ifp, ctx.ifaces, next) {
2037                 if (ifp->active)
2038                         dhcpcd_initstate1(ifp, argc, argv, 0);
2039         }
2040         if_learnaddrs(&ctx, ctx.ifaces, &ifaddrs);
2041
2042         if (ctx.options & DHCPCD_BACKGROUND && dhcpcd_daemonise(&ctx))
2043                 goto exit_success;
2044
2045         opt = 0;
2046         TAILQ_FOREACH(ifp, ctx.ifaces, next) {
2047                 if (ifp->active) {
2048                         run_preinit(ifp);
2049                         if (!(ifp->options->options & DHCPCD_LINK) ||
2050                             ifp->carrier != LINK_DOWN)
2051                                 opt = 1;
2052                 }
2053         }
2054
2055         if (!(ctx.options & DHCPCD_BACKGROUND)) {
2056                 if (ctx.options & DHCPCD_MASTER)
2057                         t = ifo->timeout;
2058                 else {
2059                         t = 0;
2060                         TAILQ_FOREACH(ifp, ctx.ifaces, next) {
2061                                 if (ifp->active) {
2062                                         t = ifp->options->timeout;
2063                                         break;
2064                                 }
2065                         }
2066                 }
2067                 if (opt == 0 &&
2068                     ctx.options & DHCPCD_LINK &&
2069                     !(ctx.options & DHCPCD_WAITIP))
2070                 {
2071                         logfunc_t *logfunc;
2072
2073                         logfunc = ctx.options & DHCPCD_INACTIVE ?
2074                             logdebugx : logwarnx;
2075                         logfunc("no interfaces have a carrier");
2076                         if (dhcpcd_daemonise(&ctx))
2077                                 goto exit_success;
2078                 } else if (t > 0 &&
2079                     /* Test mode removes the daemonise bit, so check for both */
2080                     ctx.options & (DHCPCD_DAEMONISE | DHCPCD_TEST))
2081                 {
2082                         eloop_timeout_add_sec(ctx.eloop, t,
2083                             handle_exit_timeout, &ctx);
2084                 }
2085         }
2086         free_options(&ctx, ifo);
2087         ifo = NULL;
2088
2089         TAILQ_FOREACH(ifp, ctx.ifaces, next) {
2090                 if (ifp->active)
2091                         eloop_timeout_add_sec(ctx.eloop, 0,
2092                             dhcpcd_prestartinterface, ifp);
2093         }
2094
2095         i = eloop_start(ctx.eloop, &ctx.sigset);
2096         if (i < 0) {
2097                 logerr("%s: eloop_start", __func__);
2098                 goto exit_failure;
2099         }
2100         goto exit1;
2101
2102 exit_success:
2103         i = EXIT_SUCCESS;
2104         goto exit1;
2105
2106 exit_failure:
2107         i = EXIT_FAILURE;
2108
2109 exit1:
2110         if (ifaddrs != NULL)
2111                 freeifaddrs(ifaddrs);
2112         if (control_stop(&ctx) == -1)
2113                 logerr("%s: control_stop", __func__);
2114         /* Free memory and close fd's */
2115         if (ctx.ifaces) {
2116                 while ((ifp = TAILQ_FIRST(ctx.ifaces))) {
2117                         TAILQ_REMOVE(ctx.ifaces, ifp, next);
2118                         if_free(ifp);
2119                 }
2120                 free(ctx.ifaces);
2121         }
2122         free_options(&ctx, ifo);
2123 #ifdef HAVE_OPEN_MEMSTREAM
2124         if (ctx.script_fp)
2125                 fclose(ctx.script_fp);
2126 #endif
2127         free(ctx.script_buf);
2128         free(ctx.script_env);
2129         rt_dispose(&ctx);
2130         free(ctx.duid);
2131         if (ctx.link_fd != -1) {
2132                 eloop_event_delete(ctx.eloop, ctx.link_fd);
2133                 close(ctx.link_fd);
2134         }
2135         if_closesockets(&ctx);
2136         free_globals(&ctx);
2137 #ifdef INET6
2138         ipv6_ctxfree(&ctx);
2139 #endif
2140         dev_stop(&ctx);
2141         eloop_free(ctx.eloop);
2142
2143         if (ctx.options & DHCPCD_STARTED && !(ctx.options & DHCPCD_FORKED))
2144                 loginfox(PACKAGE " exited");
2145         logclose();
2146         free(ctx.logfile);
2147 #ifdef USE_SIGNALS
2148         if (ctx.options & DHCPCD_FORKED)
2149                 _exit(i); /* so atexit won't remove our pidfile */
2150 #endif
2151         return i;
2152 }