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