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