dhclient - Remove cur_time global.
[dragonfly.git] / sbin / dhclient / dhclient.c
1 /*      $OpenBSD: src/sbin/dhclient/dhclient.c,v 1.152 2012/08/26 23:33:29 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                         }
242                 }
243                 break;
244         case RTM_IFANNOUNCE:
245                 ifan = (struct if_announcemsghdr *)rtm;
246                 if (ifan->ifan_what == IFAN_DEPARTURE &&
247                     ifan->ifan_index == ifi->index) {
248                         errmsg = "interface departure";
249                         goto die;
250                 }
251                 break;
252         default:
253                 break;
254         }
255         return;
256
257 die:
258         script_init("FAIL");
259         script_go();
260         error("routehandler: %s", errmsg);
261 }
262
263 int
264 main(int argc, char *argv[])
265 {
266         int      ch, fd, quiet = 0, i = 0, pipe_fd[2];
267         struct passwd *pw;
268
269         /* Initially, log errors to stderr as well as to syslogd. */
270         openlog(getprogname(), LOG_PID | LOG_NDELAY, DHCPD_LOG_FACILITY);
271         setlogmask(LOG_UPTO(LOG_INFO));
272
273         while ((ch = getopt(argc, argv, "c:dl:qu")) != -1)
274                 switch (ch) {
275                 case 'c':
276                         path_dhclient_conf = optarg;
277                         break;
278                 case 'd':
279                         no_daemon = 1;
280                         break;
281                 case 'l':
282                         path_dhclient_db = optarg;
283                         break;
284                 case 'q':
285                         quiet = 1;
286                         break;
287                 case 'u':
288                         unknown_ok = 0;
289                         break;
290                 default:
291                         usage();
292                 }
293
294         argc -= optind;
295         argv += optind;
296
297         if (argc != 1)
298                 usage();
299
300         ifi = calloc(1, sizeof(*ifi));
301         if (ifi == NULL)
302                 error("ifi calloc");
303         client = calloc(1, sizeof(*client));
304         if (client == NULL)
305                 error("client calloc");
306         config = calloc(1, sizeof(*config));
307         if (config == NULL)
308                 error("config calloc");
309
310         get_ifname(ifi->name, argv[0]);
311         if (path_dhclient_db == NULL && asprintf(&path_dhclient_db, "%s.%s",
312             _PATH_DHCLIENT_DB, ifi->name) == -1)
313                 error("asprintf");
314
315         if (quiet)
316                 log_perror = 0;
317
318         tzset();
319
320         memset(&sockaddr_broadcast, 0, sizeof(sockaddr_broadcast));
321         sockaddr_broadcast.sin_family = AF_INET;
322         sockaddr_broadcast.sin_port = htons(REMOTE_PORT);
323         sockaddr_broadcast.sin_addr.s_addr = INADDR_BROADCAST;
324         sockaddr_broadcast.sin_len = sizeof(sockaddr_broadcast);
325         inaddr_any.s_addr = INADDR_ANY;
326
327         read_client_conf();
328
329         if (interface_status(ifi->name) == 0) {
330                 interface_link_forceup(ifi->name);
331                 /* Give it up to 4 seconds of silent grace to find link */
332                 i = -4;
333         } else
334                 i = 0;
335
336         while (!(ifi->linkstat = interface_status(ifi->name))) {
337                 if (i == 0)
338                         fprintf(stderr, "%s: no link ...", ifi->name);
339                 else if (i > 0)
340                         fprintf(stderr, ".");
341                 fflush(stderr);
342                 if (++i > config->link_timeout) {
343                         fprintf(stderr, " sleeping\n");
344                         goto dispatch;
345                 }
346                 sleep(1);
347         }
348         if (i > 0)
349                 fprintf(stderr, " got link\n");
350
351  dispatch:
352         if ((nullfd = open(_PATH_DEVNULL, O_RDWR, 0)) == -1)
353                 error("cannot open %s: %m", _PATH_DEVNULL);
354
355         if ((pw = getpwnam("_dhcp")) == NULL)
356                 error("no such user: _dhcp");
357
358         if (pipe(pipe_fd) == -1)
359                 error("pipe");
360
361         fork_privchld(pipe_fd[0], pipe_fd[1]);
362
363         close(pipe_fd[0]);
364         privfd = pipe_fd[1];
365
366         if ((fd = open(path_dhclient_db, O_RDONLY|O_EXLOCK|O_CREAT, 0)) == -1)
367                 error("can't open and lock %s: %m", path_dhclient_db);
368         read_client_leases();
369         if ((leaseFile = fopen(path_dhclient_db, "w")) == NULL)
370                 error("can't open %s: %m", path_dhclient_db);
371         rewrite_client_leases();
372         close(fd);
373
374         if ((routefd = socket(PF_ROUTE, SOCK_RAW, 0)) == -1)
375                 error("socket(PF_ROUTE, SOCK_RAW): %m");
376
377         /* set up the interface */
378         discover_interface();
379
380         if (chroot(_PATH_VAREMPTY) == -1)
381                 error("chroot");
382         if (chdir("/") == -1)
383                 error("chdir(\"/\")");
384
385         if (setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) == -1)
386                 error("setresgid");
387         if (setgroups(1, &pw->pw_gid) == -1)
388                 error("setgroups");
389         if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) == -1)
390                 error("setresuid");
391
392         endpwent();
393
394         setproctitle("%s", ifi->name);
395
396         if (ifi->linkstat) {
397                 client->state = S_REBOOTING;
398                 state_reboot();
399         } else
400                 go_daemon();
401
402         dispatch();
403
404         /* not reached */
405         return (0);
406 }
407
408 void
409 usage(void)
410 {
411         fprintf(stderr, "usage: %s [-dqu] [-c file] [-l file] interface\n",
412             getprogname());
413         exit(1);
414 }
415
416 /*
417  * Individual States:
418  *
419  * Each routine is called from the dhclient_state_machine() in one of
420  * these conditions:
421  * -> entering INIT state
422  * -> recvpacket_flag == 0: timeout in this state
423  * -> otherwise: received a packet in this state
424  *
425  * Return conditions as handled by dhclient_state_machine():
426  * Returns 1, sendpacket_flag = 1: send packet, reset timer.
427  * Returns 1, sendpacket_flag = 0: just reset the timer (wait for a milestone).
428  * Returns 0: finish the nap which was interrupted for no good reason.
429  *
430  * Several per-interface variables are used to keep track of the process:
431  *   active_lease: the lease that is being used on the interface
432  *                 (null pointer if not configured yet).
433  *   offered_leases: leases corresponding to DHCPOFFER messages that have
434  *                   been sent to us by DHCP servers.
435  *   acked_leases: leases corresponding to DHCPACK messages that have been
436  *                 sent to us by DHCP servers.
437  *   sendpacket: DHCP packet we're trying to send.
438  *   destination: IP address to send sendpacket to
439  * In addition, there are several relevant per-lease variables.
440  *   T1_expiry, T2_expiry, lease_expiry: lease milestones
441  * In the active lease, these control the process of renewing the lease;
442  * In leases on the acked_leases list, this simply determines when we
443  * can no longer legitimately use the lease.
444  */
445 void
446 state_reboot(void)
447 {
448         /* Cancel all timeouts, since a link state change gets us here
449            and can happen anytime. */
450         cancel_timeout();
451
452         /* If we don't remember an active lease, go straight to INIT. */
453         if (!client->active || client->active->is_bootp) {
454                 client->state = S_INIT;
455                 state_init();
456                 return;
457         }
458
459         /* make_request doesn't initialize xid because it normally comes
460            from the DHCPDISCOVER, but we haven't sent a DHCPDISCOVER,
461            so pick an xid now. */
462         client->xid = arc4random();
463
464         /* Make a DHCPREQUEST packet, and set appropriate per-interface
465            flags. */
466         make_request(client->active);
467         client->destination = iaddr_broadcast;
468         client->first_sending = time(NULL);
469         client->interval = 0;
470
471         /* Send out the first DHCPREQUEST packet. */
472         send_request();
473 }
474
475 /*
476  * Called when a lease has completely expired and we've
477  * been unable to renew it.
478  */
479 void
480 state_init(void)
481 {
482         /* Make a DHCPDISCOVER packet, and set appropriate per-interface
483            flags. */
484         make_discover(client->active);
485         client->xid = client->packet.xid;
486         client->destination = iaddr_broadcast;
487         client->state = S_SELECTING;
488         client->first_sending = time(NULL);
489         client->interval = 0;
490
491         /* Add an immediate timeout to cause the first DHCPDISCOVER packet
492            to go out. */
493         send_discover();
494 }
495
496 /*
497  * state_selecting is called when one or more DHCPOFFER packets
498  * have been received and a configurable period of time has passed.
499  */
500 void
501 state_selecting(void)
502 {
503         struct client_lease *lp, *next, *picked;
504         time_t cur_time;
505
506         /* Cancel state_selecting and send_discover timeouts, since either
507            one could have got us here. */
508         cancel_timeout();
509
510         /* We have received one or more DHCPOFFER packets.   Currently,
511            the only criterion by which we judge leases is whether or
512            not we get a response when we arp for them. */
513         picked = NULL;
514         for (lp = client->offered_leases; lp; lp = next) {
515                 next = lp->next;
516
517                 if (!picked) {
518                         picked = lp;
519                 } else {
520                         make_decline(lp);
521                         send_decline();
522                         free_client_lease(lp);
523                 }
524         }
525         client->offered_leases = NULL;
526
527         /* If we just tossed all the leases we were offered, go back
528            to square one. */
529         if (!picked) {
530                 client->state = S_INIT;
531                 state_init();
532                 return;
533         }
534         picked->next = NULL;
535
536         time(&cur_time);
537
538         /* If it was a BOOTREPLY, we can just take the address right now. */
539         if (!picked->options[DHO_DHCP_MESSAGE_TYPE].len) {
540                 client->new = picked;
541
542                 /* Make up some lease expiry times
543                    XXX these should be configurable. */
544                 client->new->expiry = cur_time + 12000;
545                 client->new->renewal += cur_time + 8000;
546                 client->new->rebind += cur_time + 10000;
547
548                 client->state = S_REQUESTING;
549
550                 /* Bind to the address we received. */
551                 bind_lease();
552                 return;
553         }
554
555         /* Go to the REQUESTING state. */
556         client->destination = iaddr_broadcast;
557         client->state = S_REQUESTING;
558         client->first_sending = cur_time;
559         client->interval = 0;
560
561         /* Make a DHCPREQUEST packet from the lease we picked. */
562         make_request(picked);
563         client->xid = client->packet.xid;
564
565         /* Toss the lease we picked - we'll get it back in a DHCPACK. */
566         free_client_lease(picked);
567
568         /* Add an immediate timeout to send the first DHCPREQUEST packet. */
569         send_request();
570 }
571
572 void
573 dhcpack(struct iaddr client_addr, struct option_data *options)
574 {
575         struct client_lease *lease;
576         time_t cur_time;
577
578
579         if (client->state != S_REBOOTING &&
580             client->state != S_REQUESTING &&
581             client->state != S_RENEWING &&
582             client->state != S_REBINDING)
583                 return;
584
585
586         lease = packet_to_lease(options);
587         if (!lease) {
588                 note("packet_to_lease failed.");
589                 return;
590         }
591
592         client->new = lease;
593
594         /* Stop resending DHCPREQUEST. */
595         cancel_timeout();
596
597         /* Figure out the lease time. */
598         if (client->new->options[DHO_DHCP_LEASE_TIME].data)
599                 client->new->expiry =
600                     getULong(client->new->options[DHO_DHCP_LEASE_TIME].data);
601         else
602                 client->new->expiry = DEFAULT_LEASE_TIME;
603         /* A number that looks negative here is really just very large,
604            because the lease expiry offset is unsigned. */
605         if (client->new->expiry < 0)
606                 client->new->expiry = TIME_MAX;
607         /* XXX should be fixed by resetting the client state */
608         if (client->new->expiry < 60)
609                 client->new->expiry = 60;
610
611         /* Take the server-provided renewal time if there is one;
612            otherwise figure it out according to the spec. */
613         if (client->new->options[DHO_DHCP_RENEWAL_TIME].len)
614                 client->new->renewal =
615                     getULong(client->new->options[DHO_DHCP_RENEWAL_TIME].data);
616         else
617                 client->new->renewal = client->new->expiry / 2;
618
619         /* Same deal with the rebind time. */
620         if (client->new->options[DHO_DHCP_REBINDING_TIME].len)
621                 client->new->rebind =
622                     getULong(client->new->options[DHO_DHCP_REBINDING_TIME].data);
623         else
624                 client->new->rebind = client->new->renewal +
625                     client->new->renewal / 2 + client->new->renewal / 4;
626
627         time(&cur_time);
628
629         client->new->expiry += cur_time;
630         /* Lease lengths can never be negative. */
631         if (client->new->expiry < cur_time)
632                 client->new->expiry = TIME_MAX;
633         client->new->renewal += cur_time;
634         if (client->new->renewal < cur_time)
635                 client->new->renewal = TIME_MAX;
636         client->new->rebind += cur_time;
637         if (client->new->rebind < cur_time)
638                 client->new->rebind = TIME_MAX;
639
640         bind_lease();
641 }
642
643 void
644 bind_lease(void)
645 {
646         /* Run the client script with the new parameters. */
647         script_init((client->state == S_REQUESTING ? "BOUND" :
648             (client->state == S_RENEWING ? "RENEW" :
649                 (client->state == S_REBOOTING ? "REBOOT" : "REBIND"))));
650         if (client->active && client->state != S_REBOOTING)
651                 script_write_params("old_", client->active);
652         script_write_params("new_", client->new);
653         script_go();
654
655         /* Replace the old active lease with the new one. */
656         if (client->active)
657                 free_client_lease(client->active);
658         client->active = client->new;
659         client->new = NULL;
660
661         /* Write out new leases file. */
662         rewrite_client_leases();
663
664         /* Set timeout to start the renewal process. */
665         set_timeout(client->active->renewal, state_bound);
666
667         note("bound to %s -- renewal in %lld seconds.",
668             piaddr(client->active->address),
669             (long long)(client->active->renewal - time(NULL)));
670         client->state = S_BOUND;
671         reinitialize_interface();
672         go_daemon();
673 }
674
675 /*
676  * state_bound is called when we've successfully bound to a particular
677  * lease, but the renewal time on that lease has expired.   We are
678  * expected to unicast a DHCPREQUEST to the server that gave us our
679  * original lease.
680  */
681 void
682 state_bound(void)
683 {
684         /* T1 has expired. */
685         make_request(client->active);
686         client->xid = client->packet.xid;
687
688         if (client->active->options[DHO_DHCP_SERVER_IDENTIFIER].len == 4) {
689                 memcpy(client->destination.iabuf,
690                     client->active->options[DHO_DHCP_SERVER_IDENTIFIER].data,
691                     4);
692                 client->destination.len = 4;
693         } else
694                 client->destination = iaddr_broadcast;
695
696         client->first_sending = time(NULL);
697         client->interval = 0;
698         client->state = S_RENEWING;
699
700         /* Send the first packet immediately. */
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         /* If this lease was acquired through a BOOTREPLY, record that
747            fact. */
748         if (!options[DHO_DHCP_MESSAGE_TYPE].len)
749                 lease->is_bootp = 1;
750
751         /* Figure out when we're supposed to stop selecting. */
752         stop_selecting = client->first_sending + config->select_interval;
753
754         /* If this is the lease we asked for, put it at the head of the
755            list, and don't mess with the arp request timeout. */
756         if (addr_eq(lease->address, client->requested_address)) {
757                 lease->next = client->offered_leases;
758                 client->offered_leases = lease;
759         } else {
760                 /* Put the lease at the end of the list. */
761                 lease->next = NULL;
762                 if (!client->offered_leases)
763                         client->offered_leases = lease;
764                 else {
765                         for (lp = client->offered_leases; lp->next;
766                             lp = lp->next)
767                                 ;       /* nothing */
768                         lp->next = lease;
769                 }
770         }
771
772         /* If the selecting interval has expired, go immediately to
773            state_selecting().  Otherwise, time out into
774            state_selecting at the select interval. */
775         if (stop_selecting <= time(NULL))
776                 state_selecting();
777         else {
778                 set_timeout(stop_selecting, state_selecting);
779         }
780 }
781
782 /*
783  * Allocate a client_lease structure and initialize it from the
784  * parameters in the specified packet.
785  */
786 struct client_lease *
787 packet_to_lease(struct option_data *options)
788 {
789         struct client_lease *lease;
790         int i;
791
792         lease = malloc(sizeof(struct client_lease));
793
794         if (!lease) {
795                 warning("dhcpoffer: no memory to record lease.");
796                 return (NULL);
797         }
798
799         memset(lease, 0, sizeof(*lease));
800
801         /* Copy the lease options. */
802         for (i = 0; i < 256; i++) {
803                 if (options[i].len) {
804                         lease->options[i] = options[i];
805                         options[i].data = NULL;
806                         options[i].len = 0;
807                         if (!check_option(lease, i)) {
808                                 warning("Invalid lease option - ignoring offer");
809                                 free_client_lease(lease);
810                                 return (NULL);
811                         }
812                 }
813         }
814
815         lease->address.len = sizeof(client->packet.yiaddr);
816         memcpy(lease->address.iabuf, &client->packet.yiaddr,
817             lease->address.len);
818
819         /* If the server name was filled out, copy it. */
820         if ((!lease->options[DHO_DHCP_OPTION_OVERLOAD].len ||
821             !(lease->options[DHO_DHCP_OPTION_OVERLOAD].data[0] & 2)) &&
822             client->packet.sname[0]) {
823                 lease->server_name = malloc(DHCP_SNAME_LEN + 1);
824                 if (!lease->server_name) {
825                         warning("dhcpoffer: no memory for server name.");
826                         free_client_lease(lease);
827                         return (NULL);
828                 }
829                 memcpy(lease->server_name, client->packet.sname,
830                     DHCP_SNAME_LEN);
831                 lease->server_name[DHCP_SNAME_LEN] = '\0';
832                 if (!res_hnok(lease->server_name)) {
833                         warning("Bogus server name %s", lease->server_name);
834                         free(lease->server_name);
835                         lease->server_name = NULL;
836                 }
837         }
838
839         /* Ditto for the filename. */
840         if ((!lease->options[DHO_DHCP_OPTION_OVERLOAD].len ||
841             !(lease->options[DHO_DHCP_OPTION_OVERLOAD].data[0] & 1)) &&
842             client->packet.file[0]) {
843                 /* Don't count on the NUL terminator. */
844                 lease->filename = malloc(DHCP_FILE_LEN + 1);
845                 if (!lease->filename) {
846                         warning("dhcpoffer: no memory for filename.");
847                         free_client_lease(lease);
848                         return (NULL);
849                 }
850                 memcpy(lease->filename, client->packet.file, DHCP_FILE_LEN);
851                 lease->filename[DHCP_FILE_LEN] = '\0';
852         }
853         return lease;
854 }
855
856 void
857 dhcpnak(struct iaddr client_addr, struct option_data *options)
858 {
859
860         if (client->state != S_REBOOTING &&
861             client->state != S_REQUESTING &&
862             client->state != S_RENEWING &&
863             client->state != S_REBINDING)
864                 return;
865
866
867         if (!client->active) {
868                 note("DHCPNAK with no active lease.");
869                 return;
870         }
871
872         free_client_lease(client->active);
873         client->active = NULL;
874
875         /* Stop sending DHCPREQUEST packets... */
876         cancel_timeout();
877
878         client->state = S_INIT;
879         state_init();
880 }
881
882 /*
883  * Send out a DHCPDISCOVER packet, and set a timeout to send out another
884  * one after the right interval has expired.  If we don't get an offer by
885  * the time we reach the panic interval, call the panic function.
886  */
887 void
888 send_discover(void)
889 {
890         time_t cur_time;
891         int interval, increase = 1;
892
893         time(&cur_time);
894
895         /* Figure out how long it's been since we started transmitting. */
896         interval = cur_time - client->first_sending;
897
898         /* If we're past the panic timeout, call the script and tell it
899            we haven't found anything for this interface yet. */
900         if (interval > config->timeout) {
901                 state_panic();
902                 return;
903         }
904
905         /*
906          * If we're supposed to increase the interval, do so.  If it's
907          * currently zero (i.e., we haven't sent any packets yet), set
908          * it to initial_interval; otherwise, add to it a random
909          * number between zero and two times itself.  On average, this
910          * means that it will double with every transmission.
911          */
912         if (increase) {
913                 if (!client->interval)
914                         client->interval = config->initial_interval;
915                 else {
916                         client->interval += (arc4random() >> 2) %
917                             (2 * client->interval);
918                 }
919
920                 /* Don't backoff past cutoff. */
921                 if (client->interval > config->backoff_cutoff)
922                         client->interval = ((config->backoff_cutoff / 2)
923                                  + ((arc4random() >> 2) %
924                                     config->backoff_cutoff));
925         } else if (!client->interval)
926                 client->interval = config->initial_interval;
927
928         /* If the backoff would take us to the panic timeout, just use that
929            as the interval. */
930         if (cur_time + client->interval >
931             client->first_sending + config->timeout)
932                 client->interval = (client->first_sending +
933                          config->timeout) - cur_time + 1;
934
935         /* Record the number of seconds since we started sending. */
936         if (interval < 65536)
937                 client->packet.secs = htons(interval);
938         else
939                 client->packet.secs = htons(65535);
940         client->secs = client->packet.secs;
941
942         note("DHCPDISCOVER on %s to %s port %d interval %ld",
943             ifi->name, inet_ntoa(sockaddr_broadcast.sin_addr),
944             ntohs(sockaddr_broadcast.sin_port), client->interval);
945
946         /* Send out a packet. */
947         send_packet(inaddr_any, &sockaddr_broadcast, NULL);
948
949         set_timeout_interval(client->interval, send_discover);
950 }
951
952 /*
953  * state_panic gets called if we haven't received any offers in a preset
954  * amount of time.   When this happens, we try to use existing leases
955  * that haven't yet expired, and failing that, we call the client script
956  * and hope it can do something.
957  */
958 void
959 state_panic(void)
960 {
961         struct client_lease *loop = client->active;
962         struct client_lease *lp;
963         time_t cur_time;
964
965         note("No DHCPOFFERS received.");
966
967         /* We may not have an active lease, but we may have some
968            predefined leases that we can try. */
969         if (!client->active && client->leases)
970                 goto activate_next;
971
972         /* Run through the list of leases and see if one can be used. */
973         time(&cur_time);
974         while (client->active) {
975                 if (client->active->expiry > cur_time) {
976                         note("Trying recorded lease %s",
977                             piaddr(client->active->address));
978                         /* Run the client script with the existing
979                            parameters. */
980                         script_init("TIMEOUT");
981                         script_write_params("new_", client->active);
982
983                         /* If the old lease is still good and doesn't
984                            yet need renewal, go into BOUND state and
985                            timeout at the renewal time. */
986                         if (!script_go()) {
987                                 if (cur_time < client->active->renewal) {
988                                         client->state = S_BOUND;
989                                         note("bound: renewal in %lld seconds.",
990                                             (long long)(client->active->renewal
991                                             - cur_time));
992                                         set_timeout(client->active->renewal,
993                                             state_bound);
994                                 } else {
995                                         client->state = S_BOUND;
996                                         note("bound: immediate renewal.");
997                                         state_bound();
998                                 }
999                                 reinitialize_interface();
1000                                 go_daemon();
1001                                 return;
1002                         }
1003                 }
1004
1005                 /* If there are no other leases, give up. */
1006                 if (!client->leases) {
1007                         client->leases = client->active;
1008                         client->active = NULL;
1009                         break;
1010                 }
1011
1012 activate_next:
1013                 /* Otherwise, put the active lease at the end of the
1014                    lease list, and try another lease.. */
1015                 for (lp = client->leases; lp->next; lp = lp->next)
1016                         ;
1017                 lp->next = client->active;
1018                 if (lp->next)
1019                         lp->next->next = NULL;
1020                 client->active = client->leases;
1021                 client->leases = client->leases->next;
1022
1023                 /* If we already tried this lease, we've exhausted the
1024                    set of leases, so we might as well give up for
1025                    now. */
1026                 if (client->active == loop)
1027                         break;
1028                 else if (!loop)
1029                         loop = client->active;
1030         }
1031
1032         /* No leases were available, or what was available didn't work, so
1033            tell the shell script that we failed to allocate an address,
1034            and try again later. */
1035         note("No working leases in persistent database - sleeping.");
1036         script_init("FAIL");
1037         script_go();
1038         client->state = S_INIT;
1039         set_timeout_interval(config->retry_interval, state_init);
1040         go_daemon();
1041 }
1042
1043 void
1044 send_request(void)
1045 {
1046         struct sockaddr_in destination;
1047         struct in_addr from;
1048         time_t cur_time;
1049         int interval;
1050
1051         time(&cur_time);
1052
1053         /* Figure out how long it's been since we started transmitting. */
1054         interval = (int)(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();
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         set_timeout_interval(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_IGNORE:
1526                                         /* handled below */
1527                                         break;
1528                                 case ACTION_DEFAULT:
1529                                         dp = lease->options[i].data;
1530                                         len = lease->options[i].len;
1531                                         break;
1532                                 case ACTION_SUPERSEDE:
1533 supersede:
1534                                         dp = config->defaults[i].data;
1535                                         len = config->defaults[i].len;
1536                                         break;
1537                                 case ACTION_PREPEND:
1538                                         len = config->defaults[i].len +
1539                                             lease->options[i].len;
1540                                         if (len >= sizeof(dbuf)) {
1541                                                 warning("no space to %s %s",
1542                                                     "prepend option",
1543                                                     dhcp_options[i].name);
1544                                                 goto supersede;
1545                                         }
1546                                         dp = dbuf;
1547                                         memcpy(dp,
1548                                             config->defaults[i].data,
1549                                             config->defaults[i].len);
1550                                         memcpy(dp +
1551                                             config->defaults[i].len,
1552                                             lease->options[i].data,
1553                                             lease->options[i].len);
1554                                         dp[len] = '\0';
1555                                         break;
1556                                 case ACTION_APPEND:
1557                                         len = config->defaults[i].len +
1558                                             lease->options[i].len;
1559                                         if (len >= sizeof(dbuf)) {
1560                                                 warning("no space to %s %s",
1561                                                     "append option",
1562                                                     dhcp_options[i].name);
1563                                                 goto supersede;
1564                                         }
1565                                         dp = dbuf;
1566                                         memcpy(dp, lease->options[i].data,
1567                                             lease->options[i].len);
1568                                         memcpy(dp + lease->options[i].len,
1569                                             config->defaults[i].data,
1570                                             config->defaults[i].len);
1571                                         dp[len] = '\0';
1572                                 }
1573                         } else {
1574                                 dp = config->defaults[i].data;
1575                                 len = config->defaults[i].len;
1576                         }
1577                 } else if (lease->options[i].len) {
1578                         len = lease->options[i].len;
1579                         dp = lease->options[i].data;
1580                 } else {
1581                         len = 0;
1582                 }
1583                 if (len && config->default_actions[i] == ACTION_IGNORE) {
1584                         len = 0;
1585                 }
1586                 if (len) {
1587                         char name[256];
1588
1589                         if (dhcp_option_ev_name(name, sizeof(name),
1590                             &dhcp_options[i]))
1591                                 script_set_env(prefix, name,
1592                                     pretty_print_option(i, dp, len, 0, 0));
1593                 }
1594         }
1595         snprintf(tbuf, sizeof(tbuf), "%d", (int)lease->expiry);
1596         script_set_env(prefix, "expiry", tbuf);
1597 }
1598
1599 void
1600 script_write_params(char *prefix, struct client_lease *lease)
1601 {
1602         size_t           fn_len = 0, sn_len = 0, pr_len = 0;
1603         struct imsg_hdr  hdr;
1604         struct buf      *buf;
1605         int              i;
1606
1607         if (lease->filename != NULL)
1608                 fn_len = strlen(lease->filename);
1609         if (lease->server_name != NULL)
1610                 sn_len = strlen(lease->server_name);
1611         if (prefix != NULL)
1612                 pr_len = strlen(prefix);
1613
1614         hdr.code = IMSG_SCRIPT_WRITE_PARAMS;
1615         hdr.len = sizeof(hdr) + sizeof(struct client_lease) +
1616             sizeof(size_t) + fn_len + sizeof(size_t) + sn_len +
1617             sizeof(size_t) + pr_len;
1618
1619         for (i = 0; i < 256; i++)
1620                 hdr.len += sizeof(int) + lease->options[i].len;
1621
1622         scripttime = time(NULL);
1623
1624         buf = buf_open(hdr.len);
1625
1626         buf_add(buf, &hdr, sizeof(hdr));
1627         buf_add(buf, lease, sizeof(struct client_lease));
1628         buf_add(buf, &fn_len, sizeof(fn_len));
1629         buf_add(buf, lease->filename, fn_len);
1630         buf_add(buf, &sn_len, sizeof(sn_len));
1631         buf_add(buf, lease->server_name, sn_len);
1632         buf_add(buf, &pr_len, sizeof(pr_len));
1633         buf_add(buf, prefix, pr_len);
1634
1635         for (i = 0; i < 256; i++) {
1636                 buf_add(buf, &lease->options[i].len,
1637                     sizeof(lease->options[i].len));
1638                 buf_add(buf, lease->options[i].data,
1639                     lease->options[i].len);
1640         }
1641
1642         buf_close(privfd, buf);
1643 }
1644
1645 int
1646 script_go(void)
1647 {
1648         struct imsg_hdr  hdr;
1649         struct buf      *buf;
1650         int              ret;
1651
1652         scripttime = time(NULL);
1653
1654         hdr.code = IMSG_SCRIPT_GO;
1655         hdr.len = sizeof(struct imsg_hdr);
1656
1657         buf = buf_open(hdr.len);
1658
1659         buf_add(buf, &hdr, sizeof(hdr));
1660         buf_close(privfd, buf);
1661
1662         bzero(&hdr, sizeof(hdr));
1663         buf_read(privfd, &hdr, sizeof(hdr));
1664         if (hdr.code != IMSG_SCRIPT_GO_RET)
1665                 error("unexpected msg type %u", hdr.code);
1666         if (hdr.len != sizeof(hdr) + sizeof(int))
1667                 error("received corrupted message");
1668         buf_read(privfd, &ret, sizeof(ret));
1669
1670         return (ret);
1671 }
1672
1673 int
1674 priv_script_go(void)
1675 {
1676         char *scriptName, *argv[2], **envp;
1677         int pid, wpid, wstatus;
1678
1679         scripttime = time(NULL);
1680
1681         scriptName = config->script_name;
1682         envp = client->scriptEnv;
1683
1684         argv[0] = scriptName;
1685         argv[1] = NULL;
1686
1687         pid = fork();
1688         if (pid < 0) {
1689                 error("fork: %m");
1690                 wstatus = 0;
1691         } else if (pid) {
1692                 do {
1693                         wpid = wait(&wstatus);
1694                 } while (wpid != pid && wpid > 0);
1695                 if (wpid < 0) {
1696                         error("wait: %m");
1697                         wstatus = 0;
1698                 }
1699         } else {
1700                 execve(scriptName, argv, envp);
1701                 error("execve (%s, ...): %m", scriptName);
1702         }
1703
1704         script_flush_env();
1705
1706         return (WEXITSTATUS(wstatus));
1707 }
1708
1709 void
1710 script_set_env(const char *prefix, const char *name, const char *value)
1711 {
1712         int i, j, namelen;
1713
1714         namelen = strlen(name);
1715
1716         for (i = 0; client->scriptEnv[i]; i++)
1717                 if (strncmp(client->scriptEnv[i], name, namelen) == 0 &&
1718                     client->scriptEnv[i][namelen] == '=')
1719                         break;
1720
1721         if (client->scriptEnv[i])
1722                 /* Reuse the slot. */
1723                 free(client->scriptEnv[i]);
1724         else {
1725                 /* New variable.  Expand if necessary. */
1726                 if (i >= client->scriptEnvsize - 1) {
1727                         char **newscriptEnv;
1728                         int newscriptEnvsize = client->scriptEnvsize + 50;
1729
1730                         newscriptEnv = realloc(client->scriptEnv,
1731                             newscriptEnvsize);
1732                         if (newscriptEnv == NULL) {
1733                                 free(client->scriptEnv);
1734                                 client->scriptEnv = NULL;
1735                                 client->scriptEnvsize = 0;
1736                                 error("script_set_env: no memory for variable");
1737                         }
1738                         client->scriptEnv = newscriptEnv;
1739                         client->scriptEnvsize = newscriptEnvsize;
1740                 }
1741                 /* need to set the NULL pointer at end of array beyond
1742                    the new slot. */
1743                 client->scriptEnv[i + 1] = NULL;
1744         }
1745         /* Allocate space and format the variable in the appropriate slot. */
1746         client->scriptEnv[i] = malloc(strlen(prefix) + strlen(name) + 1 +
1747             strlen(value) + 1);
1748         if (client->scriptEnv[i] == NULL)
1749                 error("script_set_env: no memory for variable assignment");
1750
1751         /* No `` or $() command substitution allowed in environment values! */
1752         for (j = 0; j < strlen(value); j++)
1753                 switch (value[j]) {
1754                 case '`':
1755                 case '$':
1756                         error("illegal character (%c) in value '%s'", value[j],
1757                             value);
1758                         /* not reached */
1759                 }
1760         snprintf(client->scriptEnv[i], strlen(prefix) + strlen(name) +
1761             1 + strlen(value) + 1, "%s%s=%s", prefix, name, value);
1762 }
1763
1764 void
1765 script_flush_env(void)
1766 {
1767         int i;
1768
1769         for (i = 0; client->scriptEnv[i]; i++) {
1770                 free(client->scriptEnv[i]);
1771                 client->scriptEnv[i] = NULL;
1772         }
1773         client->scriptEnvsize = 0;
1774 }
1775
1776 int
1777 dhcp_option_ev_name(char *buf, size_t buflen, const struct option *option)
1778 {
1779         size_t i;
1780
1781         for (i = 0; option->name[i]; i++) {
1782                 if (i + 1 == buflen)
1783                         return 0;
1784                 if (option->name[i] == '-')
1785                         buf[i] = '_';
1786                 else
1787                         buf[i] = option->name[i];
1788         }
1789
1790         buf[i] = 0;
1791         return 1;
1792 }
1793
1794 void
1795 go_daemon(void)
1796 {
1797         static int state = 0;
1798
1799         if (no_daemon || state)
1800                 return;
1801
1802         state = 1;
1803
1804         /* Stop logging to stderr... */
1805         log_perror = 0;
1806
1807         if (daemon(1, 0) == -1)
1808                 error("daemon");
1809
1810         /* we are chrooted, daemon(3) fails to open /dev/null */
1811         if (nullfd != -1) {
1812                 dup2(nullfd, STDIN_FILENO);
1813                 dup2(nullfd, STDOUT_FILENO);
1814                 dup2(nullfd, STDERR_FILENO);
1815                 close(nullfd);
1816                 nullfd = -1;
1817         }
1818 }
1819
1820 int
1821 check_option(struct client_lease *l, int option)
1822 {
1823         char *opbuf;
1824         char *sbuf;
1825
1826         /* we use this, since this is what gets passed to dhclient-script */
1827
1828         opbuf = pretty_print_option(option, l->options[option].data,
1829             l->options[option].len, 0, 0);
1830
1831         sbuf = option_as_string(option, l->options[option].data,
1832             l->options[option].len);
1833
1834         switch (option) {
1835         case DHO_SUBNET_MASK:
1836         case DHO_SWAP_SERVER:
1837         case DHO_BROADCAST_ADDRESS:
1838         case DHO_DHCP_SERVER_IDENTIFIER:
1839         case DHO_ROUTER_SOLICITATION_ADDRESS:
1840         case DHO_DHCP_REQUESTED_ADDRESS:
1841                 if (ipv4addrs(opbuf) == 0) {
1842                         warning("Invalid IP address in option %s: %s",
1843                             dhcp_options[option].name, opbuf);
1844                         return (0);
1845                 }
1846                 if (l->options[option].len != 4) { /* RFC 2132 */
1847                         warning("warning: Only 1 IP address allowed in "
1848                             "%s option; length %d, must be 4",
1849                             dhcp_options[option].name,
1850                             l->options[option].len);
1851                         l->options[option].len = 4;
1852                 }
1853                 return (1);
1854         case DHO_TIME_SERVERS:
1855         case DHO_NAME_SERVERS:
1856         case DHO_ROUTERS:
1857         case DHO_DOMAIN_NAME_SERVERS:
1858         case DHO_LOG_SERVERS:
1859         case DHO_COOKIE_SERVERS:
1860         case DHO_LPR_SERVERS:
1861         case DHO_IMPRESS_SERVERS:
1862         case DHO_RESOURCE_LOCATION_SERVERS:
1863         case DHO_NIS_SERVERS:
1864         case DHO_NTP_SERVERS:
1865         case DHO_NETBIOS_NAME_SERVERS:
1866         case DHO_NETBIOS_DD_SERVER:
1867         case DHO_FONT_SERVERS:
1868                 if (ipv4addrs(opbuf) == 0) {
1869                         warning("Invalid IP address in option %s: %s",
1870                             dhcp_options[option].name, opbuf);
1871                         return (0);
1872                 }
1873                 return (1);
1874         case DHO_HOST_NAME:
1875         case DHO_DOMAIN_NAME:
1876         case DHO_NIS_DOMAIN:
1877                 if (!res_hnok(sbuf)) {
1878                         warning("Bogus Host Name option %d: %s (%s)", option,
1879                             sbuf, opbuf);
1880                         l->options[option].len = 0;
1881                         free(l->options[option].data);
1882                 }
1883                 return (1);
1884         case DHO_PAD:
1885         case DHO_TIME_OFFSET:
1886         case DHO_BOOT_SIZE:
1887         case DHO_MERIT_DUMP:
1888         case DHO_ROOT_PATH:
1889         case DHO_EXTENSIONS_PATH:
1890         case DHO_IP_FORWARDING:
1891         case DHO_NON_LOCAL_SOURCE_ROUTING:
1892         case DHO_POLICY_FILTER:
1893         case DHO_MAX_DGRAM_REASSEMBLY:
1894         case DHO_DEFAULT_IP_TTL:
1895         case DHO_PATH_MTU_AGING_TIMEOUT:
1896         case DHO_PATH_MTU_PLATEAU_TABLE:
1897         case DHO_INTERFACE_MTU:
1898         case DHO_ALL_SUBNETS_LOCAL:
1899         case DHO_PERFORM_MASK_DISCOVERY:
1900         case DHO_MASK_SUPPLIER:
1901         case DHO_ROUTER_DISCOVERY:
1902         case DHO_STATIC_ROUTES:
1903         case DHO_TRAILER_ENCAPSULATION:
1904         case DHO_ARP_CACHE_TIMEOUT:
1905         case DHO_IEEE802_3_ENCAPSULATION:
1906         case DHO_DEFAULT_TCP_TTL:
1907         case DHO_TCP_KEEPALIVE_INTERVAL:
1908         case DHO_TCP_KEEPALIVE_GARBAGE:
1909         case DHO_VENDOR_ENCAPSULATED_OPTIONS:
1910         case DHO_NETBIOS_NODE_TYPE:
1911         case DHO_NETBIOS_SCOPE:
1912         case DHO_X_DISPLAY_MANAGER:
1913         case DHO_DHCP_LEASE_TIME:
1914         case DHO_DHCP_OPTION_OVERLOAD:
1915         case DHO_DHCP_MESSAGE_TYPE:
1916         case DHO_DHCP_PARAMETER_REQUEST_LIST:
1917         case DHO_DHCP_MESSAGE:
1918         case DHO_DHCP_MAX_MESSAGE_SIZE:
1919         case DHO_DHCP_RENEWAL_TIME:
1920         case DHO_DHCP_REBINDING_TIME:
1921         case DHO_DHCP_CLASS_IDENTIFIER:
1922         case DHO_DHCP_CLIENT_IDENTIFIER:
1923         case DHO_DHCP_USER_CLASS_ID:
1924         case DHO_TFTP_SERVER:
1925         case DHO_END:
1926                 return (1);
1927         default:
1928                 if (!unknown_ok)
1929                         warning("unknown dhcp option value 0x%x", option);
1930                 return (unknown_ok);
1931         }
1932 }
1933
1934 int
1935 res_hnok(const char *name)
1936 {
1937         const char *dn = name;
1938         int pch = '.', ch = *dn++;
1939         int warn = 0;
1940
1941         while (ch != '\0') {
1942                 int nch = *dn++;
1943
1944                 if (ch == '.') {
1945                         ;
1946                 } else if (pch == '.' || nch == '.' || nch == '\0') {
1947                         if (!isalnum(ch))
1948                                 return (0);
1949                 } else if (!isalnum(ch) && ch != '-' && ch != '_')
1950                                 return (0);
1951                 else if (ch == '_' && warn == 0) {
1952                         warning("warning: hostname %s contains an "
1953                             "underscore which violates RFC 952", name);
1954                         warn++;
1955                 }
1956                 pch = ch, ch = nch;
1957         }
1958         return (1);
1959 }
1960
1961 /* Does buf consist only of dotted decimal ipv4 addrs?
1962  * return how many if so,
1963  * otherwise, return 0
1964  */
1965 int
1966 ipv4addrs(char * buf)
1967 {
1968         struct in_addr jnk;
1969         int count = 0;
1970
1971         while (inet_aton(buf, &jnk) == 1){
1972                 count++;
1973                 while (*buf == '.' || isdigit(*buf))
1974                         buf++;
1975                 if (*buf == '\0')
1976                         return (count);
1977                 while (*buf ==  ' ')
1978                         buf++;
1979         }
1980         return (0);
1981 }
1982
1983 char *
1984 option_as_string(unsigned int code, unsigned char *data, int len)
1985 {
1986         static char optbuf[32768]; /* XXX */
1987         char *op = optbuf;
1988         int opleft = sizeof(optbuf);
1989         unsigned char *dp = data;
1990
1991         if (code > 255)
1992                 error("option_as_string: bad code %d", code);
1993
1994         for (; dp < data + len; dp++) {
1995                 if (!isascii(*dp) || !isprint(*dp)) {
1996                         if (dp + 1 != data + len || *dp != 0) {
1997                                 size_t oplen;
1998                                 snprintf(op, opleft, "\\%03o", *dp);
1999                                 oplen = strlen(op);
2000                                 op += oplen;
2001                                 opleft -= oplen;
2002                         }
2003                 } else if (*dp == '"' || *dp == '\'' || *dp == '$' ||
2004                     *dp == '`' || *dp == '\\') {
2005                         *op++ = '\\';
2006                         *op++ = *dp;
2007                         opleft -= 2;
2008                 } else {
2009                         *op++ = *dp;
2010                         opleft--;
2011                 }
2012         }
2013         if (opleft < 1)
2014                 goto toobig;
2015         *op = 0;
2016         return optbuf;
2017 toobig:
2018         warning("dhcp option too large");
2019         return "<error>";
2020 }
2021
2022 int
2023 fork_privchld(int fd, int fd2)
2024 {
2025         struct pollfd pfd[1];
2026         int nfds, pfail = 0;
2027
2028         switch (fork()) {
2029         case -1:
2030                 error("cannot fork");
2031                 break;
2032         case 0:
2033                 break;
2034         default:
2035                 return (0);
2036         }
2037
2038         if (chdir("/") == -1)
2039                 error("chdir(\"/\")");
2040
2041         setproctitle("%s [priv]", ifi->name);
2042
2043         dup2(nullfd, STDIN_FILENO);
2044         dup2(nullfd, STDOUT_FILENO);
2045         dup2(nullfd, STDERR_FILENO);
2046         close(nullfd);
2047         close(fd2);
2048
2049         for (;;) {
2050                 pfd[0].fd = fd;
2051                 pfd[0].events = POLLIN;
2052                 if ((nfds = poll(pfd, 1, INFTIM)) == -1)
2053                         if (errno != EINTR)
2054                                 error("poll error");
2055
2056                 /*
2057                  * Handle temporary errors, but bail if they persist.
2058                  */
2059                 if (nfds == 0 || !(pfd[0].revents & POLLIN)) {
2060                         if (pfail > POLL_FAILURES)
2061                                 error("poll failed > %d times", POLL_FAILURES);
2062                         sleep(pfail * POLL_FAILURE_WAIT);
2063                         pfail++;
2064                         continue;
2065                 }
2066
2067                 dispatch_imsg(fd);
2068         }
2069 }
2070
2071 void
2072 get_ifname(char *ifname, char *arg)
2073 {
2074         struct ifgroupreq ifgr;
2075         struct ifg_req *ifg;
2076         int s, len;
2077
2078         if (!strcmp(arg, "egress")) {
2079                 s = socket(AF_INET, SOCK_DGRAM, 0);
2080                 if (s == -1)
2081                         error("socket error");
2082                 bzero(&ifgr, sizeof(ifgr));
2083                 strlcpy(ifgr.ifgr_name, "egress", sizeof(ifgr.ifgr_name));
2084                 if (ioctl(s, SIOCGIFGMEMB, (caddr_t)&ifgr) == -1) {
2085                         if (errno == ENOENT)
2086                                 error("no interface in group egress found");
2087                         error("ioctl SIOCGIFGMEMB: %m");
2088                 }
2089                 len = ifgr.ifgr_len;
2090                 if ((ifgr.ifgr_groups = calloc(1, len)) == NULL)
2091                         error("get_ifname");
2092                 if (ioctl(s, SIOCGIFGMEMB, (caddr_t)&ifgr) == -1)
2093                         error("ioctl SIOCGIFGMEMB: %m");
2094
2095                 arg = NULL;
2096                 for (ifg = ifgr.ifgr_groups;
2097                      ifg && len >= sizeof(struct ifg_req); ifg++) {
2098                         len -= sizeof(struct ifg_req);
2099                         if (arg)
2100                                 error("too many interfaces in group egress");
2101                         arg = ifg->ifgrq_member;
2102                 }
2103
2104                 if (strlcpy(ifi->name, arg, IFNAMSIZ) >= IFNAMSIZ)
2105                         error("Interface name too long: %m");
2106
2107                 free(ifgr.ifgr_groups);
2108                 close(s);
2109         } else if (strlcpy(ifi->name, arg, IFNAMSIZ) >= IFNAMSIZ)
2110                 error("Interface name too long");
2111 }