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