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