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