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