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