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