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