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