a409730c4a1b4f35d04a24962fdf34687e37a9e3
[dragonfly.git] / sbin / dhclient / dhclient.c
1 /* $OpenBSD: src/sbin/dhclient/dhclient.c,v 1.124 2009/03/10 23:19:36 krw Exp $ */
2
3 /*
4  * Copyright 2004 Henning Brauer <henning@openbsd.org>
5  * Copyright (c) 1995, 1996, 1997, 1998, 1999
6  * The Internet Software Consortium.    All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. Neither the name of The Internet Software Consortium nor the names
18  *    of its contributors may be used to endorse or promote products derived
19  *    from this software without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE INTERNET SOFTWARE CONSORTIUM AND
22  * CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
23  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
24  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
25  * DISCLAIMED.  IN NO EVENT SHALL THE INTERNET SOFTWARE CONSORTIUM OR
26  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
27  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
28  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
29  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
30  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
31  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
32  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  *
35  * This software has been written for the Internet Software Consortium
36  * by Ted Lemon <mellon@fugue.com> in cooperation with Vixie
37  * Enterprises.  To learn more about the Internet Software Consortium,
38  * see ``http://www.vix.com/isc''.  To learn more about Vixie
39  * Enterprises, see ``http://www.vix.com''.
40  *
41  * This client was substantially modified and enhanced by Elliot Poger
42  * for use on Linux while he was working on the MosquitoNet project at
43  * Stanford.
44  *
45  * The current version owes much to Elliot's Linux enhancements, but
46  * was substantially reorganized and partially rewritten by Ted Lemon
47  * so as to use the same networking framework that the Internet Software
48  * Consortium DHCP server uses.   Much system-specific configuration code
49  * was moved into a shell script so that as support for more operating
50  * systems is added, it will not be necessary to port and maintain
51  * system-specific configuration code to these operating systems - instead,
52  * the shell script can invoke the native tools to accomplish the same
53  * purpose.
54  */
55
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
593         if (client->state != S_REBOOTING &&
594             client->state != S_REQUESTING &&
595             client->state != S_RENEWING &&
596             client->state != S_REBINDING)
597                 return;
598
599
600         lease = packet_to_lease(options);
601         if (!lease) {
602                 note("packet_to_lease failed.");
603                 return;
604         }
605
606         client->new = lease;
607
608         /* Stop resending DHCPREQUEST. */
609         cancel_timeout(send_request);
610
611         /* Figure out the lease time. */
612         if (client->new->options[DHO_DHCP_LEASE_TIME].data)
613                 client->new->expiry =
614                     getULong(client->new->options[DHO_DHCP_LEASE_TIME].data);
615         else
616                 client->new->expiry = DEFAULT_LEASE_TIME;
617         /* A number that looks negative here is really just very large,
618            because the lease expiry offset is unsigned. */
619         if (client->new->expiry < 0)
620                 client->new->expiry = TIME_MAX;
621         /* XXX should be fixed by resetting the client state */
622         if (client->new->expiry < 60)
623                 client->new->expiry = 60;
624
625         /* Take the server-provided renewal time if there is one;
626            otherwise figure it out according to the spec. */
627         if (client->new->options[DHO_DHCP_RENEWAL_TIME].len)
628                 client->new->renewal =
629                     getULong(client->new->options[DHO_DHCP_RENEWAL_TIME].data);
630         else
631                 client->new->renewal = client->new->expiry / 2;
632
633         /* Same deal with the rebind time. */
634         if (client->new->options[DHO_DHCP_REBINDING_TIME].len)
635                 client->new->rebind =
636                     getULong(client->new->options[DHO_DHCP_REBINDING_TIME].data);
637         else
638                 client->new->rebind = client->new->renewal +
639                     client->new->renewal / 2 + client->new->renewal / 4;
640
641         client->new->expiry += cur_time;
642         /* Lease lengths can never be negative. */
643         if (client->new->expiry < cur_time)
644                 client->new->expiry = TIME_MAX;
645         client->new->renewal += cur_time;
646         if (client->new->renewal < cur_time)
647                 client->new->renewal = TIME_MAX;
648         client->new->rebind += cur_time;
649         if (client->new->rebind < cur_time)
650                 client->new->rebind = TIME_MAX;
651
652         bind_lease();
653 }
654
655 void
656 bind_lease(void)
657 {
658         /* Remember the medium. */
659         client->new->medium = client->medium;
660
661         /* Write out the new lease. */
662         write_client_lease(client->new, 0);
663
664         /* Run the client script with the new parameters. */
665         script_init((client->state == S_REQUESTING ? "BOUND" :
666             (client->state == S_RENEWING ? "RENEW" :
667             (client->state == S_REBOOTING ? "REBOOT" : "REBIND"))),
668             client->new->medium);
669         if (client->active && client->state != S_REBOOTING)
670                 script_write_params("old_", client->active);
671         script_write_params("new_", client->new);
672         if (client->alias)
673                 script_write_params("alias_", client->alias);
674         script_go();
675
676         /* Replace the old active lease with the new one. */
677         if (client->active)
678                 free_client_lease(client->active);
679         client->active = client->new;
680         client->new = NULL;
681
682         /* Set up a timeout to start the renewal process. */
683         add_timeout(client->active->renewal, state_bound);
684
685         note("bound to %s -- renewal in %ld seconds.",
686             piaddr(client->active->address),
687             client->active->renewal - cur_time);
688         client->state = S_BOUND;
689         reinitialize_interface();
690         go_daemon();
691 }
692
693 /*
694  * state_bound is called when we've successfully bound to a particular
695  * lease, but the renewal time on that lease has expired.   We are
696  * expected to unicast a DHCPREQUEST to the server that gave us our
697  * original lease.
698  */
699 void
700 state_bound(void)
701 {
702         /* T1 has expired. */
703         make_request(client->active);
704         client->xid = client->packet.xid;
705
706         if (client->active->options[DHO_DHCP_SERVER_IDENTIFIER].len == 4) {
707                 memcpy(client->destination.iabuf,
708                     client->active->options[DHO_DHCP_SERVER_IDENTIFIER].data,
709                     4);
710                 client->destination.len = 4;
711         } else
712                 client->destination = iaddr_broadcast;
713
714         client->first_sending = cur_time;
715         client->interval = config->initial_interval;
716         client->state = S_RENEWING;
717
718         /* Send the first packet immediately. */
719         send_request();
720 }
721
722 void
723 dhcpoffer(struct iaddr client_addr, struct option_data *options)
724 {
725         struct client_lease *lease, *lp;
726         int i;
727         int arp_timeout_needed, stop_selecting;
728         char *name = options[DHO_DHCP_MESSAGE_TYPE].len ? "DHCPOFFER" :
729             "BOOTREPLY";
730
731
732         if (client->state != S_SELECTING)
733                 return;
734
735
736         /* If this lease doesn't supply the minimum required parameters,
737            blow it off. */
738         for (i = 0; config->required_options[i]; i++) {
739                 if (!options[config->required_options[i]].len) {
740                         note("%s isn't satisfactory.", name);
741                         return;
742                 }
743         }
744
745         /* If we've already seen this lease, don't record it again. */
746         for (lease = client->offered_leases;
747             lease; lease = lease->next) {
748                 if (lease->address.len == sizeof(client->packet.yiaddr) &&
749                     !memcmp(lease->address.iabuf,
750                     &client->packet.yiaddr, lease->address.len)) {
751                         debug("%s already seen.", name);
752                         return;
753                 }
754         }
755
756         lease = packet_to_lease(options);
757         if (!lease) {
758                 note("packet_to_lease failed.");
759                 return;
760         }
761
762         /* If this lease was acquired through a BOOTREPLY, record that
763            fact. */
764         if (!options[DHO_DHCP_MESSAGE_TYPE].len)
765                 lease->is_bootp = 1;
766
767         /* Record the medium under which this lease was offered. */
768         lease->medium = client->medium;
769
770         /* Send out an ARP Request for the offered IP address. */
771         script_init("ARPSEND", lease->medium);
772         script_write_params("check_", lease);
773         /* If the script can't send an ARP request without waiting,
774            we'll be waiting when we do the ARPCHECK, so don't wait now. */
775         if (script_go())
776                 arp_timeout_needed = 0;
777         else
778                 arp_timeout_needed = 2;
779
780         /* Figure out when we're supposed to stop selecting. */
781         stop_selecting = client->first_sending + config->select_interval;
782
783         /* If this is the lease we asked for, put it at the head of the
784            list, and don't mess with the arp request timeout. */
785         if (lease->address.len == client->requested_address.len &&
786             !memcmp(lease->address.iabuf,
787             client->requested_address.iabuf,
788             client->requested_address.len)) {
789                 lease->next = client->offered_leases;
790                 client->offered_leases = lease;
791         } else {
792                 /* If we already have an offer, and arping for this
793                    offer would take us past the selection timeout,
794                    then don't extend the timeout - just hope for the
795                    best. */
796                 if (client->offered_leases &&
797                     (cur_time + arp_timeout_needed) > stop_selecting)
798                         arp_timeout_needed = 0;
799
800                 /* Put the lease at the end of the list. */
801                 lease->next = NULL;
802                 if (!client->offered_leases)
803                         client->offered_leases = lease;
804                 else {
805                         for (lp = client->offered_leases; lp->next;
806                             lp = lp->next)
807                                 ;       /* nothing */
808                         lp->next = lease;
809                 }
810         }
811
812         /* If we're supposed to stop selecting before we've had time
813            to wait for the ARPREPLY, add some delay to wait for
814            the ARPREPLY. */
815         if (stop_selecting - cur_time < arp_timeout_needed)
816                 stop_selecting = cur_time + arp_timeout_needed;
817
818         /* If the selecting interval has expired, go immediately to
819            state_selecting().  Otherwise, time out into
820            state_selecting at the select interval. */
821         if (stop_selecting <= 0)
822                 state_selecting();
823         else {
824                 add_timeout(stop_selecting, state_selecting);
825                 cancel_timeout(send_discover);
826         }
827 }
828
829 /*
830  * Allocate a client_lease structure and initialize it from the
831  * parameters in the specified packet.
832  */
833 struct client_lease *
834 packet_to_lease(struct option_data *options)
835 {
836         struct client_lease *lease;
837         int i;
838
839         lease = malloc(sizeof(struct client_lease));
840
841         if (!lease) {
842                 warning("dhcpoffer: no memory to record lease.");
843                 return (NULL);
844         }
845
846         memset(lease, 0, sizeof(*lease));
847
848         /* Copy the lease options. */
849         for (i = 0; i < 256; i++) {
850                 if (options[i].len) {
851                         lease->options[i] = options[i];
852                         options[i].data = NULL;
853                         options[i].len = 0;
854                         if (!check_option(lease, i)) {
855                                 warning("Invalid lease option - ignoring offer");
856                                 free_client_lease(lease);
857                                 return (NULL);
858                         }
859                 }
860         }
861
862         lease->address.len = sizeof(client->packet.yiaddr);
863         memcpy(lease->address.iabuf, &client->packet.yiaddr,
864             lease->address.len);
865
866         /* If the server name was filled out, copy it. */
867         if ((!lease->options[DHO_DHCP_OPTION_OVERLOAD].len ||
868             !(lease->options[DHO_DHCP_OPTION_OVERLOAD].data[0] & 2)) &&
869             client->packet.sname[0]) {
870                 lease->server_name = malloc(DHCP_SNAME_LEN + 1);
871                 if (!lease->server_name) {
872                         warning("dhcpoffer: no memory for server name.");
873                         free_client_lease(lease);
874                         return (NULL);
875                 }
876                 memcpy(lease->server_name, client->packet.sname,
877                     DHCP_SNAME_LEN);
878                 lease->server_name[DHCP_SNAME_LEN] = '\0';
879                 if (!res_hnok(lease->server_name)) {
880                         warning("Bogus server name %s", lease->server_name);
881                         free(lease->server_name);
882                         lease->server_name = NULL;
883                 }
884         }
885
886         /* Ditto for the filename. */
887         if ((!lease->options[DHO_DHCP_OPTION_OVERLOAD].len ||
888             !(lease->options[DHO_DHCP_OPTION_OVERLOAD].data[0] & 1)) &&
889             client->packet.file[0]) {
890                 /* Don't count on the NUL terminator. */
891                 lease->filename = malloc(DHCP_FILE_LEN + 1);
892                 if (!lease->filename) {
893                         warning("dhcpoffer: no memory for filename.");
894                         free_client_lease(lease);
895                         return (NULL);
896                 }
897                 memcpy(lease->filename, client->packet.file, DHCP_FILE_LEN);
898                 lease->filename[DHCP_FILE_LEN] = '\0';
899         }
900         return lease;
901 }
902
903 void
904 dhcpnak(struct iaddr client_addr, struct option_data *options)
905 {
906
907         if (client->state != S_REBOOTING &&
908             client->state != S_REQUESTING &&
909             client->state != S_RENEWING &&
910             client->state != S_REBINDING)
911                 return;
912
913
914         if (!client->active) {
915                 note("DHCPNAK with no active lease.");
916                 return;
917         }
918
919         free_client_lease(client->active);
920         client->active = NULL;
921
922         /* Stop sending DHCPREQUEST packets... */
923         cancel_timeout(send_request);
924
925         client->state = S_INIT;
926         state_init();
927 }
928
929 /*
930  * Send out a DHCPDISCOVER packet, and set a timeout to send out another
931  * one after the right interval has expired.  If we don't get an offer by
932  * the time we reach the panic interval, call the panic function.
933  */
934 void
935 send_discover(void)
936 {
937         int interval, increase = 1;
938
939         /* Figure out how long it's been since we started transmitting. */
940         interval = cur_time - client->first_sending;
941
942         /* If we're past the panic timeout, call the script and tell it
943            we haven't found anything for this interface yet. */
944         if (interval > config->timeout) {
945                 state_panic();
946                 return;
947         }
948
949         /* If we're selecting media, try the whole list before doing
950            the exponential backoff, but if we've already received an
951            offer, stop looping, because we obviously have it right. */
952         if (!client->offered_leases && config->media) {
953                 int fail = 0;
954 again:
955                 if (client->medium) {
956                         client->medium = client->medium->next;
957                         increase = 0;
958                 }
959                 if (!client->medium) {
960                         if (fail)
961                                 error("No valid media types for %s!", ifi->name);
962                         client->medium = config->media;
963                         increase = 1;
964                 }
965
966                 note("Trying medium \"%s\" %d", client->medium->string,
967                     increase);
968                 script_init("MEDIUM", client->medium);
969                 if (script_go())
970                         goto again;
971         }
972
973         /*
974          * If we're supposed to increase the interval, do so.  If it's
975          * currently zero (i.e., we haven't sent any packets yet), set
976          * it to initial_interval; otherwise, add to it a random
977          * number between zero and two times itself.  On average, this
978          * means that it will double with every transmission.
979          */
980         if (increase) {
981                 if (!client->interval)
982                         client->interval = config->initial_interval;
983                 else {
984                         client->interval += (arc4random() >> 2) %
985                             (2 * client->interval);
986                 }
987
988                 /* Don't backoff past cutoff. */
989                 if (client->interval > config->backoff_cutoff)
990                         client->interval = ((config->backoff_cutoff / 2)
991                                  + ((arc4random() >> 2) %
992                                     config->backoff_cutoff));
993         } else if (!client->interval)
994                 client->interval = config->initial_interval;
995
996         /* If the backoff would take us to the panic timeout, just use that
997            as the interval. */
998         if (cur_time + client->interval >
999             client->first_sending + config->timeout)
1000                 client->interval = (client->first_sending +
1001                          config->timeout) - cur_time + 1;
1002
1003         /* Record the number of seconds since we started sending. */
1004         if (interval < 65536)
1005                 client->packet.secs = htons(interval);
1006         else
1007                 client->packet.secs = htons(65535);
1008         client->secs = client->packet.secs;
1009
1010         note("DHCPDISCOVER on %s to %s port %d interval %ld",
1011             ifi->name, inet_ntoa(sockaddr_broadcast.sin_addr),
1012             ntohs(sockaddr_broadcast.sin_port), client->interval);
1013
1014         /* Send out a packet. */
1015         send_packet(inaddr_any, &sockaddr_broadcast, NULL);
1016
1017         add_timeout(cur_time + client->interval, send_discover);
1018 }
1019
1020 /*
1021  * state_panic gets called if we haven't received any offers in a preset
1022  * amount of time.   When this happens, we try to use existing leases
1023  * that haven't yet expired, and failing that, we call the client script
1024  * and hope it can do something.
1025  */
1026 void
1027 state_panic(void)
1028 {
1029         struct client_lease *loop = client->active;
1030         struct client_lease *lp;
1031
1032         note("No DHCPOFFERS received.");
1033
1034         /* We may not have an active lease, but we may have some
1035            predefined leases that we can try. */
1036         if (!client->active && client->leases)
1037                 goto activate_next;
1038
1039         /* Run through the list of leases and see if one can be used. */
1040         while (client->active) {
1041                 if (client->active->expiry > cur_time) {
1042                         note("Trying recorded lease %s",
1043                             piaddr(client->active->address));
1044                         /* Run the client script with the existing
1045                            parameters. */
1046                         script_init("TIMEOUT",
1047                             client->active->medium);
1048                         script_write_params("new_", client->active);
1049                         if (client->alias)
1050                                 script_write_params("alias_",
1051                                     client->alias);
1052
1053                         /* If the old lease is still good and doesn't
1054                            yet need renewal, go into BOUND state and
1055                            timeout at the renewal time. */
1056                         if (!script_go()) {
1057                                 if (cur_time <
1058                                     client->active->renewal) {
1059                                         client->state = S_BOUND;
1060                                         note("bound: renewal in %ld seconds.",
1061                                             client->active->renewal -
1062                                             cur_time);
1063                                         add_timeout(client->active->renewal,
1064                                             state_bound);
1065                                 } else {
1066                                         client->state = S_BOUND;
1067                                         note("bound: immediate renewal.");
1068                                         state_bound();
1069                                 }
1070                                 reinitialize_interface();
1071                                 go_daemon();
1072                                 return;
1073                         }
1074                 }
1075
1076                 /* If there are no other leases, give up. */
1077                 if (!client->leases) {
1078                         client->leases = client->active;
1079                         client->active = NULL;
1080                         break;
1081                 }
1082
1083 activate_next:
1084                 /* Otherwise, put the active lease at the end of the
1085                    lease list, and try another lease.. */
1086                 for (lp = client->leases; lp->next; lp = lp->next)
1087                         ;
1088                 lp->next = client->active;
1089                 if (lp->next)
1090                         lp->next->next = NULL;
1091                 client->active = client->leases;
1092                 client->leases = client->leases->next;
1093
1094                 /* If we already tried this lease, we've exhausted the
1095                    set of leases, so we might as well give up for
1096                    now. */
1097                 if (client->active == loop)
1098                         break;
1099                 else if (!loop)
1100                         loop = client->active;
1101         }
1102
1103         /* No leases were available, or what was available didn't work, so
1104            tell the shell script that we failed to allocate an address,
1105            and try again later. */
1106         note("No working leases in persistent database - sleeping.");
1107         script_init("FAIL", NULL);
1108         if (client->alias)
1109                 script_write_params("alias_", client->alias);
1110         script_go();
1111         client->state = S_INIT;
1112         add_timeout(cur_time + config->retry_interval, state_init);
1113         go_daemon();
1114 }
1115
1116 void
1117 send_request(void)
1118 {
1119         struct sockaddr_in destination;
1120         struct in_addr from;
1121         int interval;
1122
1123         /* Figure out how long it's been since we started transmitting. */
1124         interval = cur_time - client->first_sending;
1125
1126         /* If we're in the INIT-REBOOT or REQUESTING state and we're
1127            past the reboot timeout, go to INIT and see if we can
1128            DISCOVER an address... */
1129         /* XXX In the INIT-REBOOT state, if we don't get an ACK, it
1130            means either that we're on a network with no DHCP server,
1131            or that our server is down.  In the latter case, assuming
1132            that there is a backup DHCP server, DHCPDISCOVER will get
1133            us a new address, but we could also have successfully
1134            reused our old address.  In the former case, we're hosed
1135            anyway.  This is not a win-prone situation. */
1136         if ((client->state == S_REBOOTING ||
1137             client->state == S_REQUESTING) &&
1138             interval > config->reboot_timeout) {
1139 cancel:
1140                 client->state = S_INIT;
1141                 cancel_timeout(send_request);
1142                 state_init();
1143                 return;
1144         }
1145
1146         /* If we're in the reboot state, make sure the media is set up
1147            correctly. */
1148         if (client->state == S_REBOOTING &&
1149             !client->medium &&
1150             client->active->medium) {
1151                 script_init("MEDIUM", client->active->medium);
1152
1153                 /* If the medium we chose won't fly, go to INIT state. */
1154                 if (script_go())
1155                         goto cancel;
1156
1157                 /* Record the medium. */
1158                 client->medium = client->active->medium;
1159         }
1160
1161         /* If the lease has expired, relinquish the address and go back
1162            to the INIT state. */
1163         if (client->state != S_REQUESTING &&
1164             cur_time > client->active->expiry) {
1165                 /* Run the client script with the new parameters. */
1166                 script_init("EXPIRE", NULL);
1167                 script_write_params("old_", client->active);
1168                 if (client->alias)
1169                         script_write_params("alias_", client->alias);
1170                 script_go();
1171
1172                 /* Now do a preinit on the interface so that we can
1173                    discover a new address. */
1174                 script_init("PREINIT", NULL);
1175                 if (client->alias)
1176                         script_write_params("alias_", client->alias);
1177                 script_go();
1178
1179                 client->state = S_INIT;
1180                 state_init();
1181                 return;
1182         }
1183
1184         /* Do the exponential backoff... */
1185         if (!client->interval)
1186                 client->interval = config->initial_interval;
1187         else
1188                 client->interval += ((arc4random() >> 2) %
1189                     (2 * client->interval));
1190
1191         /* Don't backoff past cutoff. */
1192         if (client->interval > config->backoff_cutoff)
1193                 client->interval = ((config->backoff_cutoff / 2) +
1194                     ((arc4random() >> 2) % client->interval));
1195
1196         /* If the backoff would take us to the expiry time, just set the
1197            timeout to the expiry time. */
1198         if (client->state != S_REQUESTING && cur_time + client->interval >
1199             client->active->expiry)
1200                 client->interval = client->active->expiry - cur_time + 1;
1201
1202         /* If the lease T2 time has elapsed, or if we're not yet bound,
1203            broadcast the DHCPREQUEST rather than unicasting. */
1204         memset(&destination, 0, sizeof(destination));
1205         if (client->state == S_REQUESTING ||
1206             client->state == S_REBOOTING ||
1207             cur_time > client->active->rebind)
1208                 destination.sin_addr.s_addr = INADDR_BROADCAST;
1209         else
1210                 memcpy(&destination.sin_addr.s_addr, client->destination.iabuf,
1211                     sizeof(destination.sin_addr.s_addr));
1212         destination.sin_port = htons(REMOTE_PORT);
1213         destination.sin_family = AF_INET;
1214         destination.sin_len = sizeof(destination);
1215
1216         if (client->state != S_REQUESTING)
1217                 memcpy(&from, client->active->address.iabuf, sizeof(from));
1218         else
1219                 from.s_addr = INADDR_ANY;
1220
1221         /* Record the number of seconds since we started sending. */
1222         if (client->state == S_REQUESTING)
1223                 client->packet.secs = client->secs;
1224         else {
1225                 if (interval < 65536)
1226                         client->packet.secs = htons(interval);
1227                 else
1228                         client->packet.secs = htons(65535);
1229         }
1230
1231         note("DHCPREQUEST on %s to %s port %d", ifi->name,
1232             inet_ntoa(destination.sin_addr), ntohs(destination.sin_port));
1233
1234         /* Send out a packet. */
1235         send_packet(from, &destination, NULL);
1236
1237         add_timeout(cur_time + client->interval, send_request);
1238 }
1239
1240 void
1241 send_decline(void)
1242 {
1243         note("DHCPDECLINE on %s to %s port %d", ifi->name,
1244             inet_ntoa(sockaddr_broadcast.sin_addr),
1245             ntohs(sockaddr_broadcast.sin_port));
1246
1247         /* Send out a packet. */
1248         send_packet(inaddr_any, &sockaddr_broadcast, NULL);
1249 }
1250
1251 void
1252 make_discover(struct client_lease *lease)
1253 {
1254         unsigned char discover = DHCPDISCOVER;
1255         struct option_data options[256];
1256         int i;
1257
1258         memset(options, 0, sizeof(options));
1259         memset(&client->packet, 0, sizeof(client->packet));
1260
1261         /* Set DHCP_MESSAGE_TYPE to DHCPDISCOVER */
1262         i = DHO_DHCP_MESSAGE_TYPE;
1263         options[i].data = &discover;
1264         options[i].len = sizeof(discover);
1265
1266         /* Request the options we want */
1267         i  = DHO_DHCP_PARAMETER_REQUEST_LIST;
1268         options[i].data = config->requested_options;
1269         options[i].len = config->requested_option_count;
1270
1271         /* If we had an address, try to get it again. */
1272         if (lease) {
1273                 client->requested_address = lease->address;
1274                 i = DHO_DHCP_REQUESTED_ADDRESS;
1275                 options[i].data = lease->address.iabuf;
1276                 options[i].len = lease->address.len;
1277         } else
1278                 client->requested_address.len = 0;
1279
1280         /* Send any options requested in the config file. */
1281         for (i = 0; i < 256; i++)
1282                 if (!options[i].data &&
1283                     config->send_options[i].data) {
1284                         options[i].data = config->send_options[i].data;
1285                         options[i].len = config->send_options[i].len;
1286                 }
1287
1288         /* Set up the option buffer to fit in a minimal UDP packet. */
1289         i = cons_options(client->packet.options, 576 - DHCP_FIXED_LEN,
1290             options);
1291         if (i == -1 || client->packet.options[i] != DHO_END)
1292                 error("options do not fit in DHCPDISCOVER packet.");
1293         client->packet_length = DHCP_FIXED_NON_UDP+i+1;
1294         if (client->packet_length < BOOTP_MIN_LEN)
1295                 client->packet_length = BOOTP_MIN_LEN;
1296
1297         client->packet.op = BOOTREQUEST;
1298         client->packet.htype = ifi->hw_address.htype;
1299         client->packet.hlen = ifi->hw_address.hlen;
1300         client->packet.hops = 0;
1301         client->packet.xid = arc4random();
1302         client->packet.secs = 0; /* filled in by send_discover. */
1303         client->packet.flags = 0;
1304
1305         memset(&client->packet.ciaddr, 0, sizeof(client->packet.ciaddr));
1306         memset(&client->packet.yiaddr, 0, sizeof(client->packet.yiaddr));
1307         memset(&client->packet.siaddr, 0, sizeof(client->packet.siaddr));
1308         memset(&client->packet.giaddr, 0, sizeof(client->packet.giaddr));
1309         memcpy(client->packet.chaddr, ifi->hw_address.haddr,
1310             ifi->hw_address.hlen);
1311 }
1312
1313 void
1314 make_request(struct client_lease * lease)
1315 {
1316         unsigned char request = DHCPREQUEST;
1317         struct option_data options[256];
1318         int i;
1319
1320         memset(options, 0, sizeof(options));
1321         memset(&client->packet, 0, sizeof(client->packet));
1322
1323         /* Set DHCP_MESSAGE_TYPE to DHCPREQUEST */
1324         i = DHO_DHCP_MESSAGE_TYPE;
1325         options[i].data = &request;
1326         options[i].len = sizeof(request);
1327
1328         /* Request the options we want */
1329         i = DHO_DHCP_PARAMETER_REQUEST_LIST;
1330         options[i].data = config->requested_options;
1331         options[i].len = config->requested_option_count;
1332
1333         /* If we are requesting an address that hasn't yet been assigned
1334            to us, use the DHCP Requested Address option. */
1335         if (client->state == S_REQUESTING) {
1336                 /* Send back the server identifier... */
1337                 i = DHO_DHCP_SERVER_IDENTIFIER;
1338                 options[i].data = lease->options[i].data;
1339                 options[i].len = lease->options[i].len;
1340         }
1341         if (client->state == S_REQUESTING ||
1342             client->state == S_REBOOTING) {
1343                 client->requested_address = lease->address;
1344                 i = DHO_DHCP_REQUESTED_ADDRESS;
1345                 options[i].data = lease->address.iabuf;
1346                 options[i].len = lease->address.len;
1347         } else
1348                 client->requested_address.len = 0;
1349
1350         /* Send any options requested in the config file. */
1351         for (i = 0; i < 256; i++)
1352                 if (!options[i].data && config->send_options[i].data) {
1353                         options[i].data = config->send_options[i].data;
1354                         options[i].len = config->send_options[i].len;
1355                 }
1356
1357         /* Set up the option buffer to fit in a minimal UDP packet. */
1358         i = cons_options(client->packet.options, 576 - DHCP_FIXED_LEN,
1359             options);
1360         if (i == -1 || client->packet.options[i] != DHO_END)
1361                 error("options do not fit in DHCPREQUEST packet.");
1362         client->packet_length = DHCP_FIXED_NON_UDP+i+1;
1363         if (client->packet_length < BOOTP_MIN_LEN)
1364                 client->packet_length = BOOTP_MIN_LEN;
1365
1366         client->packet.op = BOOTREQUEST;
1367         client->packet.htype = ifi->hw_address.htype;
1368         client->packet.hlen = ifi->hw_address.hlen;
1369         client->packet.hops = 0;
1370         client->packet.xid = client->xid;
1371         client->packet.secs = 0; /* Filled in by send_request. */
1372         client->packet.flags = 0;
1373
1374         /* If we own the address we're requesting, put it in ciaddr;
1375            otherwise set ciaddr to zero. */
1376         if (client->state == S_BOUND ||
1377             client->state == S_RENEWING ||
1378             client->state == S_REBINDING) {
1379                 memcpy(&client->packet.ciaddr,
1380                     lease->address.iabuf, lease->address.len);
1381         } else {
1382                 memset(&client->packet.ciaddr, 0,
1383                     sizeof(client->packet.ciaddr));
1384         }
1385
1386         memset(&client->packet.yiaddr, 0, sizeof(client->packet.yiaddr));
1387         memset(&client->packet.siaddr, 0, sizeof(client->packet.siaddr));
1388         memset(&client->packet.giaddr, 0, sizeof(client->packet.giaddr));
1389         memcpy(client->packet.chaddr, ifi->hw_address.haddr,
1390             ifi->hw_address.hlen);
1391 }
1392
1393 void
1394 make_decline(struct client_lease *lease)
1395 {
1396         struct option_data options[256];
1397         unsigned char decline = DHCPDECLINE;
1398         int i;
1399
1400         memset(options, 0, sizeof(options));
1401         memset(&client->packet, 0, sizeof(client->packet));
1402
1403         /* Set DHCP_MESSAGE_TYPE to DHCPDECLINE */
1404         i = DHO_DHCP_MESSAGE_TYPE;
1405         options[i].data = &decline;
1406         options[i].len = sizeof(decline);
1407
1408         /* Send back the server identifier... */
1409         i = DHO_DHCP_SERVER_IDENTIFIER;
1410         options[i].data = lease->options[i].data;
1411         options[i].len = lease->options[i].len;
1412
1413         /* Send back the address we're declining. */
1414         i = DHO_DHCP_REQUESTED_ADDRESS;
1415         options[i].data = lease->address.iabuf;
1416         options[i].len = lease->address.len;
1417
1418         /* Send the uid if the user supplied one. */
1419         i = DHO_DHCP_CLIENT_IDENTIFIER;
1420         if (config->send_options[i].len) {
1421                 options[i].data = config->send_options[i].data;
1422                 options[i].len = config->send_options[i].len;
1423         }
1424
1425         /* Set up the option buffer to fit in a minimal UDP packet. */
1426         i = cons_options(client->packet.options, 576 - DHCP_FIXED_LEN,
1427             options);
1428         if (i == -1 || client->packet.options[i] != DHO_END)
1429                 error("options do not fit in DHCPDECLINE packet.");
1430         client->packet_length = DHCP_FIXED_NON_UDP+i+1;
1431         if (client->packet_length < BOOTP_MIN_LEN)
1432                 client->packet_length = BOOTP_MIN_LEN;
1433
1434         client->packet.op = BOOTREQUEST;
1435         client->packet.htype = ifi->hw_address.htype;
1436         client->packet.hlen = ifi->hw_address.hlen;
1437         client->packet.hops = 0;
1438         client->packet.xid = client->xid;
1439         client->packet.secs = 0; /* Filled in by send_request. */
1440         client->packet.flags = 0;
1441
1442         /* ciaddr must always be zero. */
1443         memset(&client->packet.ciaddr, 0, sizeof(client->packet.ciaddr));
1444         memset(&client->packet.yiaddr, 0, sizeof(client->packet.yiaddr));
1445         memset(&client->packet.siaddr, 0, sizeof(client->packet.siaddr));
1446         memset(&client->packet.giaddr, 0, sizeof(client->packet.giaddr));
1447         memcpy(client->packet.chaddr, ifi->hw_address.haddr,
1448             ifi->hw_address.hlen);
1449 }
1450
1451 void
1452 free_client_lease(struct client_lease *lease)
1453 {
1454         int i;
1455
1456         if (lease->server_name)
1457                 free(lease->server_name);
1458         if (lease->filename)
1459                 free(lease->filename);
1460         for (i = 0; i < 256; i++) {
1461                 if (lease->options[i].len)
1462                         free(lease->options[i].data);
1463         }
1464         free(lease);
1465 }
1466
1467 void
1468 rewrite_client_leases(void)
1469 {
1470         struct client_lease *lp;
1471
1472         if (!leaseFile) /* XXX */
1473                 error("lease file not open");
1474
1475         fflush(leaseFile);
1476         rewind(leaseFile);
1477
1478         for (lp = client->leases; lp; lp = lp->next)
1479                 write_client_lease(lp, 1);
1480         if (client->active)
1481                 write_client_lease(client->active, 1);
1482
1483         fflush(leaseFile);
1484         ftruncate(fileno(leaseFile), ftello(leaseFile));
1485         fsync(fileno(leaseFile));
1486 }
1487
1488 void
1489 write_client_lease(struct client_lease *lease, int rewrite)
1490 {
1491         static int leases_written;
1492         struct tm *t;
1493         int i;
1494
1495         if (!rewrite) {
1496                 if (leases_written++ > 20) {
1497                         rewrite_client_leases();
1498                         leases_written = 0;
1499                 }
1500         }
1501
1502         /* If the lease came from the config file, we don't need to stash
1503            a copy in the lease database. */
1504         if (lease->is_static)
1505                 return;
1506
1507         if (!leaseFile) /* XXX */
1508                 error("lease file not open");
1509
1510         fprintf(leaseFile, "lease {\n");
1511         if (lease->is_bootp)
1512                 fprintf(leaseFile, "  bootp;\n");
1513         fprintf(leaseFile, "  interface \"%s\";\n", ifi->name);
1514         fprintf(leaseFile, "  fixed-address %s;\n", piaddr(lease->address));
1515         if (lease->filename)
1516                 fprintf(leaseFile, "  filename \"%s\";\n", lease->filename);
1517         if (lease->server_name)
1518                 fprintf(leaseFile, "  server-name \"%s\";\n",
1519                     lease->server_name);
1520         if (lease->medium)
1521                 fprintf(leaseFile, "  medium \"%s\";\n", lease->medium->string);
1522         for (i = 0; i < 256; i++)
1523                 if (lease->options[i].len)
1524                         fprintf(leaseFile, "  option %s %s;\n",
1525                             dhcp_options[i].name,
1526                             pretty_print_option(i, lease->options[i].data,
1527                             lease->options[i].len, 1, 1));
1528
1529         t = gmtime(&lease->renewal);
1530         fprintf(leaseFile, "  renew %d %d/%d/%d %02d:%02d:%02d;\n",
1531             t->tm_wday, t->tm_year + 1900, t->tm_mon + 1, t->tm_mday,
1532             t->tm_hour, t->tm_min, t->tm_sec);
1533         t = gmtime(&lease->rebind);
1534         fprintf(leaseFile, "  rebind %d %d/%d/%d %02d:%02d:%02d;\n",
1535             t->tm_wday, t->tm_year + 1900, t->tm_mon + 1, t->tm_mday,
1536             t->tm_hour, t->tm_min, t->tm_sec);
1537         t = gmtime(&lease->expiry);
1538         fprintf(leaseFile, "  expire %d %d/%d/%d %02d:%02d:%02d;\n",
1539             t->tm_wday, t->tm_year + 1900, t->tm_mon + 1, t->tm_mday,
1540             t->tm_hour, t->tm_min, t->tm_sec);
1541         fprintf(leaseFile, "}\n");
1542         fflush(leaseFile);
1543 }
1544
1545 void
1546 script_init(char *reason, struct string_list *medium)
1547 {
1548         size_t           len, mediumlen = 0;
1549         struct imsg_hdr  hdr;
1550         struct buf      *buf;
1551
1552         if (medium != NULL && medium->string != NULL)
1553                 mediumlen = strlen(medium->string);
1554
1555         hdr.code = IMSG_SCRIPT_INIT;
1556         hdr.len = sizeof(struct imsg_hdr) +
1557             sizeof(size_t) + mediumlen +
1558             sizeof(size_t) + strlen(reason);
1559
1560         buf = buf_open(hdr.len);
1561
1562         buf_add(buf, &hdr, sizeof(hdr));
1563         buf_add(buf, &mediumlen, sizeof(mediumlen));
1564         if (mediumlen > 0)
1565                 buf_add(buf, medium->string, mediumlen);
1566         len = strlen(reason);
1567         buf_add(buf, &len, sizeof(len));
1568         buf_add(buf, reason, len);
1569
1570         buf_close(privfd, buf);
1571 }
1572
1573 void
1574 priv_script_init(char *reason, char *medium)
1575 {
1576         client->scriptEnvsize = 100;
1577         if (client->scriptEnv == NULL)
1578                 client->scriptEnv =
1579                     calloc(client->scriptEnvsize, sizeof(char *));
1580         if (client->scriptEnv == NULL)
1581                 error("script_init: no memory for environment");
1582
1583         client->scriptEnv[0] = strdup(CLIENT_PATH);
1584         if (client->scriptEnv[0] == NULL)
1585                 error("script_init: no memory for environment");
1586
1587         client->scriptEnv[1] = NULL;
1588
1589         script_set_env("", "interface", ifi->name);
1590
1591         if (medium)
1592                 script_set_env("", "medium", medium);
1593
1594         script_set_env("", "reason", reason);
1595 }
1596
1597 void
1598 priv_script_write_params(char *prefix, struct client_lease *lease)
1599 {
1600         u_int8_t dbuf[1500];
1601         int i, len = 0;
1602         char tbuf[128];
1603
1604         script_set_env(prefix, "ip_address", piaddr(lease->address));
1605
1606         if (lease->options[DHO_SUBNET_MASK].len &&
1607             (lease->options[DHO_SUBNET_MASK].len <
1608             sizeof(lease->address.iabuf))) {
1609                 struct iaddr netmask, subnet, broadcast;
1610
1611                 memcpy(netmask.iabuf, lease->options[DHO_SUBNET_MASK].data,
1612                     lease->options[DHO_SUBNET_MASK].len);
1613                 netmask.len = lease->options[DHO_SUBNET_MASK].len;
1614
1615                 subnet = subnet_number(lease->address, netmask);
1616                 if (subnet.len) {
1617                         script_set_env(prefix, "network_number",
1618                             piaddr(subnet));
1619                         if (!lease->options[DHO_BROADCAST_ADDRESS].len) {
1620                                 broadcast = broadcast_addr(subnet, netmask);
1621                                 if (broadcast.len)
1622                                         script_set_env(prefix,
1623                                             "broadcast_address",
1624                                             piaddr(broadcast));
1625                         }
1626                 }
1627         }
1628
1629         if (lease->filename)
1630                 script_set_env(prefix, "filename", lease->filename);
1631         if (lease->server_name)
1632                 script_set_env(prefix, "server_name",
1633                     lease->server_name);
1634         for (i = 0; i < 256; i++) {
1635                 u_int8_t *dp = NULL;
1636
1637                 if (config->defaults[i].len) {
1638                         if (lease->options[i].len) {
1639                                 switch (config->default_actions[i]) {
1640                                 case ACTION_DEFAULT:
1641                                         dp = lease->options[i].data;
1642                                         len = lease->options[i].len;
1643                                         break;
1644                                 case ACTION_SUPERSEDE:
1645 supersede:
1646                                         dp = config->defaults[i].data;
1647                                         len = config->defaults[i].len;
1648                                         break;
1649                                 case ACTION_PREPEND:
1650                                         len = config->defaults[i].len +
1651                                             lease->options[i].len;
1652                                         if (len > sizeof(dbuf)) {
1653                                                 warning("no space to %s %s",
1654                                                     "prepend option",
1655                                                     dhcp_options[i].name);
1656                                                 goto supersede;
1657                                         }
1658                                         dp = dbuf;
1659                                         memcpy(dp,
1660                                             config->defaults[i].data,
1661                                             config->defaults[i].len);
1662                                         memcpy(dp +
1663                                             config->defaults[i].len,
1664                                             lease->options[i].data,
1665                                             lease->options[i].len);
1666                                         dp[len] = '\0';
1667                                         break;
1668                                 case ACTION_APPEND:
1669                                         len = config->defaults[i].len +
1670                                             lease->options[i].len;
1671                                         if (len > sizeof(dbuf)) {
1672                                                 warning("no space to %s %s",
1673                                                     "append option",
1674                                                     dhcp_options[i].name);
1675                                                 goto supersede;
1676                                         }
1677                                         dp = dbuf;
1678                                         memcpy(dp, lease->options[i].data,
1679                                             lease->options[i].len);
1680                                         memcpy(dp + lease->options[i].len,
1681                                             config->defaults[i].data,
1682                                             config->defaults[i].len);
1683                                         dp[len] = '\0';
1684                                 }
1685                         } else {
1686                                 dp = config->defaults[i].data;
1687                                 len = config->defaults[i].len;
1688                         }
1689                 } else if (lease->options[i].len) {
1690                         len = lease->options[i].len;
1691                         dp = lease->options[i].data;
1692                 } else {
1693                         len = 0;
1694                 }
1695                 if (len) {
1696                         char name[256];
1697
1698                         if (dhcp_option_ev_name(name, sizeof(name),
1699                             &dhcp_options[i]))
1700                                 script_set_env(prefix, name,
1701                                     pretty_print_option(i, dp, len, 0, 0));
1702                 }
1703         }
1704         snprintf(tbuf, sizeof(tbuf), "%d", (int)lease->expiry);
1705         script_set_env(prefix, "expiry", tbuf);
1706 }
1707
1708 void
1709 script_write_params(char *prefix, struct client_lease *lease)
1710 {
1711         size_t           fn_len = 0, sn_len = 0, pr_len = 0;
1712         struct imsg_hdr  hdr;
1713         struct buf      *buf;
1714         int              i;
1715
1716         if (lease->filename != NULL)
1717                 fn_len = strlen(lease->filename);
1718         if (lease->server_name != NULL)
1719                 sn_len = strlen(lease->server_name);
1720         if (prefix != NULL)
1721                 pr_len = strlen(prefix);
1722
1723         hdr.code = IMSG_SCRIPT_WRITE_PARAMS;
1724         hdr.len = sizeof(hdr) + sizeof(struct client_lease) +
1725             sizeof(size_t) + fn_len + sizeof(size_t) + sn_len +
1726             sizeof(size_t) + pr_len;
1727
1728         for (i = 0; i < 256; i++)
1729                 hdr.len += sizeof(int) + lease->options[i].len;
1730
1731         scripttime = time(NULL);
1732
1733         buf = buf_open(hdr.len);
1734
1735         buf_add(buf, &hdr, sizeof(hdr));
1736         buf_add(buf, lease, sizeof(struct client_lease));
1737         buf_add(buf, &fn_len, sizeof(fn_len));
1738         buf_add(buf, lease->filename, fn_len);
1739         buf_add(buf, &sn_len, sizeof(sn_len));
1740         buf_add(buf, lease->server_name, sn_len);
1741         buf_add(buf, &pr_len, sizeof(pr_len));
1742         buf_add(buf, prefix, pr_len);
1743
1744         for (i = 0; i < 256; i++) {
1745                 buf_add(buf, &lease->options[i].len,
1746                     sizeof(lease->options[i].len));
1747                 buf_add(buf, lease->options[i].data,
1748                     lease->options[i].len);
1749         }
1750
1751         buf_close(privfd, buf);
1752 }
1753
1754 int
1755 script_go(void)
1756 {
1757         struct imsg_hdr  hdr;
1758         struct buf      *buf;
1759         int              ret;
1760
1761         scripttime = time(NULL);
1762
1763         hdr.code = IMSG_SCRIPT_GO;
1764         hdr.len = sizeof(struct imsg_hdr);
1765
1766         buf = buf_open(hdr.len);
1767
1768         buf_add(buf, &hdr, sizeof(hdr));
1769         buf_close(privfd, buf);
1770
1771         bzero(&hdr, sizeof(hdr));
1772         buf_read(privfd, &hdr, sizeof(hdr));
1773         if (hdr.code != IMSG_SCRIPT_GO_RET)
1774                 error("unexpected msg type %u", hdr.code);
1775         if (hdr.len != sizeof(hdr) + sizeof(int))
1776                 error("received corrupted message");
1777         buf_read(privfd, &ret, sizeof(ret));
1778
1779         return (ret);
1780 }
1781
1782 int
1783 priv_script_go(void)
1784 {
1785         char *scriptName, *argv[2], **envp;
1786         int pid, wpid, wstatus;
1787
1788         scripttime = time(NULL);
1789
1790         scriptName = config->script_name;
1791         envp = client->scriptEnv;
1792
1793         argv[0] = scriptName;
1794         argv[1] = NULL;
1795
1796         pid = fork();
1797         if (pid < 0) {
1798                 error("fork: %m");
1799                 wstatus = 0;
1800         } else if (pid) {
1801                 do {
1802                         wpid = wait(&wstatus);
1803                 } while (wpid != pid && wpid > 0);
1804                 if (wpid < 0) {
1805                         error("wait: %m");
1806                         wstatus = 0;
1807                 }
1808         } else {
1809                 execve(scriptName, argv, envp);
1810                 error("execve (%s, ...): %m", scriptName);
1811         }
1812
1813         script_flush_env();
1814
1815         return (WEXITSTATUS(wstatus));
1816 }
1817
1818 void
1819 script_set_env(const char *prefix, const char *name, const char *value)
1820 {
1821         int i, j, namelen;
1822
1823         namelen = strlen(name);
1824
1825         for (i = 0; client->scriptEnv[i]; i++)
1826                 if (strncmp(client->scriptEnv[i], name, namelen) == 0 &&
1827                     client->scriptEnv[i][namelen] == '=')
1828                         break;
1829
1830         if (client->scriptEnv[i])
1831                 /* Reuse the slot. */
1832                 free(client->scriptEnv[i]);
1833         else {
1834                 /* New variable.  Expand if necessary. */
1835                 if (i >= client->scriptEnvsize - 1) {
1836                         char **newscriptEnv;
1837                         int newscriptEnvsize = client->scriptEnvsize + 50;
1838
1839                         newscriptEnv = realloc(client->scriptEnv,
1840                             newscriptEnvsize);
1841                         if (newscriptEnv == NULL) {
1842                                 free(client->scriptEnv);
1843                                 client->scriptEnv = NULL;
1844                                 client->scriptEnvsize = 0;
1845                                 error("script_set_env: no memory for variable");
1846                         }
1847                         client->scriptEnv = newscriptEnv;
1848                         client->scriptEnvsize = newscriptEnvsize;
1849                 }
1850                 /* need to set the NULL pointer at end of array beyond
1851                    the new slot. */
1852                 client->scriptEnv[i + 1] = NULL;
1853         }
1854         /* Allocate space and format the variable in the appropriate slot. */
1855         client->scriptEnv[i] = malloc(strlen(prefix) + strlen(name) + 1 +
1856             strlen(value) + 1);
1857         if (client->scriptEnv[i] == NULL)
1858                 error("script_set_env: no memory for variable assignment");
1859
1860         /* No `` or $() command substitution allowed in environment values! */
1861         for (j = 0; j < strlen(value); j++)
1862                 switch (value[j]) {
1863                 case '`':
1864                 case '$':
1865                         error("illegal character (%c) in value '%s'", value[j],
1866                             value);
1867                         /* not reached */
1868                 }
1869         snprintf(client->scriptEnv[i], strlen(prefix) + strlen(name) +
1870             1 + strlen(value) + 1, "%s%s=%s", prefix, name, value);
1871 }
1872
1873 void
1874 script_flush_env(void)
1875 {
1876         int i;
1877
1878         for (i = 0; client->scriptEnv[i]; i++) {
1879                 free(client->scriptEnv[i]);
1880                 client->scriptEnv[i] = NULL;
1881         }
1882         client->scriptEnvsize = 0;
1883 }
1884
1885 int
1886 dhcp_option_ev_name(char *buf, size_t buflen, const struct option *option)
1887 {
1888         size_t i;
1889
1890         for (i = 0; option->name[i]; i++) {
1891                 if (i + 1 == buflen)
1892                         return 0;
1893                 if (option->name[i] == '-')
1894                         buf[i] = '_';
1895                 else
1896                         buf[i] = option->name[i];
1897         }
1898
1899         buf[i] = 0;
1900         return 1;
1901 }
1902
1903 void
1904 go_daemon(void)
1905 {
1906         static int state = 0;
1907
1908         if (no_daemon || state)
1909                 return;
1910
1911         state = 1;
1912
1913         /* Stop logging to stderr... */
1914         log_perror = 0;
1915
1916         if (daemon(1, 0) == -1)
1917                 error("daemon");
1918
1919         /* we are chrooted, daemon(3) fails to open /dev/null */
1920         if (nullfd != -1) {
1921                 dup2(nullfd, STDIN_FILENO);
1922                 dup2(nullfd, STDOUT_FILENO);
1923                 dup2(nullfd, STDERR_FILENO);
1924                 close(nullfd);
1925                 nullfd = -1;
1926         }
1927 }
1928
1929 int
1930 check_option(struct client_lease *l, int option)
1931 {
1932         char *opbuf;
1933         char *sbuf;
1934
1935         /* we use this, since this is what gets passed to dhclient-script */
1936
1937         opbuf = pretty_print_option(option, l->options[option].data,
1938             l->options[option].len, 0, 0);
1939
1940         sbuf = option_as_string(option, l->options[option].data,
1941             l->options[option].len);
1942
1943         switch (option) {
1944         case DHO_SUBNET_MASK:
1945         case DHO_TIME_SERVERS:
1946         case DHO_NAME_SERVERS:
1947         case DHO_ROUTERS:
1948         case DHO_DOMAIN_NAME_SERVERS:
1949         case DHO_LOG_SERVERS:
1950         case DHO_COOKIE_SERVERS:
1951         case DHO_LPR_SERVERS:
1952         case DHO_IMPRESS_SERVERS:
1953         case DHO_RESOURCE_LOCATION_SERVERS:
1954         case DHO_SWAP_SERVER:
1955         case DHO_BROADCAST_ADDRESS:
1956         case DHO_NIS_SERVERS:
1957         case DHO_NTP_SERVERS:
1958         case DHO_NETBIOS_NAME_SERVERS:
1959         case DHO_NETBIOS_DD_SERVER:
1960         case DHO_FONT_SERVERS:
1961         case DHO_DHCP_SERVER_IDENTIFIER:
1962                 if (!ipv4addrs(opbuf)) {
1963                         warning("Invalid IP address in option: %s", opbuf);
1964                         return (0);
1965                 }
1966                 return (1);
1967         case DHO_HOST_NAME:
1968         case DHO_DOMAIN_NAME:
1969         case DHO_NIS_DOMAIN:
1970                 if (!res_hnok(sbuf)) {
1971                         warning("Bogus Host Name option %d: %s (%s)", option,
1972                             sbuf, opbuf);
1973                         l->options[option].len = 0;
1974                         free(l->options[option].data);
1975                 }
1976                 return (1);
1977         case DHO_PAD:
1978         case DHO_TIME_OFFSET:
1979         case DHO_BOOT_SIZE:
1980         case DHO_MERIT_DUMP:
1981         case DHO_ROOT_PATH:
1982         case DHO_EXTENSIONS_PATH:
1983         case DHO_IP_FORWARDING:
1984         case DHO_NON_LOCAL_SOURCE_ROUTING:
1985         case DHO_POLICY_FILTER:
1986         case DHO_MAX_DGRAM_REASSEMBLY:
1987         case DHO_DEFAULT_IP_TTL:
1988         case DHO_PATH_MTU_AGING_TIMEOUT:
1989         case DHO_PATH_MTU_PLATEAU_TABLE:
1990         case DHO_INTERFACE_MTU:
1991         case DHO_ALL_SUBNETS_LOCAL:
1992         case DHO_PERFORM_MASK_DISCOVERY:
1993         case DHO_MASK_SUPPLIER:
1994         case DHO_ROUTER_DISCOVERY:
1995         case DHO_ROUTER_SOLICITATION_ADDRESS:
1996         case DHO_STATIC_ROUTES:
1997         case DHO_TRAILER_ENCAPSULATION:
1998         case DHO_ARP_CACHE_TIMEOUT:
1999         case DHO_IEEE802_3_ENCAPSULATION:
2000         case DHO_DEFAULT_TCP_TTL:
2001         case DHO_TCP_KEEPALIVE_INTERVAL:
2002         case DHO_TCP_KEEPALIVE_GARBAGE:
2003         case DHO_VENDOR_ENCAPSULATED_OPTIONS:
2004         case DHO_NETBIOS_NODE_TYPE:
2005         case DHO_NETBIOS_SCOPE:
2006         case DHO_X_DISPLAY_MANAGER:
2007         case DHO_DHCP_REQUESTED_ADDRESS:
2008         case DHO_DHCP_LEASE_TIME:
2009         case DHO_DHCP_OPTION_OVERLOAD:
2010         case DHO_DHCP_MESSAGE_TYPE:
2011         case DHO_DHCP_PARAMETER_REQUEST_LIST:
2012         case DHO_DHCP_MESSAGE:
2013         case DHO_DHCP_MAX_MESSAGE_SIZE:
2014         case DHO_DHCP_RENEWAL_TIME:
2015         case DHO_DHCP_REBINDING_TIME:
2016         case DHO_DHCP_CLASS_IDENTIFIER:
2017         case DHO_DHCP_CLIENT_IDENTIFIER:
2018         case DHO_DHCP_USER_CLASS_ID:
2019         case DHO_END:
2020                 return (1);
2021         default:
2022                 warning("unknown dhcp option value 0x%x", option);
2023                 return (unknown_ok);
2024         }
2025 }
2026
2027 int
2028 res_hnok(const char *name)
2029 {
2030         const char *dn = name;
2031         int pch = '.', ch = *dn++;
2032         int warn = 0;
2033
2034         while (ch != '\0') {
2035                 int nch = *dn++;
2036
2037                 if (ch == '.') {
2038                         ;
2039                 } else if (pch == '.' || nch == '.' || nch == '\0') {
2040                         if (!isalnum(ch))
2041                                 return (0);
2042                 } else if (!isalnum(ch) && ch != '-' && ch != '_')
2043                                 return (0);
2044                 else if (ch == '_' && warn == 0) {
2045                         warning("warning: hostname %s contains an "
2046                             "underscore which violates RFC 952", name);
2047                         warn++;
2048                 }
2049                 pch = ch, ch = nch;
2050         }
2051         return (1);
2052 }
2053
2054 /* Does buf consist only of dotted decimal ipv4 addrs?
2055  * return how many if so,
2056  * otherwise, return 0
2057  */
2058 int
2059 ipv4addrs(char * buf)
2060 {
2061         struct in_addr jnk;
2062         int count = 0;
2063
2064         while (inet_aton(buf, &jnk) == 1){
2065                 count++;
2066                 while (*buf == '.' || isdigit(*buf))
2067                         buf++;
2068                 if (*buf == '\0')
2069                         return (count);
2070                 while (*buf ==  ' ')
2071                         buf++;
2072         }
2073         return (0);
2074 }
2075
2076 char *
2077 option_as_string(unsigned int code, unsigned char *data, int len)
2078 {
2079         static char optbuf[32768]; /* XXX */
2080         char *op = optbuf;
2081         int opleft = sizeof(optbuf);
2082         unsigned char *dp = data;
2083
2084         if (code > 255)
2085                 error("option_as_string: bad code %d", code);
2086
2087         for (; dp < data + len; dp++) {
2088                 if (!isascii(*dp) || !isprint(*dp)) {
2089                         if (dp + 1 != data + len || *dp != 0) {
2090                                 size_t oplen;
2091                                 snprintf(op, opleft, "\\%03o", *dp);
2092                                 oplen = strlen(op);
2093                                 op += oplen;
2094                                 opleft -= oplen;
2095                         }
2096                 } else if (*dp == '"' || *dp == '\'' || *dp == '$' ||
2097                     *dp == '`' || *dp == '\\') {
2098                         *op++ = '\\';
2099                         *op++ = *dp;
2100                         opleft -= 2;
2101                 } else {
2102                         *op++ = *dp;
2103                         opleft--;
2104                 }
2105         }
2106         if (opleft < 1)
2107                 goto toobig;
2108         *op = 0;
2109         return optbuf;
2110 toobig:
2111         warning("dhcp option too large");
2112         return "<error>";
2113 }
2114
2115 int
2116 fork_privchld(int fd, int fd2)
2117 {
2118         struct pollfd pfd[1];
2119         int nfds, pfail = 0;
2120
2121         switch (fork()) {
2122         case -1:
2123                 error("cannot fork");
2124                 break;
2125         case 0:
2126                 break;
2127         default:
2128                 return (0);
2129         }
2130
2131         if (chdir("/") == -1)
2132                 error("chdir(\"/\")");
2133
2134         setproctitle("%s [priv]", ifi->name);
2135
2136         dup2(nullfd, STDIN_FILENO);
2137         dup2(nullfd, STDOUT_FILENO);
2138         dup2(nullfd, STDERR_FILENO);
2139         close(nullfd);
2140         close(fd2);
2141
2142         for (;;) {
2143                 pfd[0].fd = fd;
2144                 pfd[0].events = POLLIN;
2145                 if ((nfds = poll(pfd, 1, INFTIM)) == -1)
2146                         if (errno != EINTR)
2147                                 error("poll error");
2148
2149                 /*
2150                  * Handle temporary errors, but bail if they persist.
2151                  */
2152                 if (nfds == 0 || !(pfd[0].revents & POLLIN)) {
2153                         if (pfail > POLL_FAILURES)
2154                                 error("poll failed > %d times", POLL_FAILURES);
2155                         sleep(pfail * POLL_FAILURE_WAIT);
2156                         pfail++;
2157                         continue;
2158                 }
2159
2160                 dispatch_imsg(fd);
2161         }
2162 }