1 /* $OpenBSD: src/sbin/dhclient/dhclient.c,v 1.129 2009/06/06 04:02:42 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
64 #define CLIENT_PATH "PATH=/usr/bin:/usr/sbin:/bin:/sbin"
65 #define DEFAULT_LEASE_TIME 43200 /* 12 hours... */
66 #define TIME_MAX 2147483647
67 #define POLL_FAILURES 10
68 #define POLL_FAILURE_WAIT 1 /* Back off multiplier (seconds) */
72 char *path_dhclient_conf = _PATH_DHCLIENT_CONF;
73 char *path_dhclient_db = NULL;
82 struct iaddr iaddr_broadcast = { 4, { 255, 255, 255, 255 } };
83 struct in_addr inaddr_any;
84 struct sockaddr_in sockaddr_broadcast;
86 struct interface_info *ifi;
87 struct client_state *client;
88 struct client_config *config;
90 int findproto(char *, int);
91 struct sockaddr *get_ifa(char *, int);
93 int check_option(struct client_lease *l, int option);
94 int ipv4addrs(char * buf);
95 int res_hnok(const char *dn);
96 char *option_as_string(unsigned int code, unsigned char *data, int len);
97 int fork_privchld(int, int);
100 ((a) > 0 ? (1 + (((a) - 1) | (sizeof(long) - 1))) : sizeof(long))
101 #define ADVANCE(x, n) (x += ROUNDUP((n)->sa_len))
104 static FILE *leaseFile;
107 findproto(char *cp, int n)
114 for (i = 1; i; i <<= 1) {
116 sa = (struct sockaddr *)cp;
122 if (sa->sa_family == AF_INET)
124 if (sa->sa_family == AF_INET6)
137 get_ifa(char *cp, int n)
144 for (i = 1; i; i <<= 1)
146 sa = (struct sockaddr *)cp;
154 struct iaddr defaddr = { .len = 4 }; /* NULL is for silence warnings */
161 struct rt_msghdr *rtm;
162 struct if_msghdr *ifm;
163 struct ifa_msghdr *ifam;
164 struct if_announcemsghdr *ifan;
165 struct client_lease *l;
166 time_t t = time(NULL);
170 char *errmsg, buf[64];
173 n = read(routefd, &msg, sizeof(msg));
174 } while (n == -1 && errno == EINTR);
176 rtm = (struct rt_msghdr *)msg;
177 if (n < sizeof(rtm->rtm_msglen) || n < rtm->rtm_msglen ||
178 rtm->rtm_version != RTM_VERSION)
181 switch (rtm->rtm_type) {
183 ifam = (struct ifa_msghdr *)rtm;
184 if (ifam->ifam_index != ifi->index)
186 if (findproto((char *)(ifam + 1), ifam->ifam_addrs) != AF_INET)
188 sa = get_ifa((char *)(ifam + 1), ifam->ifam_addrs);
190 errmsg = "sa == NULL";
194 if ((a.len = sizeof(struct in_addr)) > sizeof(a.iabuf))
195 error("king bula sez: len mismatch");
196 memcpy(a.iabuf, &((struct sockaddr_in *)sa)->sin_addr, a.len);
197 if (addr_eq(a, defaddr))
200 for (l = client->active; l != NULL; l = l->next)
201 if (addr_eq(a, l->address))
204 if (l != NULL || (client->alias &&
205 addr_eq(a, client->alias->address)))
206 /* new addr is the one we set */
208 snprintf(buf, sizeof(buf), "%s: %s",
209 "new address not one we set", piaddr(a));
213 ifam = (struct ifa_msghdr *)rtm;
214 if (ifam->ifam_index != ifi->index)
216 if (findproto((char *)(ifam + 1), ifam->ifam_addrs) != AF_INET)
218 if (scripttime == 0 || t < scripttime + 10)
220 errmsg = "interface address deleted";
223 ifm = (struct if_msghdr *)rtm;
224 if (ifm->ifm_index != ifi->index)
226 if ((rtm->rtm_flags & RTF_UP) == 0) {
227 errmsg = "interface down";
232 LINK_STATE_IS_UP(ifm->ifm_data.ifi_link_state) ? 1 : 0;
233 if (linkstat != ifi->linkstat) {
235 debug("link state %s -> %s",
236 ifi->linkstat ? "up" : "down",
237 linkstat ? "up" : "down");
239 ifi->linkstat = interface_link_status(ifi->name);
241 client->state = S_INIT;
247 ifan = (struct if_announcemsghdr *)rtm;
248 if (ifan->ifan_what == IFAN_DEPARTURE &&
249 ifan->ifan_index == ifi->index) {
250 errmsg = "interface departure";
260 script_init("FAIL", NULL);
262 script_write_params("alias_", client->alias);
264 error("routehandler: %s", errmsg);
268 main(int argc, char *argv[])
270 int ch, fd, quiet = 0, i = 0, pipe_fd[2];
273 /* Initially, log errors to stderr as well as to syslogd. */
274 openlog(getprogname(), LOG_PID | LOG_NDELAY, DHCPD_LOG_FACILITY);
275 setlogmask(LOG_UPTO(LOG_INFO));
277 while ((ch = getopt(argc, argv, "c:dl:qu")) != -1)
280 path_dhclient_conf = optarg;
286 path_dhclient_db = optarg;
304 ifi = calloc(1, sizeof(*ifi));
307 client = calloc(1, sizeof(*client));
309 error("client calloc");
310 config = calloc(1, sizeof(*config));
312 error("config calloc");
314 if (strlcpy(ifi->name, argv[0], IFNAMSIZ) >= IFNAMSIZ)
315 error("Interface name too long");
316 if (path_dhclient_db == NULL && asprintf(&path_dhclient_db, "%s.%s",
317 _PATH_DHCLIENT_DB, ifi->name) == -1)
326 memset(&sockaddr_broadcast, 0, sizeof(sockaddr_broadcast));
327 sockaddr_broadcast.sin_family = AF_INET;
328 sockaddr_broadcast.sin_port = htons(REMOTE_PORT);
329 sockaddr_broadcast.sin_addr.s_addr = INADDR_BROADCAST;
330 sockaddr_broadcast.sin_len = sizeof(sockaddr_broadcast);
331 inaddr_any.s_addr = INADDR_ANY;
335 if (interface_status(ifi->name) == 0) {
336 interface_link_forceup(ifi->name);
337 /* Give it up to 4 seconds of silent grace to find link */
342 while (!(ifi->linkstat = interface_link_status(ifi->name))) {
344 fprintf(stderr, "%s: no link ...", ifi->name);
346 fprintf(stderr, ".");
348 if (++i > config->link_timeout) {
349 fprintf(stderr, " sleeping\n");
355 fprintf(stderr, " got link\n");
358 if ((nullfd = open(_PATH_DEVNULL, O_RDWR, 0)) == -1)
359 error("cannot open %s: %m", _PATH_DEVNULL);
361 if ((pw = getpwnam("_dhcp")) == NULL)
362 error("no such user: _dhcp");
364 if (pipe(pipe_fd) == -1)
367 fork_privchld(pipe_fd[0], pipe_fd[1]);
372 if ((fd = open(path_dhclient_db, O_RDONLY|O_EXLOCK|O_CREAT, 0)) == -1)
373 error("can't open and lock %s: %m", path_dhclient_db);
374 read_client_leases();
375 if ((leaseFile = fopen(path_dhclient_db, "w")) == NULL)
376 error("can't open %s: %m", path_dhclient_db);
377 rewrite_client_leases();
380 priv_script_init("PREINIT", NULL);
382 priv_script_write_params("alias_", client->alias);
385 if ((routefd = socket(PF_ROUTE, SOCK_RAW, 0)) == -1)
386 error("socket(PF_ROUTE, SOCK_RAW): %m");
388 /* set up the interface */
389 discover_interface();
391 if (chroot(_PATH_VAREMPTY) == -1)
393 if (chdir("/") == -1)
394 error("chdir(\"/\")");
396 if (setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) == -1)
398 if (setgroups(1, &pw->pw_gid) == -1)
400 if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) == -1)
405 setproctitle("%s", ifi->name);
408 client->state = S_INIT;
422 fprintf(stderr, "usage: %s [-dqu] [-c file] [-l file] interface\n",
430 * Each routine is called from the dhclient_state_machine() in one of
432 * -> entering INIT state
433 * -> recvpacket_flag == 0: timeout in this state
434 * -> otherwise: received a packet in this state
436 * Return conditions as handled by dhclient_state_machine():
437 * Returns 1, sendpacket_flag = 1: send packet, reset timer.
438 * Returns 1, sendpacket_flag = 0: just reset the timer (wait for a milestone).
439 * Returns 0: finish the nap which was interrupted for no good reason.
441 * Several per-interface variables are used to keep track of the process:
442 * active_lease: the lease that is being used on the interface
443 * (null pointer if not configured yet).
444 * offered_leases: leases corresponding to DHCPOFFER messages that have
445 * been sent to us by DHCP servers.
446 * acked_leases: leases corresponding to DHCPACK messages that have been
447 * sent to us by DHCP servers.
448 * sendpacket: DHCP packet we're trying to send.
449 * destination: IP address to send sendpacket to
450 * In addition, there are several relevant per-lease variables.
451 * T1_expiry, T2_expiry, lease_expiry: lease milestones
452 * In the active lease, these control the process of renewing the lease;
453 * In leases on the acked_leases list, this simply determines when we
454 * can no longer legitimately use the lease.
459 /* If we don't remember an active lease, go straight to INIT. */
460 if (!client->active || client->active->is_bootp) {
465 /* We are in the rebooting state. */
466 client->state = S_REBOOTING;
468 /* make_request doesn't initialize xid because it normally comes
469 from the DHCPDISCOVER, but we haven't sent a DHCPDISCOVER,
470 so pick an xid now. */
471 client->xid = arc4random();
473 /* Make a DHCPREQUEST packet, and set appropriate per-interface
475 make_request(client->active);
476 client->destination = iaddr_broadcast;
477 client->first_sending = cur_time;
478 client->interval = config->initial_interval;
480 /* Zap the medium list... */
481 client->medium = NULL;
483 /* Send out the first DHCPREQUEST packet. */
488 * Called when a lease has completely expired and we've
489 * been unable to renew it.
494 /* Make a DHCPDISCOVER packet, and set appropriate per-interface
496 make_discover(client->active);
497 client->xid = client->packet.xid;
498 client->destination = iaddr_broadcast;
499 client->state = S_SELECTING;
500 client->first_sending = cur_time;
501 client->interval = config->initial_interval;
503 /* Add an immediate timeout to cause the first DHCPDISCOVER packet
509 * state_selecting is called when one or more DHCPOFFER packets
510 * have been received and a configurable period of time has passed.
513 state_selecting(void)
515 struct client_lease *lp, *next, *picked;
517 /* Cancel state_selecting and send_discover timeouts, since either
518 one could have got us here. */
519 cancel_timeout(state_selecting);
520 cancel_timeout(send_discover);
522 /* We have received one or more DHCPOFFER packets. Currently,
523 the only criterion by which we judge leases is whether or
524 not we get a response when we arp for them. */
526 for (lp = client->offered_leases; lp; lp = next) {
529 /* Check to see if we got an ARPREPLY for the address
530 in this particular lease. */
532 script_init("ARPCHECK", lp->medium);
533 script_write_params("check_", lp);
535 /* If the ARPCHECK code detects another
536 machine using the offered address, it exits
537 nonzero. We need to send a DHCPDECLINE and
548 free_client_lease(lp);
551 client->offered_leases = NULL;
553 /* If we just tossed all the leases we were offered, go back
556 client->state = S_INIT;
561 /* If it was a BOOTREPLY, we can just take the address right now. */
562 if (!picked->options[DHO_DHCP_MESSAGE_TYPE].len) {
563 client->new = picked;
565 /* Make up some lease expiry times
566 XXX these should be configurable. */
567 client->new->expiry = cur_time + 12000;
568 client->new->renewal += cur_time + 8000;
569 client->new->rebind += cur_time + 10000;
571 client->state = S_REQUESTING;
573 /* Bind to the address we received. */
578 /* Go to the REQUESTING state. */
579 client->destination = iaddr_broadcast;
580 client->state = S_REQUESTING;
581 client->first_sending = cur_time;
582 client->interval = config->initial_interval;
584 /* Make a DHCPREQUEST packet from the lease we picked. */
585 make_request(picked);
586 client->xid = client->packet.xid;
588 /* Toss the lease we picked - we'll get it back in a DHCPACK. */
589 free_client_lease(picked);
591 /* Add an immediate timeout to send the first DHCPREQUEST packet. */
596 dhcpack(struct iaddr client_addr, struct option_data *options)
598 struct client_lease *lease;
601 if (client->state != S_REBOOTING &&
602 client->state != S_REQUESTING &&
603 client->state != S_RENEWING &&
604 client->state != S_REBINDING)
608 lease = packet_to_lease(options);
610 note("packet_to_lease failed.");
616 /* Stop resending DHCPREQUEST. */
617 cancel_timeout(send_request);
619 /* Figure out the lease time. */
620 if (client->new->options[DHO_DHCP_LEASE_TIME].data)
621 client->new->expiry =
622 getULong(client->new->options[DHO_DHCP_LEASE_TIME].data);
624 client->new->expiry = DEFAULT_LEASE_TIME;
625 /* A number that looks negative here is really just very large,
626 because the lease expiry offset is unsigned. */
627 if (client->new->expiry < 0)
628 client->new->expiry = TIME_MAX;
629 /* XXX should be fixed by resetting the client state */
630 if (client->new->expiry < 60)
631 client->new->expiry = 60;
633 /* Take the server-provided renewal time if there is one;
634 otherwise figure it out according to the spec. */
635 if (client->new->options[DHO_DHCP_RENEWAL_TIME].len)
636 client->new->renewal =
637 getULong(client->new->options[DHO_DHCP_RENEWAL_TIME].data);
639 client->new->renewal = client->new->expiry / 2;
641 /* Same deal with the rebind time. */
642 if (client->new->options[DHO_DHCP_REBINDING_TIME].len)
643 client->new->rebind =
644 getULong(client->new->options[DHO_DHCP_REBINDING_TIME].data);
646 client->new->rebind = client->new->renewal +
647 client->new->renewal / 2 + client->new->renewal / 4;
649 client->new->expiry += cur_time;
650 /* Lease lengths can never be negative. */
651 if (client->new->expiry < cur_time)
652 client->new->expiry = TIME_MAX;
653 client->new->renewal += cur_time;
654 if (client->new->renewal < cur_time)
655 client->new->renewal = TIME_MAX;
656 client->new->rebind += cur_time;
657 if (client->new->rebind < cur_time)
658 client->new->rebind = TIME_MAX;
666 /* Remember the medium. */
667 client->new->medium = client->medium;
669 /* Write out the new lease. */
670 write_client_lease(client->new, 0);
672 /* Run the client script with the new parameters. */
673 script_init((client->state == S_REQUESTING ? "BOUND" :
674 (client->state == S_RENEWING ? "RENEW" :
675 (client->state == S_REBOOTING ? "REBOOT" : "REBIND"))),
676 client->new->medium);
677 if (client->active && client->state != S_REBOOTING)
678 script_write_params("old_", client->active);
679 script_write_params("new_", client->new);
681 script_write_params("alias_", client->alias);
684 /* Replace the old active lease with the new one. */
686 free_client_lease(client->active);
687 client->active = client->new;
690 /* Set up a timeout to start the renewal process. */
691 add_timeout(client->active->renewal, state_bound);
693 note("bound to %s -- renewal in %ld seconds.",
694 piaddr(client->active->address),
695 client->active->renewal - cur_time);
696 client->state = S_BOUND;
697 reinitialize_interface();
702 * state_bound is called when we've successfully bound to a particular
703 * lease, but the renewal time on that lease has expired. We are
704 * expected to unicast a DHCPREQUEST to the server that gave us our
710 /* T1 has expired. */
711 make_request(client->active);
712 client->xid = client->packet.xid;
714 if (client->active->options[DHO_DHCP_SERVER_IDENTIFIER].len == 4) {
715 memcpy(client->destination.iabuf,
716 client->active->options[DHO_DHCP_SERVER_IDENTIFIER].data,
718 client->destination.len = 4;
720 client->destination = iaddr_broadcast;
722 client->first_sending = cur_time;
723 client->interval = config->initial_interval;
724 client->state = S_RENEWING;
726 /* Send the first packet immediately. */
731 dhcpoffer(struct iaddr client_addr, struct option_data *options)
733 struct client_lease *lease, *lp;
735 int arp_timeout_needed, stop_selecting;
736 char *name = options[DHO_DHCP_MESSAGE_TYPE].len ? "DHCPOFFER" :
740 if (client->state != S_SELECTING)
744 /* If this lease doesn't supply the minimum required parameters,
746 for (i = 0; config->required_options[i]; i++) {
747 if (!options[config->required_options[i]].len) {
748 note("%s isn't satisfactory.", name);
753 /* If we've already seen this lease, don't record it again. */
754 for (lease = client->offered_leases;
755 lease; lease = lease->next) {
756 if (lease->address.len == sizeof(client->packet.yiaddr) &&
757 !memcmp(lease->address.iabuf,
758 &client->packet.yiaddr, lease->address.len)) {
760 debug("%s already seen.", name);
766 lease = packet_to_lease(options);
768 note("packet_to_lease failed.");
772 /* If this lease was acquired through a BOOTREPLY, record that
774 if (!options[DHO_DHCP_MESSAGE_TYPE].len)
777 /* Record the medium under which this lease was offered. */
778 lease->medium = client->medium;
780 /* Send out an ARP Request for the offered IP address. */
781 script_init("ARPSEND", lease->medium);
782 script_write_params("check_", lease);
783 /* If the script can't send an ARP request without waiting,
784 we'll be waiting when we do the ARPCHECK, so don't wait now. */
786 arp_timeout_needed = 0;
788 arp_timeout_needed = 2;
790 /* Figure out when we're supposed to stop selecting. */
791 stop_selecting = client->first_sending + config->select_interval;
793 /* If this is the lease we asked for, put it at the head of the
794 list, and don't mess with the arp request timeout. */
795 if (lease->address.len == client->requested_address.len &&
796 !memcmp(lease->address.iabuf,
797 client->requested_address.iabuf,
798 client->requested_address.len)) {
799 lease->next = client->offered_leases;
800 client->offered_leases = lease;
802 /* If we already have an offer, and arping for this
803 offer would take us past the selection timeout,
804 then don't extend the timeout - just hope for the
806 if (client->offered_leases &&
807 (cur_time + arp_timeout_needed) > stop_selecting)
808 arp_timeout_needed = 0;
810 /* Put the lease at the end of the list. */
812 if (!client->offered_leases)
813 client->offered_leases = lease;
815 for (lp = client->offered_leases; lp->next;
822 /* If we're supposed to stop selecting before we've had time
823 to wait for the ARPREPLY, add some delay to wait for
825 if (stop_selecting - cur_time < arp_timeout_needed)
826 stop_selecting = cur_time + arp_timeout_needed;
828 /* If the selecting interval has expired, go immediately to
829 state_selecting(). Otherwise, time out into
830 state_selecting at the select interval. */
831 if (stop_selecting <= 0)
834 add_timeout(stop_selecting, state_selecting);
835 cancel_timeout(send_discover);
840 * Allocate a client_lease structure and initialize it from the
841 * parameters in the specified packet.
843 struct client_lease *
844 packet_to_lease(struct option_data *options)
846 struct client_lease *lease;
849 lease = malloc(sizeof(struct client_lease));
852 warning("dhcpoffer: no memory to record lease.");
856 memset(lease, 0, sizeof(*lease));
858 /* Copy the lease options. */
859 for (i = 0; i < 256; i++) {
860 if (options[i].len) {
861 lease->options[i] = options[i];
862 options[i].data = NULL;
864 if (!check_option(lease, i)) {
865 warning("Invalid lease option - ignoring offer");
866 free_client_lease(lease);
872 lease->address.len = sizeof(client->packet.yiaddr);
873 memcpy(lease->address.iabuf, &client->packet.yiaddr,
876 /* If the server name was filled out, copy it. */
877 if ((!lease->options[DHO_DHCP_OPTION_OVERLOAD].len ||
878 !(lease->options[DHO_DHCP_OPTION_OVERLOAD].data[0] & 2)) &&
879 client->packet.sname[0]) {
880 lease->server_name = malloc(DHCP_SNAME_LEN + 1);
881 if (!lease->server_name) {
882 warning("dhcpoffer: no memory for server name.");
883 free_client_lease(lease);
886 memcpy(lease->server_name, client->packet.sname,
888 lease->server_name[DHCP_SNAME_LEN] = '\0';
889 if (!res_hnok(lease->server_name)) {
890 warning("Bogus server name %s", lease->server_name);
891 free(lease->server_name);
892 lease->server_name = NULL;
896 /* Ditto for the filename. */
897 if ((!lease->options[DHO_DHCP_OPTION_OVERLOAD].len ||
898 !(lease->options[DHO_DHCP_OPTION_OVERLOAD].data[0] & 1)) &&
899 client->packet.file[0]) {
900 /* Don't count on the NUL terminator. */
901 lease->filename = malloc(DHCP_FILE_LEN + 1);
902 if (!lease->filename) {
903 warning("dhcpoffer: no memory for filename.");
904 free_client_lease(lease);
907 memcpy(lease->filename, client->packet.file, DHCP_FILE_LEN);
908 lease->filename[DHCP_FILE_LEN] = '\0';
914 dhcpnak(struct iaddr client_addr, struct option_data *options)
917 if (client->state != S_REBOOTING &&
918 client->state != S_REQUESTING &&
919 client->state != S_RENEWING &&
920 client->state != S_REBINDING)
924 if (!client->active) {
925 note("DHCPNAK with no active lease.");
929 free_client_lease(client->active);
930 client->active = NULL;
932 /* Stop sending DHCPREQUEST packets... */
933 cancel_timeout(send_request);
935 client->state = S_INIT;
940 * Send out a DHCPDISCOVER packet, and set a timeout to send out another
941 * one after the right interval has expired. If we don't get an offer by
942 * the time we reach the panic interval, call the panic function.
947 int interval, increase = 1;
949 /* Figure out how long it's been since we started transmitting. */
950 interval = cur_time - client->first_sending;
952 /* If we're past the panic timeout, call the script and tell it
953 we haven't found anything for this interface yet. */
954 if (interval > config->timeout) {
959 /* If we're selecting media, try the whole list before doing
960 the exponential backoff, but if we've already received an
961 offer, stop looping, because we obviously have it right. */
962 if (!client->offered_leases && config->media) {
965 if (client->medium) {
966 client->medium = client->medium->next;
969 if (!client->medium) {
971 error("No valid media types for %s!", ifi->name);
972 client->medium = config->media;
976 note("Trying medium \"%s\" %d", client->medium->string,
978 script_init("MEDIUM", client->medium);
984 * If we're supposed to increase the interval, do so. If it's
985 * currently zero (i.e., we haven't sent any packets yet), set
986 * it to initial_interval; otherwise, add to it a random
987 * number between zero and two times itself. On average, this
988 * means that it will double with every transmission.
991 if (!client->interval)
992 client->interval = config->initial_interval;
994 client->interval += (arc4random() >> 2) %
995 (2 * client->interval);
998 /* Don't backoff past cutoff. */
999 if (client->interval > config->backoff_cutoff)
1000 client->interval = ((config->backoff_cutoff / 2)
1001 + ((arc4random() >> 2) %
1002 config->backoff_cutoff));
1003 } else if (!client->interval)
1004 client->interval = config->initial_interval;
1006 /* If the backoff would take us to the panic timeout, just use that
1008 if (cur_time + client->interval >
1009 client->first_sending + config->timeout)
1010 client->interval = (client->first_sending +
1011 config->timeout) - cur_time + 1;
1013 /* Record the number of seconds since we started sending. */
1014 if (interval < 65536)
1015 client->packet.secs = htons(interval);
1017 client->packet.secs = htons(65535);
1018 client->secs = client->packet.secs;
1020 note("DHCPDISCOVER on %s to %s port %d interval %ld",
1021 ifi->name, inet_ntoa(sockaddr_broadcast.sin_addr),
1022 ntohs(sockaddr_broadcast.sin_port), client->interval);
1024 /* Send out a packet. */
1025 send_packet(inaddr_any, &sockaddr_broadcast, NULL);
1027 add_timeout(cur_time + client->interval, send_discover);
1031 * state_panic gets called if we haven't received any offers in a preset
1032 * amount of time. When this happens, we try to use existing leases
1033 * that haven't yet expired, and failing that, we call the client script
1034 * and hope it can do something.
1039 struct client_lease *loop = client->active;
1040 struct client_lease *lp;
1042 note("No DHCPOFFERS received.");
1044 /* We may not have an active lease, but we may have some
1045 predefined leases that we can try. */
1046 if (!client->active && client->leases)
1049 /* Run through the list of leases and see if one can be used. */
1050 while (client->active) {
1051 if (client->active->expiry > cur_time) {
1052 note("Trying recorded lease %s",
1053 piaddr(client->active->address));
1054 /* Run the client script with the existing
1056 script_init("TIMEOUT",
1057 client->active->medium);
1058 script_write_params("new_", client->active);
1060 script_write_params("alias_",
1063 /* If the old lease is still good and doesn't
1064 yet need renewal, go into BOUND state and
1065 timeout at the renewal time. */
1068 client->active->renewal) {
1069 client->state = S_BOUND;
1070 note("bound: renewal in %ld seconds.",
1071 client->active->renewal -
1073 add_timeout(client->active->renewal,
1076 client->state = S_BOUND;
1077 note("bound: immediate renewal.");
1080 reinitialize_interface();
1086 /* If there are no other leases, give up. */
1087 if (!client->leases) {
1088 client->leases = client->active;
1089 client->active = NULL;
1094 /* Otherwise, put the active lease at the end of the
1095 lease list, and try another lease.. */
1096 for (lp = client->leases; lp->next; lp = lp->next)
1098 lp->next = client->active;
1100 lp->next->next = NULL;
1101 client->active = client->leases;
1102 client->leases = client->leases->next;
1104 /* If we already tried this lease, we've exhausted the
1105 set of leases, so we might as well give up for
1107 if (client->active == loop)
1110 loop = client->active;
1113 /* No leases were available, or what was available didn't work, so
1114 tell the shell script that we failed to allocate an address,
1115 and try again later. */
1116 note("No working leases in persistent database - sleeping.");
1117 script_init("FAIL", NULL);
1119 script_write_params("alias_", client->alias);
1121 client->state = S_INIT;
1122 add_timeout(cur_time + config->retry_interval, state_init);
1129 struct sockaddr_in destination;
1130 struct in_addr from;
1133 /* Figure out how long it's been since we started transmitting. */
1134 interval = cur_time - client->first_sending;
1136 /* If we're in the INIT-REBOOT or REQUESTING state and we're
1137 past the reboot timeout, go to INIT and see if we can
1138 DISCOVER an address... */
1139 /* XXX In the INIT-REBOOT state, if we don't get an ACK, it
1140 means either that we're on a network with no DHCP server,
1141 or that our server is down. In the latter case, assuming
1142 that there is a backup DHCP server, DHCPDISCOVER will get
1143 us a new address, but we could also have successfully
1144 reused our old address. In the former case, we're hosed
1145 anyway. This is not a win-prone situation. */
1146 if ((client->state == S_REBOOTING ||
1147 client->state == S_REQUESTING) &&
1148 interval > config->reboot_timeout) {
1150 client->state = S_INIT;
1151 cancel_timeout(send_request);
1156 /* If we're in the reboot state, make sure the media is set up
1158 if (client->state == S_REBOOTING &&
1160 client->active->medium) {
1161 script_init("MEDIUM", client->active->medium);
1163 /* If the medium we chose won't fly, go to INIT state. */
1167 /* Record the medium. */
1168 client->medium = client->active->medium;
1171 /* If the lease has expired, relinquish the address and go back
1172 to the INIT state. */
1173 if (client->state != S_REQUESTING &&
1174 cur_time > client->active->expiry) {
1175 /* Run the client script with the new parameters. */
1176 script_init("EXPIRE", NULL);
1177 script_write_params("old_", client->active);
1179 script_write_params("alias_", client->alias);
1182 /* Now do a preinit on the interface so that we can
1183 discover a new address. */
1184 script_init("PREINIT", NULL);
1186 script_write_params("alias_", client->alias);
1189 client->state = S_INIT;
1194 /* Do the exponential backoff... */
1195 if (!client->interval)
1196 client->interval = config->initial_interval;
1198 client->interval += ((arc4random() >> 2) %
1199 (2 * client->interval));
1201 /* Don't backoff past cutoff. */
1202 if (client->interval > config->backoff_cutoff)
1203 client->interval = ((config->backoff_cutoff / 2) +
1204 ((arc4random() >> 2) % client->interval));
1206 /* If the backoff would take us to the expiry time, just set the
1207 timeout to the expiry time. */
1208 if (client->state != S_REQUESTING && cur_time + client->interval >
1209 client->active->expiry)
1210 client->interval = client->active->expiry - cur_time + 1;
1212 /* If the lease T2 time has elapsed, or if we're not yet bound,
1213 broadcast the DHCPREQUEST rather than unicasting. */
1214 memset(&destination, 0, sizeof(destination));
1215 if (client->state == S_REQUESTING ||
1216 client->state == S_REBOOTING ||
1217 cur_time > client->active->rebind)
1218 destination.sin_addr.s_addr = INADDR_BROADCAST;
1220 memcpy(&destination.sin_addr.s_addr, client->destination.iabuf,
1221 sizeof(destination.sin_addr.s_addr));
1222 destination.sin_port = htons(REMOTE_PORT);
1223 destination.sin_family = AF_INET;
1224 destination.sin_len = sizeof(destination);
1226 if (client->state != S_REQUESTING)
1227 memcpy(&from, client->active->address.iabuf, sizeof(from));
1229 from.s_addr = INADDR_ANY;
1231 /* Record the number of seconds since we started sending. */
1232 if (client->state == S_REQUESTING)
1233 client->packet.secs = client->secs;
1235 if (interval < 65536)
1236 client->packet.secs = htons(interval);
1238 client->packet.secs = htons(65535);
1241 note("DHCPREQUEST on %s to %s port %d", ifi->name,
1242 inet_ntoa(destination.sin_addr), ntohs(destination.sin_port));
1244 /* Send out a packet. */
1245 send_packet(from, &destination, NULL);
1247 add_timeout(cur_time + client->interval, send_request);
1253 note("DHCPDECLINE on %s to %s port %d", ifi->name,
1254 inet_ntoa(sockaddr_broadcast.sin_addr),
1255 ntohs(sockaddr_broadcast.sin_port));
1257 /* Send out a packet. */
1258 send_packet(inaddr_any, &sockaddr_broadcast, NULL);
1262 make_discover(struct client_lease *lease)
1264 unsigned char discover = DHCPDISCOVER;
1265 struct option_data options[256];
1268 memset(options, 0, sizeof(options));
1269 memset(&client->packet, 0, sizeof(client->packet));
1271 /* Set DHCP_MESSAGE_TYPE to DHCPDISCOVER */
1272 i = DHO_DHCP_MESSAGE_TYPE;
1273 options[i].data = &discover;
1274 options[i].len = sizeof(discover);
1276 /* Request the options we want */
1277 i = DHO_DHCP_PARAMETER_REQUEST_LIST;
1278 options[i].data = config->requested_options;
1279 options[i].len = config->requested_option_count;
1281 /* If we had an address, try to get it again. */
1283 client->requested_address = lease->address;
1284 i = DHO_DHCP_REQUESTED_ADDRESS;
1285 options[i].data = lease->address.iabuf;
1286 options[i].len = lease->address.len;
1288 client->requested_address.len = 0;
1290 /* Send any options requested in the config file. */
1291 for (i = 0; i < 256; i++)
1292 if (!options[i].data &&
1293 config->send_options[i].data) {
1294 options[i].data = config->send_options[i].data;
1295 options[i].len = config->send_options[i].len;
1298 /* Set up the option buffer to fit in a minimal UDP packet. */
1299 i = cons_options(client->packet.options, 576 - DHCP_FIXED_LEN,
1301 if (i == -1 || client->packet.options[i] != DHO_END)
1302 error("options do not fit in DHCPDISCOVER packet.");
1303 client->packet_length = DHCP_FIXED_NON_UDP+i+1;
1304 if (client->packet_length < BOOTP_MIN_LEN)
1305 client->packet_length = BOOTP_MIN_LEN;
1307 client->packet.op = BOOTREQUEST;
1308 client->packet.htype = ifi->hw_address.htype;
1309 client->packet.hlen = ifi->hw_address.hlen;
1310 client->packet.hops = 0;
1311 client->packet.xid = arc4random();
1312 client->packet.secs = 0; /* filled in by send_discover. */
1313 client->packet.flags = 0;
1315 memset(&client->packet.ciaddr, 0, sizeof(client->packet.ciaddr));
1316 memset(&client->packet.yiaddr, 0, sizeof(client->packet.yiaddr));
1317 memset(&client->packet.siaddr, 0, sizeof(client->packet.siaddr));
1318 memset(&client->packet.giaddr, 0, sizeof(client->packet.giaddr));
1319 memcpy(client->packet.chaddr, ifi->hw_address.haddr,
1320 ifi->hw_address.hlen);
1324 make_request(struct client_lease * lease)
1326 unsigned char request = DHCPREQUEST;
1327 struct option_data options[256];
1330 memset(options, 0, sizeof(options));
1331 memset(&client->packet, 0, sizeof(client->packet));
1333 /* Set DHCP_MESSAGE_TYPE to DHCPREQUEST */
1334 i = DHO_DHCP_MESSAGE_TYPE;
1335 options[i].data = &request;
1336 options[i].len = sizeof(request);
1338 /* Request the options we want */
1339 i = DHO_DHCP_PARAMETER_REQUEST_LIST;
1340 options[i].data = config->requested_options;
1341 options[i].len = config->requested_option_count;
1343 /* If we are requesting an address that hasn't yet been assigned
1344 to us, use the DHCP Requested Address option. */
1345 if (client->state == S_REQUESTING) {
1346 /* Send back the server identifier... */
1347 i = DHO_DHCP_SERVER_IDENTIFIER;
1348 options[i].data = lease->options[i].data;
1349 options[i].len = lease->options[i].len;
1351 if (client->state == S_REQUESTING ||
1352 client->state == S_REBOOTING) {
1353 client->requested_address = lease->address;
1354 i = DHO_DHCP_REQUESTED_ADDRESS;
1355 options[i].data = lease->address.iabuf;
1356 options[i].len = lease->address.len;
1358 client->requested_address.len = 0;
1360 /* Send any options requested in the config file. */
1361 for (i = 0; i < 256; i++)
1362 if (!options[i].data && config->send_options[i].data) {
1363 options[i].data = config->send_options[i].data;
1364 options[i].len = config->send_options[i].len;
1367 /* Set up the option buffer to fit in a minimal UDP packet. */
1368 i = cons_options(client->packet.options, 576 - DHCP_FIXED_LEN,
1370 if (i == -1 || client->packet.options[i] != DHO_END)
1371 error("options do not fit in DHCPREQUEST packet.");
1372 client->packet_length = DHCP_FIXED_NON_UDP+i+1;
1373 if (client->packet_length < BOOTP_MIN_LEN)
1374 client->packet_length = BOOTP_MIN_LEN;
1376 client->packet.op = BOOTREQUEST;
1377 client->packet.htype = ifi->hw_address.htype;
1378 client->packet.hlen = ifi->hw_address.hlen;
1379 client->packet.hops = 0;
1380 client->packet.xid = client->xid;
1381 client->packet.secs = 0; /* Filled in by send_request. */
1382 client->packet.flags = 0;
1384 /* If we own the address we're requesting, put it in ciaddr;
1385 otherwise set ciaddr to zero. */
1386 if (client->state == S_BOUND ||
1387 client->state == S_RENEWING ||
1388 client->state == S_REBINDING) {
1389 memcpy(&client->packet.ciaddr,
1390 lease->address.iabuf, lease->address.len);
1392 memset(&client->packet.ciaddr, 0,
1393 sizeof(client->packet.ciaddr));
1396 memset(&client->packet.yiaddr, 0, sizeof(client->packet.yiaddr));
1397 memset(&client->packet.siaddr, 0, sizeof(client->packet.siaddr));
1398 memset(&client->packet.giaddr, 0, sizeof(client->packet.giaddr));
1399 memcpy(client->packet.chaddr, ifi->hw_address.haddr,
1400 ifi->hw_address.hlen);
1404 make_decline(struct client_lease *lease)
1406 struct option_data options[256];
1407 unsigned char decline = DHCPDECLINE;
1410 memset(options, 0, sizeof(options));
1411 memset(&client->packet, 0, sizeof(client->packet));
1413 /* Set DHCP_MESSAGE_TYPE to DHCPDECLINE */
1414 i = DHO_DHCP_MESSAGE_TYPE;
1415 options[i].data = &decline;
1416 options[i].len = sizeof(decline);
1418 /* Send back the server identifier... */
1419 i = DHO_DHCP_SERVER_IDENTIFIER;
1420 options[i].data = lease->options[i].data;
1421 options[i].len = lease->options[i].len;
1423 /* Send back the address we're declining. */
1424 i = DHO_DHCP_REQUESTED_ADDRESS;
1425 options[i].data = lease->address.iabuf;
1426 options[i].len = lease->address.len;
1428 /* Send the uid if the user supplied one. */
1429 i = DHO_DHCP_CLIENT_IDENTIFIER;
1430 if (config->send_options[i].len) {
1431 options[i].data = config->send_options[i].data;
1432 options[i].len = config->send_options[i].len;
1435 /* Set up the option buffer to fit in a minimal UDP packet. */
1436 i = cons_options(client->packet.options, 576 - DHCP_FIXED_LEN,
1438 if (i == -1 || client->packet.options[i] != DHO_END)
1439 error("options do not fit in DHCPDECLINE packet.");
1440 client->packet_length = DHCP_FIXED_NON_UDP+i+1;
1441 if (client->packet_length < BOOTP_MIN_LEN)
1442 client->packet_length = BOOTP_MIN_LEN;
1444 client->packet.op = BOOTREQUEST;
1445 client->packet.htype = ifi->hw_address.htype;
1446 client->packet.hlen = ifi->hw_address.hlen;
1447 client->packet.hops = 0;
1448 client->packet.xid = client->xid;
1449 client->packet.secs = 0; /* Filled in by send_request. */
1450 client->packet.flags = 0;
1452 /* ciaddr must always be zero. */
1453 memset(&client->packet.ciaddr, 0, sizeof(client->packet.ciaddr));
1454 memset(&client->packet.yiaddr, 0, sizeof(client->packet.yiaddr));
1455 memset(&client->packet.siaddr, 0, sizeof(client->packet.siaddr));
1456 memset(&client->packet.giaddr, 0, sizeof(client->packet.giaddr));
1457 memcpy(client->packet.chaddr, ifi->hw_address.haddr,
1458 ifi->hw_address.hlen);
1462 free_client_lease(struct client_lease *lease)
1466 if (lease->server_name)
1467 free(lease->server_name);
1468 if (lease->filename)
1469 free(lease->filename);
1470 for (i = 0; i < 256; i++) {
1471 if (lease->options[i].len)
1472 free(lease->options[i].data);
1478 rewrite_client_leases(void)
1480 struct client_lease *lp;
1482 if (!leaseFile) /* XXX */
1483 error("lease file not open");
1488 for (lp = client->leases; lp; lp = lp->next)
1489 write_client_lease(lp, 1);
1491 write_client_lease(client->active, 1);
1494 ftruncate(fileno(leaseFile), ftello(leaseFile));
1495 fsync(fileno(leaseFile));
1499 write_client_lease(struct client_lease *lease, int rewrite)
1501 static int leases_written;
1506 if (leases_written++ > 20) {
1507 rewrite_client_leases();
1512 /* If the lease came from the config file, we don't need to stash
1513 a copy in the lease database. */
1514 if (lease->is_static)
1517 if (!leaseFile) /* XXX */
1518 error("lease file not open");
1520 fprintf(leaseFile, "lease {\n");
1521 if (lease->is_bootp)
1522 fprintf(leaseFile, " bootp;\n");
1523 fprintf(leaseFile, " interface \"%s\";\n", ifi->name);
1524 fprintf(leaseFile, " fixed-address %s;\n", piaddr(lease->address));
1525 if (lease->filename)
1526 fprintf(leaseFile, " filename \"%s\";\n", lease->filename);
1527 if (lease->server_name)
1528 fprintf(leaseFile, " server-name \"%s\";\n",
1529 lease->server_name);
1531 fprintf(leaseFile, " medium \"%s\";\n", lease->medium->string);
1532 for (i = 0; i < 256; i++)
1533 if (lease->options[i].len)
1534 fprintf(leaseFile, " option %s %s;\n",
1535 dhcp_options[i].name,
1536 pretty_print_option(i, lease->options[i].data,
1537 lease->options[i].len, 1, 1));
1539 t = gmtime(&lease->renewal);
1540 fprintf(leaseFile, " renew %d %d/%d/%d %02d:%02d:%02d;\n",
1541 t->tm_wday, t->tm_year + 1900, t->tm_mon + 1, t->tm_mday,
1542 t->tm_hour, t->tm_min, t->tm_sec);
1543 t = gmtime(&lease->rebind);
1544 fprintf(leaseFile, " rebind %d %d/%d/%d %02d:%02d:%02d;\n",
1545 t->tm_wday, t->tm_year + 1900, t->tm_mon + 1, t->tm_mday,
1546 t->tm_hour, t->tm_min, t->tm_sec);
1547 t = gmtime(&lease->expiry);
1548 fprintf(leaseFile, " expire %d %d/%d/%d %02d:%02d:%02d;\n",
1549 t->tm_wday, t->tm_year + 1900, t->tm_mon + 1, t->tm_mday,
1550 t->tm_hour, t->tm_min, t->tm_sec);
1551 fprintf(leaseFile, "}\n");
1556 script_init(char *reason, struct string_list *medium)
1558 size_t len, mediumlen = 0;
1559 struct imsg_hdr hdr;
1562 if (medium != NULL && medium->string != NULL)
1563 mediumlen = strlen(medium->string);
1565 hdr.code = IMSG_SCRIPT_INIT;
1566 hdr.len = sizeof(struct imsg_hdr) +
1567 sizeof(size_t) + mediumlen +
1568 sizeof(size_t) + strlen(reason);
1570 buf = buf_open(hdr.len);
1572 buf_add(buf, &hdr, sizeof(hdr));
1573 buf_add(buf, &mediumlen, sizeof(mediumlen));
1575 buf_add(buf, medium->string, mediumlen);
1576 len = strlen(reason);
1577 buf_add(buf, &len, sizeof(len));
1578 buf_add(buf, reason, len);
1580 buf_close(privfd, buf);
1584 priv_script_init(char *reason, char *medium)
1586 client->scriptEnvsize = 100;
1587 if (client->scriptEnv == NULL)
1589 calloc(client->scriptEnvsize, sizeof(char *));
1590 if (client->scriptEnv == NULL)
1591 error("script_init: no memory for environment");
1593 client->scriptEnv[0] = strdup(CLIENT_PATH);
1594 if (client->scriptEnv[0] == NULL)
1595 error("script_init: no memory for environment");
1597 client->scriptEnv[1] = NULL;
1599 script_set_env("", "interface", ifi->name);
1602 script_set_env("", "medium", medium);
1604 script_set_env("", "reason", reason);
1608 priv_script_write_params(char *prefix, struct client_lease *lease)
1610 u_int8_t dbuf[1500];
1614 script_set_env(prefix, "ip_address", piaddr(lease->address));
1616 if (lease->options[DHO_SUBNET_MASK].len &&
1617 (lease->options[DHO_SUBNET_MASK].len <
1618 sizeof(lease->address.iabuf))) {
1619 struct iaddr netmask, subnet, broadcast;
1621 memcpy(netmask.iabuf, lease->options[DHO_SUBNET_MASK].data,
1622 lease->options[DHO_SUBNET_MASK].len);
1623 netmask.len = lease->options[DHO_SUBNET_MASK].len;
1625 subnet = subnet_number(lease->address, netmask);
1627 script_set_env(prefix, "network_number",
1629 if (!lease->options[DHO_BROADCAST_ADDRESS].len) {
1630 broadcast = broadcast_addr(subnet, netmask);
1632 script_set_env(prefix,
1633 "broadcast_address",
1639 if (lease->filename)
1640 script_set_env(prefix, "filename", lease->filename);
1641 if (lease->server_name)
1642 script_set_env(prefix, "server_name",
1643 lease->server_name);
1644 for (i = 0; i < 256; i++) {
1645 u_int8_t *dp = NULL;
1647 if (config->defaults[i].len) {
1648 if (lease->options[i].len) {
1649 switch (config->default_actions[i]) {
1650 case ACTION_DEFAULT:
1651 dp = lease->options[i].data;
1652 len = lease->options[i].len;
1654 case ACTION_SUPERSEDE:
1656 dp = config->defaults[i].data;
1657 len = config->defaults[i].len;
1659 case ACTION_PREPEND:
1660 len = config->defaults[i].len +
1661 lease->options[i].len;
1662 if (len > sizeof(dbuf)) {
1663 warning("no space to %s %s",
1665 dhcp_options[i].name);
1670 config->defaults[i].data,
1671 config->defaults[i].len);
1673 config->defaults[i].len,
1674 lease->options[i].data,
1675 lease->options[i].len);
1679 len = config->defaults[i].len +
1680 lease->options[i].len;
1681 if (len > sizeof(dbuf)) {
1682 warning("no space to %s %s",
1684 dhcp_options[i].name);
1688 memcpy(dp, lease->options[i].data,
1689 lease->options[i].len);
1690 memcpy(dp + lease->options[i].len,
1691 config->defaults[i].data,
1692 config->defaults[i].len);
1696 dp = config->defaults[i].data;
1697 len = config->defaults[i].len;
1699 } else if (lease->options[i].len) {
1700 len = lease->options[i].len;
1701 dp = lease->options[i].data;
1708 if (dhcp_option_ev_name(name, sizeof(name),
1710 script_set_env(prefix, name,
1711 pretty_print_option(i, dp, len, 0, 0));
1714 snprintf(tbuf, sizeof(tbuf), "%d", (int)lease->expiry);
1715 script_set_env(prefix, "expiry", tbuf);
1719 script_write_params(char *prefix, struct client_lease *lease)
1721 size_t fn_len = 0, sn_len = 0, pr_len = 0;
1722 struct imsg_hdr hdr;
1726 if (lease->filename != NULL)
1727 fn_len = strlen(lease->filename);
1728 if (lease->server_name != NULL)
1729 sn_len = strlen(lease->server_name);
1731 pr_len = strlen(prefix);
1733 hdr.code = IMSG_SCRIPT_WRITE_PARAMS;
1734 hdr.len = sizeof(hdr) + sizeof(struct client_lease) +
1735 sizeof(size_t) + fn_len + sizeof(size_t) + sn_len +
1736 sizeof(size_t) + pr_len;
1738 for (i = 0; i < 256; i++)
1739 hdr.len += sizeof(int) + lease->options[i].len;
1741 scripttime = time(NULL);
1743 buf = buf_open(hdr.len);
1745 buf_add(buf, &hdr, sizeof(hdr));
1746 buf_add(buf, lease, sizeof(struct client_lease));
1747 buf_add(buf, &fn_len, sizeof(fn_len));
1748 buf_add(buf, lease->filename, fn_len);
1749 buf_add(buf, &sn_len, sizeof(sn_len));
1750 buf_add(buf, lease->server_name, sn_len);
1751 buf_add(buf, &pr_len, sizeof(pr_len));
1752 buf_add(buf, prefix, pr_len);
1754 for (i = 0; i < 256; i++) {
1755 buf_add(buf, &lease->options[i].len,
1756 sizeof(lease->options[i].len));
1757 buf_add(buf, lease->options[i].data,
1758 lease->options[i].len);
1761 buf_close(privfd, buf);
1767 struct imsg_hdr hdr;
1771 scripttime = time(NULL);
1773 hdr.code = IMSG_SCRIPT_GO;
1774 hdr.len = sizeof(struct imsg_hdr);
1776 buf = buf_open(hdr.len);
1778 buf_add(buf, &hdr, sizeof(hdr));
1779 buf_close(privfd, buf);
1781 bzero(&hdr, sizeof(hdr));
1782 buf_read(privfd, &hdr, sizeof(hdr));
1783 if (hdr.code != IMSG_SCRIPT_GO_RET)
1784 error("unexpected msg type %u", hdr.code);
1785 if (hdr.len != sizeof(hdr) + sizeof(int))
1786 error("received corrupted message");
1787 buf_read(privfd, &ret, sizeof(ret));
1793 priv_script_go(void)
1795 char *scriptName, *argv[2], **envp;
1796 int pid, wpid, wstatus;
1798 scripttime = time(NULL);
1800 scriptName = config->script_name;
1801 envp = client->scriptEnv;
1803 argv[0] = scriptName;
1812 wpid = wait(&wstatus);
1813 } while (wpid != pid && wpid > 0);
1819 execve(scriptName, argv, envp);
1820 error("execve (%s, ...): %m", scriptName);
1825 return (WEXITSTATUS(wstatus));
1829 script_set_env(const char *prefix, const char *name, const char *value)
1833 namelen = strlen(name);
1835 for (i = 0; client->scriptEnv[i]; i++)
1836 if (strncmp(client->scriptEnv[i], name, namelen) == 0 &&
1837 client->scriptEnv[i][namelen] == '=')
1840 if (client->scriptEnv[i])
1841 /* Reuse the slot. */
1842 free(client->scriptEnv[i]);
1844 /* New variable. Expand if necessary. */
1845 if (i >= client->scriptEnvsize - 1) {
1846 char **newscriptEnv;
1847 int newscriptEnvsize = client->scriptEnvsize + 50;
1849 newscriptEnv = realloc(client->scriptEnv,
1851 if (newscriptEnv == NULL) {
1852 free(client->scriptEnv);
1853 client->scriptEnv = NULL;
1854 client->scriptEnvsize = 0;
1855 error("script_set_env: no memory for variable");
1857 client->scriptEnv = newscriptEnv;
1858 client->scriptEnvsize = newscriptEnvsize;
1860 /* need to set the NULL pointer at end of array beyond
1862 client->scriptEnv[i + 1] = NULL;
1864 /* Allocate space and format the variable in the appropriate slot. */
1865 client->scriptEnv[i] = malloc(strlen(prefix) + strlen(name) + 1 +
1867 if (client->scriptEnv[i] == NULL)
1868 error("script_set_env: no memory for variable assignment");
1870 /* No `` or $() command substitution allowed in environment values! */
1871 for (j = 0; j < strlen(value); j++)
1875 error("illegal character (%c) in value '%s'", value[j],
1879 snprintf(client->scriptEnv[i], strlen(prefix) + strlen(name) +
1880 1 + strlen(value) + 1, "%s%s=%s", prefix, name, value);
1884 script_flush_env(void)
1888 for (i = 0; client->scriptEnv[i]; i++) {
1889 free(client->scriptEnv[i]);
1890 client->scriptEnv[i] = NULL;
1892 client->scriptEnvsize = 0;
1896 dhcp_option_ev_name(char *buf, size_t buflen, const struct option *option)
1900 for (i = 0; option->name[i]; i++) {
1901 if (i + 1 == buflen)
1903 if (option->name[i] == '-')
1906 buf[i] = option->name[i];
1916 static int state = 0;
1918 if (no_daemon || state)
1923 /* Stop logging to stderr... */
1926 if (daemon(1, 0) == -1)
1929 /* we are chrooted, daemon(3) fails to open /dev/null */
1931 dup2(nullfd, STDIN_FILENO);
1932 dup2(nullfd, STDOUT_FILENO);
1933 dup2(nullfd, STDERR_FILENO);
1940 check_option(struct client_lease *l, int option)
1945 /* we use this, since this is what gets passed to dhclient-script */
1947 opbuf = pretty_print_option(option, l->options[option].data,
1948 l->options[option].len, 0, 0);
1950 sbuf = option_as_string(option, l->options[option].data,
1951 l->options[option].len);
1954 case DHO_SUBNET_MASK:
1955 case DHO_TIME_SERVERS:
1956 case DHO_NAME_SERVERS:
1958 case DHO_DOMAIN_NAME_SERVERS:
1959 case DHO_LOG_SERVERS:
1960 case DHO_COOKIE_SERVERS:
1961 case DHO_LPR_SERVERS:
1962 case DHO_IMPRESS_SERVERS:
1963 case DHO_RESOURCE_LOCATION_SERVERS:
1964 case DHO_SWAP_SERVER:
1965 case DHO_BROADCAST_ADDRESS:
1966 case DHO_NIS_SERVERS:
1967 case DHO_NTP_SERVERS:
1968 case DHO_NETBIOS_NAME_SERVERS:
1969 case DHO_NETBIOS_DD_SERVER:
1970 case DHO_FONT_SERVERS:
1971 case DHO_DHCP_SERVER_IDENTIFIER:
1972 if (!ipv4addrs(opbuf)) {
1973 warning("Invalid IP address in option: %s", opbuf);
1978 case DHO_DOMAIN_NAME:
1979 case DHO_NIS_DOMAIN:
1980 if (!res_hnok(sbuf)) {
1981 warning("Bogus Host Name option %d: %s (%s)", option,
1983 l->options[option].len = 0;
1984 free(l->options[option].data);
1988 case DHO_TIME_OFFSET:
1990 case DHO_MERIT_DUMP:
1992 case DHO_EXTENSIONS_PATH:
1993 case DHO_IP_FORWARDING:
1994 case DHO_NON_LOCAL_SOURCE_ROUTING:
1995 case DHO_POLICY_FILTER:
1996 case DHO_MAX_DGRAM_REASSEMBLY:
1997 case DHO_DEFAULT_IP_TTL:
1998 case DHO_PATH_MTU_AGING_TIMEOUT:
1999 case DHO_PATH_MTU_PLATEAU_TABLE:
2000 case DHO_INTERFACE_MTU:
2001 case DHO_ALL_SUBNETS_LOCAL:
2002 case DHO_PERFORM_MASK_DISCOVERY:
2003 case DHO_MASK_SUPPLIER:
2004 case DHO_ROUTER_DISCOVERY:
2005 case DHO_ROUTER_SOLICITATION_ADDRESS:
2006 case DHO_STATIC_ROUTES:
2007 case DHO_TRAILER_ENCAPSULATION:
2008 case DHO_ARP_CACHE_TIMEOUT:
2009 case DHO_IEEE802_3_ENCAPSULATION:
2010 case DHO_DEFAULT_TCP_TTL:
2011 case DHO_TCP_KEEPALIVE_INTERVAL:
2012 case DHO_TCP_KEEPALIVE_GARBAGE:
2013 case DHO_VENDOR_ENCAPSULATED_OPTIONS:
2014 case DHO_NETBIOS_NODE_TYPE:
2015 case DHO_NETBIOS_SCOPE:
2016 case DHO_X_DISPLAY_MANAGER:
2017 case DHO_DHCP_REQUESTED_ADDRESS:
2018 case DHO_DHCP_LEASE_TIME:
2019 case DHO_DHCP_OPTION_OVERLOAD:
2020 case DHO_DHCP_MESSAGE_TYPE:
2021 case DHO_DHCP_PARAMETER_REQUEST_LIST:
2022 case DHO_DHCP_MESSAGE:
2023 case DHO_DHCP_MAX_MESSAGE_SIZE:
2024 case DHO_DHCP_RENEWAL_TIME:
2025 case DHO_DHCP_REBINDING_TIME:
2026 case DHO_DHCP_CLASS_IDENTIFIER:
2027 case DHO_DHCP_CLIENT_IDENTIFIER:
2028 case DHO_DHCP_USER_CLASS_ID:
2032 warning("unknown dhcp option value 0x%x", option);
2033 return (unknown_ok);
2038 res_hnok(const char *name)
2040 const char *dn = name;
2041 int pch = '.', ch = *dn++;
2044 while (ch != '\0') {
2049 } else if (pch == '.' || nch == '.' || nch == '\0') {
2052 } else if (!isalnum(ch) && ch != '-' && ch != '_')
2054 else if (ch == '_' && warn == 0) {
2055 warning("warning: hostname %s contains an "
2056 "underscore which violates RFC 952", name);
2064 /* Does buf consist only of dotted decimal ipv4 addrs?
2065 * return how many if so,
2066 * otherwise, return 0
2069 ipv4addrs(char * buf)
2074 while (inet_aton(buf, &jnk) == 1){
2076 while (*buf == '.' || isdigit(*buf))
2087 option_as_string(unsigned int code, unsigned char *data, int len)
2089 static char optbuf[32768]; /* XXX */
2091 int opleft = sizeof(optbuf);
2092 unsigned char *dp = data;
2095 error("option_as_string: bad code %d", code);
2097 for (; dp < data + len; dp++) {
2098 if (!isascii(*dp) || !isprint(*dp)) {
2099 if (dp + 1 != data + len || *dp != 0) {
2101 snprintf(op, opleft, "\\%03o", *dp);
2106 } else if (*dp == '"' || *dp == '\'' || *dp == '$' ||
2107 *dp == '`' || *dp == '\\') {
2121 warning("dhcp option too large");
2126 fork_privchld(int fd, int fd2)
2128 struct pollfd pfd[1];
2129 int nfds, pfail = 0;
2133 error("cannot fork");
2141 if (chdir("/") == -1)
2142 error("chdir(\"/\")");
2144 setproctitle("%s [priv]", ifi->name);
2146 dup2(nullfd, STDIN_FILENO);
2147 dup2(nullfd, STDOUT_FILENO);
2148 dup2(nullfd, STDERR_FILENO);
2154 pfd[0].events = POLLIN;
2155 if ((nfds = poll(pfd, 1, INFTIM)) == -1)
2157 error("poll error");
2160 * Handle temporary errors, but bail if they persist.
2162 if (nfds == 0 || !(pfd[0].revents & POLLIN)) {
2163 if (pfail > POLL_FAILURES)
2164 error("poll failed > %d times", POLL_FAILURES);
2165 sleep(pfail * POLL_FAILURE_WAIT);