f9c3a4d1cf73ab5328d72fb88bb11ca48cd3b7cc
[dragonfly.git] / sbin / dhclient / dhclient.c
1 /*      $OpenBSD: src/sbin/dhclient/dhclient.c,v 1.158 2012/10/27 23:08:53 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_request();
472 }
473
474 /*
475  * Called when a lease has completely expired and we've
476  * been unable to renew it.
477  */
478 void
479 state_init(void)
480 {
481         /* Make a DHCPDISCOVER packet, and set appropriate per-interface
482            flags. */
483         make_discover(client->active);
484         client->xid = client->packet.xid;
485         client->destination = iaddr_broadcast;
486         client->state = S_SELECTING;
487         client->first_sending = time(NULL);
488         client->interval = 0;
489
490         send_discover();
491 }
492
493 /*
494  * state_selecting is called when one or more DHCPOFFER packets
495  * have been received and a configurable period of time has passed.
496  */
497 void
498 state_selecting(void)
499 {
500         struct client_lease *lp, *next, *picked;
501         time_t cur_time;
502
503         /* Cancel state_selecting and send_discover timeouts, since either
504            one could have got us here. */
505         cancel_timeout();
506
507         /* We have received one or more DHCPOFFER packets.   Currently,
508            the only criterion by which we judge leases is whether or
509            not we get a response when we arp for them. */
510         picked = NULL;
511         for (lp = client->offered_leases; lp; lp = next) {
512                 next = lp->next;
513
514                 if (!picked) {
515                         picked = lp;
516                 } else {
517                         make_decline(lp);
518                         send_decline();
519                         free_client_lease(lp);
520                 }
521         }
522         client->offered_leases = NULL;
523
524         /* If we just tossed all the leases we were offered, go back
525            to square one. */
526         if (!picked) {
527                 client->state = S_INIT;
528                 state_init();
529                 return;
530         }
531         picked->next = NULL;
532
533         time(&cur_time);
534
535         /* If it was a BOOTREPLY, we can just take the address right now. */
536         if (!picked->options[DHO_DHCP_MESSAGE_TYPE].len) {
537                 client->new = picked;
538
539                 /* Make up some lease expiry times
540                    XXX these should be configurable. */
541                 client->new->expiry = cur_time + 12000;
542                 client->new->renewal += cur_time + 8000;
543                 client->new->rebind += cur_time + 10000;
544
545                 client->state = S_REQUESTING;
546
547                 /* Bind to the address we received. */
548                 bind_lease();
549                 return;
550         }
551
552         /* Go to the REQUESTING state. */
553         client->destination = iaddr_broadcast;
554         client->state = S_REQUESTING;
555         client->first_sending = cur_time;
556         client->interval = 0;
557
558         /* Make a DHCPREQUEST packet from the lease we picked. */
559         make_request(picked);
560         client->xid = client->packet.xid;
561
562         /* Toss the lease we picked - we'll get it back in a DHCPACK. */
563         free_client_lease(picked);
564
565         send_request();
566 }
567
568 void
569 dhcpack(struct iaddr client_addr, struct option_data *options)
570 {
571         struct client_lease *lease;
572         time_t cur_time;
573
574
575         if (client->state != S_REBOOTING &&
576             client->state != S_REQUESTING &&
577             client->state != S_RENEWING &&
578             client->state != S_REBINDING)
579                 return;
580
581
582         lease = packet_to_lease(options);
583         if (!lease) {
584                 note("packet_to_lease failed.");
585                 return;
586         }
587
588         client->new = lease;
589
590         /* Stop resending DHCPREQUEST. */
591         cancel_timeout();
592
593         /* Figure out the lease time. */
594         if (client->new->options[DHO_DHCP_LEASE_TIME].data)
595                 client->new->expiry =
596                     getULong(client->new->options[DHO_DHCP_LEASE_TIME].data);
597         else
598                 client->new->expiry = DEFAULT_LEASE_TIME;
599         /* A number that looks negative here is really just very large,
600            because the lease expiry offset is unsigned. */
601         if (client->new->expiry < 0)
602                 client->new->expiry = TIME_MAX;
603         /* XXX should be fixed by resetting the client state */
604         if (client->new->expiry < 60)
605                 client->new->expiry = 60;
606
607         /* Take the server-provided renewal time if there is one;
608            otherwise figure it out according to the spec. */
609         if (client->new->options[DHO_DHCP_RENEWAL_TIME].len)
610                 client->new->renewal =
611                     getULong(client->new->options[DHO_DHCP_RENEWAL_TIME].data);
612         else
613                 client->new->renewal = client->new->expiry / 2;
614
615         /* Same deal with the rebind time. */
616         if (client->new->options[DHO_DHCP_REBINDING_TIME].len)
617                 client->new->rebind =
618                     getULong(client->new->options[DHO_DHCP_REBINDING_TIME].data);
619         else
620                 client->new->rebind = client->new->renewal +
621                     client->new->renewal / 2 + client->new->renewal / 4;
622
623         time(&cur_time);
624
625         client->new->expiry += cur_time;
626         /* Lease lengths can never be negative. */
627         if (client->new->expiry < cur_time)
628                 client->new->expiry = TIME_MAX;
629         client->new->renewal += cur_time;
630         if (client->new->renewal < cur_time)
631                 client->new->renewal = TIME_MAX;
632         client->new->rebind += cur_time;
633         if (client->new->rebind < cur_time)
634                 client->new->rebind = TIME_MAX;
635
636         bind_lease();
637 }
638
639 void
640 bind_lease(void)
641 {
642         /* Run the client script with the new parameters. */
643         script_init((client->state == S_REQUESTING ? "BOUND" :
644             (client->state == S_RENEWING ? "RENEW" :
645                 (client->state == S_REBOOTING ? "REBOOT" : "REBIND"))));
646         if (client->active && client->state != S_REBOOTING)
647                 script_write_params("old_", client->active);
648         script_write_params("new_", client->new);
649         script_go();
650
651         /* Replace the old active lease with the new one. */
652         if (client->active)
653                 free_client_lease(client->active);
654         client->active = client->new;
655         client->new = NULL;
656
657         /* Write out new leases file. */
658         rewrite_client_leases();
659
660         /* Set timeout to start the renewal process. */
661         set_timeout(client->active->renewal, state_bound);
662
663         note("bound to %s -- renewal in %lld seconds.",
664             piaddr(client->active->address),
665             (long long)(client->active->renewal - time(NULL)));
666         client->state = S_BOUND;
667         go_daemon();
668 }
669
670 /*
671  * state_bound is called when we've successfully bound to a particular
672  * lease, but the renewal time on that lease has expired.   We are
673  * expected to unicast a DHCPREQUEST to the server that gave us our
674  * original lease.
675  */
676 void
677 state_bound(void)
678 {
679         /* T1 has expired. */
680         make_request(client->active);
681         client->xid = client->packet.xid;
682
683         if (client->active->options[DHO_DHCP_SERVER_IDENTIFIER].len == 4) {
684                 memcpy(client->destination.iabuf,
685                     client->active->options[DHO_DHCP_SERVER_IDENTIFIER].data,
686                     4);
687                 client->destination.len = 4;
688         } else
689                 client->destination = iaddr_broadcast;
690
691         client->first_sending = time(NULL);
692         client->interval = 0;
693         client->state = S_RENEWING;
694
695         send_request();
696 }
697
698 void
699 dhcpoffer(struct iaddr client_addr, struct option_data *options)
700 {
701         struct client_lease *lease, *lp;
702         int i;
703         time_t stop_selecting;
704         char *name = options[DHO_DHCP_MESSAGE_TYPE].len ? "DHCPOFFER" :
705             "BOOTREPLY";
706
707
708         if (client->state != S_SELECTING)
709                 return;
710
711
712         /* If this lease doesn't supply the minimum required parameters,
713            blow it off. */
714         for (i = 0; config->required_options[i]; i++) {
715                 if (!options[config->required_options[i]].len) {
716                         note("%s isn't satisfactory.", name);
717                         return;
718                 }
719         }
720
721         /* If we've already seen this lease, don't record it again. */
722         for (lease = client->offered_leases;
723             lease; lease = lease->next) {
724                 if (lease->address.len == sizeof(client->packet.yiaddr) &&
725                     !memcmp(lease->address.iabuf,
726                     &client->packet.yiaddr, lease->address.len)) {
727 #ifdef DEBUG
728                         debug("%s already seen.", name);
729 #endif
730                         return;
731                 }
732         }
733
734         lease = packet_to_lease(options);
735         if (!lease) {
736                 note("packet_to_lease failed.");
737                 return;
738         }
739
740         /*
741          * Reject offers whose subnet is already configured on another
742          * interface.
743          */
744         if (subnet_exists(lease))
745                 return;
746
747         /* If this lease was acquired through a BOOTREPLY, record that
748            fact. */
749         if (!options[DHO_DHCP_MESSAGE_TYPE].len)
750                 lease->is_bootp = 1;
751
752         /* Figure out when we're supposed to stop selecting. */
753         stop_selecting = client->first_sending + config->select_interval;
754
755         /* If this is the lease we asked for, put it at the head of the
756            list, and don't mess with the arp request timeout. */
757         if (addr_eq(lease->address, client->requested_address)) {
758                 lease->next = client->offered_leases;
759                 client->offered_leases = lease;
760         } else {
761                 /* Put the lease at the end of the list. */
762                 lease->next = NULL;
763                 if (!client->offered_leases)
764                         client->offered_leases = lease;
765                 else {
766                         for (lp = client->offered_leases; lp->next;
767                             lp = lp->next)
768                                 ;       /* nothing */
769                         lp->next = lease;
770                 }
771         }
772
773         /* If the selecting interval has expired, go immediately to
774            state_selecting().  Otherwise, time out into
775            state_selecting at the select interval. */
776         if (stop_selecting <= time(NULL))
777                 state_selecting();
778         else {
779                 set_timeout(stop_selecting, state_selecting);
780         }
781 }
782
783 /*
784  * Allocate a client_lease structure and initialize it from the
785  * parameters in the specified packet.
786  */
787 struct client_lease *
788 packet_to_lease(struct option_data *options)
789 {
790         struct client_lease *lease;
791         int i;
792
793         lease = malloc(sizeof(struct client_lease));
794
795         if (!lease) {
796                 warning("dhcpoffer: no memory to record lease.");
797                 return (NULL);
798         }
799
800         memset(lease, 0, sizeof(*lease));
801
802         /* Copy the lease options. */
803         for (i = 0; i < 256; i++) {
804                 if (options[i].len) {
805                         lease->options[i] = options[i];
806                         options[i].data = NULL;
807                         options[i].len = 0;
808                         if (!check_option(lease, i)) {
809                                 warning("Invalid lease option - ignoring offer");
810                                 free_client_lease(lease);
811                                 return (NULL);
812                         }
813                 }
814         }
815
816         lease->address.len = sizeof(client->packet.yiaddr);
817         memcpy(lease->address.iabuf, &client->packet.yiaddr,
818             lease->address.len);
819
820         /* If the server name was filled out, copy it. */
821         if ((!lease->options[DHO_DHCP_OPTION_OVERLOAD].len ||
822             !(lease->options[DHO_DHCP_OPTION_OVERLOAD].data[0] & 2)) &&
823             client->packet.sname[0]) {
824                 lease->server_name = malloc(DHCP_SNAME_LEN + 1);
825                 if (!lease->server_name) {
826                         warning("dhcpoffer: no memory for server name.");
827                         free_client_lease(lease);
828                         return (NULL);
829                 }
830                 memcpy(lease->server_name, client->packet.sname,
831                     DHCP_SNAME_LEN);
832                 lease->server_name[DHCP_SNAME_LEN] = '\0';
833                 if (!res_hnok(lease->server_name)) {
834                         warning("Bogus server name %s", lease->server_name);
835                         free(lease->server_name);
836                         lease->server_name = NULL;
837                 }
838         }
839
840         /* Ditto for the filename. */
841         if ((!lease->options[DHO_DHCP_OPTION_OVERLOAD].len ||
842             !(lease->options[DHO_DHCP_OPTION_OVERLOAD].data[0] & 1)) &&
843             client->packet.file[0]) {
844                 /* Don't count on the NUL terminator. */
845                 lease->filename = malloc(DHCP_FILE_LEN + 1);
846                 if (!lease->filename) {
847                         warning("dhcpoffer: no memory for filename.");
848                         free_client_lease(lease);
849                         return (NULL);
850                 }
851                 memcpy(lease->filename, client->packet.file, DHCP_FILE_LEN);
852                 lease->filename[DHCP_FILE_LEN] = '\0';
853         }
854         return lease;
855 }
856
857 void
858 dhcpnak(struct iaddr client_addr, struct option_data *options)
859 {
860
861         if (client->state != S_REBOOTING &&
862             client->state != S_REQUESTING &&
863             client->state != S_RENEWING &&
864             client->state != S_REBINDING)
865                 return;
866
867
868         if (!client->active) {
869                 note("DHCPNAK with no active lease.");
870                 return;
871         }
872
873         free_client_lease(client->active);
874         client->active = NULL;
875
876         /* Stop sending DHCPREQUEST packets... */
877         cancel_timeout();
878
879         client->state = S_INIT;
880         state_init();
881 }
882
883 /*
884  * Send out a DHCPDISCOVER packet, and set a timeout to send out another
885  * one after the right interval has expired.  If we don't get an offer by
886  * the time we reach the panic interval, call the panic function.
887  */
888 void
889 send_discover(void)
890 {
891         time_t cur_time;
892         int interval, increase = 1;
893
894         time(&cur_time);
895
896         /* Figure out how long it's been since we started transmitting. */
897         interval = cur_time - client->first_sending;
898
899         /* If we're past the panic timeout, call the script and tell it
900            we haven't found anything for this interface yet. */
901         if (interval > config->timeout) {
902                 state_panic();
903                 return;
904         }
905
906         /*
907          * If we're supposed to increase the interval, do so.  If it's
908          * currently zero (i.e., we haven't sent any packets yet), set
909          * it to initial_interval; otherwise, add to it a random
910          * number between zero and two times itself.  On average, this
911          * means that it will double with every transmission.
912          */
913         if (increase) {
914                 if (!client->interval)
915                         client->interval = config->initial_interval;
916                 else {
917                         client->interval += (arc4random() >> 2) %
918                             (2 * client->interval);
919                 }
920
921                 /* Don't backoff past cutoff. */
922                 if (client->interval > config->backoff_cutoff)
923                         client->interval = ((config->backoff_cutoff / 2)
924                                  + ((arc4random() >> 2) %
925                                     config->backoff_cutoff));
926         } else if (!client->interval)
927                 client->interval = config->initial_interval;
928
929         /* If the backoff would take us to the panic timeout, just use that
930            as the interval. */
931         if (cur_time + client->interval >
932             client->first_sending + config->timeout)
933                 client->interval = (client->first_sending +
934                          config->timeout) - cur_time + 1;
935
936         /* Record the number of seconds since we started sending. */
937         if (interval < 65536)
938                 client->packet.secs = htons(interval);
939         else
940                 client->packet.secs = htons(65535);
941         client->secs = client->packet.secs;
942
943         note("DHCPDISCOVER on %s to %s port %d interval %ld",
944             ifi->name, inet_ntoa(sockaddr_broadcast.sin_addr),
945             ntohs(sockaddr_broadcast.sin_port), client->interval);
946
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                                 go_daemon();
1000                                 return;
1001                         }
1002                 }
1003
1004                 /* If there are no other leases, give up. */
1005                 if (!client->leases) {
1006                         client->leases = client->active;
1007                         client->active = NULL;
1008                         break;
1009                 }
1010
1011 activate_next:
1012                 /* Otherwise, put the active lease at the end of the
1013                    lease list, and try another lease.. */
1014                 for (lp = client->leases; lp->next; lp = lp->next)
1015                         ;
1016                 lp->next = client->active;
1017                 if (lp->next)
1018                         lp->next->next = NULL;
1019                 client->active = client->leases;
1020                 client->leases = client->leases->next;
1021
1022                 /* If we already tried this lease, we've exhausted the
1023                    set of leases, so we might as well give up for
1024                    now. */
1025                 if (client->active == loop)
1026                         break;
1027                 else if (!loop)
1028                         loop = client->active;
1029         }
1030
1031         /* No leases were available, or what was available didn't work, so
1032            tell the shell script that we failed to allocate an address,
1033            and try again later. */
1034         note("No working leases in persistent database - sleeping.");
1035         script_init("FAIL");
1036         script_go();
1037         client->state = S_INIT;
1038         set_timeout_interval(config->retry_interval, state_init);
1039         go_daemon();
1040 }
1041
1042 void
1043 send_request(void)
1044 {
1045         struct sockaddr_in destination;
1046         struct in_addr from;
1047         time_t cur_time;
1048         int interval;
1049
1050         time(&cur_time);
1051
1052         /* Figure out how long it's been since we started transmitting. */
1053         interval = (int)(cur_time - client->first_sending);
1054
1055         /* If we're in the INIT-REBOOT or REQUESTING state and we're
1056            past the reboot timeout, go to INIT and see if we can
1057            DISCOVER an address... */
1058         /* XXX In the INIT-REBOOT state, if we don't get an ACK, it
1059            means either that we're on a network with no DHCP server,
1060            or that our server is down.  In the latter case, assuming
1061            that there is a backup DHCP server, DHCPDISCOVER will get
1062            us a new address, but we could also have successfully
1063            reused our old address.  In the former case, we're hosed
1064            anyway.  This is not a win-prone situation. */
1065         if ((client->state == S_REBOOTING ||
1066             client->state == S_REQUESTING) &&
1067             interval > config->reboot_timeout) {
1068                 client->state = S_INIT;
1069                 cancel_timeout();
1070                 state_init();
1071                 return;
1072         }
1073
1074         /* If the lease has expired, relinquish the address and go back
1075            to the INIT state. */
1076         if (client->state != S_REQUESTING &&
1077             cur_time > client->active->expiry) {
1078                 /* Run the client script with the new parameters. */
1079                 script_init("EXPIRE");
1080                 script_write_params("old_", client->active);
1081                 script_go();
1082
1083                 client->state = S_INIT;
1084                 state_init();
1085                 return;
1086         }
1087
1088         /* Do the exponential backoff... */
1089         if (!client->interval)
1090                 client->interval = config->initial_interval;
1091         else
1092                 client->interval += ((arc4random() >> 2) %
1093                     (2 * client->interval));
1094
1095         /* Don't backoff past cutoff. */
1096         if (client->interval > config->backoff_cutoff)
1097                 client->interval = ((config->backoff_cutoff / 2) +
1098                     ((arc4random() >> 2) % client->interval));
1099
1100         /* If the backoff would take us to the expiry time, just set the
1101            timeout to the expiry time. */
1102         if (client->state != S_REQUESTING && cur_time + client->interval >
1103             client->active->expiry)
1104                 client->interval = client->active->expiry - cur_time + 1;
1105
1106         /* If the lease T2 time has elapsed, or if we're not yet bound,
1107            broadcast the DHCPREQUEST rather than unicasting. */
1108         memset(&destination, 0, sizeof(destination));
1109         if (client->state == S_REQUESTING ||
1110             client->state == S_REBOOTING ||
1111             cur_time > client->active->rebind)
1112                 destination.sin_addr.s_addr = INADDR_BROADCAST;
1113         else
1114                 memcpy(&destination.sin_addr.s_addr, client->destination.iabuf,
1115                     sizeof(destination.sin_addr.s_addr));
1116         destination.sin_port = htons(REMOTE_PORT);
1117         destination.sin_family = AF_INET;
1118         destination.sin_len = sizeof(destination);
1119
1120         if (client->state != S_REQUESTING)
1121                 memcpy(&from, client->active->address.iabuf, sizeof(from));
1122         else
1123                 from.s_addr = INADDR_ANY;
1124
1125         /* Record the number of seconds since we started sending. */
1126         if (client->state == S_REQUESTING)
1127                 client->packet.secs = client->secs;
1128         else {
1129                 if (interval < 65536)
1130                         client->packet.secs = htons(interval);
1131                 else
1132                         client->packet.secs = htons(65535);
1133         }
1134
1135         note("DHCPREQUEST on %s to %s port %d", ifi->name,
1136             inet_ntoa(destination.sin_addr), ntohs(destination.sin_port));
1137
1138         send_packet(from, &destination, NULL);
1139
1140         set_timeout_interval(client->interval, send_request);
1141 }
1142
1143 void
1144 send_decline(void)
1145 {
1146         note("DHCPDECLINE on %s to %s port %d", ifi->name,
1147             inet_ntoa(sockaddr_broadcast.sin_addr),
1148             ntohs(sockaddr_broadcast.sin_port));
1149
1150         send_packet(inaddr_any, &sockaddr_broadcast, NULL);
1151 }
1152
1153 void
1154 make_discover(struct client_lease *lease)
1155 {
1156         unsigned char discover = DHCPDISCOVER;
1157         struct option_data options[256];
1158         int i;
1159
1160         memset(options, 0, sizeof(options));
1161         memset(&client->packet, 0, sizeof(client->packet));
1162
1163         /* Set DHCP_MESSAGE_TYPE to DHCPDISCOVER */
1164         i = DHO_DHCP_MESSAGE_TYPE;
1165         options[i].data = &discover;
1166         options[i].len = sizeof(discover);
1167
1168         /* Request the options we want */
1169         i  = DHO_DHCP_PARAMETER_REQUEST_LIST;
1170         options[i].data = config->requested_options;
1171         options[i].len = config->requested_option_count;
1172
1173         /* If we had an address, try to get it again. */
1174         if (lease) {
1175                 client->requested_address = lease->address;
1176                 i = DHO_DHCP_REQUESTED_ADDRESS;
1177                 options[i].data = lease->address.iabuf;
1178                 options[i].len = lease->address.len;
1179         } else
1180                 client->requested_address.len = 0;
1181
1182         /* Send any options requested in the config file. */
1183         for (i = 0; i < 256; i++)
1184                 if (!options[i].data &&
1185                     config->send_options[i].data) {
1186                         options[i].data = config->send_options[i].data;
1187                         options[i].len = config->send_options[i].len;
1188                 }
1189
1190         /* Set up the option buffer to fit in a minimal UDP packet. */
1191         i = cons_options(options);
1192         if (i == -1 || client->packet.options[i] != DHO_END)
1193                 error("options do not fit in DHCPDISCOVER packet.");
1194         client->packet_length = DHCP_FIXED_NON_UDP+i+1;
1195         if (client->packet_length < BOOTP_MIN_LEN)
1196                 client->packet_length = BOOTP_MIN_LEN;
1197
1198         client->packet.op = BOOTREQUEST;
1199         client->packet.htype = ifi->hw_address.htype;
1200         client->packet.hlen = ifi->hw_address.hlen;
1201         client->packet.hops = 0;
1202         client->packet.xid = arc4random();
1203         client->packet.secs = 0; /* filled in by send_discover. */
1204         client->packet.flags = 0;
1205
1206         memset(&client->packet.ciaddr, 0, sizeof(client->packet.ciaddr));
1207         memset(&client->packet.yiaddr, 0, sizeof(client->packet.yiaddr));
1208         memset(&client->packet.siaddr, 0, sizeof(client->packet.siaddr));
1209         memset(&client->packet.giaddr, 0, sizeof(client->packet.giaddr));
1210         memcpy(client->packet.chaddr, ifi->hw_address.haddr,
1211             ifi->hw_address.hlen);
1212 }
1213
1214 void
1215 make_request(struct client_lease * lease)
1216 {
1217         unsigned char request = DHCPREQUEST;
1218         struct option_data options[256];
1219         int i;
1220
1221         memset(options, 0, sizeof(options));
1222         memset(&client->packet, 0, sizeof(client->packet));
1223
1224         /* Set DHCP_MESSAGE_TYPE to DHCPREQUEST */
1225         i = DHO_DHCP_MESSAGE_TYPE;
1226         options[i].data = &request;
1227         options[i].len = sizeof(request);
1228
1229         /* Request the options we want */
1230         i = DHO_DHCP_PARAMETER_REQUEST_LIST;
1231         options[i].data = config->requested_options;
1232         options[i].len = config->requested_option_count;
1233
1234         /* If we are requesting an address that hasn't yet been assigned
1235            to us, use the DHCP Requested Address option. */
1236         if (client->state == S_REQUESTING) {
1237                 /* Send back the server identifier... */
1238                 i = DHO_DHCP_SERVER_IDENTIFIER;
1239                 options[i].data = lease->options[i].data;
1240                 options[i].len = lease->options[i].len;
1241         }
1242         if (client->state == S_REQUESTING ||
1243             client->state == S_REBOOTING) {
1244                 client->requested_address = lease->address;
1245                 i = DHO_DHCP_REQUESTED_ADDRESS;
1246                 options[i].data = lease->address.iabuf;
1247                 options[i].len = lease->address.len;
1248         } else
1249                 client->requested_address.len = 0;
1250
1251         /* Send any options requested in the config file. */
1252         for (i = 0; i < 256; i++)
1253                 if (!options[i].data && config->send_options[i].data) {
1254                         options[i].data = config->send_options[i].data;
1255                         options[i].len = config->send_options[i].len;
1256                 }
1257
1258         /* Set up the option buffer to fit in a minimal UDP packet. */
1259         i = cons_options(options);
1260         if (i == -1 || client->packet.options[i] != DHO_END)
1261                 error("options do not fit in DHCPREQUEST packet.");
1262         client->packet_length = DHCP_FIXED_NON_UDP+i+1;
1263         if (client->packet_length < BOOTP_MIN_LEN)
1264                 client->packet_length = BOOTP_MIN_LEN;
1265
1266         client->packet.op = BOOTREQUEST;
1267         client->packet.htype = ifi->hw_address.htype;
1268         client->packet.hlen = ifi->hw_address.hlen;
1269         client->packet.hops = 0;
1270         client->packet.xid = client->xid;
1271         client->packet.secs = 0; /* Filled in by send_request. */
1272         client->packet.flags = 0;
1273
1274         /* If we own the address we're requesting, put it in ciaddr;
1275            otherwise set ciaddr to zero. */
1276         if (client->state == S_BOUND ||
1277             client->state == S_RENEWING ||
1278             client->state == S_REBINDING) {
1279                 memcpy(&client->packet.ciaddr,
1280                     lease->address.iabuf, lease->address.len);
1281         } else {
1282                 memset(&client->packet.ciaddr, 0,
1283                     sizeof(client->packet.ciaddr));
1284         }
1285
1286         memset(&client->packet.yiaddr, 0, sizeof(client->packet.yiaddr));
1287         memset(&client->packet.siaddr, 0, sizeof(client->packet.siaddr));
1288         memset(&client->packet.giaddr, 0, sizeof(client->packet.giaddr));
1289         memcpy(client->packet.chaddr, ifi->hw_address.haddr,
1290             ifi->hw_address.hlen);
1291 }
1292
1293 void
1294 make_decline(struct client_lease *lease)
1295 {
1296         struct option_data options[256];
1297         unsigned char decline = DHCPDECLINE;
1298         int i;
1299
1300         memset(options, 0, sizeof(options));
1301         memset(&client->packet, 0, sizeof(client->packet));
1302
1303         /* Set DHCP_MESSAGE_TYPE to DHCPDECLINE */
1304         i = DHO_DHCP_MESSAGE_TYPE;
1305         options[i].data = &decline;
1306         options[i].len = sizeof(decline);
1307
1308         /* Send back the server identifier... */
1309         i = DHO_DHCP_SERVER_IDENTIFIER;
1310         options[i].data = lease->options[i].data;
1311         options[i].len = lease->options[i].len;
1312
1313         /* Send back the address we're declining. */
1314         i = DHO_DHCP_REQUESTED_ADDRESS;
1315         options[i].data = lease->address.iabuf;
1316         options[i].len = lease->address.len;
1317
1318         /* Send the uid if the user supplied one. */
1319         i = DHO_DHCP_CLIENT_IDENTIFIER;
1320         if (config->send_options[i].len) {
1321                 options[i].data = config->send_options[i].data;
1322                 options[i].len = config->send_options[i].len;
1323         }
1324
1325         /* Set up the option buffer to fit in a minimal UDP packet. */
1326         i = cons_options(options);
1327         if (i == -1 || client->packet.options[i] != DHO_END)
1328                 error("options do not fit in DHCPDECLINE packet.");
1329         client->packet_length = DHCP_FIXED_NON_UDP+i+1;
1330         if (client->packet_length < BOOTP_MIN_LEN)
1331                 client->packet_length = BOOTP_MIN_LEN;
1332
1333         client->packet.op = BOOTREQUEST;
1334         client->packet.htype = ifi->hw_address.htype;
1335         client->packet.hlen = ifi->hw_address.hlen;
1336         client->packet.hops = 0;
1337         client->packet.xid = client->xid;
1338         client->packet.secs = 0; /* Filled in by send_request. */
1339         client->packet.flags = 0;
1340
1341         /* ciaddr must always be zero. */
1342         memset(&client->packet.ciaddr, 0, sizeof(client->packet.ciaddr));
1343         memset(&client->packet.yiaddr, 0, sizeof(client->packet.yiaddr));
1344         memset(&client->packet.siaddr, 0, sizeof(client->packet.siaddr));
1345         memset(&client->packet.giaddr, 0, sizeof(client->packet.giaddr));
1346         memcpy(client->packet.chaddr, ifi->hw_address.haddr,
1347             ifi->hw_address.hlen);
1348 }
1349
1350 void
1351 free_client_lease(struct client_lease *lease)
1352 {
1353         int i;
1354
1355         if (lease->server_name)
1356                 free(lease->server_name);
1357         if (lease->filename)
1358                 free(lease->filename);
1359         for (i = 0; i < 256; i++) {
1360                 if (lease->options[i].len)
1361                         free(lease->options[i].data);
1362         }
1363         free(lease);
1364 }
1365
1366 void
1367 rewrite_client_leases(void)
1368 {
1369         struct client_lease *lp;
1370
1371         if (!leaseFile) /* XXX */
1372                 error("lease file not open");
1373
1374         fflush(leaseFile);
1375         rewind(leaseFile);
1376
1377         for (lp = client->leases; lp; lp = lp->next) {
1378                 if (client->active && addr_eq(lp->address,
1379                         client->active->address))
1380                         continue;
1381                 write_client_lease(lp);
1382         }
1383
1384         if (client->active)
1385                 write_client_lease(client->active);
1386
1387         fflush(leaseFile);
1388         ftruncate(fileno(leaseFile), ftello(leaseFile));
1389         fsync(fileno(leaseFile));
1390 }
1391
1392 void
1393 write_client_lease(struct client_lease *lease)
1394 {
1395         struct tm *t;
1396         int i;
1397
1398         /* If the lease came from the config file, we don't need to stash
1399            a copy in the lease database. */
1400         if (lease->is_static)
1401                 return;
1402
1403         if (!leaseFile) /* XXX */
1404                 error("lease file not open");
1405
1406         fprintf(leaseFile, "lease {\n");
1407         if (lease->is_bootp)
1408                 fprintf(leaseFile, "  bootp;\n");
1409         fprintf(leaseFile, "  interface \"%s\";\n", ifi->name);
1410         fprintf(leaseFile, "  fixed-address %s;\n", piaddr(lease->address));
1411         if (lease->filename)
1412                 fprintf(leaseFile, "  filename \"%s\";\n", lease->filename);
1413         if (lease->server_name)
1414                 fprintf(leaseFile, "  server-name \"%s\";\n",
1415                     lease->server_name);
1416         for (i = 0; i < 256; i++)
1417                 if (lease->options[i].len)
1418                         fprintf(leaseFile, "  option %s %s;\n",
1419                             dhcp_options[i].name,
1420                             pretty_print_option(i, &lease->options[i], 1));
1421
1422         t = gmtime(&lease->renewal);
1423         fprintf(leaseFile, "  renew %d %d/%d/%d %02d:%02d:%02d;\n",
1424             t->tm_wday, t->tm_year + 1900, t->tm_mon + 1, t->tm_mday,
1425             t->tm_hour, t->tm_min, t->tm_sec);
1426         t = gmtime(&lease->rebind);
1427         fprintf(leaseFile, "  rebind %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->expiry);
1431         fprintf(leaseFile, "  expire %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         fprintf(leaseFile, "}\n");
1435         fflush(leaseFile);
1436 }
1437
1438 void
1439 script_init(char *reason)
1440 {
1441         size_t           len;
1442         struct imsg_hdr  hdr;
1443         struct buf      *buf;
1444
1445         hdr.code = IMSG_SCRIPT_INIT;
1446         hdr.len = sizeof(struct imsg_hdr) + sizeof(size_t) + strlen(reason);
1447         buf = buf_open(hdr.len);
1448
1449         buf_add(buf, &hdr, sizeof(hdr));
1450         len = strlen(reason);
1451         buf_add(buf, &len, sizeof(len));
1452         buf_add(buf, reason, len);
1453
1454         buf_close(privfd, buf);
1455 }
1456
1457 void
1458 priv_script_init(char *reason)
1459 {
1460         client->scriptEnvsize = 100;
1461         if (client->scriptEnv == NULL)
1462                 client->scriptEnv =
1463                     calloc(client->scriptEnvsize, sizeof(char *));
1464         if (client->scriptEnv == NULL)
1465                 error("script_init: no memory for environment");
1466
1467         client->scriptEnv[0] = strdup(CLIENT_PATH);
1468         if (client->scriptEnv[0] == NULL)
1469                 error("script_init: no memory for environment");
1470
1471         client->scriptEnv[1] = NULL;
1472
1473         script_set_env("", "interface", ifi->name);
1474
1475         script_set_env("", "reason", reason);
1476 }
1477
1478 void
1479 priv_script_write_params(char *prefix, struct client_lease *lease)
1480 {
1481         char buf[256];
1482         struct option_data o;
1483         int i;
1484
1485         script_set_env(prefix, "ip_address", piaddr(lease->address));
1486
1487         if (lease->options[DHO_SUBNET_MASK].len &&
1488             (lease->options[DHO_SUBNET_MASK].len <
1489             sizeof(lease->address.iabuf))) {
1490                 struct iaddr netmask, subnet, broadcast;
1491
1492                 memcpy(netmask.iabuf, lease->options[DHO_SUBNET_MASK].data,
1493                     lease->options[DHO_SUBNET_MASK].len);
1494                 netmask.len = lease->options[DHO_SUBNET_MASK].len;
1495
1496                 subnet = subnet_number(lease->address, netmask);
1497                 if (subnet.len) {
1498                         script_set_env(prefix, "network_number",
1499                             piaddr(subnet));
1500                         if (!lease->options[DHO_BROADCAST_ADDRESS].len) {
1501                                 broadcast = broadcast_addr(subnet, netmask);
1502                                 if (broadcast.len)
1503                                         script_set_env(prefix,
1504                                             "broadcast_address",
1505                                             piaddr(broadcast));
1506                         }
1507                 }
1508         }
1509
1510         if (lease->filename)
1511                 script_set_env(prefix, "filename", lease->filename);
1512         if (lease->server_name)
1513                 script_set_env(prefix, "server_name",
1514                     lease->server_name);
1515
1516         for (i = 0; i < 256; i++) {
1517                 if (!dhcp_option_ev_name(buf, sizeof(buf), &dhcp_options[i]))
1518                         continue;
1519
1520                 switch (config->default_actions[i]) {
1521                 case ACTION_IGNORE:
1522                          break;
1523
1524                 case ACTION_DEFAULT:
1525                         if (lease->options[i].len)
1526                                 script_set_env(prefix, buf,
1527                                     pretty_print_option(i, &lease->options[i],
1528                                         0));
1529                         else if (config->defaults[i].len)
1530                                 script_set_env(prefix, buf,
1531                                     pretty_print_option(i, &config->defaults[i],
1532                                         0));
1533                         break;
1534
1535                 case ACTION_SUPERSEDE:
1536                         if (config->defaults[i].len)
1537                                 script_set_env(prefix, buf,
1538                                     pretty_print_option(i, &config->defaults[i],
1539                                         0));
1540                         break;
1541
1542                 case ACTION_PREPEND:
1543                         o.len = config->defaults[i].len + lease->options[i].len;
1544                         if (o.len > 0) {
1545                                 o.data = calloc(1, o.len);
1546                                 if (o.data == NULL)
1547                                         error("no space to prepend '%s' to %s",
1548                                             config->defaults[i].data,
1549                                             dhcp_options[i].name);
1550                                 memcpy(o.data, config->defaults[i].data,
1551                                     config->defaults[i].len);
1552                                 memcpy(o.data + config->defaults[i].len,
1553                                     lease->options[i].data,
1554                                     lease->options[i].len);
1555                                 script_set_env(prefix, buf,
1556                                     pretty_print_option(i, &o, 0));
1557                                 free(o.data);
1558                         }
1559                         break;
1560
1561                 case ACTION_APPEND:
1562                         o.len = config->defaults[i].len + lease->options[i].len;
1563                         if (o.len > 0) {
1564                                 o.data = calloc(1, o.len);
1565                                 if (o.data == NULL)
1566                                         error("no space to append '%s' to %s",
1567                                             config->defaults[i].data,
1568                                             dhcp_options[i].name);
1569                                 memcpy(o.data, lease->options[i].data,
1570                                     lease->options[i].len);
1571                                 memcpy(o.data + lease->options[i].len,
1572                                     config->defaults[i].data,
1573                                     config->defaults[i].len);
1574                                 script_set_env(prefix, buf,
1575                                     pretty_print_option(i, &o, 0));
1576                                 free(o.data);
1577                         }
1578                         break;
1579                 }
1580         }
1581
1582         snprintf(buf, sizeof(buf), "%d", (int)lease->expiry);
1583         script_set_env(prefix, "expiry", buf);
1584 }
1585
1586 void
1587 script_write_params(char *prefix, struct client_lease *lease)
1588 {
1589         size_t           fn_len = 0, sn_len = 0, pr_len = 0;
1590         struct imsg_hdr  hdr;
1591         struct buf      *buf;
1592         int              i;
1593
1594         if (lease->filename != NULL)
1595                 fn_len = strlen(lease->filename);
1596         if (lease->server_name != NULL)
1597                 sn_len = strlen(lease->server_name);
1598         if (prefix != NULL)
1599                 pr_len = strlen(prefix);
1600
1601         hdr.code = IMSG_SCRIPT_WRITE_PARAMS;
1602         hdr.len = sizeof(hdr) + sizeof(struct client_lease) +
1603             sizeof(size_t) + fn_len + sizeof(size_t) + sn_len +
1604             sizeof(size_t) + pr_len;
1605
1606         for (i = 0; i < 256; i++)
1607                 hdr.len += sizeof(int) + lease->options[i].len;
1608
1609         scripttime = time(NULL);
1610
1611         buf = buf_open(hdr.len);
1612
1613         buf_add(buf, &hdr, sizeof(hdr));
1614         buf_add(buf, lease, sizeof(struct client_lease));
1615         buf_add(buf, &fn_len, sizeof(fn_len));
1616         buf_add(buf, lease->filename, fn_len);
1617         buf_add(buf, &sn_len, sizeof(sn_len));
1618         buf_add(buf, lease->server_name, sn_len);
1619         buf_add(buf, &pr_len, sizeof(pr_len));
1620         buf_add(buf, prefix, pr_len);
1621
1622         for (i = 0; i < 256; i++) {
1623                 buf_add(buf, &lease->options[i].len,
1624                     sizeof(lease->options[i].len));
1625                 buf_add(buf, lease->options[i].data,
1626                     lease->options[i].len);
1627         }
1628
1629         buf_close(privfd, buf);
1630 }
1631
1632 int
1633 script_go(void)
1634 {
1635         struct imsg_hdr  hdr;
1636         struct buf      *buf;
1637         int              ret;
1638
1639         scripttime = time(NULL);
1640
1641         hdr.code = IMSG_SCRIPT_GO;
1642         hdr.len = sizeof(struct imsg_hdr);
1643
1644         buf = buf_open(hdr.len);
1645
1646         buf_add(buf, &hdr, sizeof(hdr));
1647         buf_close(privfd, buf);
1648
1649         bzero(&hdr, sizeof(hdr));
1650         buf_read(privfd, &hdr, sizeof(hdr));
1651         if (hdr.code != IMSG_SCRIPT_GO_RET)
1652                 error("unexpected msg type %u", hdr.code);
1653         if (hdr.len != sizeof(hdr) + sizeof(int))
1654                 error("received corrupted message");
1655         buf_read(privfd, &ret, sizeof(ret));
1656
1657         return (ret);
1658 }
1659
1660 int
1661 priv_script_go(void)
1662 {
1663         char *scriptName, *argv[2], **envp;
1664         int pid, wpid, wstatus;
1665
1666         scripttime = time(NULL);
1667
1668         scriptName = config->script_name;
1669         envp = client->scriptEnv;
1670
1671         argv[0] = scriptName;
1672         argv[1] = NULL;
1673
1674         pid = fork();
1675         if (pid < 0) {
1676                 error("fork: %m");
1677                 wstatus = 0;
1678         } else if (pid) {
1679                 do {
1680                         wpid = wait(&wstatus);
1681                 } while (wpid != pid && wpid > 0);
1682                 if (wpid < 0) {
1683                         error("wait: %m");
1684                         wstatus = 0;
1685                 }
1686         } else {
1687                 execve(scriptName, argv, envp);
1688                 error("execve (%s, ...): %m", scriptName);
1689         }
1690
1691         script_flush_env();
1692
1693         return (WEXITSTATUS(wstatus));
1694 }
1695
1696 void
1697 script_set_env(const char *prefix, const char *name, const char *value)
1698 {
1699         int i, j, namelen;
1700
1701         namelen = strlen(name);
1702
1703         for (i = 0; client->scriptEnv[i]; i++)
1704                 if (strncmp(client->scriptEnv[i], name, namelen) == 0 &&
1705                     client->scriptEnv[i][namelen] == '=')
1706                         break;
1707
1708         if (client->scriptEnv[i])
1709                 /* Reuse the slot. */
1710                 free(client->scriptEnv[i]);
1711         else {
1712                 /* New variable.  Expand if necessary. */
1713                 if (i >= client->scriptEnvsize - 1) {
1714                         char **newscriptEnv;
1715                         int newscriptEnvsize = client->scriptEnvsize + 50;
1716
1717                         newscriptEnv = realloc(client->scriptEnv,
1718                             newscriptEnvsize);
1719                         if (newscriptEnv == NULL) {
1720                                 free(client->scriptEnv);
1721                                 client->scriptEnv = NULL;
1722                                 client->scriptEnvsize = 0;
1723                                 error("script_set_env: no memory for variable");
1724                         }
1725                         client->scriptEnv = newscriptEnv;
1726                         client->scriptEnvsize = newscriptEnvsize;
1727                 }
1728                 /* need to set the NULL pointer at end of array beyond
1729                    the new slot. */
1730                 client->scriptEnv[i + 1] = NULL;
1731         }
1732         /* Allocate space and format the variable in the appropriate slot. */
1733         client->scriptEnv[i] = malloc(strlen(prefix) + strlen(name) + 1 +
1734             strlen(value) + 1);
1735         if (client->scriptEnv[i] == NULL)
1736                 error("script_set_env: no memory for variable assignment");
1737
1738         /* No `` or $() command substitution allowed in environment values! */
1739         for (j = 0; j < strlen(value); j++)
1740                 switch (value[j]) {
1741                 case '`':
1742                 case '$':
1743                         error("illegal character (%c) in value '%s'", value[j],
1744                             value);
1745                         /* not reached */
1746                 }
1747         snprintf(client->scriptEnv[i], strlen(prefix) + strlen(name) +
1748             1 + strlen(value) + 1, "%s%s=%s", prefix, name, value);
1749 }
1750
1751 void
1752 script_flush_env(void)
1753 {
1754         int i;
1755
1756         for (i = 0; client->scriptEnv[i]; i++) {
1757                 free(client->scriptEnv[i]);
1758                 client->scriptEnv[i] = NULL;
1759         }
1760         client->scriptEnvsize = 0;
1761 }
1762
1763 int
1764 dhcp_option_ev_name(char *buf, size_t buflen, const struct option *option)
1765 {
1766         size_t i;
1767
1768         for (i = 0; option->name[i]; i++) {
1769                 if (i + 1 == buflen)
1770                         return 0;
1771                 if (option->name[i] == '-')
1772                         buf[i] = '_';
1773                 else
1774                         buf[i] = option->name[i];
1775         }
1776
1777         buf[i] = 0;
1778         return 1;
1779 }
1780
1781 void
1782 go_daemon(void)
1783 {
1784         static int state = 0;
1785
1786         if (no_daemon || state)
1787                 return;
1788
1789         state = 1;
1790
1791         /* Stop logging to stderr... */
1792         log_perror = 0;
1793
1794         if (daemon(1, 0) == -1)
1795                 error("daemon");
1796
1797         /* we are chrooted, daemon(3) fails to open /dev/null */
1798         if (nullfd != -1) {
1799                 dup2(nullfd, STDIN_FILENO);
1800                 dup2(nullfd, STDOUT_FILENO);
1801                 dup2(nullfd, STDERR_FILENO);
1802                 close(nullfd);
1803                 nullfd = -1;
1804         }
1805 }
1806
1807 int
1808 check_option(struct client_lease *l, int option)
1809 {
1810         char *opbuf;
1811         char *sbuf;
1812
1813         /* we use this, since this is what gets passed to dhclient-script */
1814
1815         opbuf = pretty_print_option(option, &l->options[option], 0);
1816
1817         sbuf = option_as_string(option, l->options[option].data,
1818             l->options[option].len);
1819
1820         switch (option) {
1821         case DHO_SUBNET_MASK:
1822         case DHO_SWAP_SERVER:
1823         case DHO_BROADCAST_ADDRESS:
1824         case DHO_DHCP_SERVER_IDENTIFIER:
1825         case DHO_ROUTER_SOLICITATION_ADDRESS:
1826         case DHO_DHCP_REQUESTED_ADDRESS:
1827                 if (ipv4addrs(opbuf) == 0) {
1828                         warning("Invalid IP address in option %s: %s",
1829                             dhcp_options[option].name, opbuf);
1830                         return (0);
1831                 }
1832                 if (l->options[option].len != 4) { /* RFC 2132 */
1833                         warning("warning: Only 1 IP address allowed in "
1834                             "%s option; length %d, must be 4",
1835                             dhcp_options[option].name,
1836                             l->options[option].len);
1837                         l->options[option].len = 4;
1838                 }
1839                 return (1);
1840         case DHO_TIME_SERVERS:
1841         case DHO_NAME_SERVERS:
1842         case DHO_ROUTERS:
1843         case DHO_DOMAIN_NAME_SERVERS:
1844         case DHO_LOG_SERVERS:
1845         case DHO_COOKIE_SERVERS:
1846         case DHO_LPR_SERVERS:
1847         case DHO_IMPRESS_SERVERS:
1848         case DHO_RESOURCE_LOCATION_SERVERS:
1849         case DHO_NIS_SERVERS:
1850         case DHO_NTP_SERVERS:
1851         case DHO_NETBIOS_NAME_SERVERS:
1852         case DHO_NETBIOS_DD_SERVER:
1853         case DHO_FONT_SERVERS:
1854                 if (ipv4addrs(opbuf) == 0) {
1855                         warning("Invalid IP address in option %s: %s",
1856                             dhcp_options[option].name, opbuf);
1857                         return (0);
1858                 }
1859                 return (1);
1860         case DHO_HOST_NAME:
1861         case DHO_DOMAIN_NAME:
1862         case DHO_NIS_DOMAIN:
1863                 if (!res_hnok(sbuf)) {
1864                         warning("Bogus Host Name option %d: %s (%s)", option,
1865                             sbuf, opbuf);
1866                         l->options[option].len = 0;
1867                         free(l->options[option].data);
1868                 }
1869                 return (1);
1870         case DHO_PAD:
1871         case DHO_TIME_OFFSET:
1872         case DHO_BOOT_SIZE:
1873         case DHO_MERIT_DUMP:
1874         case DHO_ROOT_PATH:
1875         case DHO_EXTENSIONS_PATH:
1876         case DHO_IP_FORWARDING:
1877         case DHO_NON_LOCAL_SOURCE_ROUTING:
1878         case DHO_POLICY_FILTER:
1879         case DHO_MAX_DGRAM_REASSEMBLY:
1880         case DHO_DEFAULT_IP_TTL:
1881         case DHO_PATH_MTU_AGING_TIMEOUT:
1882         case DHO_PATH_MTU_PLATEAU_TABLE:
1883         case DHO_INTERFACE_MTU:
1884         case DHO_ALL_SUBNETS_LOCAL:
1885         case DHO_PERFORM_MASK_DISCOVERY:
1886         case DHO_MASK_SUPPLIER:
1887         case DHO_ROUTER_DISCOVERY:
1888         case DHO_STATIC_ROUTES:
1889         case DHO_TRAILER_ENCAPSULATION:
1890         case DHO_ARP_CACHE_TIMEOUT:
1891         case DHO_IEEE802_3_ENCAPSULATION:
1892         case DHO_DEFAULT_TCP_TTL:
1893         case DHO_TCP_KEEPALIVE_INTERVAL:
1894         case DHO_TCP_KEEPALIVE_GARBAGE:
1895         case DHO_VENDOR_ENCAPSULATED_OPTIONS:
1896         case DHO_NETBIOS_NODE_TYPE:
1897         case DHO_NETBIOS_SCOPE:
1898         case DHO_X_DISPLAY_MANAGER:
1899         case DHO_DHCP_LEASE_TIME:
1900         case DHO_DHCP_OPTION_OVERLOAD:
1901         case DHO_DHCP_MESSAGE_TYPE:
1902         case DHO_DHCP_PARAMETER_REQUEST_LIST:
1903         case DHO_DHCP_MESSAGE:
1904         case DHO_DHCP_MAX_MESSAGE_SIZE:
1905         case DHO_DHCP_RENEWAL_TIME:
1906         case DHO_DHCP_REBINDING_TIME:
1907         case DHO_DHCP_CLASS_IDENTIFIER:
1908         case DHO_DHCP_CLIENT_IDENTIFIER:
1909         case DHO_DHCP_USER_CLASS_ID:
1910         case DHO_TFTP_SERVER:
1911         case DHO_END:
1912                 return (1);
1913         default:
1914                 if (!unknown_ok)
1915                         warning("unknown dhcp option value 0x%x", option);
1916                 return (unknown_ok);
1917         }
1918 }
1919
1920 int
1921 res_hnok(const char *name)
1922 {
1923         const char *dn = name;
1924         int pch = '.', ch = *dn++;
1925         int warn = 0;
1926
1927         while (ch != '\0') {
1928                 int nch = *dn++;
1929
1930                 if (ch == '.') {
1931                         ;
1932                 } else if (pch == '.' || nch == '.' || nch == '\0') {
1933                         if (!isalnum(ch))
1934                                 return (0);
1935                 } else if (!isalnum(ch) && ch != '-' && ch != '_')
1936                                 return (0);
1937                 else if (ch == '_' && warn == 0) {
1938                         warning("warning: hostname %s contains an "
1939                             "underscore which violates RFC 952", name);
1940                         warn++;
1941                 }
1942                 pch = ch, ch = nch;
1943         }
1944         return (1);
1945 }
1946
1947 /* Does buf consist only of dotted decimal ipv4 addrs?
1948  * return how many if so,
1949  * otherwise, return 0
1950  */
1951 int
1952 ipv4addrs(char * buf)
1953 {
1954         struct in_addr jnk;
1955         int count = 0;
1956
1957         while (inet_aton(buf, &jnk) == 1){
1958                 count++;
1959                 while (*buf == '.' || isdigit(*buf))
1960                         buf++;
1961                 if (*buf == '\0')
1962                         return (count);
1963                 while (*buf ==  ' ')
1964                         buf++;
1965         }
1966         return (0);
1967 }
1968
1969 char *
1970 option_as_string(unsigned int code, unsigned char *data, int len)
1971 {
1972         static char optbuf[32768]; /* XXX */
1973         char *op = optbuf;
1974         int opleft = sizeof(optbuf);
1975         unsigned char *dp = data;
1976
1977         if (code > 255)
1978                 error("option_as_string: bad code %d", code);
1979
1980         for (; dp < data + len; dp++) {
1981                 if (!isascii(*dp) || !isprint(*dp)) {
1982                         if (dp + 1 != data + len || *dp != 0) {
1983                                 size_t oplen;
1984                                 snprintf(op, opleft, "\\%03o", *dp);
1985                                 oplen = strlen(op);
1986                                 op += oplen;
1987                                 opleft -= oplen;
1988                         }
1989                 } else if (*dp == '"' || *dp == '\'' || *dp == '$' ||
1990                     *dp == '`' || *dp == '\\') {
1991                         *op++ = '\\';
1992                         *op++ = *dp;
1993                         opleft -= 2;
1994                 } else {
1995                         *op++ = *dp;
1996                         opleft--;
1997                 }
1998         }
1999         if (opleft < 1)
2000                 goto toobig;
2001         *op = 0;
2002         return optbuf;
2003 toobig:
2004         warning("dhcp option too large");
2005         return "<error>";
2006 }
2007
2008 int
2009 fork_privchld(int fd, int fd2)
2010 {
2011         struct pollfd pfd[1];
2012         int nfds, pfail = 0;
2013
2014         switch (fork()) {
2015         case -1:
2016                 error("cannot fork");
2017                 break;
2018         case 0:
2019                 break;
2020         default:
2021                 return (0);
2022         }
2023
2024         if (chdir("/") == -1)
2025                 error("chdir(\"/\")");
2026
2027         setproctitle("%s [priv]", ifi->name);
2028
2029         dup2(nullfd, STDIN_FILENO);
2030         dup2(nullfd, STDOUT_FILENO);
2031         dup2(nullfd, STDERR_FILENO);
2032         close(nullfd);
2033         close(fd2);
2034
2035         for (;;) {
2036                 pfd[0].fd = fd;
2037                 pfd[0].events = POLLIN;
2038                 if ((nfds = poll(pfd, 1, INFTIM)) == -1)
2039                         if (errno != EINTR)
2040                                 error("poll error");
2041
2042                 /*
2043                  * Handle temporary errors, but bail if they persist.
2044                  */
2045                 if (nfds == 0 || !(pfd[0].revents & POLLIN)) {
2046                         if (pfail > POLL_FAILURES)
2047                                 error("poll failed > %d times", POLL_FAILURES);
2048                         sleep(pfail * POLL_FAILURE_WAIT);
2049                         pfail++;
2050                         continue;
2051                 }
2052
2053                 dispatch_imsg(fd);
2054         }
2055 }
2056
2057 void
2058 get_ifname(char *ifname, char *arg)
2059 {
2060         struct ifgroupreq ifgr;
2061         struct ifg_req *ifg;
2062         int s, len;
2063
2064         if (!strcmp(arg, "egress")) {
2065                 s = socket(AF_INET, SOCK_DGRAM, 0);
2066                 if (s == -1)
2067                         error("socket error");
2068                 bzero(&ifgr, sizeof(ifgr));
2069                 strlcpy(ifgr.ifgr_name, "egress", sizeof(ifgr.ifgr_name));
2070                 if (ioctl(s, SIOCGIFGMEMB, (caddr_t)&ifgr) == -1) {
2071                         if (errno == ENOENT)
2072                                 error("no interface in group egress found");
2073                         error("ioctl SIOCGIFGMEMB: %m");
2074                 }
2075                 len = ifgr.ifgr_len;
2076                 if ((ifgr.ifgr_groups = calloc(1, len)) == NULL)
2077                         error("get_ifname");
2078                 if (ioctl(s, SIOCGIFGMEMB, (caddr_t)&ifgr) == -1)
2079                         error("ioctl SIOCGIFGMEMB: %m");
2080
2081                 arg = NULL;
2082                 for (ifg = ifgr.ifgr_groups;
2083                      ifg && len >= sizeof(struct ifg_req); ifg++) {
2084                         len -= sizeof(struct ifg_req);
2085                         if (arg)
2086                                 error("too many interfaces in group egress");
2087                         arg = ifg->ifgrq_member;
2088                 }
2089
2090                 if (strlcpy(ifi->name, arg, IFNAMSIZ) >= IFNAMSIZ)
2091                         error("Interface name too long: %m");
2092
2093                 free(ifgr.ifgr_groups);
2094                 close(s);
2095         } else if (strlcpy(ifi->name, arg, IFNAMSIZ) >= IFNAMSIZ)
2096                 error("Interface name too long");
2097 }