dhclient - Print out debug messages only when DEBUG is defined.
[dragonfly.git] / sbin / dhclient / dhclient.c
... / ...
CommitLineData
1/* $OpenBSD: src/sbin/dhclient/dhclient.c,v 1.129 2009/06/06 04:02:42 krw Exp $ */
2
3/*
4 * Copyright 2004 Henning Brauer <henning@openbsd.org>
5 * Copyright (c) 1995, 1996, 1997, 1998, 1999
6 * The Internet Software Consortium. All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 *
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
17 * 3. Neither the name of The Internet Software Consortium nor the names
18 * of its contributors may be used to endorse or promote products derived
19 * from this software without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE INTERNET SOFTWARE CONSORTIUM AND
22 * CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
23 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
24 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
25 * DISCLAIMED. IN NO EVENT SHALL THE INTERNET SOFTWARE CONSORTIUM OR
26 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
27 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
28 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
29 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
30 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
31 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
32 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * SUCH DAMAGE.
34 *
35 * This software has been written for the Internet Software Consortium
36 * by Ted Lemon <mellon@fugue.com> in cooperation with Vixie
37 * Enterprises. To learn more about the Internet Software Consortium,
38 * see ``http://www.vix.com/isc''. To learn more about Vixie
39 * Enterprises, see ``http://www.vix.com''.
40 *
41 * This client was substantially modified and enhanced by Elliot Poger
42 * for use on Linux while he was working on the MosquitoNet project at
43 * Stanford.
44 *
45 * The current version owes much to Elliot's Linux enhancements, but
46 * was substantially reorganized and partially rewritten by Ted Lemon
47 * so as to use the same networking framework that the Internet Software
48 * Consortium DHCP server uses. Much system-specific configuration code
49 * was moved into a shell script so that as support for more operating
50 * systems is added, it will not be necessary to port and maintain
51 * system-specific configuration code to these operating systems - instead,
52 * the shell script can invoke the native tools to accomplish the same
53 * purpose.
54 */
55
56#include <ctype.h>
57#include <poll.h>
58#include <pwd.h>
59#include <unistd.h>
60
61#include "dhcpd.h"
62#include "privsep.h"
63
64#define CLIENT_PATH "PATH=/usr/bin:/usr/sbin:/bin:/sbin"
65#define DEFAULT_LEASE_TIME 43200 /* 12 hours... */
66#define TIME_MAX 2147483647
67#define POLL_FAILURES 10
68#define POLL_FAILURE_WAIT 1 /* Back off multiplier (seconds) */
69
70time_t cur_time;
71
72char *path_dhclient_conf = _PATH_DHCLIENT_CONF;
73char *path_dhclient_db = NULL;
74
75int log_perror = 1;
76int privfd;
77int nullfd = -1;
78int no_daemon;
79int unknown_ok = 1;
80int routefd = -1;
81
82struct iaddr iaddr_broadcast = { 4, { 255, 255, 255, 255 } };
83struct in_addr inaddr_any;
84struct sockaddr_in sockaddr_broadcast;
85
86struct interface_info *ifi;
87struct client_state *client;
88struct client_config *config;
89
90int findproto(char *, int);
91struct sockaddr *get_ifa(char *, int);
92void usage(void);
93int check_option(struct client_lease *l, int option);
94int ipv4addrs(char * buf);
95int res_hnok(const char *dn);
96char *option_as_string(unsigned int code, unsigned char *data, int len);
97int 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
103time_t scripttime;
104static FILE *leaseFile;
105
106int
107findproto(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
136struct sockaddr *
137get_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}
154struct iaddr defaddr = { .len = 4 }; /* NULL is for silence warnings */
155
156void
157routehandler(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 for (l = client->active; l != NULL; l = l->next)
201 if (addr_eq(a, l->address))
202 break;
203
204 if (l != NULL || (client->alias &&
205 addr_eq(a, client->alias->address)))
206 /* new addr is the one we set */
207 break;
208 snprintf(buf, sizeof(buf), "%s: %s",
209 "new address not one we set", piaddr(a));
210 errmsg = buf;
211 goto die;
212 case RTM_DELADDR:
213 ifam = (struct ifa_msghdr *)rtm;
214 if (ifam->ifam_index != ifi->index)
215 break;
216 if (findproto((char *)(ifam + 1), ifam->ifam_addrs) != AF_INET)
217 break;
218 if (scripttime == 0 || t < scripttime + 10)
219 break;
220 errmsg = "interface address deleted";
221 goto die;
222 case RTM_IFINFO:
223 ifm = (struct if_msghdr *)rtm;
224 if (ifm->ifm_index != ifi->index)
225 break;
226 if ((rtm->rtm_flags & RTF_UP) == 0) {
227 errmsg = "interface down";
228 goto die;
229 }
230
231 linkstat =
232 LINK_STATE_IS_UP(ifm->ifm_data.ifi_link_state) ? 1 : 0;
233 if (linkstat != ifi->linkstat) {
234#ifdef DEBUG
235 debug("link state %s -> %s",
236 ifi->linkstat ? "up" : "down",
237 linkstat ? "up" : "down");
238#endif
239 ifi->linkstat = interface_link_status(ifi->name);
240 if (ifi->linkstat) {
241 client->state = S_INIT;
242 state_reboot();
243 }
244 }
245 break;
246 case RTM_IFANNOUNCE:
247 ifan = (struct if_announcemsghdr *)rtm;
248 if (ifan->ifan_what == IFAN_DEPARTURE &&
249 ifan->ifan_index == ifi->index) {
250 errmsg = "interface departure";
251 goto die;
252 }
253 break;
254 default:
255 break;
256 }
257 return;
258
259die:
260 script_init("FAIL", NULL);
261 if (client->alias)
262 script_write_params("alias_", client->alias);
263 script_go();
264 error("routehandler: %s", errmsg);
265}
266
267int
268main(int argc, char *argv[])
269{
270 int ch, fd, quiet = 0, i = 0, pipe_fd[2];
271 struct passwd *pw;
272
273 /* Initially, log errors to stderr as well as to syslogd. */
274 openlog(getprogname(), LOG_PID | LOG_NDELAY, DHCPD_LOG_FACILITY);
275 setlogmask(LOG_UPTO(LOG_INFO));
276
277 while ((ch = getopt(argc, argv, "c:dl:qu")) != -1)
278 switch (ch) {
279 case 'c':
280 path_dhclient_conf = optarg;
281 break;
282 case 'd':
283 no_daemon = 1;
284 break;
285 case 'l':
286 path_dhclient_db = optarg;
287 break;
288 case 'q':
289 quiet = 1;
290 break;
291 case 'u':
292 unknown_ok = 0;
293 break;
294 default:
295 usage();
296 }
297
298 argc -= optind;
299 argv += optind;
300
301 if (argc != 1)
302 usage();
303
304 ifi = calloc(1, sizeof(*ifi));
305 if (ifi == NULL)
306 error("ifi calloc");
307 client = calloc(1, sizeof(*client));
308 if (client == NULL)
309 error("client calloc");
310 config = calloc(1, sizeof(*config));
311 if (config == NULL)
312 error("config calloc");
313
314 if (strlcpy(ifi->name, argv[0], IFNAMSIZ) >= IFNAMSIZ)
315 error("Interface name too long");
316 if (path_dhclient_db == NULL && asprintf(&path_dhclient_db, "%s.%s",
317 _PATH_DHCLIENT_DB, ifi->name) == -1)
318 error("asprintf");
319
320 if (quiet)
321 log_perror = 0;
322
323 tzset();
324 time(&cur_time);
325
326 memset(&sockaddr_broadcast, 0, sizeof(sockaddr_broadcast));
327 sockaddr_broadcast.sin_family = AF_INET;
328 sockaddr_broadcast.sin_port = htons(REMOTE_PORT);
329 sockaddr_broadcast.sin_addr.s_addr = INADDR_BROADCAST;
330 sockaddr_broadcast.sin_len = sizeof(sockaddr_broadcast);
331 inaddr_any.s_addr = INADDR_ANY;
332
333 read_client_conf();
334
335 if (interface_status(ifi->name) == 0) {
336 interface_link_forceup(ifi->name);
337 /* Give it up to 4 seconds of silent grace to find link */
338 i = -4;
339 } else
340 i = 0;
341
342 while (!(ifi->linkstat = interface_link_status(ifi->name))) {
343 if (i == 0)
344 fprintf(stderr, "%s: no link ...", ifi->name);
345 else if (i > 0)
346 fprintf(stderr, ".");
347 fflush(stderr);
348 if (++i > config->link_timeout) {
349 fprintf(stderr, " sleeping\n");
350 goto dispatch;
351 }
352 sleep(1);
353 }
354 if (i > 0)
355 fprintf(stderr, " got link\n");
356
357 dispatch:
358 if ((nullfd = open(_PATH_DEVNULL, O_RDWR, 0)) == -1)
359 error("cannot open %s: %m", _PATH_DEVNULL);
360
361 if ((pw = getpwnam("_dhcp")) == NULL)
362 error("no such user: _dhcp");
363
364 if (pipe(pipe_fd) == -1)
365 error("pipe");
366
367 fork_privchld(pipe_fd[0], pipe_fd[1]);
368
369 close(pipe_fd[0]);
370 privfd = pipe_fd[1];
371
372 if ((fd = open(path_dhclient_db, O_RDONLY|O_EXLOCK|O_CREAT, 0)) == -1)
373 error("can't open and lock %s: %m", path_dhclient_db);
374 read_client_leases();
375 if ((leaseFile = fopen(path_dhclient_db, "w")) == NULL)
376 error("can't open %s: %m", path_dhclient_db);
377 rewrite_client_leases();
378 close(fd);
379
380 priv_script_init("PREINIT", NULL);
381 if (client->alias)
382 priv_script_write_params("alias_", client->alias);
383 priv_script_go();
384
385 if ((routefd = socket(PF_ROUTE, SOCK_RAW, 0)) == -1)
386 error("socket(PF_ROUTE, SOCK_RAW): %m");
387
388 /* set up the interface */
389 discover_interface();
390
391 if (chroot(_PATH_VAREMPTY) == -1)
392 error("chroot");
393 if (chdir("/") == -1)
394 error("chdir(\"/\")");
395
396 if (setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) == -1)
397 error("setresgid");
398 if (setgroups(1, &pw->pw_gid) == -1)
399 error("setgroups");
400 if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) == -1)
401 error("setresuid");
402
403 endpwent();
404
405 setproctitle("%s", ifi->name);
406
407 if (ifi->linkstat) {
408 client->state = S_INIT;
409 state_reboot();
410 } else
411 go_daemon();
412
413 dispatch();
414
415 /* not reached */
416 return (0);
417}
418
419void
420usage(void)
421{
422 fprintf(stderr, "usage: %s [-dqu] [-c file] [-l file] interface\n",
423 getprogname());
424 exit(1);
425}
426
427/*
428 * Individual States:
429 *
430 * Each routine is called from the dhclient_state_machine() in one of
431 * these conditions:
432 * -> entering INIT state
433 * -> recvpacket_flag == 0: timeout in this state
434 * -> otherwise: received a packet in this state
435 *
436 * Return conditions as handled by dhclient_state_machine():
437 * Returns 1, sendpacket_flag = 1: send packet, reset timer.
438 * Returns 1, sendpacket_flag = 0: just reset the timer (wait for a milestone).
439 * Returns 0: finish the nap which was interrupted for no good reason.
440 *
441 * Several per-interface variables are used to keep track of the process:
442 * active_lease: the lease that is being used on the interface
443 * (null pointer if not configured yet).
444 * offered_leases: leases corresponding to DHCPOFFER messages that have
445 * been sent to us by DHCP servers.
446 * acked_leases: leases corresponding to DHCPACK messages that have been
447 * sent to us by DHCP servers.
448 * sendpacket: DHCP packet we're trying to send.
449 * destination: IP address to send sendpacket to
450 * In addition, there are several relevant per-lease variables.
451 * T1_expiry, T2_expiry, lease_expiry: lease milestones
452 * In the active lease, these control the process of renewing the lease;
453 * In leases on the acked_leases list, this simply determines when we
454 * can no longer legitimately use the lease.
455 */
456void
457state_reboot(void)
458{
459 /* If we don't remember an active lease, go straight to INIT. */
460 if (!client->active || client->active->is_bootp) {
461 state_init();
462 return;
463 }
464
465 /* We are in the rebooting state. */
466 client->state = S_REBOOTING;
467
468 /* make_request doesn't initialize xid because it normally comes
469 from the DHCPDISCOVER, but we haven't sent a DHCPDISCOVER,
470 so pick an xid now. */
471 client->xid = arc4random();
472
473 /* Make a DHCPREQUEST packet, and set appropriate per-interface
474 flags. */
475 make_request(client->active);
476 client->destination = iaddr_broadcast;
477 client->first_sending = cur_time;
478 client->interval = config->initial_interval;
479
480 /* Zap the medium list... */
481 client->medium = NULL;
482
483 /* Send out the first DHCPREQUEST packet. */
484 send_request();
485}
486
487/*
488 * Called when a lease has completely expired and we've
489 * been unable to renew it.
490 */
491void
492state_init(void)
493{
494 /* Make a DHCPDISCOVER packet, and set appropriate per-interface
495 flags. */
496 make_discover(client->active);
497 client->xid = client->packet.xid;
498 client->destination = iaddr_broadcast;
499 client->state = S_SELECTING;
500 client->first_sending = cur_time;
501 client->interval = config->initial_interval;
502
503 /* Add an immediate timeout to cause the first DHCPDISCOVER packet
504 to go out. */
505 send_discover();
506}
507
508/*
509 * state_selecting is called when one or more DHCPOFFER packets
510 * have been received and a configurable period of time has passed.
511 */
512void
513state_selecting(void)
514{
515 struct client_lease *lp, *next, *picked;
516
517 /* Cancel state_selecting and send_discover timeouts, since either
518 one could have got us here. */
519 cancel_timeout(state_selecting);
520 cancel_timeout(send_discover);
521
522 /* We have received one or more DHCPOFFER packets. Currently,
523 the only criterion by which we judge leases is whether or
524 not we get a response when we arp for them. */
525 picked = NULL;
526 for (lp = client->offered_leases; lp; lp = next) {
527 next = lp->next;
528
529 /* Check to see if we got an ARPREPLY for the address
530 in this particular lease. */
531 if (!picked) {
532 script_init("ARPCHECK", lp->medium);
533 script_write_params("check_", lp);
534
535 /* If the ARPCHECK code detects another
536 machine using the offered address, it exits
537 nonzero. We need to send a DHCPDECLINE and
538 toss the lease. */
539 if (script_go()) {
540 make_decline(lp);
541 send_decline();
542 goto freeit;
543 }
544 picked = lp;
545 picked->next = NULL;
546 } else {
547freeit:
548 free_client_lease(lp);
549 }
550 }
551 client->offered_leases = NULL;
552
553 /* If we just tossed all the leases we were offered, go back
554 to square one. */
555 if (!picked) {
556 client->state = S_INIT;
557 state_init();
558 return;
559 }
560
561 /* If it was a BOOTREPLY, we can just take the address right now. */
562 if (!picked->options[DHO_DHCP_MESSAGE_TYPE].len) {
563 client->new = picked;
564
565 /* Make up some lease expiry times
566 XXX these should be configurable. */
567 client->new->expiry = cur_time + 12000;
568 client->new->renewal += cur_time + 8000;
569 client->new->rebind += cur_time + 10000;
570
571 client->state = S_REQUESTING;
572
573 /* Bind to the address we received. */
574 bind_lease();
575 return;
576 }
577
578 /* Go to the REQUESTING state. */
579 client->destination = iaddr_broadcast;
580 client->state = S_REQUESTING;
581 client->first_sending = cur_time;
582 client->interval = config->initial_interval;
583
584 /* Make a DHCPREQUEST packet from the lease we picked. */
585 make_request(picked);
586 client->xid = client->packet.xid;
587
588 /* Toss the lease we picked - we'll get it back in a DHCPACK. */
589 free_client_lease(picked);
590
591 /* Add an immediate timeout to send the first DHCPREQUEST packet. */
592 send_request();
593}
594
595void
596dhcpack(struct iaddr client_addr, struct option_data *options)
597{
598 struct client_lease *lease;
599
600
601 if (client->state != S_REBOOTING &&
602 client->state != S_REQUESTING &&
603 client->state != S_RENEWING &&
604 client->state != S_REBINDING)
605 return;
606
607
608 lease = packet_to_lease(options);
609 if (!lease) {
610 note("packet_to_lease failed.");
611 return;
612 }
613
614 client->new = lease;
615
616 /* Stop resending DHCPREQUEST. */
617 cancel_timeout(send_request);
618
619 /* Figure out the lease time. */
620 if (client->new->options[DHO_DHCP_LEASE_TIME].data)
621 client->new->expiry =
622 getULong(client->new->options[DHO_DHCP_LEASE_TIME].data);
623 else
624 client->new->expiry = DEFAULT_LEASE_TIME;
625 /* A number that looks negative here is really just very large,
626 because the lease expiry offset is unsigned. */
627 if (client->new->expiry < 0)
628 client->new->expiry = TIME_MAX;
629 /* XXX should be fixed by resetting the client state */
630 if (client->new->expiry < 60)
631 client->new->expiry = 60;
632
633 /* Take the server-provided renewal time if there is one;
634 otherwise figure it out according to the spec. */
635 if (client->new->options[DHO_DHCP_RENEWAL_TIME].len)
636 client->new->renewal =
637 getULong(client->new->options[DHO_DHCP_RENEWAL_TIME].data);
638 else
639 client->new->renewal = client->new->expiry / 2;
640
641 /* Same deal with the rebind time. */
642 if (client->new->options[DHO_DHCP_REBINDING_TIME].len)
643 client->new->rebind =
644 getULong(client->new->options[DHO_DHCP_REBINDING_TIME].data);
645 else
646 client->new->rebind = client->new->renewal +
647 client->new->renewal / 2 + client->new->renewal / 4;
648
649 client->new->expiry += cur_time;
650 /* Lease lengths can never be negative. */
651 if (client->new->expiry < cur_time)
652 client->new->expiry = TIME_MAX;
653 client->new->renewal += cur_time;
654 if (client->new->renewal < cur_time)
655 client->new->renewal = TIME_MAX;
656 client->new->rebind += cur_time;
657 if (client->new->rebind < cur_time)
658 client->new->rebind = TIME_MAX;
659
660 bind_lease();
661}
662
663void
664bind_lease(void)
665{
666 /* Remember the medium. */
667 client->new->medium = client->medium;
668
669 /* Write out the new lease. */
670 write_client_lease(client->new, 0);
671
672 /* Run the client script with the new parameters. */
673 script_init((client->state == S_REQUESTING ? "BOUND" :
674 (client->state == S_RENEWING ? "RENEW" :
675 (client->state == S_REBOOTING ? "REBOOT" : "REBIND"))),
676 client->new->medium);
677 if (client->active && client->state != S_REBOOTING)
678 script_write_params("old_", client->active);
679 script_write_params("new_", client->new);
680 if (client->alias)
681 script_write_params("alias_", client->alias);
682 script_go();
683
684 /* Replace the old active lease with the new one. */
685 if (client->active)
686 free_client_lease(client->active);
687 client->active = client->new;
688 client->new = NULL;
689
690 /* Set up a timeout to start the renewal process. */
691 add_timeout(client->active->renewal, state_bound);
692
693 note("bound to %s -- renewal in %ld seconds.",
694 piaddr(client->active->address),
695 client->active->renewal - cur_time);
696 client->state = S_BOUND;
697 reinitialize_interface();
698 go_daemon();
699}
700
701/*
702 * state_bound is called when we've successfully bound to a particular
703 * lease, but the renewal time on that lease has expired. We are
704 * expected to unicast a DHCPREQUEST to the server that gave us our
705 * original lease.
706 */
707void
708state_bound(void)
709{
710 /* T1 has expired. */
711 make_request(client->active);
712 client->xid = client->packet.xid;
713
714 if (client->active->options[DHO_DHCP_SERVER_IDENTIFIER].len == 4) {
715 memcpy(client->destination.iabuf,
716 client->active->options[DHO_DHCP_SERVER_IDENTIFIER].data,
717 4);
718 client->destination.len = 4;
719 } else
720 client->destination = iaddr_broadcast;
721
722 client->first_sending = cur_time;
723 client->interval = config->initial_interval;
724 client->state = S_RENEWING;
725
726 /* Send the first packet immediately. */
727 send_request();
728}
729
730void
731dhcpoffer(struct iaddr client_addr, struct option_data *options)
732{
733 struct client_lease *lease, *lp;
734 int i;
735 int arp_timeout_needed, stop_selecting;
736 char *name = options[DHO_DHCP_MESSAGE_TYPE].len ? "DHCPOFFER" :
737 "BOOTREPLY";
738
739
740 if (client->state != S_SELECTING)
741 return;
742
743
744 /* If this lease doesn't supply the minimum required parameters,
745 blow it off. */
746 for (i = 0; config->required_options[i]; i++) {
747 if (!options[config->required_options[i]].len) {
748 note("%s isn't satisfactory.", name);
749 return;
750 }
751 }
752
753 /* If we've already seen this lease, don't record it again. */
754 for (lease = client->offered_leases;
755 lease; lease = lease->next) {
756 if (lease->address.len == sizeof(client->packet.yiaddr) &&
757 !memcmp(lease->address.iabuf,
758 &client->packet.yiaddr, lease->address.len)) {
759#ifdef DEBUG
760 debug("%s already seen.", name);
761#endif
762 return;
763 }
764 }
765
766 lease = packet_to_lease(options);
767 if (!lease) {
768 note("packet_to_lease failed.");
769 return;
770 }
771
772 /* If this lease was acquired through a BOOTREPLY, record that
773 fact. */
774 if (!options[DHO_DHCP_MESSAGE_TYPE].len)
775 lease->is_bootp = 1;
776
777 /* Record the medium under which this lease was offered. */
778 lease->medium = client->medium;
779
780 /* Send out an ARP Request for the offered IP address. */
781 script_init("ARPSEND", lease->medium);
782 script_write_params("check_", lease);
783 /* If the script can't send an ARP request without waiting,
784 we'll be waiting when we do the ARPCHECK, so don't wait now. */
785 if (script_go())
786 arp_timeout_needed = 0;
787 else
788 arp_timeout_needed = 2;
789
790 /* Figure out when we're supposed to stop selecting. */
791 stop_selecting = client->first_sending + config->select_interval;
792
793 /* If this is the lease we asked for, put it at the head of the
794 list, and don't mess with the arp request timeout. */
795 if (lease->address.len == client->requested_address.len &&
796 !memcmp(lease->address.iabuf,
797 client->requested_address.iabuf,
798 client->requested_address.len)) {
799 lease->next = client->offered_leases;
800 client->offered_leases = lease;
801 } else {
802 /* If we already have an offer, and arping for this
803 offer would take us past the selection timeout,
804 then don't extend the timeout - just hope for the
805 best. */
806 if (client->offered_leases &&
807 (cur_time + arp_timeout_needed) > stop_selecting)
808 arp_timeout_needed = 0;
809
810 /* Put the lease at the end of the list. */
811 lease->next = NULL;
812 if (!client->offered_leases)
813 client->offered_leases = lease;
814 else {
815 for (lp = client->offered_leases; lp->next;
816 lp = lp->next)
817 ; /* nothing */
818 lp->next = lease;
819 }
820 }
821
822 /* If we're supposed to stop selecting before we've had time
823 to wait for the ARPREPLY, add some delay to wait for
824 the ARPREPLY. */
825 if (stop_selecting - cur_time < arp_timeout_needed)
826 stop_selecting = cur_time + arp_timeout_needed;
827
828 /* If the selecting interval has expired, go immediately to
829 state_selecting(). Otherwise, time out into
830 state_selecting at the select interval. */
831 if (stop_selecting <= 0)
832 state_selecting();
833 else {
834 add_timeout(stop_selecting, state_selecting);
835 cancel_timeout(send_discover);
836 }
837}
838
839/*
840 * Allocate a client_lease structure and initialize it from the
841 * parameters in the specified packet.
842 */
843struct client_lease *
844packet_to_lease(struct option_data *options)
845{
846 struct client_lease *lease;
847 int i;
848
849 lease = malloc(sizeof(struct client_lease));
850
851 if (!lease) {
852 warning("dhcpoffer: no memory to record lease.");
853 return (NULL);
854 }
855
856 memset(lease, 0, sizeof(*lease));
857
858 /* Copy the lease options. */
859 for (i = 0; i < 256; i++) {
860 if (options[i].len) {
861 lease->options[i] = options[i];
862 options[i].data = NULL;
863 options[i].len = 0;
864 if (!check_option(lease, i)) {
865 warning("Invalid lease option - ignoring offer");
866 free_client_lease(lease);
867 return (NULL);
868 }
869 }
870 }
871
872 lease->address.len = sizeof(client->packet.yiaddr);
873 memcpy(lease->address.iabuf, &client->packet.yiaddr,
874 lease->address.len);
875
876 /* If the server name was filled out, copy it. */
877 if ((!lease->options[DHO_DHCP_OPTION_OVERLOAD].len ||
878 !(lease->options[DHO_DHCP_OPTION_OVERLOAD].data[0] & 2)) &&
879 client->packet.sname[0]) {
880 lease->server_name = malloc(DHCP_SNAME_LEN + 1);
881 if (!lease->server_name) {
882 warning("dhcpoffer: no memory for server name.");
883 free_client_lease(lease);
884 return (NULL);
885 }
886 memcpy(lease->server_name, client->packet.sname,
887 DHCP_SNAME_LEN);
888 lease->server_name[DHCP_SNAME_LEN] = '\0';
889 if (!res_hnok(lease->server_name)) {
890 warning("Bogus server name %s", lease->server_name);
891 free(lease->server_name);
892 lease->server_name = NULL;
893 }
894 }
895
896 /* Ditto for the filename. */
897 if ((!lease->options[DHO_DHCP_OPTION_OVERLOAD].len ||
898 !(lease->options[DHO_DHCP_OPTION_OVERLOAD].data[0] & 1)) &&
899 client->packet.file[0]) {
900 /* Don't count on the NUL terminator. */
901 lease->filename = malloc(DHCP_FILE_LEN + 1);
902 if (!lease->filename) {
903 warning("dhcpoffer: no memory for filename.");
904 free_client_lease(lease);
905 return (NULL);
906 }
907 memcpy(lease->filename, client->packet.file, DHCP_FILE_LEN);
908 lease->filename[DHCP_FILE_LEN] = '\0';
909 }
910 return lease;
911}
912
913void
914dhcpnak(struct iaddr client_addr, struct option_data *options)
915{
916
917 if (client->state != S_REBOOTING &&
918 client->state != S_REQUESTING &&
919 client->state != S_RENEWING &&
920 client->state != S_REBINDING)
921 return;
922
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 */
944void
945send_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;
964again:
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 */
1036void
1037state_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
1093activate_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
1126void
1127send_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) {
1149cancel:
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
1250void
1251send_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
1261void
1262make_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
1323void
1324make_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
1403void
1404make_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
1461void
1462free_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
1477void
1478rewrite_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
1498void
1499write_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
1555void
1556script_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
1583void
1584priv_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
1607void
1608priv_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:
1655supersede:
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
1718void
1719script_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
1764int
1765script_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
1792int
1793priv_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
1828void
1829script_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
1883void
1884script_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
1895int
1896dhcp_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
1913void
1914go_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
1939int
1940check_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
2037int
2038res_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 */
2068int
2069ipv4addrs(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
2086char *
2087option_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;
2120toobig:
2121 warning("dhcp option too large");
2122 return "<error>";
2123}
2124
2125int
2126fork_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}