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