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