1 /* $OpenBSD: src/sbin/dhclient/dhclient.c,v 1.154 2012/09/01 19:02:27 krw Exp $ */
4 * Copyright 2004 Henning Brauer <henning@openbsd.org>
5 * Copyright (c) 1995, 1996, 1997, 1998, 1999
6 * The Internet Software Consortium. All rights reserved.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
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.
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
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''.
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
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
55 #include <sys/ioctl.h>
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) */
71 char *path_dhclient_conf = _PATH_DHCLIENT_CONF;
72 char *path_dhclient_db = NULL;
81 struct iaddr iaddr_broadcast = { 4, { 255, 255, 255, 255 } };
82 struct in_addr inaddr_any;
83 struct sockaddr_in sockaddr_broadcast;
85 struct interface_info *ifi;
86 struct client_state *client;
87 struct client_config *config;
89 int findproto(char *, int);
90 struct sockaddr *get_ifa(char *, int);
92 int check_option(struct client_lease *l, int option);
93 int ipv4addrs(char * buf);
94 int res_hnok(const char *dn);
95 char *option_as_string(unsigned int code, unsigned char *data, int len);
96 int fork_privchld(int, int);
97 void get_ifname(char *, char *);
100 static FILE *leaseFile;
103 findproto(char *cp, int n)
110 for (i = 1; i; i <<= 1) {
112 sa = (struct sockaddr *)cp;
118 if (sa->sa_family == AF_INET)
120 if (sa->sa_family == AF_INET6)
133 get_ifa(char *cp, int n)
140 for (i = 1; i; i <<= 1)
142 sa = (struct sockaddr *)cp;
150 struct iaddr defaddr = { .len = 4 }; /* NULL is for silence warnings */
157 struct rt_msghdr *rtm;
158 struct if_msghdr *ifm;
159 struct ifa_msghdr *ifam;
160 struct if_announcemsghdr *ifan;
161 struct client_lease *l;
165 char *errmsg, buf[64];
168 n = read(routefd, &msg, sizeof(msg));
169 } while (n == -1 && errno == EINTR);
171 rtm = (struct rt_msghdr *)msg;
172 if (n < sizeof(rtm->rtm_msglen) || n < rtm->rtm_msglen ||
173 rtm->rtm_version != RTM_VERSION)
176 switch (rtm->rtm_type) {
178 ifam = (struct ifa_msghdr *)rtm;
179 if (ifam->ifam_index != ifi->index)
181 if (findproto((char *)(ifam + 1), ifam->ifam_addrs) != AF_INET)
183 sa = get_ifa((char *)(ifam + 1), ifam->ifam_addrs);
185 errmsg = "sa == NULL";
189 if ((a.len = sizeof(struct in_addr)) > sizeof(a.iabuf))
190 error("king bula sez: len mismatch");
191 memcpy(a.iabuf, &((struct sockaddr_in *)sa)->sin_addr, a.len);
192 if (addr_eq(a, defaddr))
195 /* state_panic() can try unexpired existing leases */
196 if (client->active && addr_eq(a, client->active->address))
198 for (l = client->leases; l != NULL; l = l->next)
199 if (addr_eq(a, l->address))
203 /* new addr is the one we set */
205 snprintf(buf, sizeof(buf), "%s: %s",
206 "new address not one we set", piaddr(a));
210 ifam = (struct ifa_msghdr *)rtm;
211 if (ifam->ifam_index != ifi->index)
213 if (findproto((char *)(ifam + 1), ifam->ifam_addrs) != AF_INET)
215 /* XXX check addrs like RTM_NEWADDR instead of this? */
216 if (scripttime == 0 || time(NULL) < scripttime + 10)
218 errmsg = "interface address deleted";
221 ifm = (struct if_msghdr *)rtm;
222 if (ifm->ifm_index != ifi->index)
224 if ((rtm->rtm_flags & RTF_UP) == 0) {
225 errmsg = "interface down";
230 LINK_STATE_IS_UP(ifm->ifm_data.ifi_link_state) ? 1 : 0;
231 if (linkstat != ifi->linkstat) {
233 debug("link state %s -> %s",
234 ifi->linkstat ? "up" : "down",
235 linkstat ? "up" : "down");
237 ifi->linkstat = interface_status(ifi->name);
239 client->state = S_REBOOTING;
245 ifan = (struct if_announcemsghdr *)rtm;
246 if (ifan->ifan_what == IFAN_DEPARTURE &&
247 ifan->ifan_index == ifi->index) {
248 errmsg = "interface departure";
260 error("routehandler: %s", errmsg);
264 main(int argc, char *argv[])
266 int ch, fd, quiet = 0, i = 0, pipe_fd[2];
269 /* Initially, log errors to stderr as well as to syslogd. */
270 openlog(getprogname(), LOG_PID | LOG_NDELAY, DHCPD_LOG_FACILITY);
271 setlogmask(LOG_UPTO(LOG_INFO));
273 while ((ch = getopt(argc, argv, "c:dl:qu")) != -1)
276 path_dhclient_conf = optarg;
282 path_dhclient_db = optarg;
300 ifi = calloc(1, sizeof(*ifi));
303 client = calloc(1, sizeof(*client));
305 error("client calloc");
306 config = calloc(1, sizeof(*config));
308 error("config calloc");
310 get_ifname(ifi->name, argv[0]);
311 if (path_dhclient_db == NULL && asprintf(&path_dhclient_db, "%s.%s",
312 _PATH_DHCLIENT_DB, ifi->name) == -1)
320 memset(&sockaddr_broadcast, 0, sizeof(sockaddr_broadcast));
321 sockaddr_broadcast.sin_family = AF_INET;
322 sockaddr_broadcast.sin_port = htons(REMOTE_PORT);
323 sockaddr_broadcast.sin_addr.s_addr = INADDR_BROADCAST;
324 sockaddr_broadcast.sin_len = sizeof(sockaddr_broadcast);
325 inaddr_any.s_addr = INADDR_ANY;
329 if (interface_status(ifi->name) == 0) {
330 interface_link_forceup(ifi->name);
331 /* Give it up to 4 seconds of silent grace to find link */
336 while (!(ifi->linkstat = interface_status(ifi->name))) {
338 fprintf(stderr, "%s: no link ...", ifi->name);
340 fprintf(stderr, ".");
342 if (++i > config->link_timeout) {
343 fprintf(stderr, " sleeping\n");
349 fprintf(stderr, " got link\n");
352 if ((nullfd = open(_PATH_DEVNULL, O_RDWR, 0)) == -1)
353 error("cannot open %s: %m", _PATH_DEVNULL);
355 if ((pw = getpwnam("_dhcp")) == NULL)
356 error("no such user: _dhcp");
358 if (pipe(pipe_fd) == -1)
361 fork_privchld(pipe_fd[0], pipe_fd[1]);
366 if ((fd = open(path_dhclient_db, O_RDONLY|O_EXLOCK|O_CREAT, 0)) == -1)
367 error("can't open and lock %s: %m", path_dhclient_db);
368 read_client_leases();
369 if ((leaseFile = fopen(path_dhclient_db, "w")) == NULL)
370 error("can't open %s: %m", path_dhclient_db);
371 rewrite_client_leases();
374 if ((routefd = socket(PF_ROUTE, SOCK_RAW, 0)) == -1)
375 error("socket(PF_ROUTE, SOCK_RAW): %m");
377 /* set up the interface */
378 discover_interface();
380 if (chroot(_PATH_VAREMPTY) == -1)
382 if (chdir("/") == -1)
383 error("chdir(\"/\")");
385 if (setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) == -1)
387 if (setgroups(1, &pw->pw_gid) == -1)
389 if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) == -1)
394 setproctitle("%s", ifi->name);
397 client->state = S_REBOOTING;
411 fprintf(stderr, "usage: %s [-dqu] [-c file] [-l file] interface\n",
419 * Each routine is called from the dhclient_state_machine() in one of
421 * -> entering INIT state
422 * -> recvpacket_flag == 0: timeout in this state
423 * -> otherwise: received a packet in this state
425 * Return conditions as handled by dhclient_state_machine():
426 * Returns 1, sendpacket_flag = 1: send packet, reset timer.
427 * Returns 1, sendpacket_flag = 0: just reset the timer (wait for a milestone).
428 * Returns 0: finish the nap which was interrupted for no good reason.
430 * Several per-interface variables are used to keep track of the process:
431 * active_lease: the lease that is being used on the interface
432 * (null pointer if not configured yet).
433 * offered_leases: leases corresponding to DHCPOFFER messages that have
434 * been sent to us by DHCP servers.
435 * acked_leases: leases corresponding to DHCPACK messages that have been
436 * sent to us by DHCP servers.
437 * sendpacket: DHCP packet we're trying to send.
438 * destination: IP address to send sendpacket to
439 * In addition, there are several relevant per-lease variables.
440 * T1_expiry, T2_expiry, lease_expiry: lease milestones
441 * In the active lease, these control the process of renewing the lease;
442 * In leases on the acked_leases list, this simply determines when we
443 * can no longer legitimately use the lease.
448 /* Cancel all timeouts, since a link state change gets us here
449 and can happen anytime. */
452 /* If we don't remember an active lease, go straight to INIT. */
453 if (!client->active || client->active->is_bootp) {
454 client->state = S_INIT;
459 /* make_request doesn't initialize xid because it normally comes
460 from the DHCPDISCOVER, but we haven't sent a DHCPDISCOVER,
461 so pick an xid now. */
462 client->xid = arc4random();
464 /* Make a DHCPREQUEST packet, and set appropriate per-interface
466 make_request(client->active);
467 client->destination = iaddr_broadcast;
468 client->first_sending = time(NULL);
469 client->interval = 0;
475 * Called when a lease has completely expired and we've
476 * been unable to renew it.
481 /* Make a DHCPDISCOVER packet, and set appropriate per-interface
483 make_discover(client->active);
484 client->xid = client->packet.xid;
485 client->destination = iaddr_broadcast;
486 client->state = S_SELECTING;
487 client->first_sending = time(NULL);
488 client->interval = 0;
494 * state_selecting is called when one or more DHCPOFFER packets
495 * have been received and a configurable period of time has passed.
498 state_selecting(void)
500 struct client_lease *lp, *next, *picked;
503 /* Cancel state_selecting and send_discover timeouts, since either
504 one could have got us here. */
507 /* We have received one or more DHCPOFFER packets. Currently,
508 the only criterion by which we judge leases is whether or
509 not we get a response when we arp for them. */
511 for (lp = client->offered_leases; lp; lp = next) {
519 free_client_lease(lp);
522 client->offered_leases = NULL;
524 /* If we just tossed all the leases we were offered, go back
527 client->state = S_INIT;
535 /* If it was a BOOTREPLY, we can just take the address right now. */
536 if (!picked->options[DHO_DHCP_MESSAGE_TYPE].len) {
537 client->new = picked;
539 /* Make up some lease expiry times
540 XXX these should be configurable. */
541 client->new->expiry = cur_time + 12000;
542 client->new->renewal += cur_time + 8000;
543 client->new->rebind += cur_time + 10000;
545 client->state = S_REQUESTING;
547 /* Bind to the address we received. */
552 /* Go to the REQUESTING state. */
553 client->destination = iaddr_broadcast;
554 client->state = S_REQUESTING;
555 client->first_sending = cur_time;
556 client->interval = 0;
558 /* Make a DHCPREQUEST packet from the lease we picked. */
559 make_request(picked);
560 client->xid = client->packet.xid;
562 /* Toss the lease we picked - we'll get it back in a DHCPACK. */
563 free_client_lease(picked);
569 dhcpack(struct iaddr client_addr, struct option_data *options)
571 struct client_lease *lease;
575 if (client->state != S_REBOOTING &&
576 client->state != S_REQUESTING &&
577 client->state != S_RENEWING &&
578 client->state != S_REBINDING)
582 lease = packet_to_lease(options);
584 note("packet_to_lease failed.");
590 /* Stop resending DHCPREQUEST. */
593 /* Figure out the lease time. */
594 if (client->new->options[DHO_DHCP_LEASE_TIME].data)
595 client->new->expiry =
596 getULong(client->new->options[DHO_DHCP_LEASE_TIME].data);
598 client->new->expiry = DEFAULT_LEASE_TIME;
599 /* A number that looks negative here is really just very large,
600 because the lease expiry offset is unsigned. */
601 if (client->new->expiry < 0)
602 client->new->expiry = TIME_MAX;
603 /* XXX should be fixed by resetting the client state */
604 if (client->new->expiry < 60)
605 client->new->expiry = 60;
607 /* Take the server-provided renewal time if there is one;
608 otherwise figure it out according to the spec. */
609 if (client->new->options[DHO_DHCP_RENEWAL_TIME].len)
610 client->new->renewal =
611 getULong(client->new->options[DHO_DHCP_RENEWAL_TIME].data);
613 client->new->renewal = client->new->expiry / 2;
615 /* Same deal with the rebind time. */
616 if (client->new->options[DHO_DHCP_REBINDING_TIME].len)
617 client->new->rebind =
618 getULong(client->new->options[DHO_DHCP_REBINDING_TIME].data);
620 client->new->rebind = client->new->renewal +
621 client->new->renewal / 2 + client->new->renewal / 4;
625 client->new->expiry += cur_time;
626 /* Lease lengths can never be negative. */
627 if (client->new->expiry < cur_time)
628 client->new->expiry = TIME_MAX;
629 client->new->renewal += cur_time;
630 if (client->new->renewal < cur_time)
631 client->new->renewal = TIME_MAX;
632 client->new->rebind += cur_time;
633 if (client->new->rebind < cur_time)
634 client->new->rebind = TIME_MAX;
642 /* Run the client script with the new parameters. */
643 script_init((client->state == S_REQUESTING ? "BOUND" :
644 (client->state == S_RENEWING ? "RENEW" :
645 (client->state == S_REBOOTING ? "REBOOT" : "REBIND"))));
646 if (client->active && client->state != S_REBOOTING)
647 script_write_params("old_", client->active);
648 script_write_params("new_", client->new);
651 /* Replace the old active lease with the new one. */
653 free_client_lease(client->active);
654 client->active = client->new;
657 /* Write out new leases file. */
658 rewrite_client_leases();
660 /* Set timeout to start the renewal process. */
661 set_timeout(client->active->renewal, state_bound);
663 note("bound to %s -- renewal in %lld seconds.",
664 piaddr(client->active->address),
665 (long long)(client->active->renewal - time(NULL)));
666 client->state = S_BOUND;
671 * state_bound is called when we've successfully bound to a particular
672 * lease, but the renewal time on that lease has expired. We are
673 * expected to unicast a DHCPREQUEST to the server that gave us our
679 /* T1 has expired. */
680 make_request(client->active);
681 client->xid = client->packet.xid;
683 if (client->active->options[DHO_DHCP_SERVER_IDENTIFIER].len == 4) {
684 memcpy(client->destination.iabuf,
685 client->active->options[DHO_DHCP_SERVER_IDENTIFIER].data,
687 client->destination.len = 4;
689 client->destination = iaddr_broadcast;
691 client->first_sending = time(NULL);
692 client->interval = 0;
693 client->state = S_RENEWING;
699 dhcpoffer(struct iaddr client_addr, struct option_data *options)
701 struct client_lease *lease, *lp;
703 time_t stop_selecting;
704 char *name = options[DHO_DHCP_MESSAGE_TYPE].len ? "DHCPOFFER" :
708 if (client->state != S_SELECTING)
712 /* If this lease doesn't supply the minimum required parameters,
714 for (i = 0; config->required_options[i]; i++) {
715 if (!options[config->required_options[i]].len) {
716 note("%s isn't satisfactory.", name);
721 /* If we've already seen this lease, don't record it again. */
722 for (lease = client->offered_leases;
723 lease; lease = lease->next) {
724 if (lease->address.len == sizeof(client->packet.yiaddr) &&
725 !memcmp(lease->address.iabuf,
726 &client->packet.yiaddr, lease->address.len)) {
728 debug("%s already seen.", name);
734 lease = packet_to_lease(options);
736 note("packet_to_lease failed.");
740 /* If this lease was acquired through a BOOTREPLY, record that
742 if (!options[DHO_DHCP_MESSAGE_TYPE].len)
745 /* Figure out when we're supposed to stop selecting. */
746 stop_selecting = client->first_sending + config->select_interval;
748 /* If this is the lease we asked for, put it at the head of the
749 list, and don't mess with the arp request timeout. */
750 if (addr_eq(lease->address, client->requested_address)) {
751 lease->next = client->offered_leases;
752 client->offered_leases = lease;
754 /* Put the lease at the end of the list. */
756 if (!client->offered_leases)
757 client->offered_leases = lease;
759 for (lp = client->offered_leases; lp->next;
766 /* If the selecting interval has expired, go immediately to
767 state_selecting(). Otherwise, time out into
768 state_selecting at the select interval. */
769 if (stop_selecting <= time(NULL))
772 set_timeout(stop_selecting, state_selecting);
777 * Allocate a client_lease structure and initialize it from the
778 * parameters in the specified packet.
780 struct client_lease *
781 packet_to_lease(struct option_data *options)
783 struct client_lease *lease;
786 lease = malloc(sizeof(struct client_lease));
789 warning("dhcpoffer: no memory to record lease.");
793 memset(lease, 0, sizeof(*lease));
795 /* Copy the lease options. */
796 for (i = 0; i < 256; i++) {
797 if (options[i].len) {
798 lease->options[i] = options[i];
799 options[i].data = NULL;
801 if (!check_option(lease, i)) {
802 warning("Invalid lease option - ignoring offer");
803 free_client_lease(lease);
809 lease->address.len = sizeof(client->packet.yiaddr);
810 memcpy(lease->address.iabuf, &client->packet.yiaddr,
813 /* If the server name was filled out, copy it. */
814 if ((!lease->options[DHO_DHCP_OPTION_OVERLOAD].len ||
815 !(lease->options[DHO_DHCP_OPTION_OVERLOAD].data[0] & 2)) &&
816 client->packet.sname[0]) {
817 lease->server_name = malloc(DHCP_SNAME_LEN + 1);
818 if (!lease->server_name) {
819 warning("dhcpoffer: no memory for server name.");
820 free_client_lease(lease);
823 memcpy(lease->server_name, client->packet.sname,
825 lease->server_name[DHCP_SNAME_LEN] = '\0';
826 if (!res_hnok(lease->server_name)) {
827 warning("Bogus server name %s", lease->server_name);
828 free(lease->server_name);
829 lease->server_name = NULL;
833 /* Ditto for the filename. */
834 if ((!lease->options[DHO_DHCP_OPTION_OVERLOAD].len ||
835 !(lease->options[DHO_DHCP_OPTION_OVERLOAD].data[0] & 1)) &&
836 client->packet.file[0]) {
837 /* Don't count on the NUL terminator. */
838 lease->filename = malloc(DHCP_FILE_LEN + 1);
839 if (!lease->filename) {
840 warning("dhcpoffer: no memory for filename.");
841 free_client_lease(lease);
844 memcpy(lease->filename, client->packet.file, DHCP_FILE_LEN);
845 lease->filename[DHCP_FILE_LEN] = '\0';
851 dhcpnak(struct iaddr client_addr, struct option_data *options)
854 if (client->state != S_REBOOTING &&
855 client->state != S_REQUESTING &&
856 client->state != S_RENEWING &&
857 client->state != S_REBINDING)
861 if (!client->active) {
862 note("DHCPNAK with no active lease.");
866 free_client_lease(client->active);
867 client->active = NULL;
869 /* Stop sending DHCPREQUEST packets... */
872 client->state = S_INIT;
877 * Send out a DHCPDISCOVER packet, and set a timeout to send out another
878 * one after the right interval has expired. If we don't get an offer by
879 * the time we reach the panic interval, call the panic function.
885 int interval, increase = 1;
889 /* Figure out how long it's been since we started transmitting. */
890 interval = cur_time - client->first_sending;
892 /* If we're past the panic timeout, call the script and tell it
893 we haven't found anything for this interface yet. */
894 if (interval > config->timeout) {
900 * If we're supposed to increase the interval, do so. If it's
901 * currently zero (i.e., we haven't sent any packets yet), set
902 * it to initial_interval; otherwise, add to it a random
903 * number between zero and two times itself. On average, this
904 * means that it will double with every transmission.
907 if (!client->interval)
908 client->interval = config->initial_interval;
910 client->interval += (arc4random() >> 2) %
911 (2 * client->interval);
914 /* Don't backoff past cutoff. */
915 if (client->interval > config->backoff_cutoff)
916 client->interval = ((config->backoff_cutoff / 2)
917 + ((arc4random() >> 2) %
918 config->backoff_cutoff));
919 } else if (!client->interval)
920 client->interval = config->initial_interval;
922 /* If the backoff would take us to the panic timeout, just use that
924 if (cur_time + client->interval >
925 client->first_sending + config->timeout)
926 client->interval = (client->first_sending +
927 config->timeout) - cur_time + 1;
929 /* Record the number of seconds since we started sending. */
930 if (interval < 65536)
931 client->packet.secs = htons(interval);
933 client->packet.secs = htons(65535);
934 client->secs = client->packet.secs;
936 note("DHCPDISCOVER on %s to %s port %d interval %ld",
937 ifi->name, inet_ntoa(sockaddr_broadcast.sin_addr),
938 ntohs(sockaddr_broadcast.sin_port), client->interval);
940 send_packet(inaddr_any, &sockaddr_broadcast, NULL);
942 set_timeout_interval(client->interval, send_discover);
946 * state_panic gets called if we haven't received any offers in a preset
947 * amount of time. When this happens, we try to use existing leases
948 * that haven't yet expired, and failing that, we call the client script
949 * and hope it can do something.
954 struct client_lease *loop = client->active;
955 struct client_lease *lp;
958 note("No DHCPOFFERS received.");
960 /* We may not have an active lease, but we may have some
961 predefined leases that we can try. */
962 if (!client->active && client->leases)
965 /* Run through the list of leases and see if one can be used. */
967 while (client->active) {
968 if (client->active->expiry > cur_time) {
969 note("Trying recorded lease %s",
970 piaddr(client->active->address));
971 /* Run the client script with the existing
973 script_init("TIMEOUT");
974 script_write_params("new_", client->active);
976 /* If the old lease is still good and doesn't
977 yet need renewal, go into BOUND state and
978 timeout at the renewal time. */
980 if (cur_time < client->active->renewal) {
981 client->state = S_BOUND;
982 note("bound: renewal in %lld seconds.",
983 (long long)(client->active->renewal
985 set_timeout(client->active->renewal,
988 client->state = S_BOUND;
989 note("bound: immediate renewal.");
997 /* If there are no other leases, give up. */
998 if (!client->leases) {
999 client->leases = client->active;
1000 client->active = NULL;
1005 /* Otherwise, put the active lease at the end of the
1006 lease list, and try another lease.. */
1007 for (lp = client->leases; lp->next; lp = lp->next)
1009 lp->next = client->active;
1011 lp->next->next = NULL;
1012 client->active = client->leases;
1013 client->leases = client->leases->next;
1015 /* If we already tried this lease, we've exhausted the
1016 set of leases, so we might as well give up for
1018 if (client->active == loop)
1021 loop = client->active;
1024 /* No leases were available, or what was available didn't work, so
1025 tell the shell script that we failed to allocate an address,
1026 and try again later. */
1027 note("No working leases in persistent database - sleeping.");
1028 script_init("FAIL");
1030 client->state = S_INIT;
1031 set_timeout_interval(config->retry_interval, state_init);
1038 struct sockaddr_in destination;
1039 struct in_addr from;
1045 /* Figure out how long it's been since we started transmitting. */
1046 interval = (int)(cur_time - client->first_sending);
1048 /* If we're in the INIT-REBOOT or REQUESTING state and we're
1049 past the reboot timeout, go to INIT and see if we can
1050 DISCOVER an address... */
1051 /* XXX In the INIT-REBOOT state, if we don't get an ACK, it
1052 means either that we're on a network with no DHCP server,
1053 or that our server is down. In the latter case, assuming
1054 that there is a backup DHCP server, DHCPDISCOVER will get
1055 us a new address, but we could also have successfully
1056 reused our old address. In the former case, we're hosed
1057 anyway. This is not a win-prone situation. */
1058 if ((client->state == S_REBOOTING ||
1059 client->state == S_REQUESTING) &&
1060 interval > config->reboot_timeout) {
1061 client->state = S_INIT;
1067 /* If the lease has expired, relinquish the address and go back
1068 to the INIT state. */
1069 if (client->state != S_REQUESTING &&
1070 cur_time > client->active->expiry) {
1071 /* Run the client script with the new parameters. */
1072 script_init("EXPIRE");
1073 script_write_params("old_", client->active);
1076 client->state = S_INIT;
1081 /* Do the exponential backoff... */
1082 if (!client->interval)
1083 client->interval = config->initial_interval;
1085 client->interval += ((arc4random() >> 2) %
1086 (2 * client->interval));
1088 /* Don't backoff past cutoff. */
1089 if (client->interval > config->backoff_cutoff)
1090 client->interval = ((config->backoff_cutoff / 2) +
1091 ((arc4random() >> 2) % client->interval));
1093 /* If the backoff would take us to the expiry time, just set the
1094 timeout to the expiry time. */
1095 if (client->state != S_REQUESTING && cur_time + client->interval >
1096 client->active->expiry)
1097 client->interval = client->active->expiry - cur_time + 1;
1099 /* If the lease T2 time has elapsed, or if we're not yet bound,
1100 broadcast the DHCPREQUEST rather than unicasting. */
1101 memset(&destination, 0, sizeof(destination));
1102 if (client->state == S_REQUESTING ||
1103 client->state == S_REBOOTING ||
1104 cur_time > client->active->rebind)
1105 destination.sin_addr.s_addr = INADDR_BROADCAST;
1107 memcpy(&destination.sin_addr.s_addr, client->destination.iabuf,
1108 sizeof(destination.sin_addr.s_addr));
1109 destination.sin_port = htons(REMOTE_PORT);
1110 destination.sin_family = AF_INET;
1111 destination.sin_len = sizeof(destination);
1113 if (client->state != S_REQUESTING)
1114 memcpy(&from, client->active->address.iabuf, sizeof(from));
1116 from.s_addr = INADDR_ANY;
1118 /* Record the number of seconds since we started sending. */
1119 if (client->state == S_REQUESTING)
1120 client->packet.secs = client->secs;
1122 if (interval < 65536)
1123 client->packet.secs = htons(interval);
1125 client->packet.secs = htons(65535);
1128 note("DHCPREQUEST on %s to %s port %d", ifi->name,
1129 inet_ntoa(destination.sin_addr), ntohs(destination.sin_port));
1131 send_packet(from, &destination, NULL);
1133 set_timeout_interval(client->interval, send_request);
1139 note("DHCPDECLINE on %s to %s port %d", ifi->name,
1140 inet_ntoa(sockaddr_broadcast.sin_addr),
1141 ntohs(sockaddr_broadcast.sin_port));
1143 send_packet(inaddr_any, &sockaddr_broadcast, NULL);
1147 make_discover(struct client_lease *lease)
1149 unsigned char discover = DHCPDISCOVER;
1150 struct option_data options[256];
1153 memset(options, 0, sizeof(options));
1154 memset(&client->packet, 0, sizeof(client->packet));
1156 /* Set DHCP_MESSAGE_TYPE to DHCPDISCOVER */
1157 i = DHO_DHCP_MESSAGE_TYPE;
1158 options[i].data = &discover;
1159 options[i].len = sizeof(discover);
1161 /* Request the options we want */
1162 i = DHO_DHCP_PARAMETER_REQUEST_LIST;
1163 options[i].data = config->requested_options;
1164 options[i].len = config->requested_option_count;
1166 /* If we had an address, try to get it again. */
1168 client->requested_address = lease->address;
1169 i = DHO_DHCP_REQUESTED_ADDRESS;
1170 options[i].data = lease->address.iabuf;
1171 options[i].len = lease->address.len;
1173 client->requested_address.len = 0;
1175 /* Send any options requested in the config file. */
1176 for (i = 0; i < 256; i++)
1177 if (!options[i].data &&
1178 config->send_options[i].data) {
1179 options[i].data = config->send_options[i].data;
1180 options[i].len = config->send_options[i].len;
1183 /* Set up the option buffer to fit in a minimal UDP packet. */
1184 i = cons_options(options);
1185 if (i == -1 || client->packet.options[i] != DHO_END)
1186 error("options do not fit in DHCPDISCOVER packet.");
1187 client->packet_length = DHCP_FIXED_NON_UDP+i+1;
1188 if (client->packet_length < BOOTP_MIN_LEN)
1189 client->packet_length = BOOTP_MIN_LEN;
1191 client->packet.op = BOOTREQUEST;
1192 client->packet.htype = ifi->hw_address.htype;
1193 client->packet.hlen = ifi->hw_address.hlen;
1194 client->packet.hops = 0;
1195 client->packet.xid = arc4random();
1196 client->packet.secs = 0; /* filled in by send_discover. */
1197 client->packet.flags = 0;
1199 memset(&client->packet.ciaddr, 0, sizeof(client->packet.ciaddr));
1200 memset(&client->packet.yiaddr, 0, sizeof(client->packet.yiaddr));
1201 memset(&client->packet.siaddr, 0, sizeof(client->packet.siaddr));
1202 memset(&client->packet.giaddr, 0, sizeof(client->packet.giaddr));
1203 memcpy(client->packet.chaddr, ifi->hw_address.haddr,
1204 ifi->hw_address.hlen);
1208 make_request(struct client_lease * lease)
1210 unsigned char request = DHCPREQUEST;
1211 struct option_data options[256];
1214 memset(options, 0, sizeof(options));
1215 memset(&client->packet, 0, sizeof(client->packet));
1217 /* Set DHCP_MESSAGE_TYPE to DHCPREQUEST */
1218 i = DHO_DHCP_MESSAGE_TYPE;
1219 options[i].data = &request;
1220 options[i].len = sizeof(request);
1222 /* Request the options we want */
1223 i = DHO_DHCP_PARAMETER_REQUEST_LIST;
1224 options[i].data = config->requested_options;
1225 options[i].len = config->requested_option_count;
1227 /* If we are requesting an address that hasn't yet been assigned
1228 to us, use the DHCP Requested Address option. */
1229 if (client->state == S_REQUESTING) {
1230 /* Send back the server identifier... */
1231 i = DHO_DHCP_SERVER_IDENTIFIER;
1232 options[i].data = lease->options[i].data;
1233 options[i].len = lease->options[i].len;
1235 if (client->state == S_REQUESTING ||
1236 client->state == S_REBOOTING) {
1237 client->requested_address = lease->address;
1238 i = DHO_DHCP_REQUESTED_ADDRESS;
1239 options[i].data = lease->address.iabuf;
1240 options[i].len = lease->address.len;
1242 client->requested_address.len = 0;
1244 /* Send any options requested in the config file. */
1245 for (i = 0; i < 256; i++)
1246 if (!options[i].data && config->send_options[i].data) {
1247 options[i].data = config->send_options[i].data;
1248 options[i].len = config->send_options[i].len;
1251 /* Set up the option buffer to fit in a minimal UDP packet. */
1252 i = cons_options(options);
1253 if (i == -1 || client->packet.options[i] != DHO_END)
1254 error("options do not fit in DHCPREQUEST packet.");
1255 client->packet_length = DHCP_FIXED_NON_UDP+i+1;
1256 if (client->packet_length < BOOTP_MIN_LEN)
1257 client->packet_length = BOOTP_MIN_LEN;
1259 client->packet.op = BOOTREQUEST;
1260 client->packet.htype = ifi->hw_address.htype;
1261 client->packet.hlen = ifi->hw_address.hlen;
1262 client->packet.hops = 0;
1263 client->packet.xid = client->xid;
1264 client->packet.secs = 0; /* Filled in by send_request. */
1265 client->packet.flags = 0;
1267 /* If we own the address we're requesting, put it in ciaddr;
1268 otherwise set ciaddr to zero. */
1269 if (client->state == S_BOUND ||
1270 client->state == S_RENEWING ||
1271 client->state == S_REBINDING) {
1272 memcpy(&client->packet.ciaddr,
1273 lease->address.iabuf, lease->address.len);
1275 memset(&client->packet.ciaddr, 0,
1276 sizeof(client->packet.ciaddr));
1279 memset(&client->packet.yiaddr, 0, sizeof(client->packet.yiaddr));
1280 memset(&client->packet.siaddr, 0, sizeof(client->packet.siaddr));
1281 memset(&client->packet.giaddr, 0, sizeof(client->packet.giaddr));
1282 memcpy(client->packet.chaddr, ifi->hw_address.haddr,
1283 ifi->hw_address.hlen);
1287 make_decline(struct client_lease *lease)
1289 struct option_data options[256];
1290 unsigned char decline = DHCPDECLINE;
1293 memset(options, 0, sizeof(options));
1294 memset(&client->packet, 0, sizeof(client->packet));
1296 /* Set DHCP_MESSAGE_TYPE to DHCPDECLINE */
1297 i = DHO_DHCP_MESSAGE_TYPE;
1298 options[i].data = &decline;
1299 options[i].len = sizeof(decline);
1301 /* Send back the server identifier... */
1302 i = DHO_DHCP_SERVER_IDENTIFIER;
1303 options[i].data = lease->options[i].data;
1304 options[i].len = lease->options[i].len;
1306 /* Send back the address we're declining. */
1307 i = DHO_DHCP_REQUESTED_ADDRESS;
1308 options[i].data = lease->address.iabuf;
1309 options[i].len = lease->address.len;
1311 /* Send the uid if the user supplied one. */
1312 i = DHO_DHCP_CLIENT_IDENTIFIER;
1313 if (config->send_options[i].len) {
1314 options[i].data = config->send_options[i].data;
1315 options[i].len = config->send_options[i].len;
1318 /* Set up the option buffer to fit in a minimal UDP packet. */
1319 i = cons_options(options);
1320 if (i == -1 || client->packet.options[i] != DHO_END)
1321 error("options do not fit in DHCPDECLINE packet.");
1322 client->packet_length = DHCP_FIXED_NON_UDP+i+1;
1323 if (client->packet_length < BOOTP_MIN_LEN)
1324 client->packet_length = BOOTP_MIN_LEN;
1326 client->packet.op = BOOTREQUEST;
1327 client->packet.htype = ifi->hw_address.htype;
1328 client->packet.hlen = ifi->hw_address.hlen;
1329 client->packet.hops = 0;
1330 client->packet.xid = client->xid;
1331 client->packet.secs = 0; /* Filled in by send_request. */
1332 client->packet.flags = 0;
1334 /* ciaddr must always be zero. */
1335 memset(&client->packet.ciaddr, 0, sizeof(client->packet.ciaddr));
1336 memset(&client->packet.yiaddr, 0, sizeof(client->packet.yiaddr));
1337 memset(&client->packet.siaddr, 0, sizeof(client->packet.siaddr));
1338 memset(&client->packet.giaddr, 0, sizeof(client->packet.giaddr));
1339 memcpy(client->packet.chaddr, ifi->hw_address.haddr,
1340 ifi->hw_address.hlen);
1344 free_client_lease(struct client_lease *lease)
1348 if (lease->server_name)
1349 free(lease->server_name);
1350 if (lease->filename)
1351 free(lease->filename);
1352 for (i = 0; i < 256; i++) {
1353 if (lease->options[i].len)
1354 free(lease->options[i].data);
1360 rewrite_client_leases(void)
1362 struct client_lease *lp;
1364 if (!leaseFile) /* XXX */
1365 error("lease file not open");
1370 for (lp = client->leases; lp; lp = lp->next) {
1371 if (client->active && addr_eq(lp->address,
1372 client->active->address))
1374 write_client_lease(lp);
1378 write_client_lease(client->active);
1381 ftruncate(fileno(leaseFile), ftello(leaseFile));
1382 fsync(fileno(leaseFile));
1386 write_client_lease(struct client_lease *lease)
1391 /* If the lease came from the config file, we don't need to stash
1392 a copy in the lease database. */
1393 if (lease->is_static)
1396 if (!leaseFile) /* XXX */
1397 error("lease file not open");
1399 fprintf(leaseFile, "lease {\n");
1400 if (lease->is_bootp)
1401 fprintf(leaseFile, " bootp;\n");
1402 fprintf(leaseFile, " interface \"%s\";\n", ifi->name);
1403 fprintf(leaseFile, " fixed-address %s;\n", piaddr(lease->address));
1404 if (lease->filename)
1405 fprintf(leaseFile, " filename \"%s\";\n", lease->filename);
1406 if (lease->server_name)
1407 fprintf(leaseFile, " server-name \"%s\";\n",
1408 lease->server_name);
1409 for (i = 0; i < 256; i++)
1410 if (lease->options[i].len)
1411 fprintf(leaseFile, " option %s %s;\n",
1412 dhcp_options[i].name,
1413 pretty_print_option(i, lease->options[i].data,
1414 lease->options[i].len, 1, 1));
1416 t = gmtime(&lease->renewal);
1417 fprintf(leaseFile, " renew %d %d/%d/%d %02d:%02d:%02d;\n",
1418 t->tm_wday, t->tm_year + 1900, t->tm_mon + 1, t->tm_mday,
1419 t->tm_hour, t->tm_min, t->tm_sec);
1420 t = gmtime(&lease->rebind);
1421 fprintf(leaseFile, " rebind %d %d/%d/%d %02d:%02d:%02d;\n",
1422 t->tm_wday, t->tm_year + 1900, t->tm_mon + 1, t->tm_mday,
1423 t->tm_hour, t->tm_min, t->tm_sec);
1424 t = gmtime(&lease->expiry);
1425 fprintf(leaseFile, " expire %d %d/%d/%d %02d:%02d:%02d;\n",
1426 t->tm_wday, t->tm_year + 1900, t->tm_mon + 1, t->tm_mday,
1427 t->tm_hour, t->tm_min, t->tm_sec);
1428 fprintf(leaseFile, "}\n");
1433 script_init(char *reason)
1436 struct imsg_hdr hdr;
1439 hdr.code = IMSG_SCRIPT_INIT;
1440 hdr.len = sizeof(struct imsg_hdr) + sizeof(size_t) + strlen(reason);
1441 buf = buf_open(hdr.len);
1443 buf_add(buf, &hdr, sizeof(hdr));
1444 len = strlen(reason);
1445 buf_add(buf, &len, sizeof(len));
1446 buf_add(buf, reason, len);
1448 buf_close(privfd, buf);
1452 priv_script_init(char *reason)
1454 client->scriptEnvsize = 100;
1455 if (client->scriptEnv == NULL)
1457 calloc(client->scriptEnvsize, sizeof(char *));
1458 if (client->scriptEnv == NULL)
1459 error("script_init: no memory for environment");
1461 client->scriptEnv[0] = strdup(CLIENT_PATH);
1462 if (client->scriptEnv[0] == NULL)
1463 error("script_init: no memory for environment");
1465 client->scriptEnv[1] = NULL;
1467 script_set_env("", "interface", ifi->name);
1469 script_set_env("", "reason", reason);
1473 priv_script_write_params(char *prefix, struct client_lease *lease)
1475 u_int8_t dbuf[1500];
1479 script_set_env(prefix, "ip_address", piaddr(lease->address));
1481 if (lease->options[DHO_SUBNET_MASK].len &&
1482 (lease->options[DHO_SUBNET_MASK].len <
1483 sizeof(lease->address.iabuf))) {
1484 struct iaddr netmask, subnet, broadcast;
1486 memcpy(netmask.iabuf, lease->options[DHO_SUBNET_MASK].data,
1487 lease->options[DHO_SUBNET_MASK].len);
1488 netmask.len = lease->options[DHO_SUBNET_MASK].len;
1490 subnet = subnet_number(lease->address, netmask);
1492 script_set_env(prefix, "network_number",
1494 if (!lease->options[DHO_BROADCAST_ADDRESS].len) {
1495 broadcast = broadcast_addr(subnet, netmask);
1497 script_set_env(prefix,
1498 "broadcast_address",
1504 if (lease->filename)
1505 script_set_env(prefix, "filename", lease->filename);
1506 if (lease->server_name)
1507 script_set_env(prefix, "server_name",
1508 lease->server_name);
1509 for (i = 0; i < 256; i++) {
1510 u_int8_t *dp = NULL;
1512 if (config->defaults[i].len) {
1513 if (lease->options[i].len) {
1514 switch (config->default_actions[i]) {
1518 case ACTION_DEFAULT:
1519 dp = lease->options[i].data;
1520 len = lease->options[i].len;
1522 case ACTION_SUPERSEDE:
1524 dp = config->defaults[i].data;
1525 len = config->defaults[i].len;
1527 case ACTION_PREPEND:
1528 len = config->defaults[i].len +
1529 lease->options[i].len;
1530 if (len >= sizeof(dbuf)) {
1531 warning("no space to %s %s",
1533 dhcp_options[i].name);
1538 config->defaults[i].data,
1539 config->defaults[i].len);
1541 config->defaults[i].len,
1542 lease->options[i].data,
1543 lease->options[i].len);
1547 len = config->defaults[i].len +
1548 lease->options[i].len;
1549 if (len >= sizeof(dbuf)) {
1550 warning("no space to %s %s",
1552 dhcp_options[i].name);
1556 memcpy(dp, lease->options[i].data,
1557 lease->options[i].len);
1558 memcpy(dp + lease->options[i].len,
1559 config->defaults[i].data,
1560 config->defaults[i].len);
1564 dp = config->defaults[i].data;
1565 len = config->defaults[i].len;
1567 } else if (lease->options[i].len) {
1568 len = lease->options[i].len;
1569 dp = lease->options[i].data;
1573 if (len && config->default_actions[i] == ACTION_IGNORE) {
1579 if (dhcp_option_ev_name(name, sizeof(name),
1581 script_set_env(prefix, name,
1582 pretty_print_option(i, dp, len, 0, 0));
1585 snprintf(tbuf, sizeof(tbuf), "%d", (int)lease->expiry);
1586 script_set_env(prefix, "expiry", tbuf);
1590 script_write_params(char *prefix, struct client_lease *lease)
1592 size_t fn_len = 0, sn_len = 0, pr_len = 0;
1593 struct imsg_hdr hdr;
1597 if (lease->filename != NULL)
1598 fn_len = strlen(lease->filename);
1599 if (lease->server_name != NULL)
1600 sn_len = strlen(lease->server_name);
1602 pr_len = strlen(prefix);
1604 hdr.code = IMSG_SCRIPT_WRITE_PARAMS;
1605 hdr.len = sizeof(hdr) + sizeof(struct client_lease) +
1606 sizeof(size_t) + fn_len + sizeof(size_t) + sn_len +
1607 sizeof(size_t) + pr_len;
1609 for (i = 0; i < 256; i++)
1610 hdr.len += sizeof(int) + lease->options[i].len;
1612 scripttime = time(NULL);
1614 buf = buf_open(hdr.len);
1616 buf_add(buf, &hdr, sizeof(hdr));
1617 buf_add(buf, lease, sizeof(struct client_lease));
1618 buf_add(buf, &fn_len, sizeof(fn_len));
1619 buf_add(buf, lease->filename, fn_len);
1620 buf_add(buf, &sn_len, sizeof(sn_len));
1621 buf_add(buf, lease->server_name, sn_len);
1622 buf_add(buf, &pr_len, sizeof(pr_len));
1623 buf_add(buf, prefix, pr_len);
1625 for (i = 0; i < 256; i++) {
1626 buf_add(buf, &lease->options[i].len,
1627 sizeof(lease->options[i].len));
1628 buf_add(buf, lease->options[i].data,
1629 lease->options[i].len);
1632 buf_close(privfd, buf);
1638 struct imsg_hdr hdr;
1642 scripttime = time(NULL);
1644 hdr.code = IMSG_SCRIPT_GO;
1645 hdr.len = sizeof(struct imsg_hdr);
1647 buf = buf_open(hdr.len);
1649 buf_add(buf, &hdr, sizeof(hdr));
1650 buf_close(privfd, buf);
1652 bzero(&hdr, sizeof(hdr));
1653 buf_read(privfd, &hdr, sizeof(hdr));
1654 if (hdr.code != IMSG_SCRIPT_GO_RET)
1655 error("unexpected msg type %u", hdr.code);
1656 if (hdr.len != sizeof(hdr) + sizeof(int))
1657 error("received corrupted message");
1658 buf_read(privfd, &ret, sizeof(ret));
1664 priv_script_go(void)
1666 char *scriptName, *argv[2], **envp;
1667 int pid, wpid, wstatus;
1669 scripttime = time(NULL);
1671 scriptName = config->script_name;
1672 envp = client->scriptEnv;
1674 argv[0] = scriptName;
1683 wpid = wait(&wstatus);
1684 } while (wpid != pid && wpid > 0);
1690 execve(scriptName, argv, envp);
1691 error("execve (%s, ...): %m", scriptName);
1696 return (WEXITSTATUS(wstatus));
1700 script_set_env(const char *prefix, const char *name, const char *value)
1704 namelen = strlen(name);
1706 for (i = 0; client->scriptEnv[i]; i++)
1707 if (strncmp(client->scriptEnv[i], name, namelen) == 0 &&
1708 client->scriptEnv[i][namelen] == '=')
1711 if (client->scriptEnv[i])
1712 /* Reuse the slot. */
1713 free(client->scriptEnv[i]);
1715 /* New variable. Expand if necessary. */
1716 if (i >= client->scriptEnvsize - 1) {
1717 char **newscriptEnv;
1718 int newscriptEnvsize = client->scriptEnvsize + 50;
1720 newscriptEnv = realloc(client->scriptEnv,
1722 if (newscriptEnv == NULL) {
1723 free(client->scriptEnv);
1724 client->scriptEnv = NULL;
1725 client->scriptEnvsize = 0;
1726 error("script_set_env: no memory for variable");
1728 client->scriptEnv = newscriptEnv;
1729 client->scriptEnvsize = newscriptEnvsize;
1731 /* need to set the NULL pointer at end of array beyond
1733 client->scriptEnv[i + 1] = NULL;
1735 /* Allocate space and format the variable in the appropriate slot. */
1736 client->scriptEnv[i] = malloc(strlen(prefix) + strlen(name) + 1 +
1738 if (client->scriptEnv[i] == NULL)
1739 error("script_set_env: no memory for variable assignment");
1741 /* No `` or $() command substitution allowed in environment values! */
1742 for (j = 0; j < strlen(value); j++)
1746 error("illegal character (%c) in value '%s'", value[j],
1750 snprintf(client->scriptEnv[i], strlen(prefix) + strlen(name) +
1751 1 + strlen(value) + 1, "%s%s=%s", prefix, name, value);
1755 script_flush_env(void)
1759 for (i = 0; client->scriptEnv[i]; i++) {
1760 free(client->scriptEnv[i]);
1761 client->scriptEnv[i] = NULL;
1763 client->scriptEnvsize = 0;
1767 dhcp_option_ev_name(char *buf, size_t buflen, const struct option *option)
1771 for (i = 0; option->name[i]; i++) {
1772 if (i + 1 == buflen)
1774 if (option->name[i] == '-')
1777 buf[i] = option->name[i];
1787 static int state = 0;
1789 if (no_daemon || state)
1794 /* Stop logging to stderr... */
1797 if (daemon(1, 0) == -1)
1800 /* we are chrooted, daemon(3) fails to open /dev/null */
1802 dup2(nullfd, STDIN_FILENO);
1803 dup2(nullfd, STDOUT_FILENO);
1804 dup2(nullfd, STDERR_FILENO);
1811 check_option(struct client_lease *l, int option)
1816 /* we use this, since this is what gets passed to dhclient-script */
1818 opbuf = pretty_print_option(option, l->options[option].data,
1819 l->options[option].len, 0, 0);
1821 sbuf = option_as_string(option, l->options[option].data,
1822 l->options[option].len);
1825 case DHO_SUBNET_MASK:
1826 case DHO_SWAP_SERVER:
1827 case DHO_BROADCAST_ADDRESS:
1828 case DHO_DHCP_SERVER_IDENTIFIER:
1829 case DHO_ROUTER_SOLICITATION_ADDRESS:
1830 case DHO_DHCP_REQUESTED_ADDRESS:
1831 if (ipv4addrs(opbuf) == 0) {
1832 warning("Invalid IP address in option %s: %s",
1833 dhcp_options[option].name, opbuf);
1836 if (l->options[option].len != 4) { /* RFC 2132 */
1837 warning("warning: Only 1 IP address allowed in "
1838 "%s option; length %d, must be 4",
1839 dhcp_options[option].name,
1840 l->options[option].len);
1841 l->options[option].len = 4;
1844 case DHO_TIME_SERVERS:
1845 case DHO_NAME_SERVERS:
1847 case DHO_DOMAIN_NAME_SERVERS:
1848 case DHO_LOG_SERVERS:
1849 case DHO_COOKIE_SERVERS:
1850 case DHO_LPR_SERVERS:
1851 case DHO_IMPRESS_SERVERS:
1852 case DHO_RESOURCE_LOCATION_SERVERS:
1853 case DHO_NIS_SERVERS:
1854 case DHO_NTP_SERVERS:
1855 case DHO_NETBIOS_NAME_SERVERS:
1856 case DHO_NETBIOS_DD_SERVER:
1857 case DHO_FONT_SERVERS:
1858 if (ipv4addrs(opbuf) == 0) {
1859 warning("Invalid IP address in option %s: %s",
1860 dhcp_options[option].name, opbuf);
1865 case DHO_DOMAIN_NAME:
1866 case DHO_NIS_DOMAIN:
1867 if (!res_hnok(sbuf)) {
1868 warning("Bogus Host Name option %d: %s (%s)", option,
1870 l->options[option].len = 0;
1871 free(l->options[option].data);
1875 case DHO_TIME_OFFSET:
1877 case DHO_MERIT_DUMP:
1879 case DHO_EXTENSIONS_PATH:
1880 case DHO_IP_FORWARDING:
1881 case DHO_NON_LOCAL_SOURCE_ROUTING:
1882 case DHO_POLICY_FILTER:
1883 case DHO_MAX_DGRAM_REASSEMBLY:
1884 case DHO_DEFAULT_IP_TTL:
1885 case DHO_PATH_MTU_AGING_TIMEOUT:
1886 case DHO_PATH_MTU_PLATEAU_TABLE:
1887 case DHO_INTERFACE_MTU:
1888 case DHO_ALL_SUBNETS_LOCAL:
1889 case DHO_PERFORM_MASK_DISCOVERY:
1890 case DHO_MASK_SUPPLIER:
1891 case DHO_ROUTER_DISCOVERY:
1892 case DHO_STATIC_ROUTES:
1893 case DHO_TRAILER_ENCAPSULATION:
1894 case DHO_ARP_CACHE_TIMEOUT:
1895 case DHO_IEEE802_3_ENCAPSULATION:
1896 case DHO_DEFAULT_TCP_TTL:
1897 case DHO_TCP_KEEPALIVE_INTERVAL:
1898 case DHO_TCP_KEEPALIVE_GARBAGE:
1899 case DHO_VENDOR_ENCAPSULATED_OPTIONS:
1900 case DHO_NETBIOS_NODE_TYPE:
1901 case DHO_NETBIOS_SCOPE:
1902 case DHO_X_DISPLAY_MANAGER:
1903 case DHO_DHCP_LEASE_TIME:
1904 case DHO_DHCP_OPTION_OVERLOAD:
1905 case DHO_DHCP_MESSAGE_TYPE:
1906 case DHO_DHCP_PARAMETER_REQUEST_LIST:
1907 case DHO_DHCP_MESSAGE:
1908 case DHO_DHCP_MAX_MESSAGE_SIZE:
1909 case DHO_DHCP_RENEWAL_TIME:
1910 case DHO_DHCP_REBINDING_TIME:
1911 case DHO_DHCP_CLASS_IDENTIFIER:
1912 case DHO_DHCP_CLIENT_IDENTIFIER:
1913 case DHO_DHCP_USER_CLASS_ID:
1914 case DHO_TFTP_SERVER:
1919 warning("unknown dhcp option value 0x%x", option);
1920 return (unknown_ok);
1925 res_hnok(const char *name)
1927 const char *dn = name;
1928 int pch = '.', ch = *dn++;
1931 while (ch != '\0') {
1936 } else if (pch == '.' || nch == '.' || nch == '\0') {
1939 } else if (!isalnum(ch) && ch != '-' && ch != '_')
1941 else if (ch == '_' && warn == 0) {
1942 warning("warning: hostname %s contains an "
1943 "underscore which violates RFC 952", name);
1951 /* Does buf consist only of dotted decimal ipv4 addrs?
1952 * return how many if so,
1953 * otherwise, return 0
1956 ipv4addrs(char * buf)
1961 while (inet_aton(buf, &jnk) == 1){
1963 while (*buf == '.' || isdigit(*buf))
1974 option_as_string(unsigned int code, unsigned char *data, int len)
1976 static char optbuf[32768]; /* XXX */
1978 int opleft = sizeof(optbuf);
1979 unsigned char *dp = data;
1982 error("option_as_string: bad code %d", code);
1984 for (; dp < data + len; dp++) {
1985 if (!isascii(*dp) || !isprint(*dp)) {
1986 if (dp + 1 != data + len || *dp != 0) {
1988 snprintf(op, opleft, "\\%03o", *dp);
1993 } else if (*dp == '"' || *dp == '\'' || *dp == '$' ||
1994 *dp == '`' || *dp == '\\') {
2008 warning("dhcp option too large");
2013 fork_privchld(int fd, int fd2)
2015 struct pollfd pfd[1];
2016 int nfds, pfail = 0;
2020 error("cannot fork");
2028 if (chdir("/") == -1)
2029 error("chdir(\"/\")");
2031 setproctitle("%s [priv]", ifi->name);
2033 dup2(nullfd, STDIN_FILENO);
2034 dup2(nullfd, STDOUT_FILENO);
2035 dup2(nullfd, STDERR_FILENO);
2041 pfd[0].events = POLLIN;
2042 if ((nfds = poll(pfd, 1, INFTIM)) == -1)
2044 error("poll error");
2047 * Handle temporary errors, but bail if they persist.
2049 if (nfds == 0 || !(pfd[0].revents & POLLIN)) {
2050 if (pfail > POLL_FAILURES)
2051 error("poll failed > %d times", POLL_FAILURES);
2052 sleep(pfail * POLL_FAILURE_WAIT);
2062 get_ifname(char *ifname, char *arg)
2064 struct ifgroupreq ifgr;
2065 struct ifg_req *ifg;
2068 if (!strcmp(arg, "egress")) {
2069 s = socket(AF_INET, SOCK_DGRAM, 0);
2071 error("socket error");
2072 bzero(&ifgr, sizeof(ifgr));
2073 strlcpy(ifgr.ifgr_name, "egress", sizeof(ifgr.ifgr_name));
2074 if (ioctl(s, SIOCGIFGMEMB, (caddr_t)&ifgr) == -1) {
2075 if (errno == ENOENT)
2076 error("no interface in group egress found");
2077 error("ioctl SIOCGIFGMEMB: %m");
2079 len = ifgr.ifgr_len;
2080 if ((ifgr.ifgr_groups = calloc(1, len)) == NULL)
2081 error("get_ifname");
2082 if (ioctl(s, SIOCGIFGMEMB, (caddr_t)&ifgr) == -1)
2083 error("ioctl SIOCGIFGMEMB: %m");
2086 for (ifg = ifgr.ifgr_groups;
2087 ifg && len >= sizeof(struct ifg_req); ifg++) {
2088 len -= sizeof(struct ifg_req);
2090 error("too many interfaces in group egress");
2091 arg = ifg->ifgrq_member;
2094 if (strlcpy(ifi->name, arg, IFNAMSIZ) >= IFNAMSIZ)
2095 error("Interface name too long: %m");
2097 free(ifgr.ifgr_groups);
2099 } else if (strlcpy(ifi->name, arg, IFNAMSIZ) >= IFNAMSIZ)
2100 error("Interface name too long");