dhclient - Remove saved resolv.conf to avoid problems.
[dragonfly.git] / sbin / dhclient / dhclient.c
1 /*      $OpenBSD: src/sbin/dhclient/dhclient.c,v 1.156 2012/09/18 09:34:09 krw Exp $    */
2
3 /*
4  * Copyright 2004 Henning Brauer <henning@openbsd.org>
5  * Copyright (c) 1995, 1996, 1997, 1998, 1999
6  * The Internet Software Consortium.    All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
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.
17  * 3. Neither the name of The Internet Software Consortium nor the names
18  *    of its contributors may be used to endorse or promote products derived
19  *    from this software without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE INTERNET SOFTWARE CONSORTIUM AND
22  * CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
23  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
24  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
25  * DISCLAIMED.  IN NO EVENT SHALL THE INTERNET SOFTWARE CONSORTIUM OR
26  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
27  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
28  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
29  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
30  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
31  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
32  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  *
35  * This software has been written for the Internet Software Consortium
36  * by Ted Lemon <mellon@fugue.com> in cooperation with Vixie
37  * Enterprises.  To learn more about the Internet Software Consortium,
38  * see ``http://www.vix.com/isc''.  To learn more about Vixie
39  * Enterprises, see ``http://www.vix.com''.
40  *
41  * This client was substantially modified and enhanced by Elliot Poger
42  * for use on Linux while he was working on the MosquitoNet project at
43  * Stanford.
44  *
45  * The current version owes much to Elliot's Linux enhancements, but
46  * was substantially reorganized and partially rewritten by Ted Lemon
47  * so as to use the same networking framework that the Internet Software
48  * Consortium DHCP server uses.   Much system-specific configuration code
49  * was moved into a shell script so that as support for more operating
50  * systems is added, it will not be necessary to port and maintain
51  * system-specific configuration code to these operating systems - instead,
52  * the shell script can invoke the native tools to accomplish the same
53  * purpose.
54  */
55 #include <sys/ioctl.h>
56
57 #include <ctype.h>
58 #include <poll.h>
59 #include <pwd.h>
60 #include <unistd.h>
61
62 #include "dhcpd.h"
63 #include "privsep.h"
64
65 #define CLIENT_PATH             "PATH=/usr/bin:/usr/sbin:/bin:/sbin"
66 #define DEFAULT_LEASE_TIME      43200   /* 12 hours... */
67 #define TIME_MAX                2147483647
68 #define POLL_FAILURES           10
69 #define POLL_FAILURE_WAIT       1       /* Back off multiplier (seconds) */
70
71 char *path_dhclient_conf = _PATH_DHCLIENT_CONF;
72 char *path_dhclient_db = NULL;
73
74 int log_perror = 1;
75 int privfd;
76 int nullfd = -1;
77 int no_daemon;
78 int unknown_ok = 1;
79 int routefd = -1;
80
81 struct iaddr iaddr_broadcast = { 4, { 255, 255, 255, 255 } };
82 struct in_addr inaddr_any;
83 struct sockaddr_in sockaddr_broadcast;
84
85 struct interface_info *ifi;
86 struct client_state *client;
87 struct client_config *config;
88
89 int              findproto(char *, int);
90 struct sockaddr *get_ifa(char *, int);
91 void             usage(void);
92 int              check_option(struct client_lease *l, int option);
93 int              ipv4addrs(char * buf);
94 int              res_hnok(const char *dn);
95 char            *option_as_string(unsigned int code, unsigned char *data, int len);
96 int              fork_privchld(int, int);
97 void             get_ifname(char *, char *);
98
99 time_t  scripttime;
100 static FILE *leaseFile;
101
102 int
103 findproto(char *cp, int n)
104 {
105         struct sockaddr *sa;
106         int i;
107
108         if (n == 0)
109                 return -1;
110         for (i = 1; i; i <<= 1) {
111                 if (i & n) {
112                         sa = (struct sockaddr *)cp;
113                         switch (i) {
114                         case RTA_IFA:
115                         case RTA_DST:
116                         case RTA_GATEWAY:
117                         case RTA_NETMASK:
118                                 if (sa->sa_family == AF_INET)
119                                         return AF_INET;
120                                 if (sa->sa_family == AF_INET6)
121                                         return AF_INET6;
122                                 break;
123                         case RTA_IFP:
124                                 break;
125                         }
126                         RT_ADVANCE(cp, sa);
127                 }
128         }
129         return (-1);
130 }
131
132 struct sockaddr *
133 get_ifa(char *cp, int n)
134 {
135         struct sockaddr *sa;
136         int i;
137
138         if (n == 0)
139                 return (NULL);
140         for (i = 1; i; i <<= 1)
141                 if (i & n) {
142                         sa = (struct sockaddr *)cp;
143                         if (i == RTA_IFA)
144                                 return (sa);
145                         RT_ADVANCE(cp, sa);
146                 }
147
148         return (NULL);
149 }
150 struct iaddr defaddr = { .len = 4 }; /* NULL is for silence warnings */
151
152 void
153 routehandler(void)
154 {
155         int linkstat;
156         char msg[2048];
157         struct rt_msghdr *rtm;
158         struct if_msghdr *ifm;
159         struct ifa_msghdr *ifam;
160         struct if_announcemsghdr *ifan;
161         struct client_lease *l;
162         struct sockaddr *sa;
163         struct iaddr a;
164         ssize_t n;
165         char *errmsg, buf[64];
166
167         do {
168                 n = read(routefd, &msg, sizeof(msg));
169         } while (n == -1 && errno == EINTR);
170
171         rtm = (struct rt_msghdr *)msg;
172         if (n < sizeof(rtm->rtm_msglen) || n < rtm->rtm_msglen ||
173             rtm->rtm_version != RTM_VERSION)
174                 return;
175
176         switch (rtm->rtm_type) {
177         case RTM_NEWADDR:
178                 ifam = (struct ifa_msghdr *)rtm;
179                 if (ifam->ifam_index != ifi->index)
180                         break;
181                 if (findproto((char *)(ifam + 1), ifam->ifam_addrs) != AF_INET)
182                         break;
183                 sa = get_ifa((char *)(ifam + 1), ifam->ifam_addrs);
184                 if (sa == NULL) {
185                         errmsg = "sa == NULL";
186                         goto die;
187                 }
188
189                 if ((a.len = sizeof(struct in_addr)) > sizeof(a.iabuf))
190                         error("king bula sez: len mismatch");
191                 memcpy(a.iabuf, &((struct sockaddr_in *)sa)->sin_addr, a.len);
192                 if (addr_eq(a, defaddr))
193                         break;
194
195                 /* state_panic() can try unexpired existing leases */
196                 if (client->active && addr_eq(a, client->active->address))
197                         break;
198                 for (l = client->leases; l != NULL; l = l->next)
199                         if (addr_eq(a, l->address))
200                                 break;
201
202                 if (l != NULL)
203                         /* new addr is the one we set */
204                         break;
205                 snprintf(buf, sizeof(buf), "%s: %s",
206                     "new address not one we set", piaddr(a));
207                 errmsg = buf;
208                 goto die;
209         case RTM_DELADDR:
210                 ifam = (struct ifa_msghdr *)rtm;
211                 if (ifam->ifam_index != ifi->index)
212                         break;
213                 if (findproto((char *)(ifam + 1), ifam->ifam_addrs) != AF_INET)
214                         break;
215                 /* XXX check addrs like RTM_NEWADDR instead of this? */
216                 if (scripttime == 0 || time(NULL) < scripttime + 10)
217                         break;
218                 errmsg = "interface address deleted";
219                 goto die;
220         case RTM_IFINFO:
221                 ifm = (struct if_msghdr *)rtm;
222                 if (ifm->ifm_index != ifi->index)
223                         break;
224                 if ((rtm->rtm_flags & RTF_UP) == 0) {
225                         errmsg = "interface down";
226                         goto die;
227                 }
228
229                 linkstat =
230                     LINK_STATE_IS_UP(ifm->ifm_data.ifi_link_state) ? 1 : 0;
231                 if (linkstat != ifi->linkstat) {
232 #ifdef DEBUG
233                         debug("link state %s -> %s",
234                             ifi->linkstat ? "up" : "down",
235                             linkstat ? "up" : "down");
236 #endif
237                         ifi->linkstat = interface_status(ifi->name);
238                         if (ifi->linkstat) {
239                                 client->state = S_REBOOTING;
240                                 state_reboot();
241                         } else if (client->active) {
242                                 script_init("FAIL");
243                                 script_write_params("old_", client->active);
244                                 script_go();
245                         }
246                 }
247                 break;
248         case RTM_IFANNOUNCE:
249                 ifan = (struct if_announcemsghdr *)rtm;
250                 if (ifan->ifan_what == IFAN_DEPARTURE &&
251                     ifan->ifan_index == ifi->index) {
252                         errmsg = "interface departure";
253                         goto die;
254                 }
255                 break;
256         default:
257                 break;
258         }
259         return;
260
261 die:
262         script_init("FAIL");
263         script_write_params("old_", client->active);
264         script_go();
265         sleep(2);
266         error("routehandler: %s", errmsg);
267 }
268
269 int
270 main(int argc, char *argv[])
271 {
272         int      ch, fd, quiet = 0, i = 0, pipe_fd[2];
273         struct passwd *pw;
274
275         /* Initially, log errors to stderr as well as to syslogd. */
276         openlog(getprogname(), LOG_PID | LOG_NDELAY, DHCPD_LOG_FACILITY);
277         setlogmask(LOG_UPTO(LOG_INFO));
278
279         while ((ch = getopt(argc, argv, "c:dl:qu")) != -1)
280                 switch (ch) {
281                 case 'c':
282                         path_dhclient_conf = optarg;
283                         break;
284                 case 'd':
285                         no_daemon = 1;
286                         break;
287                 case 'l':
288                         path_dhclient_db = optarg;
289                         break;
290                 case 'q':
291                         quiet = 1;
292                         break;
293                 case 'u':
294                         unknown_ok = 0;
295                         break;
296                 default:
297                         usage();
298                 }
299
300         argc -= optind;
301         argv += optind;
302
303         if (argc != 1)
304                 usage();
305
306         ifi = calloc(1, sizeof(*ifi));
307         if (ifi == NULL)
308                 error("ifi calloc");
309         client = calloc(1, sizeof(*client));
310         if (client == NULL)
311                 error("client calloc");
312         config = calloc(1, sizeof(*config));
313         if (config == NULL)
314                 error("config calloc");
315
316         get_ifname(ifi->name, argv[0]);
317         if (path_dhclient_db == NULL && asprintf(&path_dhclient_db, "%s.%s",
318             _PATH_DHCLIENT_DB, ifi->name) == -1)
319                 error("asprintf");
320
321         if (quiet)
322                 log_perror = 0;
323
324         tzset();
325
326         memset(&sockaddr_broadcast, 0, sizeof(sockaddr_broadcast));
327         sockaddr_broadcast.sin_family = AF_INET;
328         sockaddr_broadcast.sin_port = htons(REMOTE_PORT);
329         sockaddr_broadcast.sin_addr.s_addr = INADDR_BROADCAST;
330         sockaddr_broadcast.sin_len = sizeof(sockaddr_broadcast);
331         inaddr_any.s_addr = INADDR_ANY;
332
333         read_client_conf();
334
335         if (interface_status(ifi->name) == 0) {
336                 interface_link_forceup(ifi->name);
337                 /* Give it up to 4 seconds of silent grace to find link */
338                 i = -4;
339         } else
340                 i = 0;
341
342         while (!(ifi->linkstat = interface_status(ifi->name))) {
343                 if (i == 0)
344                         fprintf(stderr, "%s: no link ...", ifi->name);
345                 else if (i > 0)
346                         fprintf(stderr, ".");
347                 fflush(stderr);
348                 if (++i > config->link_timeout) {
349                         fprintf(stderr, " sleeping\n");
350                         goto dispatch;
351                 }
352                 sleep(1);
353         }
354         if (i > 0)
355                 fprintf(stderr, " got link\n");
356
357  dispatch:
358         if ((nullfd = open(_PATH_DEVNULL, O_RDWR, 0)) == -1)
359                 error("cannot open %s: %m", _PATH_DEVNULL);
360
361         if ((pw = getpwnam("_dhcp")) == NULL)
362                 error("no such user: _dhcp");
363
364         if (pipe(pipe_fd) == -1)
365                 error("pipe");
366
367         fork_privchld(pipe_fd[0], pipe_fd[1]);
368
369         close(pipe_fd[0]);
370         privfd = pipe_fd[1];
371
372         if ((fd = open(path_dhclient_db, O_RDONLY|O_EXLOCK|O_CREAT, 0)) == -1)
373                 error("can't open and lock %s: %m", path_dhclient_db);
374         read_client_leases();
375         if ((leaseFile = fopen(path_dhclient_db, "w")) == NULL)
376                 error("can't open %s: %m", path_dhclient_db);
377         rewrite_client_leases();
378         close(fd);
379
380         if ((routefd = socket(PF_ROUTE, SOCK_RAW, 0)) == -1)
381                 error("socket(PF_ROUTE, SOCK_RAW): %m");
382
383         /* set up the interface */
384         discover_interface();
385
386         if (chroot(_PATH_VAREMPTY) == -1)
387                 error("chroot");
388         if (chdir("/") == -1)
389                 error("chdir(\"/\")");
390
391         if (setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) == -1)
392                 error("setresgid");
393         if (setgroups(1, &pw->pw_gid) == -1)
394                 error("setgroups");
395         if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) == -1)
396                 error("setresuid");
397
398         endpwent();
399
400         setproctitle("%s", ifi->name);
401
402         if (ifi->linkstat) {
403                 client->state = S_REBOOTING;
404                 state_reboot();
405         } else
406                 go_daemon();
407
408         dispatch();
409
410         /* not reached */
411         return (0);
412 }
413
414 void
415 usage(void)
416 {
417         fprintf(stderr, "usage: %s [-dqu] [-c file] [-l file] interface\n",
418             getprogname());
419         exit(1);
420 }
421
422 /*
423  * Individual States:
424  *
425  * Each routine is called from the dhclient_state_machine() in one of
426  * these conditions:
427  * -> entering INIT state
428  * -> recvpacket_flag == 0: timeout in this state
429  * -> otherwise: received a packet in this state
430  *
431  * Return conditions as handled by dhclient_state_machine():
432  * Returns 1, sendpacket_flag = 1: send packet, reset timer.
433  * Returns 1, sendpacket_flag = 0: just reset the timer (wait for a milestone).
434  * Returns 0: finish the nap which was interrupted for no good reason.
435  *
436  * Several per-interface variables are used to keep track of the process:
437  *   active_lease: the lease that is being used on the interface
438  *                 (null pointer if not configured yet).
439  *   offered_leases: leases corresponding to DHCPOFFER messages that have
440  *                   been sent to us by DHCP servers.
441  *   acked_leases: leases corresponding to DHCPACK messages that have been
442  *                 sent to us by DHCP servers.
443  *   sendpacket: DHCP packet we're trying to send.
444  *   destination: IP address to send sendpacket to
445  * In addition, there are several relevant per-lease variables.
446  *   T1_expiry, T2_expiry, lease_expiry: lease milestones
447  * In the active lease, these control the process of renewing the lease;
448  * In leases on the acked_leases list, this simply determines when we
449  * can no longer legitimately use the lease.
450  */
451 void
452 state_reboot(void)
453 {
454         /* Cancel all timeouts, since a link state change gets us here
455            and can happen anytime. */
456         cancel_timeout();
457
458         /* If we don't remember an active lease, go straight to INIT. */
459         if (!client->active || client->active->is_bootp) {
460                 client->state = S_INIT;
461                 state_init();
462                 return;
463         }
464
465         /* make_request doesn't initialize xid because it normally comes
466            from the DHCPDISCOVER, but we haven't sent a DHCPDISCOVER,
467            so pick an xid now. */
468         client->xid = arc4random();
469
470         /* Make a DHCPREQUEST packet, and set appropriate per-interface
471            flags. */
472         make_request(client->active);
473         client->destination = iaddr_broadcast;
474         client->first_sending = time(NULL);
475         client->interval = 0;
476
477         send_request();
478 }
479
480 /*
481  * Called when a lease has completely expired and we've
482  * been unable to renew it.
483  */
484 void
485 state_init(void)
486 {
487         /* Make a DHCPDISCOVER packet, and set appropriate per-interface
488            flags. */
489         make_discover(client->active);
490         client->xid = client->packet.xid;
491         client->destination = iaddr_broadcast;
492         client->state = S_SELECTING;
493         client->first_sending = time(NULL);
494         client->interval = 0;
495
496         send_discover();
497 }
498
499 /*
500  * state_selecting is called when one or more DHCPOFFER packets
501  * have been received and a configurable period of time has passed.
502  */
503 void
504 state_selecting(void)
505 {
506         struct client_lease *lp, *next, *picked;
507         time_t cur_time;
508
509         /* Cancel state_selecting and send_discover timeouts, since either
510            one could have got us here. */
511         cancel_timeout();
512
513         /* We have received one or more DHCPOFFER packets.   Currently,
514            the only criterion by which we judge leases is whether or
515            not we get a response when we arp for them. */
516         picked = NULL;
517         for (lp = client->offered_leases; lp; lp = next) {
518                 next = lp->next;
519
520                 if (!picked) {
521                         picked = lp;
522                 } else {
523                         make_decline(lp);
524                         send_decline();
525                         free_client_lease(lp);
526                 }
527         }
528         client->offered_leases = NULL;
529
530         /* If we just tossed all the leases we were offered, go back
531            to square one. */
532         if (!picked) {
533                 client->state = S_INIT;
534                 state_init();
535                 return;
536         }
537         picked->next = NULL;
538
539         time(&cur_time);
540
541         /* If it was a BOOTREPLY, we can just take the address right now. */
542         if (!picked->options[DHO_DHCP_MESSAGE_TYPE].len) {
543                 client->new = picked;
544
545                 /* Make up some lease expiry times
546                    XXX these should be configurable. */
547                 client->new->expiry = cur_time + 12000;
548                 client->new->renewal += cur_time + 8000;
549                 client->new->rebind += cur_time + 10000;
550
551                 client->state = S_REQUESTING;
552
553                 /* Bind to the address we received. */
554                 bind_lease();
555                 return;
556         }
557
558         /* Go to the REQUESTING state. */
559         client->destination = iaddr_broadcast;
560         client->state = S_REQUESTING;
561         client->first_sending = cur_time;
562         client->interval = 0;
563
564         /* Make a DHCPREQUEST packet from the lease we picked. */
565         make_request(picked);
566         client->xid = client->packet.xid;
567
568         /* Toss the lease we picked - we'll get it back in a DHCPACK. */
569         free_client_lease(picked);
570
571         send_request();
572 }
573
574 void
575 dhcpack(struct iaddr client_addr, struct option_data *options)
576 {
577         struct client_lease *lease;
578         time_t cur_time;
579
580
581         if (client->state != S_REBOOTING &&
582             client->state != S_REQUESTING &&
583             client->state != S_RENEWING &&
584             client->state != S_REBINDING)
585                 return;
586
587
588         lease = packet_to_lease(options);
589         if (!lease) {
590                 note("packet_to_lease failed.");
591                 return;
592         }
593
594         client->new = lease;
595
596         /* Stop resending DHCPREQUEST. */
597         cancel_timeout();
598
599         /* Figure out the lease time. */
600         if (client->new->options[DHO_DHCP_LEASE_TIME].data)
601                 client->new->expiry =
602                     getULong(client->new->options[DHO_DHCP_LEASE_TIME].data);
603         else
604                 client->new->expiry = DEFAULT_LEASE_TIME;
605         /* A number that looks negative here is really just very large,
606            because the lease expiry offset is unsigned. */
607         if (client->new->expiry < 0)
608                 client->new->expiry = TIME_MAX;
609         /* XXX should be fixed by resetting the client state */
610         if (client->new->expiry < 60)
611                 client->new->expiry = 60;
612
613         /* Take the server-provided renewal time if there is one;
614            otherwise figure it out according to the spec. */
615         if (client->new->options[DHO_DHCP_RENEWAL_TIME].len)
616                 client->new->renewal =
617                     getULong(client->new->options[DHO_DHCP_RENEWAL_TIME].data);
618         else
619                 client->new->renewal = client->new->expiry / 2;
620
621         /* Same deal with the rebind time. */
622         if (client->new->options[DHO_DHCP_REBINDING_TIME].len)
623                 client->new->rebind =
624                     getULong(client->new->options[DHO_DHCP_REBINDING_TIME].data);
625         else
626                 client->new->rebind = client->new->renewal +
627                     client->new->renewal / 2 + client->new->renewal / 4;
628
629         time(&cur_time);
630
631         client->new->expiry += cur_time;
632         /* Lease lengths can never be negative. */
633         if (client->new->expiry < cur_time)
634                 client->new->expiry = TIME_MAX;
635         client->new->renewal += cur_time;
636         if (client->new->renewal < cur_time)
637                 client->new->renewal = TIME_MAX;
638         client->new->rebind += cur_time;
639         if (client->new->rebind < cur_time)
640                 client->new->rebind = TIME_MAX;
641
642         bind_lease();
643 }
644
645 void
646 bind_lease(void)
647 {
648         /* Run the client script with the new parameters. */
649         script_init((client->state == S_REQUESTING ? "BOUND" :
650             (client->state == S_RENEWING ? "RENEW" :
651                 (client->state == S_REBOOTING ? "REBOOT" : "REBIND"))));
652         if (client->active && client->state != S_REBOOTING)
653                 script_write_params("old_", client->active);
654         script_write_params("new_", client->new);
655         script_go();
656
657         /* Replace the old active lease with the new one. */
658         if (client->active)
659                 free_client_lease(client->active);
660         client->active = client->new;
661         client->new = NULL;
662
663         /* Write out new leases file. */
664         rewrite_client_leases();
665
666         /* Set timeout to start the renewal process. */
667         set_timeout(client->active->renewal, state_bound);
668
669         note("bound to %s -- renewal in %lld seconds.",
670             piaddr(client->active->address),
671             (long long)(client->active->renewal - time(NULL)));
672         client->state = S_BOUND;
673         go_daemon();
674 }
675
676 /*
677  * state_bound is called when we've successfully bound to a particular
678  * lease, but the renewal time on that lease has expired.   We are
679  * expected to unicast a DHCPREQUEST to the server that gave us our
680  * original lease.
681  */
682 void
683 state_bound(void)
684 {
685         /* T1 has expired. */
686         make_request(client->active);
687         client->xid = client->packet.xid;
688
689         if (client->active->options[DHO_DHCP_SERVER_IDENTIFIER].len == 4) {
690                 memcpy(client->destination.iabuf,
691                     client->active->options[DHO_DHCP_SERVER_IDENTIFIER].data,
692                     4);
693                 client->destination.len = 4;
694         } else
695                 client->destination = iaddr_broadcast;
696
697         client->first_sending = time(NULL);
698         client->interval = 0;
699         client->state = S_RENEWING;
700
701         send_request();
702 }
703
704 void
705 dhcpoffer(struct iaddr client_addr, struct option_data *options)
706 {
707         struct client_lease *lease, *lp;
708         int i;
709         time_t stop_selecting;
710         char *name = options[DHO_DHCP_MESSAGE_TYPE].len ? "DHCPOFFER" :
711             "BOOTREPLY";
712
713
714         if (client->state != S_SELECTING)
715                 return;
716
717
718         /* If this lease doesn't supply the minimum required parameters,
719            blow it off. */
720         for (i = 0; config->required_options[i]; i++) {
721                 if (!options[config->required_options[i]].len) {
722                         note("%s isn't satisfactory.", name);
723                         return;
724                 }
725         }
726
727         /* If we've already seen this lease, don't record it again. */
728         for (lease = client->offered_leases;
729             lease; lease = lease->next) {
730                 if (lease->address.len == sizeof(client->packet.yiaddr) &&
731                     !memcmp(lease->address.iabuf,
732                     &client->packet.yiaddr, lease->address.len)) {
733 #ifdef DEBUG
734                         debug("%s already seen.", name);
735 #endif
736                         return;
737                 }
738         }
739
740         lease = packet_to_lease(options);
741         if (!lease) {
742                 note("packet_to_lease failed.");
743                 return;
744         }
745
746         /*
747          * Reject offers whose subnet is already configured on another
748          * interface.
749          */
750         if (subnet_exists(lease))
751                 return;
752
753         /* If this lease was acquired through a BOOTREPLY, record that
754            fact. */
755         if (!options[DHO_DHCP_MESSAGE_TYPE].len)
756                 lease->is_bootp = 1;
757
758         /* Figure out when we're supposed to stop selecting. */
759         stop_selecting = client->first_sending + config->select_interval;
760
761         /* If this is the lease we asked for, put it at the head of the
762            list, and don't mess with the arp request timeout. */
763         if (addr_eq(lease->address, client->requested_address)) {
764                 lease->next = client->offered_leases;
765                 client->offered_leases = lease;
766         } else {
767                 /* Put the lease at the end of the list. */
768                 lease->next = NULL;
769                 if (!client->offered_leases)
770                         client->offered_leases = lease;
771                 else {
772                         for (lp = client->offered_leases; lp->next;
773                             lp = lp->next)
774                                 ;       /* nothing */
775                         lp->next = lease;
776                 }
777         }
778
779         /* If the selecting interval has expired, go immediately to
780            state_selecting().  Otherwise, time out into
781            state_selecting at the select interval. */
782         if (stop_selecting <= time(NULL))
783                 state_selecting();
784         else {
785                 set_timeout(stop_selecting, state_selecting);
786         }
787 }
788
789 /*
790  * Allocate a client_lease structure and initialize it from the
791  * parameters in the specified packet.
792  */
793 struct client_lease *
794 packet_to_lease(struct option_data *options)
795 {
796         struct client_lease *lease;
797         int i;
798
799         lease = malloc(sizeof(struct client_lease));
800
801         if (!lease) {
802                 warning("dhcpoffer: no memory to record lease.");
803                 return (NULL);
804         }
805
806         memset(lease, 0, sizeof(*lease));
807
808         /* Copy the lease options. */
809         for (i = 0; i < 256; i++) {
810                 if (options[i].len) {
811                         lease->options[i] = options[i];
812                         options[i].data = NULL;
813                         options[i].len = 0;
814                         if (!check_option(lease, i)) {
815                                 warning("Invalid lease option - ignoring offer");
816                                 free_client_lease(lease);
817                                 return (NULL);
818                         }
819                 }
820         }
821
822         lease->address.len = sizeof(client->packet.yiaddr);
823         memcpy(lease->address.iabuf, &client->packet.yiaddr,
824             lease->address.len);
825
826         /* If the server name was filled out, copy it. */
827         if ((!lease->options[DHO_DHCP_OPTION_OVERLOAD].len ||
828             !(lease->options[DHO_DHCP_OPTION_OVERLOAD].data[0] & 2)) &&
829             client->packet.sname[0]) {
830                 lease->server_name = malloc(DHCP_SNAME_LEN + 1);
831                 if (!lease->server_name) {
832                         warning("dhcpoffer: no memory for server name.");
833                         free_client_lease(lease);
834                         return (NULL);
835                 }
836                 memcpy(lease->server_name, client->packet.sname,
837                     DHCP_SNAME_LEN);
838                 lease->server_name[DHCP_SNAME_LEN] = '\0';
839                 if (!res_hnok(lease->server_name)) {
840                         warning("Bogus server name %s", lease->server_name);
841                         free(lease->server_name);
842                         lease->server_name = NULL;
843                 }
844         }
845
846         /* Ditto for the filename. */
847         if ((!lease->options[DHO_DHCP_OPTION_OVERLOAD].len ||
848             !(lease->options[DHO_DHCP_OPTION_OVERLOAD].data[0] & 1)) &&
849             client->packet.file[0]) {
850                 /* Don't count on the NUL terminator. */
851                 lease->filename = malloc(DHCP_FILE_LEN + 1);
852                 if (!lease->filename) {
853                         warning("dhcpoffer: no memory for filename.");
854                         free_client_lease(lease);
855                         return (NULL);
856                 }
857                 memcpy(lease->filename, client->packet.file, DHCP_FILE_LEN);
858                 lease->filename[DHCP_FILE_LEN] = '\0';
859         }
860         return lease;
861 }
862
863 void
864 dhcpnak(struct iaddr client_addr, struct option_data *options)
865 {
866
867         if (client->state != S_REBOOTING &&
868             client->state != S_REQUESTING &&
869             client->state != S_RENEWING &&
870             client->state != S_REBINDING)
871                 return;
872
873
874         if (!client->active) {
875                 note("DHCPNAK with no active lease.");
876                 return;
877         }
878
879         free_client_lease(client->active);
880         client->active = NULL;
881
882         /* Stop sending DHCPREQUEST packets... */
883         cancel_timeout();
884
885         client->state = S_INIT;
886         state_init();
887 }
888
889 /*
890  * Send out a DHCPDISCOVER packet, and set a timeout to send out another
891  * one after the right interval has expired.  If we don't get an offer by
892  * the time we reach the panic interval, call the panic function.
893  */
894 void
895 send_discover(void)
896 {
897         time_t cur_time;
898         int interval, increase = 1;
899
900         time(&cur_time);
901
902         /* Figure out how long it's been since we started transmitting. */
903         interval = cur_time - client->first_sending;
904
905         /* If we're past the panic timeout, call the script and tell it
906            we haven't found anything for this interface yet. */
907         if (interval > config->timeout) {
908                 state_panic();
909                 return;
910         }
911
912         /*
913          * If we're supposed to increase the interval, do so.  If it's
914          * currently zero (i.e., we haven't sent any packets yet), set
915          * it to initial_interval; otherwise, add to it a random
916          * number between zero and two times itself.  On average, this
917          * means that it will double with every transmission.
918          */
919         if (increase) {
920                 if (!client->interval)
921                         client->interval = config->initial_interval;
922                 else {
923                         client->interval += (arc4random() >> 2) %
924                             (2 * client->interval);
925                 }
926
927                 /* Don't backoff past cutoff. */
928                 if (client->interval > config->backoff_cutoff)
929                         client->interval = ((config->backoff_cutoff / 2)
930                                  + ((arc4random() >> 2) %
931                                     config->backoff_cutoff));
932         } else if (!client->interval)
933                 client->interval = config->initial_interval;
934
935         /* If the backoff would take us to the panic timeout, just use that
936            as the interval. */
937         if (cur_time + client->interval >
938             client->first_sending + config->timeout)
939                 client->interval = (client->first_sending +
940                          config->timeout) - cur_time + 1;
941
942         /* Record the number of seconds since we started sending. */
943         if (interval < 65536)
944                 client->packet.secs = htons(interval);
945         else
946                 client->packet.secs = htons(65535);
947         client->secs = client->packet.secs;
948
949         note("DHCPDISCOVER on %s to %s port %d interval %ld",
950             ifi->name, inet_ntoa(sockaddr_broadcast.sin_addr),
951             ntohs(sockaddr_broadcast.sin_port), client->interval);
952
953         send_packet(inaddr_any, &sockaddr_broadcast, NULL);
954
955         set_timeout_interval(client->interval, send_discover);
956 }
957
958 /*
959  * state_panic gets called if we haven't received any offers in a preset
960  * amount of time.   When this happens, we try to use existing leases
961  * that haven't yet expired, and failing that, we call the client script
962  * and hope it can do something.
963  */
964 void
965 state_panic(void)
966 {
967         struct client_lease *loop = client->active;
968         struct client_lease *lp;
969         time_t cur_time;
970
971         note("No DHCPOFFERS received.");
972
973         /* We may not have an active lease, but we may have some
974            predefined leases that we can try. */
975         if (!client->active && client->leases)
976                 goto activate_next;
977
978         /* Run through the list of leases and see if one can be used. */
979         time(&cur_time);
980         while (client->active) {
981                 if (client->active->expiry > cur_time) {
982                         note("Trying recorded lease %s",
983                             piaddr(client->active->address));
984                         /* Run the client script with the existing
985                            parameters. */
986                         script_init("TIMEOUT");
987                         script_write_params("new_", client->active);
988
989                         /* If the old lease is still good and doesn't
990                            yet need renewal, go into BOUND state and
991                            timeout at the renewal time. */
992                         if (!script_go()) {
993                                 if (cur_time < client->active->renewal) {
994                                         client->state = S_BOUND;
995                                         note("bound: renewal in %lld seconds.",
996                                             (long long)(client->active->renewal
997                                             - cur_time));
998                                         set_timeout(client->active->renewal,
999                                             state_bound);
1000                                 } else {
1001                                         client->state = S_BOUND;
1002                                         note("bound: immediate renewal.");
1003                                         state_bound();
1004                                 }
1005                                 go_daemon();
1006                                 return;
1007                         }
1008                 }
1009
1010                 /* If there are no other leases, give up. */
1011                 if (!client->leases) {
1012                         client->leases = client->active;
1013                         client->active = NULL;
1014                         break;
1015                 }
1016
1017 activate_next:
1018                 /* Otherwise, put the active lease at the end of the
1019                    lease list, and try another lease.. */
1020                 for (lp = client->leases; lp->next; lp = lp->next)
1021                         ;
1022                 lp->next = client->active;
1023                 if (lp->next)
1024                         lp->next->next = NULL;
1025                 client->active = client->leases;
1026                 client->leases = client->leases->next;
1027
1028                 /* If we already tried this lease, we've exhausted the
1029                    set of leases, so we might as well give up for
1030                    now. */
1031                 if (client->active == loop)
1032                         break;
1033                 else if (!loop)
1034                         loop = client->active;
1035         }
1036
1037         /* No leases were available, or what was available didn't work, so
1038            tell the shell script that we failed to allocate an address,
1039            and try again later. */
1040         note("No working leases in persistent database - sleeping.");
1041         script_init("FAIL");
1042         script_go();
1043         client->state = S_INIT;
1044         set_timeout_interval(config->retry_interval, state_init);
1045         go_daemon();
1046 }
1047
1048 void
1049 send_request(void)
1050 {
1051         struct sockaddr_in destination;
1052         struct in_addr from;
1053         time_t cur_time;
1054         int interval;
1055
1056         time(&cur_time);
1057
1058         /* Figure out how long it's been since we started transmitting. */
1059         interval = (int)(cur_time - client->first_sending);
1060
1061         /* If we're in the INIT-REBOOT or REQUESTING state and we're
1062            past the reboot timeout, go to INIT and see if we can
1063            DISCOVER an address... */
1064         /* XXX In the INIT-REBOOT state, if we don't get an ACK, it
1065            means either that we're on a network with no DHCP server,
1066            or that our server is down.  In the latter case, assuming
1067            that there is a backup DHCP server, DHCPDISCOVER will get
1068            us a new address, but we could also have successfully
1069            reused our old address.  In the former case, we're hosed
1070            anyway.  This is not a win-prone situation. */
1071         if ((client->state == S_REBOOTING ||
1072             client->state == S_REQUESTING) &&
1073             interval > config->reboot_timeout) {
1074                 client->state = S_INIT;
1075                 cancel_timeout();
1076                 state_init();
1077                 return;
1078         }
1079
1080         /* If the lease has expired, relinquish the address and go back
1081            to the INIT state. */
1082         if (client->state != S_REQUESTING &&
1083             cur_time > client->active->expiry) {
1084                 /* Run the client script with the new parameters. */
1085                 script_init("EXPIRE");
1086                 script_write_params("old_", client->active);
1087                 script_go();
1088
1089                 client->state = S_INIT;
1090                 state_init();
1091                 return;
1092         }
1093
1094         /* Do the exponential backoff... */
1095         if (!client->interval)
1096                 client->interval = config->initial_interval;
1097         else
1098                 client->interval += ((arc4random() >> 2) %
1099                     (2 * client->interval));
1100
1101         /* Don't backoff past cutoff. */
1102         if (client->interval > config->backoff_cutoff)
1103                 client->interval = ((config->backoff_cutoff / 2) +
1104                     ((arc4random() >> 2) % client->interval));
1105
1106         /* If the backoff would take us to the expiry time, just set the
1107            timeout to the expiry time. */
1108         if (client->state != S_REQUESTING && cur_time + client->interval >
1109             client->active->expiry)
1110                 client->interval = client->active->expiry - cur_time + 1;
1111
1112         /* If the lease T2 time has elapsed, or if we're not yet bound,
1113            broadcast the DHCPREQUEST rather than unicasting. */
1114         memset(&destination, 0, sizeof(destination));
1115         if (client->state == S_REQUESTING ||
1116             client->state == S_REBOOTING ||
1117             cur_time > client->active->rebind)
1118                 destination.sin_addr.s_addr = INADDR_BROADCAST;
1119         else
1120                 memcpy(&destination.sin_addr.s_addr, client->destination.iabuf,
1121                     sizeof(destination.sin_addr.s_addr));
1122         destination.sin_port = htons(REMOTE_PORT);
1123         destination.sin_family = AF_INET;
1124         destination.sin_len = sizeof(destination);
1125
1126         if (client->state != S_REQUESTING)
1127                 memcpy(&from, client->active->address.iabuf, sizeof(from));
1128         else
1129                 from.s_addr = INADDR_ANY;
1130
1131         /* Record the number of seconds since we started sending. */
1132         if (client->state == S_REQUESTING)
1133                 client->packet.secs = client->secs;
1134         else {
1135                 if (interval < 65536)
1136                         client->packet.secs = htons(interval);
1137                 else
1138                         client->packet.secs = htons(65535);
1139         }
1140
1141         note("DHCPREQUEST on %s to %s port %d", ifi->name,
1142             inet_ntoa(destination.sin_addr), ntohs(destination.sin_port));
1143
1144         send_packet(from, &destination, NULL);
1145
1146         set_timeout_interval(client->interval, send_request);
1147 }
1148
1149 void
1150 send_decline(void)
1151 {
1152         note("DHCPDECLINE on %s to %s port %d", ifi->name,
1153             inet_ntoa(sockaddr_broadcast.sin_addr),
1154             ntohs(sockaddr_broadcast.sin_port));
1155
1156         send_packet(inaddr_any, &sockaddr_broadcast, NULL);
1157 }
1158
1159 void
1160 make_discover(struct client_lease *lease)
1161 {
1162         unsigned char discover = DHCPDISCOVER;
1163         struct option_data options[256];
1164         int i;
1165
1166         memset(options, 0, sizeof(options));
1167         memset(&client->packet, 0, sizeof(client->packet));
1168
1169         /* Set DHCP_MESSAGE_TYPE to DHCPDISCOVER */
1170         i = DHO_DHCP_MESSAGE_TYPE;
1171         options[i].data = &discover;
1172         options[i].len = sizeof(discover);
1173
1174         /* Request the options we want */
1175         i  = DHO_DHCP_PARAMETER_REQUEST_LIST;
1176         options[i].data = config->requested_options;
1177         options[i].len = config->requested_option_count;
1178
1179         /* If we had an address, try to get it again. */
1180         if (lease) {
1181                 client->requested_address = lease->address;
1182                 i = DHO_DHCP_REQUESTED_ADDRESS;
1183                 options[i].data = lease->address.iabuf;
1184                 options[i].len = lease->address.len;
1185         } else
1186                 client->requested_address.len = 0;
1187
1188         /* Send any options requested in the config file. */
1189         for (i = 0; i < 256; i++)
1190                 if (!options[i].data &&
1191                     config->send_options[i].data) {
1192                         options[i].data = config->send_options[i].data;
1193                         options[i].len = config->send_options[i].len;
1194                 }
1195
1196         /* Set up the option buffer to fit in a minimal UDP packet. */
1197         i = cons_options(options);
1198         if (i == -1 || client->packet.options[i] != DHO_END)
1199                 error("options do not fit in DHCPDISCOVER packet.");
1200         client->packet_length = DHCP_FIXED_NON_UDP+i+1;
1201         if (client->packet_length < BOOTP_MIN_LEN)
1202                 client->packet_length = BOOTP_MIN_LEN;
1203
1204         client->packet.op = BOOTREQUEST;
1205         client->packet.htype = ifi->hw_address.htype;
1206         client->packet.hlen = ifi->hw_address.hlen;
1207         client->packet.hops = 0;
1208         client->packet.xid = arc4random();
1209         client->packet.secs = 0; /* filled in by send_discover. */
1210         client->packet.flags = 0;
1211
1212         memset(&client->packet.ciaddr, 0, sizeof(client->packet.ciaddr));
1213         memset(&client->packet.yiaddr, 0, sizeof(client->packet.yiaddr));
1214         memset(&client->packet.siaddr, 0, sizeof(client->packet.siaddr));
1215         memset(&client->packet.giaddr, 0, sizeof(client->packet.giaddr));
1216         memcpy(client->packet.chaddr, ifi->hw_address.haddr,
1217             ifi->hw_address.hlen);
1218 }
1219
1220 void
1221 make_request(struct client_lease * lease)
1222 {
1223         unsigned char request = DHCPREQUEST;
1224         struct option_data options[256];
1225         int i;
1226
1227         memset(options, 0, sizeof(options));
1228         memset(&client->packet, 0, sizeof(client->packet));
1229
1230         /* Set DHCP_MESSAGE_TYPE to DHCPREQUEST */
1231         i = DHO_DHCP_MESSAGE_TYPE;
1232         options[i].data = &request;
1233         options[i].len = sizeof(request);
1234
1235         /* Request the options we want */
1236         i = DHO_DHCP_PARAMETER_REQUEST_LIST;
1237         options[i].data = config->requested_options;
1238         options[i].len = config->requested_option_count;
1239
1240         /* If we are requesting an address that hasn't yet been assigned
1241            to us, use the DHCP Requested Address option. */
1242         if (client->state == S_REQUESTING) {
1243                 /* Send back the server identifier... */
1244                 i = DHO_DHCP_SERVER_IDENTIFIER;
1245                 options[i].data = lease->options[i].data;
1246                 options[i].len = lease->options[i].len;
1247         }
1248         if (client->state == S_REQUESTING ||
1249             client->state == S_REBOOTING) {
1250                 client->requested_address = lease->address;
1251                 i = DHO_DHCP_REQUESTED_ADDRESS;
1252                 options[i].data = lease->address.iabuf;
1253                 options[i].len = lease->address.len;
1254         } else
1255                 client->requested_address.len = 0;
1256
1257         /* Send any options requested in the config file. */
1258         for (i = 0; i < 256; i++)
1259                 if (!options[i].data && config->send_options[i].data) {
1260                         options[i].data = config->send_options[i].data;
1261                         options[i].len = config->send_options[i].len;
1262                 }
1263
1264         /* Set up the option buffer to fit in a minimal UDP packet. */
1265         i = cons_options(options);
1266         if (i == -1 || client->packet.options[i] != DHO_END)
1267                 error("options do not fit in DHCPREQUEST packet.");
1268         client->packet_length = DHCP_FIXED_NON_UDP+i+1;
1269         if (client->packet_length < BOOTP_MIN_LEN)
1270                 client->packet_length = BOOTP_MIN_LEN;
1271
1272         client->packet.op = BOOTREQUEST;
1273         client->packet.htype = ifi->hw_address.htype;
1274         client->packet.hlen = ifi->hw_address.hlen;
1275         client->packet.hops = 0;
1276         client->packet.xid = client->xid;
1277         client->packet.secs = 0; /* Filled in by send_request. */
1278         client->packet.flags = 0;
1279
1280         /* If we own the address we're requesting, put it in ciaddr;
1281            otherwise set ciaddr to zero. */
1282         if (client->state == S_BOUND ||
1283             client->state == S_RENEWING ||
1284             client->state == S_REBINDING) {
1285                 memcpy(&client->packet.ciaddr,
1286                     lease->address.iabuf, lease->address.len);
1287         } else {
1288                 memset(&client->packet.ciaddr, 0,
1289                     sizeof(client->packet.ciaddr));
1290         }
1291
1292         memset(&client->packet.yiaddr, 0, sizeof(client->packet.yiaddr));
1293         memset(&client->packet.siaddr, 0, sizeof(client->packet.siaddr));
1294         memset(&client->packet.giaddr, 0, sizeof(client->packet.giaddr));
1295         memcpy(client->packet.chaddr, ifi->hw_address.haddr,
1296             ifi->hw_address.hlen);
1297 }
1298
1299 void
1300 make_decline(struct client_lease *lease)
1301 {
1302         struct option_data options[256];
1303         unsigned char decline = DHCPDECLINE;
1304         int i;
1305
1306         memset(options, 0, sizeof(options));
1307         memset(&client->packet, 0, sizeof(client->packet));
1308
1309         /* Set DHCP_MESSAGE_TYPE to DHCPDECLINE */
1310         i = DHO_DHCP_MESSAGE_TYPE;
1311         options[i].data = &decline;
1312         options[i].len = sizeof(decline);
1313
1314         /* Send back the server identifier... */
1315         i = DHO_DHCP_SERVER_IDENTIFIER;
1316         options[i].data = lease->options[i].data;
1317         options[i].len = lease->options[i].len;
1318
1319         /* Send back the address we're declining. */
1320         i = DHO_DHCP_REQUESTED_ADDRESS;
1321         options[i].data = lease->address.iabuf;
1322         options[i].len = lease->address.len;
1323
1324         /* Send the uid if the user supplied one. */
1325         i = DHO_DHCP_CLIENT_IDENTIFIER;
1326         if (config->send_options[i].len) {
1327                 options[i].data = config->send_options[i].data;
1328                 options[i].len = config->send_options[i].len;
1329         }
1330
1331         /* Set up the option buffer to fit in a minimal UDP packet. */
1332         i = cons_options(options);
1333         if (i == -1 || client->packet.options[i] != DHO_END)
1334                 error("options do not fit in DHCPDECLINE packet.");
1335         client->packet_length = DHCP_FIXED_NON_UDP+i+1;
1336         if (client->packet_length < BOOTP_MIN_LEN)
1337                 client->packet_length = BOOTP_MIN_LEN;
1338
1339         client->packet.op = BOOTREQUEST;
1340         client->packet.htype = ifi->hw_address.htype;
1341         client->packet.hlen = ifi->hw_address.hlen;
1342         client->packet.hops = 0;
1343         client->packet.xid = client->xid;
1344         client->packet.secs = 0; /* Filled in by send_request. */
1345         client->packet.flags = 0;
1346
1347         /* ciaddr must always be zero. */
1348         memset(&client->packet.ciaddr, 0, sizeof(client->packet.ciaddr));
1349         memset(&client->packet.yiaddr, 0, sizeof(client->packet.yiaddr));
1350         memset(&client->packet.siaddr, 0, sizeof(client->packet.siaddr));
1351         memset(&client->packet.giaddr, 0, sizeof(client->packet.giaddr));
1352         memcpy(client->packet.chaddr, ifi->hw_address.haddr,
1353             ifi->hw_address.hlen);
1354 }
1355
1356 void
1357 free_client_lease(struct client_lease *lease)
1358 {
1359         int i;
1360
1361         if (lease->server_name)
1362                 free(lease->server_name);
1363         if (lease->filename)
1364                 free(lease->filename);
1365         for (i = 0; i < 256; i++) {
1366                 if (lease->options[i].len)
1367                         free(lease->options[i].data);
1368         }
1369         free(lease);
1370 }
1371
1372 void
1373 rewrite_client_leases(void)
1374 {
1375         struct client_lease *lp;
1376
1377         if (!leaseFile) /* XXX */
1378                 error("lease file not open");
1379
1380         fflush(leaseFile);
1381         rewind(leaseFile);
1382
1383         for (lp = client->leases; lp; lp = lp->next) {
1384                 if (client->active && addr_eq(lp->address,
1385                         client->active->address))
1386                         continue;
1387                 write_client_lease(lp);
1388         }
1389
1390         if (client->active)
1391                 write_client_lease(client->active);
1392
1393         fflush(leaseFile);
1394         ftruncate(fileno(leaseFile), ftello(leaseFile));
1395         fsync(fileno(leaseFile));
1396 }
1397
1398 void
1399 write_client_lease(struct client_lease *lease)
1400 {
1401         struct tm *t;
1402         int i;
1403
1404         /* If the lease came from the config file, we don't need to stash
1405            a copy in the lease database. */
1406         if (lease->is_static)
1407                 return;
1408
1409         if (!leaseFile) /* XXX */
1410                 error("lease file not open");
1411
1412         fprintf(leaseFile, "lease {\n");
1413         if (lease->is_bootp)
1414                 fprintf(leaseFile, "  bootp;\n");
1415         fprintf(leaseFile, "  interface \"%s\";\n", ifi->name);
1416         fprintf(leaseFile, "  fixed-address %s;\n", piaddr(lease->address));
1417         if (lease->filename)
1418                 fprintf(leaseFile, "  filename \"%s\";\n", lease->filename);
1419         if (lease->server_name)
1420                 fprintf(leaseFile, "  server-name \"%s\";\n",
1421                     lease->server_name);
1422         for (i = 0; i < 256; i++)
1423                 if (lease->options[i].len)
1424                         fprintf(leaseFile, "  option %s %s;\n",
1425                             dhcp_options[i].name,
1426                             pretty_print_option(i, lease->options[i].data,
1427                             lease->options[i].len, 1, 1));
1428
1429         t = gmtime(&lease->renewal);
1430         fprintf(leaseFile, "  renew %d %d/%d/%d %02d:%02d:%02d;\n",
1431             t->tm_wday, t->tm_year + 1900, t->tm_mon + 1, t->tm_mday,
1432             t->tm_hour, t->tm_min, t->tm_sec);
1433         t = gmtime(&lease->rebind);
1434         fprintf(leaseFile, "  rebind %d %d/%d/%d %02d:%02d:%02d;\n",
1435             t->tm_wday, t->tm_year + 1900, t->tm_mon + 1, t->tm_mday,
1436             t->tm_hour, t->tm_min, t->tm_sec);
1437         t = gmtime(&lease->expiry);
1438         fprintf(leaseFile, "  expire %d %d/%d/%d %02d:%02d:%02d;\n",
1439             t->tm_wday, t->tm_year + 1900, t->tm_mon + 1, t->tm_mday,
1440             t->tm_hour, t->tm_min, t->tm_sec);
1441         fprintf(leaseFile, "}\n");
1442         fflush(leaseFile);
1443 }
1444
1445 void
1446 script_init(char *reason)
1447 {
1448         size_t           len;
1449         struct imsg_hdr  hdr;
1450         struct buf      *buf;
1451
1452         hdr.code = IMSG_SCRIPT_INIT;
1453         hdr.len = sizeof(struct imsg_hdr) + sizeof(size_t) + strlen(reason);
1454         buf = buf_open(hdr.len);
1455
1456         buf_add(buf, &hdr, sizeof(hdr));
1457         len = strlen(reason);
1458         buf_add(buf, &len, sizeof(len));
1459         buf_add(buf, reason, len);
1460
1461         buf_close(privfd, buf);
1462 }
1463
1464 void
1465 priv_script_init(char *reason)
1466 {
1467         client->scriptEnvsize = 100;
1468         if (client->scriptEnv == NULL)
1469                 client->scriptEnv =
1470                     calloc(client->scriptEnvsize, sizeof(char *));
1471         if (client->scriptEnv == NULL)
1472                 error("script_init: no memory for environment");
1473
1474         client->scriptEnv[0] = strdup(CLIENT_PATH);
1475         if (client->scriptEnv[0] == NULL)
1476                 error("script_init: no memory for environment");
1477
1478         client->scriptEnv[1] = NULL;
1479
1480         script_set_env("", "interface", ifi->name);
1481
1482         script_set_env("", "reason", reason);
1483 }
1484
1485 void
1486 priv_script_write_params(char *prefix, struct client_lease *lease)
1487 {
1488         u_int8_t dbuf[1500];
1489         int i, len = 0;
1490         char tbuf[128];
1491
1492         script_set_env(prefix, "ip_address", piaddr(lease->address));
1493
1494         if (lease->options[DHO_SUBNET_MASK].len &&
1495             (lease->options[DHO_SUBNET_MASK].len <
1496             sizeof(lease->address.iabuf))) {
1497                 struct iaddr netmask, subnet, broadcast;
1498
1499                 memcpy(netmask.iabuf, lease->options[DHO_SUBNET_MASK].data,
1500                     lease->options[DHO_SUBNET_MASK].len);
1501                 netmask.len = lease->options[DHO_SUBNET_MASK].len;
1502
1503                 subnet = subnet_number(lease->address, netmask);
1504                 if (subnet.len) {
1505                         script_set_env(prefix, "network_number",
1506                             piaddr(subnet));
1507                         if (!lease->options[DHO_BROADCAST_ADDRESS].len) {
1508                                 broadcast = broadcast_addr(subnet, netmask);
1509                                 if (broadcast.len)
1510                                         script_set_env(prefix,
1511                                             "broadcast_address",
1512                                             piaddr(broadcast));
1513                         }
1514                 }
1515         }
1516
1517         if (lease->filename)
1518                 script_set_env(prefix, "filename", lease->filename);
1519         if (lease->server_name)
1520                 script_set_env(prefix, "server_name",
1521                     lease->server_name);
1522         for (i = 0; i < 256; i++) {
1523                 u_int8_t *dp = NULL;
1524
1525                 if (config->defaults[i].len) {
1526                         if (lease->options[i].len) {
1527                                 switch (config->default_actions[i]) {
1528                                 case ACTION_IGNORE:
1529                                         /* handled below */
1530                                         break;
1531                                 case ACTION_DEFAULT:
1532                                         dp = lease->options[i].data;
1533                                         len = lease->options[i].len;
1534                                         break;
1535                                 case ACTION_SUPERSEDE:
1536 supersede:
1537                                         dp = config->defaults[i].data;
1538                                         len = config->defaults[i].len;
1539                                         break;
1540                                 case ACTION_PREPEND:
1541                                         len = config->defaults[i].len +
1542                                             lease->options[i].len;
1543                                         if (len >= sizeof(dbuf)) {
1544                                                 warning("no space to %s %s",
1545                                                     "prepend option",
1546                                                     dhcp_options[i].name);
1547                                                 goto supersede;
1548                                         }
1549                                         dp = dbuf;
1550                                         memcpy(dp,
1551                                             config->defaults[i].data,
1552                                             config->defaults[i].len);
1553                                         memcpy(dp +
1554                                             config->defaults[i].len,
1555                                             lease->options[i].data,
1556                                             lease->options[i].len);
1557                                         dp[len] = '\0';
1558                                         break;
1559                                 case ACTION_APPEND:
1560                                         len = config->defaults[i].len +
1561                                             lease->options[i].len;
1562                                         if (len >= sizeof(dbuf)) {
1563                                                 warning("no space to %s %s",
1564                                                     "append option",
1565                                                     dhcp_options[i].name);
1566                                                 goto supersede;
1567                                         }
1568                                         dp = dbuf;
1569                                         memcpy(dp, lease->options[i].data,
1570                                             lease->options[i].len);
1571                                         memcpy(dp + lease->options[i].len,
1572                                             config->defaults[i].data,
1573                                             config->defaults[i].len);
1574                                         dp[len] = '\0';
1575                                 }
1576                         } else {
1577                                 dp = config->defaults[i].data;
1578                                 len = config->defaults[i].len;
1579                         }
1580                 } else if (lease->options[i].len) {
1581                         len = lease->options[i].len;
1582                         dp = lease->options[i].data;
1583                 } else {
1584                         len = 0;
1585                 }
1586                 if (len && config->default_actions[i] == ACTION_IGNORE) {
1587                         len = 0;
1588                 }
1589                 if (len) {
1590                         char name[256];
1591
1592                         if (dhcp_option_ev_name(name, sizeof(name),
1593                             &dhcp_options[i]))
1594                                 script_set_env(prefix, name,
1595                                     pretty_print_option(i, dp, len, 0, 0));
1596                 }
1597         }
1598         snprintf(tbuf, sizeof(tbuf), "%d", (int)lease->expiry);
1599         script_set_env(prefix, "expiry", tbuf);
1600 }
1601
1602 void
1603 script_write_params(char *prefix, struct client_lease *lease)
1604 {
1605         size_t           fn_len = 0, sn_len = 0, pr_len = 0;
1606         struct imsg_hdr  hdr;
1607         struct buf      *buf;
1608         int              i;
1609
1610         if (lease->filename != NULL)
1611                 fn_len = strlen(lease->filename);
1612         if (lease->server_name != NULL)
1613                 sn_len = strlen(lease->server_name);
1614         if (prefix != NULL)
1615                 pr_len = strlen(prefix);
1616
1617         hdr.code = IMSG_SCRIPT_WRITE_PARAMS;
1618         hdr.len = sizeof(hdr) + sizeof(struct client_lease) +
1619             sizeof(size_t) + fn_len + sizeof(size_t) + sn_len +
1620             sizeof(size_t) + pr_len;
1621
1622         for (i = 0; i < 256; i++)
1623                 hdr.len += sizeof(int) + lease->options[i].len;
1624
1625         scripttime = time(NULL);
1626
1627         buf = buf_open(hdr.len);
1628
1629         buf_add(buf, &hdr, sizeof(hdr));
1630         buf_add(buf, lease, sizeof(struct client_lease));
1631         buf_add(buf, &fn_len, sizeof(fn_len));
1632         buf_add(buf, lease->filename, fn_len);
1633         buf_add(buf, &sn_len, sizeof(sn_len));
1634         buf_add(buf, lease->server_name, sn_len);
1635         buf_add(buf, &pr_len, sizeof(pr_len));
1636         buf_add(buf, prefix, pr_len);
1637
1638         for (i = 0; i < 256; i++) {
1639                 buf_add(buf, &lease->options[i].len,
1640                     sizeof(lease->options[i].len));
1641                 buf_add(buf, lease->options[i].data,
1642                     lease->options[i].len);
1643         }
1644
1645         buf_close(privfd, buf);
1646 }
1647
1648 int
1649 script_go(void)
1650 {
1651         struct imsg_hdr  hdr;
1652         struct buf      *buf;
1653         int              ret;
1654
1655         scripttime = time(NULL);
1656
1657         hdr.code = IMSG_SCRIPT_GO;
1658         hdr.len = sizeof(struct imsg_hdr);
1659
1660         buf = buf_open(hdr.len);
1661
1662         buf_add(buf, &hdr, sizeof(hdr));
1663         buf_close(privfd, buf);
1664
1665         bzero(&hdr, sizeof(hdr));
1666         buf_read(privfd, &hdr, sizeof(hdr));
1667         if (hdr.code != IMSG_SCRIPT_GO_RET)
1668                 error("unexpected msg type %u", hdr.code);
1669         if (hdr.len != sizeof(hdr) + sizeof(int))
1670                 error("received corrupted message");
1671         buf_read(privfd, &ret, sizeof(ret));
1672
1673         return (ret);
1674 }
1675
1676 int
1677 priv_script_go(void)
1678 {
1679         char *scriptName, *argv[2], **envp;
1680         int pid, wpid, wstatus;
1681
1682         scripttime = time(NULL);
1683
1684         scriptName = config->script_name;
1685         envp = client->scriptEnv;
1686
1687         argv[0] = scriptName;
1688         argv[1] = NULL;
1689
1690         pid = fork();
1691         if (pid < 0) {
1692                 error("fork: %m");
1693                 wstatus = 0;
1694         } else if (pid) {
1695                 do {
1696                         wpid = wait(&wstatus);
1697                 } while (wpid != pid && wpid > 0);
1698                 if (wpid < 0) {
1699                         error("wait: %m");
1700                         wstatus = 0;
1701                 }
1702         } else {
1703                 execve(scriptName, argv, envp);
1704                 error("execve (%s, ...): %m", scriptName);
1705         }
1706
1707         script_flush_env();
1708
1709         return (WEXITSTATUS(wstatus));
1710 }
1711
1712 void
1713 script_set_env(const char *prefix, const char *name, const char *value)
1714 {
1715         int i, j, namelen;
1716
1717         namelen = strlen(name);
1718
1719         for (i = 0; client->scriptEnv[i]; i++)
1720                 if (strncmp(client->scriptEnv[i], name, namelen) == 0 &&
1721                     client->scriptEnv[i][namelen] == '=')
1722                         break;
1723
1724         if (client->scriptEnv[i])
1725                 /* Reuse the slot. */
1726                 free(client->scriptEnv[i]);
1727         else {
1728                 /* New variable.  Expand if necessary. */
1729                 if (i >= client->scriptEnvsize - 1) {
1730                         char **newscriptEnv;
1731                         int newscriptEnvsize = client->scriptEnvsize + 50;
1732
1733                         newscriptEnv = realloc(client->scriptEnv,
1734                             newscriptEnvsize);
1735                         if (newscriptEnv == NULL) {
1736                                 free(client->scriptEnv);
1737                                 client->scriptEnv = NULL;
1738                                 client->scriptEnvsize = 0;
1739                                 error("script_set_env: no memory for variable");
1740                         }
1741                         client->scriptEnv = newscriptEnv;
1742                         client->scriptEnvsize = newscriptEnvsize;
1743                 }
1744                 /* need to set the NULL pointer at end of array beyond
1745                    the new slot. */
1746                 client->scriptEnv[i + 1] = NULL;
1747         }
1748         /* Allocate space and format the variable in the appropriate slot. */
1749         client->scriptEnv[i] = malloc(strlen(prefix) + strlen(name) + 1 +
1750             strlen(value) + 1);
1751         if (client->scriptEnv[i] == NULL)
1752                 error("script_set_env: no memory for variable assignment");
1753
1754         /* No `` or $() command substitution allowed in environment values! */
1755         for (j = 0; j < strlen(value); j++)
1756                 switch (value[j]) {
1757                 case '`':
1758                 case '$':
1759                         error("illegal character (%c) in value '%s'", value[j],
1760                             value);
1761                         /* not reached */
1762                 }
1763         snprintf(client->scriptEnv[i], strlen(prefix) + strlen(name) +
1764             1 + strlen(value) + 1, "%s%s=%s", prefix, name, value);
1765 }
1766
1767 void
1768 script_flush_env(void)
1769 {
1770         int i;
1771
1772         for (i = 0; client->scriptEnv[i]; i++) {
1773                 free(client->scriptEnv[i]);
1774                 client->scriptEnv[i] = NULL;
1775         }
1776         client->scriptEnvsize = 0;
1777 }
1778
1779 int
1780 dhcp_option_ev_name(char *buf, size_t buflen, const struct option *option)
1781 {
1782         size_t i;
1783
1784         for (i = 0; option->name[i]; i++) {
1785                 if (i + 1 == buflen)
1786                         return 0;
1787                 if (option->name[i] == '-')
1788                         buf[i] = '_';
1789                 else
1790                         buf[i] = option->name[i];
1791         }
1792
1793         buf[i] = 0;
1794         return 1;
1795 }
1796
1797 void
1798 go_daemon(void)
1799 {
1800         static int state = 0;
1801
1802         if (no_daemon || state)
1803                 return;
1804
1805         state = 1;
1806
1807         /* Stop logging to stderr... */
1808         log_perror = 0;
1809
1810         if (daemon(1, 0) == -1)
1811                 error("daemon");
1812
1813         /* we are chrooted, daemon(3) fails to open /dev/null */
1814         if (nullfd != -1) {
1815                 dup2(nullfd, STDIN_FILENO);
1816                 dup2(nullfd, STDOUT_FILENO);
1817                 dup2(nullfd, STDERR_FILENO);
1818                 close(nullfd);
1819                 nullfd = -1;
1820         }
1821 }
1822
1823 int
1824 check_option(struct client_lease *l, int option)
1825 {
1826         char *opbuf;
1827         char *sbuf;
1828
1829         /* we use this, since this is what gets passed to dhclient-script */
1830
1831         opbuf = pretty_print_option(option, l->options[option].data,
1832             l->options[option].len, 0, 0);
1833
1834         sbuf = option_as_string(option, l->options[option].data,
1835             l->options[option].len);
1836
1837         switch (option) {
1838         case DHO_SUBNET_MASK:
1839         case DHO_SWAP_SERVER:
1840         case DHO_BROADCAST_ADDRESS:
1841         case DHO_DHCP_SERVER_IDENTIFIER:
1842         case DHO_ROUTER_SOLICITATION_ADDRESS:
1843         case DHO_DHCP_REQUESTED_ADDRESS:
1844                 if (ipv4addrs(opbuf) == 0) {
1845                         warning("Invalid IP address in option %s: %s",
1846                             dhcp_options[option].name, opbuf);
1847                         return (0);
1848                 }
1849                 if (l->options[option].len != 4) { /* RFC 2132 */
1850                         warning("warning: Only 1 IP address allowed in "
1851                             "%s option; length %d, must be 4",
1852                             dhcp_options[option].name,
1853                             l->options[option].len);
1854                         l->options[option].len = 4;
1855                 }
1856                 return (1);
1857         case DHO_TIME_SERVERS:
1858         case DHO_NAME_SERVERS:
1859         case DHO_ROUTERS:
1860         case DHO_DOMAIN_NAME_SERVERS:
1861         case DHO_LOG_SERVERS:
1862         case DHO_COOKIE_SERVERS:
1863         case DHO_LPR_SERVERS:
1864         case DHO_IMPRESS_SERVERS:
1865         case DHO_RESOURCE_LOCATION_SERVERS:
1866         case DHO_NIS_SERVERS:
1867         case DHO_NTP_SERVERS:
1868         case DHO_NETBIOS_NAME_SERVERS:
1869         case DHO_NETBIOS_DD_SERVER:
1870         case DHO_FONT_SERVERS:
1871                 if (ipv4addrs(opbuf) == 0) {
1872                         warning("Invalid IP address in option %s: %s",
1873                             dhcp_options[option].name, opbuf);
1874                         return (0);
1875                 }
1876                 return (1);
1877         case DHO_HOST_NAME:
1878         case DHO_DOMAIN_NAME:
1879         case DHO_NIS_DOMAIN:
1880                 if (!res_hnok(sbuf)) {
1881                         warning("Bogus Host Name option %d: %s (%s)", option,
1882                             sbuf, opbuf);
1883                         l->options[option].len = 0;
1884                         free(l->options[option].data);
1885                 }
1886                 return (1);
1887         case DHO_PAD:
1888         case DHO_TIME_OFFSET:
1889         case DHO_BOOT_SIZE:
1890         case DHO_MERIT_DUMP:
1891         case DHO_ROOT_PATH:
1892         case DHO_EXTENSIONS_PATH:
1893         case DHO_IP_FORWARDING:
1894         case DHO_NON_LOCAL_SOURCE_ROUTING:
1895         case DHO_POLICY_FILTER:
1896         case DHO_MAX_DGRAM_REASSEMBLY:
1897         case DHO_DEFAULT_IP_TTL:
1898         case DHO_PATH_MTU_AGING_TIMEOUT:
1899         case DHO_PATH_MTU_PLATEAU_TABLE:
1900         case DHO_INTERFACE_MTU:
1901         case DHO_ALL_SUBNETS_LOCAL:
1902         case DHO_PERFORM_MASK_DISCOVERY:
1903         case DHO_MASK_SUPPLIER:
1904         case DHO_ROUTER_DISCOVERY:
1905         case DHO_STATIC_ROUTES:
1906         case DHO_TRAILER_ENCAPSULATION:
1907         case DHO_ARP_CACHE_TIMEOUT:
1908         case DHO_IEEE802_3_ENCAPSULATION:
1909         case DHO_DEFAULT_TCP_TTL:
1910         case DHO_TCP_KEEPALIVE_INTERVAL:
1911         case DHO_TCP_KEEPALIVE_GARBAGE:
1912         case DHO_VENDOR_ENCAPSULATED_OPTIONS:
1913         case DHO_NETBIOS_NODE_TYPE:
1914         case DHO_NETBIOS_SCOPE:
1915         case DHO_X_DISPLAY_MANAGER:
1916         case DHO_DHCP_LEASE_TIME:
1917         case DHO_DHCP_OPTION_OVERLOAD:
1918         case DHO_DHCP_MESSAGE_TYPE:
1919         case DHO_DHCP_PARAMETER_REQUEST_LIST:
1920         case DHO_DHCP_MESSAGE:
1921         case DHO_DHCP_MAX_MESSAGE_SIZE:
1922         case DHO_DHCP_RENEWAL_TIME:
1923         case DHO_DHCP_REBINDING_TIME:
1924         case DHO_DHCP_CLASS_IDENTIFIER:
1925         case DHO_DHCP_CLIENT_IDENTIFIER:
1926         case DHO_DHCP_USER_CLASS_ID:
1927         case DHO_TFTP_SERVER:
1928         case DHO_END:
1929                 return (1);
1930         default:
1931                 if (!unknown_ok)
1932                         warning("unknown dhcp option value 0x%x", option);
1933                 return (unknown_ok);
1934         }
1935 }
1936
1937 int
1938 res_hnok(const char *name)
1939 {
1940         const char *dn = name;
1941         int pch = '.', ch = *dn++;
1942         int warn = 0;
1943
1944         while (ch != '\0') {
1945                 int nch = *dn++;
1946
1947                 if (ch == '.') {
1948                         ;
1949                 } else if (pch == '.' || nch == '.' || nch == '\0') {
1950                         if (!isalnum(ch))
1951                                 return (0);
1952                 } else if (!isalnum(ch) && ch != '-' && ch != '_')
1953                                 return (0);
1954                 else if (ch == '_' && warn == 0) {
1955                         warning("warning: hostname %s contains an "
1956                             "underscore which violates RFC 952", name);
1957                         warn++;
1958                 }
1959                 pch = ch, ch = nch;
1960         }
1961         return (1);
1962 }
1963
1964 /* Does buf consist only of dotted decimal ipv4 addrs?
1965  * return how many if so,
1966  * otherwise, return 0
1967  */
1968 int
1969 ipv4addrs(char * buf)
1970 {
1971         struct in_addr jnk;
1972         int count = 0;
1973
1974         while (inet_aton(buf, &jnk) == 1){
1975                 count++;
1976                 while (*buf == '.' || isdigit(*buf))
1977                         buf++;
1978                 if (*buf == '\0')
1979                         return (count);
1980                 while (*buf ==  ' ')
1981                         buf++;
1982         }
1983         return (0);
1984 }
1985
1986 char *
1987 option_as_string(unsigned int code, unsigned char *data, int len)
1988 {
1989         static char optbuf[32768]; /* XXX */
1990         char *op = optbuf;
1991         int opleft = sizeof(optbuf);
1992         unsigned char *dp = data;
1993
1994         if (code > 255)
1995                 error("option_as_string: bad code %d", code);
1996
1997         for (; dp < data + len; dp++) {
1998                 if (!isascii(*dp) || !isprint(*dp)) {
1999                         if (dp + 1 != data + len || *dp != 0) {
2000                                 size_t oplen;
2001                                 snprintf(op, opleft, "\\%03o", *dp);
2002                                 oplen = strlen(op);
2003                                 op += oplen;
2004                                 opleft -= oplen;
2005                         }
2006                 } else if (*dp == '"' || *dp == '\'' || *dp == '$' ||
2007                     *dp == '`' || *dp == '\\') {
2008                         *op++ = '\\';
2009                         *op++ = *dp;
2010                         opleft -= 2;
2011                 } else {
2012                         *op++ = *dp;
2013                         opleft--;
2014                 }
2015         }
2016         if (opleft < 1)
2017                 goto toobig;
2018         *op = 0;
2019         return optbuf;
2020 toobig:
2021         warning("dhcp option too large");
2022         return "<error>";
2023 }
2024
2025 int
2026 fork_privchld(int fd, int fd2)
2027 {
2028         struct pollfd pfd[1];
2029         int nfds, pfail = 0;
2030
2031         switch (fork()) {
2032         case -1:
2033                 error("cannot fork");
2034                 break;
2035         case 0:
2036                 break;
2037         default:
2038                 return (0);
2039         }
2040
2041         if (chdir("/") == -1)
2042                 error("chdir(\"/\")");
2043
2044         setproctitle("%s [priv]", ifi->name);
2045
2046         dup2(nullfd, STDIN_FILENO);
2047         dup2(nullfd, STDOUT_FILENO);
2048         dup2(nullfd, STDERR_FILENO);
2049         close(nullfd);
2050         close(fd2);
2051
2052         for (;;) {
2053                 pfd[0].fd = fd;
2054                 pfd[0].events = POLLIN;
2055                 if ((nfds = poll(pfd, 1, INFTIM)) == -1)
2056                         if (errno != EINTR)
2057                                 error("poll error");
2058
2059                 /*
2060                  * Handle temporary errors, but bail if they persist.
2061                  */
2062                 if (nfds == 0 || !(pfd[0].revents & POLLIN)) {
2063                         if (pfail > POLL_FAILURES)
2064                                 error("poll failed > %d times", POLL_FAILURES);
2065                         sleep(pfail * POLL_FAILURE_WAIT);
2066                         pfail++;
2067                         continue;
2068                 }
2069
2070                 dispatch_imsg(fd);
2071         }
2072 }
2073
2074 void
2075 get_ifname(char *ifname, char *arg)
2076 {
2077         struct ifgroupreq ifgr;
2078         struct ifg_req *ifg;
2079         int s, len;
2080
2081         if (!strcmp(arg, "egress")) {
2082                 s = socket(AF_INET, SOCK_DGRAM, 0);
2083                 if (s == -1)
2084                         error("socket error");
2085                 bzero(&ifgr, sizeof(ifgr));
2086                 strlcpy(ifgr.ifgr_name, "egress", sizeof(ifgr.ifgr_name));
2087                 if (ioctl(s, SIOCGIFGMEMB, (caddr_t)&ifgr) == -1) {
2088                         if (errno == ENOENT)
2089                                 error("no interface in group egress found");
2090                         error("ioctl SIOCGIFGMEMB: %m");
2091                 }
2092                 len = ifgr.ifgr_len;
2093                 if ((ifgr.ifgr_groups = calloc(1, len)) == NULL)
2094                         error("get_ifname");
2095                 if (ioctl(s, SIOCGIFGMEMB, (caddr_t)&ifgr) == -1)
2096                         error("ioctl SIOCGIFGMEMB: %m");
2097
2098                 arg = NULL;
2099                 for (ifg = ifgr.ifgr_groups;
2100                      ifg && len >= sizeof(struct ifg_req); ifg++) {
2101                         len -= sizeof(struct ifg_req);
2102                         if (arg)
2103                                 error("too many interfaces in group egress");
2104                         arg = ifg->ifgrq_member;
2105                 }
2106
2107                 if (strlcpy(ifi->name, arg, IFNAMSIZ) >= IFNAMSIZ)
2108                         error("Interface name too long: %m");
2109
2110                 free(ifgr.ifgr_groups);
2111                 close(s);
2112         } else if (strlcpy(ifi->name, arg, IFNAMSIZ) >= IFNAMSIZ)
2113                 error("Interface name too long");
2114 }