1 /* $OpenBSD: src/sbin/dhclient/dhclient.c,v 1.131 2009/07/19 00:18:02 stevesk 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 /* state_panic() can try unexpired existing leases */
201 if (client->active && addr_eq(a, client->active->address))
203 for (l = client->leases; l != NULL; l = l->next)
204 if (addr_eq(a, l->address))
207 if (l != NULL || (client->alias &&
208 addr_eq(a, client->alias->address)))
209 /* new addr is the one we set */
211 snprintf(buf, sizeof(buf), "%s: %s",
212 "new address not one we set", piaddr(a));
216 ifam = (struct ifa_msghdr *)rtm;
217 if (ifam->ifam_index != ifi->index)
219 if (findproto((char *)(ifam + 1), ifam->ifam_addrs) != AF_INET)
221 /* XXX check addrs like RTM_NEWADDR instead of this? */
222 if (scripttime == 0 || t < scripttime + 10)
224 errmsg = "interface address deleted";
227 ifm = (struct if_msghdr *)rtm;
228 if (ifm->ifm_index != ifi->index)
230 if ((rtm->rtm_flags & RTF_UP) == 0) {
231 errmsg = "interface down";
236 LINK_STATE_IS_UP(ifm->ifm_data.ifi_link_state) ? 1 : 0;
237 if (linkstat != ifi->linkstat) {
239 debug("link state %s -> %s",
240 ifi->linkstat ? "up" : "down",
241 linkstat ? "up" : "down");
243 ifi->linkstat = interface_link_status(ifi->name);
245 client->state = S_INIT;
251 ifan = (struct if_announcemsghdr *)rtm;
252 if (ifan->ifan_what == IFAN_DEPARTURE &&
253 ifan->ifan_index == ifi->index) {
254 errmsg = "interface departure";
264 script_init("FAIL", NULL);
266 script_write_params("alias_", client->alias);
268 error("routehandler: %s", errmsg);
272 main(int argc, char *argv[])
274 int ch, fd, quiet = 0, i = 0, pipe_fd[2];
277 /* Initially, log errors to stderr as well as to syslogd. */
278 openlog(getprogname(), LOG_PID | LOG_NDELAY, DHCPD_LOG_FACILITY);
279 setlogmask(LOG_UPTO(LOG_INFO));
281 while ((ch = getopt(argc, argv, "c:dl:qu")) != -1)
284 path_dhclient_conf = optarg;
290 path_dhclient_db = optarg;
308 ifi = calloc(1, sizeof(*ifi));
311 client = calloc(1, sizeof(*client));
313 error("client calloc");
314 config = calloc(1, sizeof(*config));
316 error("config calloc");
318 if (strlcpy(ifi->name, argv[0], IFNAMSIZ) >= IFNAMSIZ)
319 error("Interface name too long");
320 if (path_dhclient_db == NULL && asprintf(&path_dhclient_db, "%s.%s",
321 _PATH_DHCLIENT_DB, ifi->name) == -1)
330 memset(&sockaddr_broadcast, 0, sizeof(sockaddr_broadcast));
331 sockaddr_broadcast.sin_family = AF_INET;
332 sockaddr_broadcast.sin_port = htons(REMOTE_PORT);
333 sockaddr_broadcast.sin_addr.s_addr = INADDR_BROADCAST;
334 sockaddr_broadcast.sin_len = sizeof(sockaddr_broadcast);
335 inaddr_any.s_addr = INADDR_ANY;
339 if (interface_status(ifi->name) == 0) {
340 interface_link_forceup(ifi->name);
341 /* Give it up to 4 seconds of silent grace to find link */
346 while (!(ifi->linkstat = interface_link_status(ifi->name))) {
348 fprintf(stderr, "%s: no link ...", ifi->name);
350 fprintf(stderr, ".");
352 if (++i > config->link_timeout) {
353 fprintf(stderr, " sleeping\n");
359 fprintf(stderr, " got link\n");
362 if ((nullfd = open(_PATH_DEVNULL, O_RDWR, 0)) == -1)
363 error("cannot open %s: %m", _PATH_DEVNULL);
365 if ((pw = getpwnam("_dhcp")) == NULL)
366 error("no such user: _dhcp");
368 if (pipe(pipe_fd) == -1)
371 fork_privchld(pipe_fd[0], pipe_fd[1]);
376 if ((fd = open(path_dhclient_db, O_RDONLY|O_EXLOCK|O_CREAT, 0)) == -1)
377 error("can't open and lock %s: %m", path_dhclient_db);
378 read_client_leases();
379 if ((leaseFile = fopen(path_dhclient_db, "w")) == NULL)
380 error("can't open %s: %m", path_dhclient_db);
381 rewrite_client_leases();
384 priv_script_init("PREINIT", NULL);
386 priv_script_write_params("alias_", client->alias);
389 if ((routefd = socket(PF_ROUTE, SOCK_RAW, 0)) == -1)
390 error("socket(PF_ROUTE, SOCK_RAW): %m");
392 /* set up the interface */
393 discover_interface();
395 if (chroot(_PATH_VAREMPTY) == -1)
397 if (chdir("/") == -1)
398 error("chdir(\"/\")");
400 if (setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) == -1)
402 if (setgroups(1, &pw->pw_gid) == -1)
404 if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) == -1)
409 setproctitle("%s", ifi->name);
412 client->state = S_INIT;
426 fprintf(stderr, "usage: %s [-dqu] [-c file] [-l file] interface\n",
434 * Each routine is called from the dhclient_state_machine() in one of
436 * -> entering INIT state
437 * -> recvpacket_flag == 0: timeout in this state
438 * -> otherwise: received a packet in this state
440 * Return conditions as handled by dhclient_state_machine():
441 * Returns 1, sendpacket_flag = 1: send packet, reset timer.
442 * Returns 1, sendpacket_flag = 0: just reset the timer (wait for a milestone).
443 * Returns 0: finish the nap which was interrupted for no good reason.
445 * Several per-interface variables are used to keep track of the process:
446 * active_lease: the lease that is being used on the interface
447 * (null pointer if not configured yet).
448 * offered_leases: leases corresponding to DHCPOFFER messages that have
449 * been sent to us by DHCP servers.
450 * acked_leases: leases corresponding to DHCPACK messages that have been
451 * sent to us by DHCP servers.
452 * sendpacket: DHCP packet we're trying to send.
453 * destination: IP address to send sendpacket to
454 * In addition, there are several relevant per-lease variables.
455 * T1_expiry, T2_expiry, lease_expiry: lease milestones
456 * In the active lease, these control the process of renewing the lease;
457 * In leases on the acked_leases list, this simply determines when we
458 * can no longer legitimately use the lease.
463 /* If we don't remember an active lease, go straight to INIT. */
464 if (!client->active || client->active->is_bootp) {
469 /* We are in the rebooting state. */
470 client->state = S_REBOOTING;
472 /* make_request doesn't initialize xid because it normally comes
473 from the DHCPDISCOVER, but we haven't sent a DHCPDISCOVER,
474 so pick an xid now. */
475 client->xid = arc4random();
477 /* Make a DHCPREQUEST packet, and set appropriate per-interface
479 make_request(client->active);
480 client->destination = iaddr_broadcast;
481 client->first_sending = cur_time;
482 client->interval = config->initial_interval;
484 /* Zap the medium list... */
485 client->medium = NULL;
487 /* Send out the first DHCPREQUEST packet. */
492 * Called when a lease has completely expired and we've
493 * been unable to renew it.
498 /* Make a DHCPDISCOVER packet, and set appropriate per-interface
500 make_discover(client->active);
501 client->xid = client->packet.xid;
502 client->destination = iaddr_broadcast;
503 client->state = S_SELECTING;
504 client->first_sending = cur_time;
505 client->interval = config->initial_interval;
507 /* Add an immediate timeout to cause the first DHCPDISCOVER packet
513 * state_selecting is called when one or more DHCPOFFER packets
514 * have been received and a configurable period of time has passed.
517 state_selecting(void)
519 struct client_lease *lp, *next, *picked;
521 /* Cancel state_selecting and send_discover timeouts, since either
522 one could have got us here. */
523 cancel_timeout(state_selecting);
524 cancel_timeout(send_discover);
526 /* We have received one or more DHCPOFFER packets. Currently,
527 the only criterion by which we judge leases is whether or
528 not we get a response when we arp for them. */
530 for (lp = client->offered_leases; lp; lp = next) {
533 /* Check to see if we got an ARPREPLY for the address
534 in this particular lease. */
536 script_init("ARPCHECK", lp->medium);
537 script_write_params("check_", lp);
539 /* If the ARPCHECK code detects another
540 machine using the offered address, it exits
541 nonzero. We need to send a DHCPDECLINE and
552 free_client_lease(lp);
555 client->offered_leases = NULL;
557 /* If we just tossed all the leases we were offered, go back
560 client->state = S_INIT;
565 /* If it was a BOOTREPLY, we can just take the address right now. */
566 if (!picked->options[DHO_DHCP_MESSAGE_TYPE].len) {
567 client->new = picked;
569 /* Make up some lease expiry times
570 XXX these should be configurable. */
571 client->new->expiry = cur_time + 12000;
572 client->new->renewal += cur_time + 8000;
573 client->new->rebind += cur_time + 10000;
575 client->state = S_REQUESTING;
577 /* Bind to the address we received. */
582 /* Go to the REQUESTING state. */
583 client->destination = iaddr_broadcast;
584 client->state = S_REQUESTING;
585 client->first_sending = cur_time;
586 client->interval = config->initial_interval;
588 /* Make a DHCPREQUEST packet from the lease we picked. */
589 make_request(picked);
590 client->xid = client->packet.xid;
592 /* Toss the lease we picked - we'll get it back in a DHCPACK. */
593 free_client_lease(picked);
595 /* Add an immediate timeout to send the first DHCPREQUEST packet. */
600 dhcpack(struct iaddr client_addr, struct option_data *options)
602 struct client_lease *lease;
605 if (client->state != S_REBOOTING &&
606 client->state != S_REQUESTING &&
607 client->state != S_RENEWING &&
608 client->state != S_REBINDING)
612 lease = packet_to_lease(options);
614 note("packet_to_lease failed.");
620 /* Stop resending DHCPREQUEST. */
621 cancel_timeout(send_request);
623 /* Figure out the lease time. */
624 if (client->new->options[DHO_DHCP_LEASE_TIME].data)
625 client->new->expiry =
626 getULong(client->new->options[DHO_DHCP_LEASE_TIME].data);
628 client->new->expiry = DEFAULT_LEASE_TIME;
629 /* A number that looks negative here is really just very large,
630 because the lease expiry offset is unsigned. */
631 if (client->new->expiry < 0)
632 client->new->expiry = TIME_MAX;
633 /* XXX should be fixed by resetting the client state */
634 if (client->new->expiry < 60)
635 client->new->expiry = 60;
637 /* Take the server-provided renewal time if there is one;
638 otherwise figure it out according to the spec. */
639 if (client->new->options[DHO_DHCP_RENEWAL_TIME].len)
640 client->new->renewal =
641 getULong(client->new->options[DHO_DHCP_RENEWAL_TIME].data);
643 client->new->renewal = client->new->expiry / 2;
645 /* Same deal with the rebind time. */
646 if (client->new->options[DHO_DHCP_REBINDING_TIME].len)
647 client->new->rebind =
648 getULong(client->new->options[DHO_DHCP_REBINDING_TIME].data);
650 client->new->rebind = client->new->renewal +
651 client->new->renewal / 2 + client->new->renewal / 4;
653 client->new->expiry += cur_time;
654 /* Lease lengths can never be negative. */
655 if (client->new->expiry < cur_time)
656 client->new->expiry = TIME_MAX;
657 client->new->renewal += cur_time;
658 if (client->new->renewal < cur_time)
659 client->new->renewal = TIME_MAX;
660 client->new->rebind += cur_time;
661 if (client->new->rebind < cur_time)
662 client->new->rebind = TIME_MAX;
670 /* Remember the medium. */
671 client->new->medium = client->medium;
673 /* Write out the new lease. */
674 write_client_lease(client->new, 0);
676 /* Run the client script with the new parameters. */
677 script_init((client->state == S_REQUESTING ? "BOUND" :
678 (client->state == S_RENEWING ? "RENEW" :
679 (client->state == S_REBOOTING ? "REBOOT" : "REBIND"))),
680 client->new->medium);
681 if (client->active && client->state != S_REBOOTING)
682 script_write_params("old_", client->active);
683 script_write_params("new_", client->new);
685 script_write_params("alias_", client->alias);
688 /* Replace the old active lease with the new one. */
690 free_client_lease(client->active);
691 client->active = client->new;
694 /* Set up a timeout to start the renewal process. */
695 add_timeout(client->active->renewal, state_bound);
697 note("bound to %s -- renewal in %ld seconds.",
698 piaddr(client->active->address),
699 client->active->renewal - cur_time);
700 client->state = S_BOUND;
701 reinitialize_interface();
706 * state_bound is called when we've successfully bound to a particular
707 * lease, but the renewal time on that lease has expired. We are
708 * expected to unicast a DHCPREQUEST to the server that gave us our
714 /* T1 has expired. */
715 make_request(client->active);
716 client->xid = client->packet.xid;
718 if (client->active->options[DHO_DHCP_SERVER_IDENTIFIER].len == 4) {
719 memcpy(client->destination.iabuf,
720 client->active->options[DHO_DHCP_SERVER_IDENTIFIER].data,
722 client->destination.len = 4;
724 client->destination = iaddr_broadcast;
726 client->first_sending = cur_time;
727 client->interval = config->initial_interval;
728 client->state = S_RENEWING;
730 /* Send the first packet immediately. */
735 dhcpoffer(struct iaddr client_addr, struct option_data *options)
737 struct client_lease *lease, *lp;
739 int arp_timeout_needed, stop_selecting;
740 char *name = options[DHO_DHCP_MESSAGE_TYPE].len ? "DHCPOFFER" :
744 if (client->state != S_SELECTING)
748 /* If this lease doesn't supply the minimum required parameters,
750 for (i = 0; config->required_options[i]; i++) {
751 if (!options[config->required_options[i]].len) {
752 note("%s isn't satisfactory.", name);
757 /* If we've already seen this lease, don't record it again. */
758 for (lease = client->offered_leases;
759 lease; lease = lease->next) {
760 if (lease->address.len == sizeof(client->packet.yiaddr) &&
761 !memcmp(lease->address.iabuf,
762 &client->packet.yiaddr, lease->address.len)) {
764 debug("%s already seen.", name);
770 lease = packet_to_lease(options);
772 note("packet_to_lease failed.");
776 /* If this lease was acquired through a BOOTREPLY, record that
778 if (!options[DHO_DHCP_MESSAGE_TYPE].len)
781 /* Record the medium under which this lease was offered. */
782 lease->medium = client->medium;
784 /* Send out an ARP Request for the offered IP address. */
785 script_init("ARPSEND", lease->medium);
786 script_write_params("check_", lease);
787 /* If the script can't send an ARP request without waiting,
788 we'll be waiting when we do the ARPCHECK, so don't wait now. */
790 arp_timeout_needed = 0;
792 arp_timeout_needed = 2;
794 /* Figure out when we're supposed to stop selecting. */
795 stop_selecting = client->first_sending + config->select_interval;
797 /* If this is the lease we asked for, put it at the head of the
798 list, and don't mess with the arp request timeout. */
799 if (addr_eq(lease->address, client->requested_address)) {
800 lease->next = client->offered_leases;
801 client->offered_leases = lease;
803 /* If we already have an offer, and arping for this
804 offer would take us past the selection timeout,
805 then don't extend the timeout - just hope for the
807 if (client->offered_leases &&
808 (cur_time + arp_timeout_needed) > stop_selecting)
809 arp_timeout_needed = 0;
811 /* Put the lease at the end of the list. */
813 if (!client->offered_leases)
814 client->offered_leases = lease;
816 for (lp = client->offered_leases; lp->next;
823 /* If we're supposed to stop selecting before we've had time
824 to wait for the ARPREPLY, add some delay to wait for
826 if (stop_selecting - cur_time < arp_timeout_needed)
827 stop_selecting = cur_time + arp_timeout_needed;
829 /* If the selecting interval has expired, go immediately to
830 state_selecting(). Otherwise, time out into
831 state_selecting at the select interval. */
832 if (stop_selecting <= 0)
835 add_timeout(stop_selecting, state_selecting);
836 cancel_timeout(send_discover);
841 * Allocate a client_lease structure and initialize it from the
842 * parameters in the specified packet.
844 struct client_lease *
845 packet_to_lease(struct option_data *options)
847 struct client_lease *lease;
850 lease = malloc(sizeof(struct client_lease));
853 warning("dhcpoffer: no memory to record lease.");
857 memset(lease, 0, sizeof(*lease));
859 /* Copy the lease options. */
860 for (i = 0; i < 256; i++) {
861 if (options[i].len) {
862 lease->options[i] = options[i];
863 options[i].data = NULL;
865 if (!check_option(lease, i)) {
866 warning("Invalid lease option - ignoring offer");
867 free_client_lease(lease);
873 lease->address.len = sizeof(client->packet.yiaddr);
874 memcpy(lease->address.iabuf, &client->packet.yiaddr,
877 /* If the server name was filled out, copy it. */
878 if ((!lease->options[DHO_DHCP_OPTION_OVERLOAD].len ||
879 !(lease->options[DHO_DHCP_OPTION_OVERLOAD].data[0] & 2)) &&
880 client->packet.sname[0]) {
881 lease->server_name = malloc(DHCP_SNAME_LEN + 1);
882 if (!lease->server_name) {
883 warning("dhcpoffer: no memory for server name.");
884 free_client_lease(lease);
887 memcpy(lease->server_name, client->packet.sname,
889 lease->server_name[DHCP_SNAME_LEN] = '\0';
890 if (!res_hnok(lease->server_name)) {
891 warning("Bogus server name %s", lease->server_name);
892 free(lease->server_name);
893 lease->server_name = NULL;
897 /* Ditto for the filename. */
898 if ((!lease->options[DHO_DHCP_OPTION_OVERLOAD].len ||
899 !(lease->options[DHO_DHCP_OPTION_OVERLOAD].data[0] & 1)) &&
900 client->packet.file[0]) {
901 /* Don't count on the NUL terminator. */
902 lease->filename = malloc(DHCP_FILE_LEN + 1);
903 if (!lease->filename) {
904 warning("dhcpoffer: no memory for filename.");
905 free_client_lease(lease);
908 memcpy(lease->filename, client->packet.file, DHCP_FILE_LEN);
909 lease->filename[DHCP_FILE_LEN] = '\0';
915 dhcpnak(struct iaddr client_addr, struct option_data *options)
918 if (client->state != S_REBOOTING &&
919 client->state != S_REQUESTING &&
920 client->state != S_RENEWING &&
921 client->state != S_REBINDING)
925 if (!client->active) {
926 note("DHCPNAK with no active lease.");
930 free_client_lease(client->active);
931 client->active = NULL;
933 /* Stop sending DHCPREQUEST packets... */
934 cancel_timeout(send_request);
936 client->state = S_INIT;
941 * Send out a DHCPDISCOVER packet, and set a timeout to send out another
942 * one after the right interval has expired. If we don't get an offer by
943 * the time we reach the panic interval, call the panic function.
948 int interval, increase = 1;
950 /* Figure out how long it's been since we started transmitting. */
951 interval = cur_time - client->first_sending;
953 /* If we're past the panic timeout, call the script and tell it
954 we haven't found anything for this interface yet. */
955 if (interval > config->timeout) {
960 /* If we're selecting media, try the whole list before doing
961 the exponential backoff, but if we've already received an
962 offer, stop looping, because we obviously have it right. */
963 if (!client->offered_leases && config->media) {
966 if (client->medium) {
967 client->medium = client->medium->next;
970 if (!client->medium) {
972 error("No valid media types for %s!", ifi->name);
973 client->medium = config->media;
977 note("Trying medium \"%s\" %d", client->medium->string,
979 script_init("MEDIUM", client->medium);
985 * If we're supposed to increase the interval, do so. If it's
986 * currently zero (i.e., we haven't sent any packets yet), set
987 * it to initial_interval; otherwise, add to it a random
988 * number between zero and two times itself. On average, this
989 * means that it will double with every transmission.
992 if (!client->interval)
993 client->interval = config->initial_interval;
995 client->interval += (arc4random() >> 2) %
996 (2 * client->interval);
999 /* Don't backoff past cutoff. */
1000 if (client->interval > config->backoff_cutoff)
1001 client->interval = ((config->backoff_cutoff / 2)
1002 + ((arc4random() >> 2) %
1003 config->backoff_cutoff));
1004 } else if (!client->interval)
1005 client->interval = config->initial_interval;
1007 /* If the backoff would take us to the panic timeout, just use that
1009 if (cur_time + client->interval >
1010 client->first_sending + config->timeout)
1011 client->interval = (client->first_sending +
1012 config->timeout) - cur_time + 1;
1014 /* Record the number of seconds since we started sending. */
1015 if (interval < 65536)
1016 client->packet.secs = htons(interval);
1018 client->packet.secs = htons(65535);
1019 client->secs = client->packet.secs;
1021 note("DHCPDISCOVER on %s to %s port %d interval %ld",
1022 ifi->name, inet_ntoa(sockaddr_broadcast.sin_addr),
1023 ntohs(sockaddr_broadcast.sin_port), client->interval);
1025 /* Send out a packet. */
1026 send_packet(inaddr_any, &sockaddr_broadcast, NULL);
1028 add_timeout(cur_time + client->interval, send_discover);
1032 * state_panic gets called if we haven't received any offers in a preset
1033 * amount of time. When this happens, we try to use existing leases
1034 * that haven't yet expired, and failing that, we call the client script
1035 * and hope it can do something.
1040 struct client_lease *loop = client->active;
1041 struct client_lease *lp;
1043 note("No DHCPOFFERS received.");
1045 /* We may not have an active lease, but we may have some
1046 predefined leases that we can try. */
1047 if (!client->active && client->leases)
1050 /* Run through the list of leases and see if one can be used. */
1051 while (client->active) {
1052 if (client->active->expiry > cur_time) {
1053 note("Trying recorded lease %s",
1054 piaddr(client->active->address));
1055 /* Run the client script with the existing
1057 script_init("TIMEOUT",
1058 client->active->medium);
1059 script_write_params("new_", client->active);
1061 script_write_params("alias_",
1064 /* If the old lease is still good and doesn't
1065 yet need renewal, go into BOUND state and
1066 timeout at the renewal time. */
1069 client->active->renewal) {
1070 client->state = S_BOUND;
1071 note("bound: renewal in %ld seconds.",
1072 client->active->renewal -
1074 add_timeout(client->active->renewal,
1077 client->state = S_BOUND;
1078 note("bound: immediate renewal.");
1081 reinitialize_interface();
1087 /* If there are no other leases, give up. */
1088 if (!client->leases) {
1089 client->leases = client->active;
1090 client->active = NULL;
1095 /* Otherwise, put the active lease at the end of the
1096 lease list, and try another lease.. */
1097 for (lp = client->leases; lp->next; lp = lp->next)
1099 lp->next = client->active;
1101 lp->next->next = NULL;
1102 client->active = client->leases;
1103 client->leases = client->leases->next;
1105 /* If we already tried this lease, we've exhausted the
1106 set of leases, so we might as well give up for
1108 if (client->active == loop)
1111 loop = client->active;
1114 /* No leases were available, or what was available didn't work, so
1115 tell the shell script that we failed to allocate an address,
1116 and try again later. */
1117 note("No working leases in persistent database - sleeping.");
1118 script_init("FAIL", NULL);
1120 script_write_params("alias_", client->alias);
1122 client->state = S_INIT;
1123 add_timeout(cur_time + config->retry_interval, state_init);
1130 struct sockaddr_in destination;
1131 struct in_addr from;
1134 /* Figure out how long it's been since we started transmitting. */
1135 interval = cur_time - client->first_sending;
1137 /* If we're in the INIT-REBOOT or REQUESTING state and we're
1138 past the reboot timeout, go to INIT and see if we can
1139 DISCOVER an address... */
1140 /* XXX In the INIT-REBOOT state, if we don't get an ACK, it
1141 means either that we're on a network with no DHCP server,
1142 or that our server is down. In the latter case, assuming
1143 that there is a backup DHCP server, DHCPDISCOVER will get
1144 us a new address, but we could also have successfully
1145 reused our old address. In the former case, we're hosed
1146 anyway. This is not a win-prone situation. */
1147 if ((client->state == S_REBOOTING ||
1148 client->state == S_REQUESTING) &&
1149 interval > config->reboot_timeout) {
1151 client->state = S_INIT;
1152 cancel_timeout(send_request);
1157 /* If we're in the reboot state, make sure the media is set up
1159 if (client->state == S_REBOOTING &&
1161 client->active->medium) {
1162 script_init("MEDIUM", client->active->medium);
1164 /* If the medium we chose won't fly, go to INIT state. */
1168 /* Record the medium. */
1169 client->medium = client->active->medium;
1172 /* If the lease has expired, relinquish the address and go back
1173 to the INIT state. */
1174 if (client->state != S_REQUESTING &&
1175 cur_time > client->active->expiry) {
1176 /* Run the client script with the new parameters. */
1177 script_init("EXPIRE", NULL);
1178 script_write_params("old_", client->active);
1180 script_write_params("alias_", client->alias);
1183 /* Now do a preinit on the interface so that we can
1184 discover a new address. */
1185 script_init("PREINIT", NULL);
1187 script_write_params("alias_", client->alias);
1190 client->state = S_INIT;
1195 /* Do the exponential backoff... */
1196 if (!client->interval)
1197 client->interval = config->initial_interval;
1199 client->interval += ((arc4random() >> 2) %
1200 (2 * client->interval));
1202 /* Don't backoff past cutoff. */
1203 if (client->interval > config->backoff_cutoff)
1204 client->interval = ((config->backoff_cutoff / 2) +
1205 ((arc4random() >> 2) % client->interval));
1207 /* If the backoff would take us to the expiry time, just set the
1208 timeout to the expiry time. */
1209 if (client->state != S_REQUESTING && cur_time + client->interval >
1210 client->active->expiry)
1211 client->interval = client->active->expiry - cur_time + 1;
1213 /* If the lease T2 time has elapsed, or if we're not yet bound,
1214 broadcast the DHCPREQUEST rather than unicasting. */
1215 memset(&destination, 0, sizeof(destination));
1216 if (client->state == S_REQUESTING ||
1217 client->state == S_REBOOTING ||
1218 cur_time > client->active->rebind)
1219 destination.sin_addr.s_addr = INADDR_BROADCAST;
1221 memcpy(&destination.sin_addr.s_addr, client->destination.iabuf,
1222 sizeof(destination.sin_addr.s_addr));
1223 destination.sin_port = htons(REMOTE_PORT);
1224 destination.sin_family = AF_INET;
1225 destination.sin_len = sizeof(destination);
1227 if (client->state != S_REQUESTING)
1228 memcpy(&from, client->active->address.iabuf, sizeof(from));
1230 from.s_addr = INADDR_ANY;
1232 /* Record the number of seconds since we started sending. */
1233 if (client->state == S_REQUESTING)
1234 client->packet.secs = client->secs;
1236 if (interval < 65536)
1237 client->packet.secs = htons(interval);
1239 client->packet.secs = htons(65535);
1242 note("DHCPREQUEST on %s to %s port %d", ifi->name,
1243 inet_ntoa(destination.sin_addr), ntohs(destination.sin_port));
1245 /* Send out a packet. */
1246 send_packet(from, &destination, NULL);
1248 add_timeout(cur_time + client->interval, send_request);
1254 note("DHCPDECLINE on %s to %s port %d", ifi->name,
1255 inet_ntoa(sockaddr_broadcast.sin_addr),
1256 ntohs(sockaddr_broadcast.sin_port));
1258 /* Send out a packet. */
1259 send_packet(inaddr_any, &sockaddr_broadcast, NULL);
1263 make_discover(struct client_lease *lease)
1265 unsigned char discover = DHCPDISCOVER;
1266 struct option_data options[256];
1269 memset(options, 0, sizeof(options));
1270 memset(&client->packet, 0, sizeof(client->packet));
1272 /* Set DHCP_MESSAGE_TYPE to DHCPDISCOVER */
1273 i = DHO_DHCP_MESSAGE_TYPE;
1274 options[i].data = &discover;
1275 options[i].len = sizeof(discover);
1277 /* Request the options we want */
1278 i = DHO_DHCP_PARAMETER_REQUEST_LIST;
1279 options[i].data = config->requested_options;
1280 options[i].len = config->requested_option_count;
1282 /* If we had an address, try to get it again. */
1284 client->requested_address = lease->address;
1285 i = DHO_DHCP_REQUESTED_ADDRESS;
1286 options[i].data = lease->address.iabuf;
1287 options[i].len = lease->address.len;
1289 client->requested_address.len = 0;
1291 /* Send any options requested in the config file. */
1292 for (i = 0; i < 256; i++)
1293 if (!options[i].data &&
1294 config->send_options[i].data) {
1295 options[i].data = config->send_options[i].data;
1296 options[i].len = config->send_options[i].len;
1299 /* Set up the option buffer to fit in a minimal UDP packet. */
1300 i = cons_options(client->packet.options, 576 - DHCP_FIXED_LEN,
1302 if (i == -1 || client->packet.options[i] != DHO_END)
1303 error("options do not fit in DHCPDISCOVER packet.");
1304 client->packet_length = DHCP_FIXED_NON_UDP+i+1;
1305 if (client->packet_length < BOOTP_MIN_LEN)
1306 client->packet_length = BOOTP_MIN_LEN;
1308 client->packet.op = BOOTREQUEST;
1309 client->packet.htype = ifi->hw_address.htype;
1310 client->packet.hlen = ifi->hw_address.hlen;
1311 client->packet.hops = 0;
1312 client->packet.xid = arc4random();
1313 client->packet.secs = 0; /* filled in by send_discover. */
1314 client->packet.flags = 0;
1316 memset(&client->packet.ciaddr, 0, sizeof(client->packet.ciaddr));
1317 memset(&client->packet.yiaddr, 0, sizeof(client->packet.yiaddr));
1318 memset(&client->packet.siaddr, 0, sizeof(client->packet.siaddr));
1319 memset(&client->packet.giaddr, 0, sizeof(client->packet.giaddr));
1320 memcpy(client->packet.chaddr, ifi->hw_address.haddr,
1321 ifi->hw_address.hlen);
1325 make_request(struct client_lease * lease)
1327 unsigned char request = DHCPREQUEST;
1328 struct option_data options[256];
1331 memset(options, 0, sizeof(options));
1332 memset(&client->packet, 0, sizeof(client->packet));
1334 /* Set DHCP_MESSAGE_TYPE to DHCPREQUEST */
1335 i = DHO_DHCP_MESSAGE_TYPE;
1336 options[i].data = &request;
1337 options[i].len = sizeof(request);
1339 /* Request the options we want */
1340 i = DHO_DHCP_PARAMETER_REQUEST_LIST;
1341 options[i].data = config->requested_options;
1342 options[i].len = config->requested_option_count;
1344 /* If we are requesting an address that hasn't yet been assigned
1345 to us, use the DHCP Requested Address option. */
1346 if (client->state == S_REQUESTING) {
1347 /* Send back the server identifier... */
1348 i = DHO_DHCP_SERVER_IDENTIFIER;
1349 options[i].data = lease->options[i].data;
1350 options[i].len = lease->options[i].len;
1352 if (client->state == S_REQUESTING ||
1353 client->state == S_REBOOTING) {
1354 client->requested_address = lease->address;
1355 i = DHO_DHCP_REQUESTED_ADDRESS;
1356 options[i].data = lease->address.iabuf;
1357 options[i].len = lease->address.len;
1359 client->requested_address.len = 0;
1361 /* Send any options requested in the config file. */
1362 for (i = 0; i < 256; i++)
1363 if (!options[i].data && config->send_options[i].data) {
1364 options[i].data = config->send_options[i].data;
1365 options[i].len = config->send_options[i].len;
1368 /* Set up the option buffer to fit in a minimal UDP packet. */
1369 i = cons_options(client->packet.options, 576 - DHCP_FIXED_LEN,
1371 if (i == -1 || client->packet.options[i] != DHO_END)
1372 error("options do not fit in DHCPREQUEST packet.");
1373 client->packet_length = DHCP_FIXED_NON_UDP+i+1;
1374 if (client->packet_length < BOOTP_MIN_LEN)
1375 client->packet_length = BOOTP_MIN_LEN;
1377 client->packet.op = BOOTREQUEST;
1378 client->packet.htype = ifi->hw_address.htype;
1379 client->packet.hlen = ifi->hw_address.hlen;
1380 client->packet.hops = 0;
1381 client->packet.xid = client->xid;
1382 client->packet.secs = 0; /* Filled in by send_request. */
1383 client->packet.flags = 0;
1385 /* If we own the address we're requesting, put it in ciaddr;
1386 otherwise set ciaddr to zero. */
1387 if (client->state == S_BOUND ||
1388 client->state == S_RENEWING ||
1389 client->state == S_REBINDING) {
1390 memcpy(&client->packet.ciaddr,
1391 lease->address.iabuf, lease->address.len);
1393 memset(&client->packet.ciaddr, 0,
1394 sizeof(client->packet.ciaddr));
1397 memset(&client->packet.yiaddr, 0, sizeof(client->packet.yiaddr));
1398 memset(&client->packet.siaddr, 0, sizeof(client->packet.siaddr));
1399 memset(&client->packet.giaddr, 0, sizeof(client->packet.giaddr));
1400 memcpy(client->packet.chaddr, ifi->hw_address.haddr,
1401 ifi->hw_address.hlen);
1405 make_decline(struct client_lease *lease)
1407 struct option_data options[256];
1408 unsigned char decline = DHCPDECLINE;
1411 memset(options, 0, sizeof(options));
1412 memset(&client->packet, 0, sizeof(client->packet));
1414 /* Set DHCP_MESSAGE_TYPE to DHCPDECLINE */
1415 i = DHO_DHCP_MESSAGE_TYPE;
1416 options[i].data = &decline;
1417 options[i].len = sizeof(decline);
1419 /* Send back the server identifier... */
1420 i = DHO_DHCP_SERVER_IDENTIFIER;
1421 options[i].data = lease->options[i].data;
1422 options[i].len = lease->options[i].len;
1424 /* Send back the address we're declining. */
1425 i = DHO_DHCP_REQUESTED_ADDRESS;
1426 options[i].data = lease->address.iabuf;
1427 options[i].len = lease->address.len;
1429 /* Send the uid if the user supplied one. */
1430 i = DHO_DHCP_CLIENT_IDENTIFIER;
1431 if (config->send_options[i].len) {
1432 options[i].data = config->send_options[i].data;
1433 options[i].len = config->send_options[i].len;
1436 /* Set up the option buffer to fit in a minimal UDP packet. */
1437 i = cons_options(client->packet.options, 576 - DHCP_FIXED_LEN,
1439 if (i == -1 || client->packet.options[i] != DHO_END)
1440 error("options do not fit in DHCPDECLINE packet.");
1441 client->packet_length = DHCP_FIXED_NON_UDP+i+1;
1442 if (client->packet_length < BOOTP_MIN_LEN)
1443 client->packet_length = BOOTP_MIN_LEN;
1445 client->packet.op = BOOTREQUEST;
1446 client->packet.htype = ifi->hw_address.htype;
1447 client->packet.hlen = ifi->hw_address.hlen;
1448 client->packet.hops = 0;
1449 client->packet.xid = client->xid;
1450 client->packet.secs = 0; /* Filled in by send_request. */
1451 client->packet.flags = 0;
1453 /* ciaddr must always be zero. */
1454 memset(&client->packet.ciaddr, 0, sizeof(client->packet.ciaddr));
1455 memset(&client->packet.yiaddr, 0, sizeof(client->packet.yiaddr));
1456 memset(&client->packet.siaddr, 0, sizeof(client->packet.siaddr));
1457 memset(&client->packet.giaddr, 0, sizeof(client->packet.giaddr));
1458 memcpy(client->packet.chaddr, ifi->hw_address.haddr,
1459 ifi->hw_address.hlen);
1463 free_client_lease(struct client_lease *lease)
1467 if (lease->server_name)
1468 free(lease->server_name);
1469 if (lease->filename)
1470 free(lease->filename);
1471 for (i = 0; i < 256; i++) {
1472 if (lease->options[i].len)
1473 free(lease->options[i].data);
1479 rewrite_client_leases(void)
1481 struct client_lease *lp;
1483 if (!leaseFile) /* XXX */
1484 error("lease file not open");
1489 for (lp = client->leases; lp; lp = lp->next)
1490 write_client_lease(lp, 1);
1492 write_client_lease(client->active, 1);
1495 ftruncate(fileno(leaseFile), ftello(leaseFile));
1496 fsync(fileno(leaseFile));
1500 write_client_lease(struct client_lease *lease, int rewrite)
1502 static int leases_written;
1507 if (leases_written++ > 20) {
1508 rewrite_client_leases();
1513 /* If the lease came from the config file, we don't need to stash
1514 a copy in the lease database. */
1515 if (lease->is_static)
1518 if (!leaseFile) /* XXX */
1519 error("lease file not open");
1521 fprintf(leaseFile, "lease {\n");
1522 if (lease->is_bootp)
1523 fprintf(leaseFile, " bootp;\n");
1524 fprintf(leaseFile, " interface \"%s\";\n", ifi->name);
1525 fprintf(leaseFile, " fixed-address %s;\n", piaddr(lease->address));
1526 if (lease->filename)
1527 fprintf(leaseFile, " filename \"%s\";\n", lease->filename);
1528 if (lease->server_name)
1529 fprintf(leaseFile, " server-name \"%s\";\n",
1530 lease->server_name);
1532 fprintf(leaseFile, " medium \"%s\";\n", lease->medium->string);
1533 for (i = 0; i < 256; i++)
1534 if (lease->options[i].len)
1535 fprintf(leaseFile, " option %s %s;\n",
1536 dhcp_options[i].name,
1537 pretty_print_option(i, lease->options[i].data,
1538 lease->options[i].len, 1, 1));
1540 t = gmtime(&lease->renewal);
1541 fprintf(leaseFile, " renew %d %d/%d/%d %02d:%02d:%02d;\n",
1542 t->tm_wday, t->tm_year + 1900, t->tm_mon + 1, t->tm_mday,
1543 t->tm_hour, t->tm_min, t->tm_sec);
1544 t = gmtime(&lease->rebind);
1545 fprintf(leaseFile, " rebind %d %d/%d/%d %02d:%02d:%02d;\n",
1546 t->tm_wday, t->tm_year + 1900, t->tm_mon + 1, t->tm_mday,
1547 t->tm_hour, t->tm_min, t->tm_sec);
1548 t = gmtime(&lease->expiry);
1549 fprintf(leaseFile, " expire %d %d/%d/%d %02d:%02d:%02d;\n",
1550 t->tm_wday, t->tm_year + 1900, t->tm_mon + 1, t->tm_mday,
1551 t->tm_hour, t->tm_min, t->tm_sec);
1552 fprintf(leaseFile, "}\n");
1557 script_init(char *reason, struct string_list *medium)
1559 size_t len, mediumlen = 0;
1560 struct imsg_hdr hdr;
1563 if (medium != NULL && medium->string != NULL)
1564 mediumlen = strlen(medium->string);
1566 hdr.code = IMSG_SCRIPT_INIT;
1567 hdr.len = sizeof(struct imsg_hdr) +
1568 sizeof(size_t) + mediumlen +
1569 sizeof(size_t) + strlen(reason);
1571 buf = buf_open(hdr.len);
1573 buf_add(buf, &hdr, sizeof(hdr));
1574 buf_add(buf, &mediumlen, sizeof(mediumlen));
1576 buf_add(buf, medium->string, mediumlen);
1577 len = strlen(reason);
1578 buf_add(buf, &len, sizeof(len));
1579 buf_add(buf, reason, len);
1581 buf_close(privfd, buf);
1585 priv_script_init(char *reason, char *medium)
1587 client->scriptEnvsize = 100;
1588 if (client->scriptEnv == NULL)
1590 calloc(client->scriptEnvsize, sizeof(char *));
1591 if (client->scriptEnv == NULL)
1592 error("script_init: no memory for environment");
1594 client->scriptEnv[0] = strdup(CLIENT_PATH);
1595 if (client->scriptEnv[0] == NULL)
1596 error("script_init: no memory for environment");
1598 client->scriptEnv[1] = NULL;
1600 script_set_env("", "interface", ifi->name);
1603 script_set_env("", "medium", medium);
1605 script_set_env("", "reason", reason);
1609 priv_script_write_params(char *prefix, struct client_lease *lease)
1611 u_int8_t dbuf[1500];
1615 script_set_env(prefix, "ip_address", piaddr(lease->address));
1617 if (lease->options[DHO_SUBNET_MASK].len &&
1618 (lease->options[DHO_SUBNET_MASK].len <
1619 sizeof(lease->address.iabuf))) {
1620 struct iaddr netmask, subnet, broadcast;
1622 memcpy(netmask.iabuf, lease->options[DHO_SUBNET_MASK].data,
1623 lease->options[DHO_SUBNET_MASK].len);
1624 netmask.len = lease->options[DHO_SUBNET_MASK].len;
1626 subnet = subnet_number(lease->address, netmask);
1628 script_set_env(prefix, "network_number",
1630 if (!lease->options[DHO_BROADCAST_ADDRESS].len) {
1631 broadcast = broadcast_addr(subnet, netmask);
1633 script_set_env(prefix,
1634 "broadcast_address",
1640 if (lease->filename)
1641 script_set_env(prefix, "filename", lease->filename);
1642 if (lease->server_name)
1643 script_set_env(prefix, "server_name",
1644 lease->server_name);
1645 for (i = 0; i < 256; i++) {
1646 u_int8_t *dp = NULL;
1648 if (config->defaults[i].len) {
1649 if (lease->options[i].len) {
1650 switch (config->default_actions[i]) {
1651 case ACTION_DEFAULT:
1652 dp = lease->options[i].data;
1653 len = lease->options[i].len;
1655 case ACTION_SUPERSEDE:
1657 dp = config->defaults[i].data;
1658 len = config->defaults[i].len;
1660 case ACTION_PREPEND:
1661 len = config->defaults[i].len +
1662 lease->options[i].len;
1663 if (len > sizeof(dbuf)) {
1664 warning("no space to %s %s",
1666 dhcp_options[i].name);
1671 config->defaults[i].data,
1672 config->defaults[i].len);
1674 config->defaults[i].len,
1675 lease->options[i].data,
1676 lease->options[i].len);
1680 len = config->defaults[i].len +
1681 lease->options[i].len;
1682 if (len > sizeof(dbuf)) {
1683 warning("no space to %s %s",
1685 dhcp_options[i].name);
1689 memcpy(dp, lease->options[i].data,
1690 lease->options[i].len);
1691 memcpy(dp + lease->options[i].len,
1692 config->defaults[i].data,
1693 config->defaults[i].len);
1697 dp = config->defaults[i].data;
1698 len = config->defaults[i].len;
1700 } else if (lease->options[i].len) {
1701 len = lease->options[i].len;
1702 dp = lease->options[i].data;
1709 if (dhcp_option_ev_name(name, sizeof(name),
1711 script_set_env(prefix, name,
1712 pretty_print_option(i, dp, len, 0, 0));
1715 snprintf(tbuf, sizeof(tbuf), "%d", (int)lease->expiry);
1716 script_set_env(prefix, "expiry", tbuf);
1720 script_write_params(char *prefix, struct client_lease *lease)
1722 size_t fn_len = 0, sn_len = 0, pr_len = 0;
1723 struct imsg_hdr hdr;
1727 if (lease->filename != NULL)
1728 fn_len = strlen(lease->filename);
1729 if (lease->server_name != NULL)
1730 sn_len = strlen(lease->server_name);
1732 pr_len = strlen(prefix);
1734 hdr.code = IMSG_SCRIPT_WRITE_PARAMS;
1735 hdr.len = sizeof(hdr) + sizeof(struct client_lease) +
1736 sizeof(size_t) + fn_len + sizeof(size_t) + sn_len +
1737 sizeof(size_t) + pr_len;
1739 for (i = 0; i < 256; i++)
1740 hdr.len += sizeof(int) + lease->options[i].len;
1742 scripttime = time(NULL);
1744 buf = buf_open(hdr.len);
1746 buf_add(buf, &hdr, sizeof(hdr));
1747 buf_add(buf, lease, sizeof(struct client_lease));
1748 buf_add(buf, &fn_len, sizeof(fn_len));
1749 buf_add(buf, lease->filename, fn_len);
1750 buf_add(buf, &sn_len, sizeof(sn_len));
1751 buf_add(buf, lease->server_name, sn_len);
1752 buf_add(buf, &pr_len, sizeof(pr_len));
1753 buf_add(buf, prefix, pr_len);
1755 for (i = 0; i < 256; i++) {
1756 buf_add(buf, &lease->options[i].len,
1757 sizeof(lease->options[i].len));
1758 buf_add(buf, lease->options[i].data,
1759 lease->options[i].len);
1762 buf_close(privfd, buf);
1768 struct imsg_hdr hdr;
1772 scripttime = time(NULL);
1774 hdr.code = IMSG_SCRIPT_GO;
1775 hdr.len = sizeof(struct imsg_hdr);
1777 buf = buf_open(hdr.len);
1779 buf_add(buf, &hdr, sizeof(hdr));
1780 buf_close(privfd, buf);
1782 bzero(&hdr, sizeof(hdr));
1783 buf_read(privfd, &hdr, sizeof(hdr));
1784 if (hdr.code != IMSG_SCRIPT_GO_RET)
1785 error("unexpected msg type %u", hdr.code);
1786 if (hdr.len != sizeof(hdr) + sizeof(int))
1787 error("received corrupted message");
1788 buf_read(privfd, &ret, sizeof(ret));
1794 priv_script_go(void)
1796 char *scriptName, *argv[2], **envp;
1797 int pid, wpid, wstatus;
1799 scripttime = time(NULL);
1801 scriptName = config->script_name;
1802 envp = client->scriptEnv;
1804 argv[0] = scriptName;
1813 wpid = wait(&wstatus);
1814 } while (wpid != pid && wpid > 0);
1820 execve(scriptName, argv, envp);
1821 error("execve (%s, ...): %m", scriptName);
1826 return (WEXITSTATUS(wstatus));
1830 script_set_env(const char *prefix, const char *name, const char *value)
1834 namelen = strlen(name);
1836 for (i = 0; client->scriptEnv[i]; i++)
1837 if (strncmp(client->scriptEnv[i], name, namelen) == 0 &&
1838 client->scriptEnv[i][namelen] == '=')
1841 if (client->scriptEnv[i])
1842 /* Reuse the slot. */
1843 free(client->scriptEnv[i]);
1845 /* New variable. Expand if necessary. */
1846 if (i >= client->scriptEnvsize - 1) {
1847 char **newscriptEnv;
1848 int newscriptEnvsize = client->scriptEnvsize + 50;
1850 newscriptEnv = realloc(client->scriptEnv,
1852 if (newscriptEnv == NULL) {
1853 free(client->scriptEnv);
1854 client->scriptEnv = NULL;
1855 client->scriptEnvsize = 0;
1856 error("script_set_env: no memory for variable");
1858 client->scriptEnv = newscriptEnv;
1859 client->scriptEnvsize = newscriptEnvsize;
1861 /* need to set the NULL pointer at end of array beyond
1863 client->scriptEnv[i + 1] = NULL;
1865 /* Allocate space and format the variable in the appropriate slot. */
1866 client->scriptEnv[i] = malloc(strlen(prefix) + strlen(name) + 1 +
1868 if (client->scriptEnv[i] == NULL)
1869 error("script_set_env: no memory for variable assignment");
1871 /* No `` or $() command substitution allowed in environment values! */
1872 for (j = 0; j < strlen(value); j++)
1876 error("illegal character (%c) in value '%s'", value[j],
1880 snprintf(client->scriptEnv[i], strlen(prefix) + strlen(name) +
1881 1 + strlen(value) + 1, "%s%s=%s", prefix, name, value);
1885 script_flush_env(void)
1889 for (i = 0; client->scriptEnv[i]; i++) {
1890 free(client->scriptEnv[i]);
1891 client->scriptEnv[i] = NULL;
1893 client->scriptEnvsize = 0;
1897 dhcp_option_ev_name(char *buf, size_t buflen, const struct option *option)
1901 for (i = 0; option->name[i]; i++) {
1902 if (i + 1 == buflen)
1904 if (option->name[i] == '-')
1907 buf[i] = option->name[i];
1917 static int state = 0;
1919 if (no_daemon || state)
1924 /* Stop logging to stderr... */
1927 if (daemon(1, 0) == -1)
1930 /* we are chrooted, daemon(3) fails to open /dev/null */
1932 dup2(nullfd, STDIN_FILENO);
1933 dup2(nullfd, STDOUT_FILENO);
1934 dup2(nullfd, STDERR_FILENO);
1941 check_option(struct client_lease *l, int option)
1946 /* we use this, since this is what gets passed to dhclient-script */
1948 opbuf = pretty_print_option(option, l->options[option].data,
1949 l->options[option].len, 0, 0);
1951 sbuf = option_as_string(option, l->options[option].data,
1952 l->options[option].len);
1955 case DHO_SUBNET_MASK:
1956 case DHO_TIME_SERVERS:
1957 case DHO_NAME_SERVERS:
1959 case DHO_DOMAIN_NAME_SERVERS:
1960 case DHO_LOG_SERVERS:
1961 case DHO_COOKIE_SERVERS:
1962 case DHO_LPR_SERVERS:
1963 case DHO_IMPRESS_SERVERS:
1964 case DHO_RESOURCE_LOCATION_SERVERS:
1965 case DHO_SWAP_SERVER:
1966 case DHO_BROADCAST_ADDRESS:
1967 case DHO_NIS_SERVERS:
1968 case DHO_NTP_SERVERS:
1969 case DHO_NETBIOS_NAME_SERVERS:
1970 case DHO_NETBIOS_DD_SERVER:
1971 case DHO_FONT_SERVERS:
1972 case DHO_DHCP_SERVER_IDENTIFIER:
1973 if (!ipv4addrs(opbuf)) {
1974 warning("Invalid IP address in option: %s", opbuf);
1979 case DHO_DOMAIN_NAME:
1980 case DHO_NIS_DOMAIN:
1981 if (!res_hnok(sbuf)) {
1982 warning("Bogus Host Name option %d: %s (%s)", option,
1984 l->options[option].len = 0;
1985 free(l->options[option].data);
1989 case DHO_TIME_OFFSET:
1991 case DHO_MERIT_DUMP:
1993 case DHO_EXTENSIONS_PATH:
1994 case DHO_IP_FORWARDING:
1995 case DHO_NON_LOCAL_SOURCE_ROUTING:
1996 case DHO_POLICY_FILTER:
1997 case DHO_MAX_DGRAM_REASSEMBLY:
1998 case DHO_DEFAULT_IP_TTL:
1999 case DHO_PATH_MTU_AGING_TIMEOUT:
2000 case DHO_PATH_MTU_PLATEAU_TABLE:
2001 case DHO_INTERFACE_MTU:
2002 case DHO_ALL_SUBNETS_LOCAL:
2003 case DHO_PERFORM_MASK_DISCOVERY:
2004 case DHO_MASK_SUPPLIER:
2005 case DHO_ROUTER_DISCOVERY:
2006 case DHO_ROUTER_SOLICITATION_ADDRESS:
2007 case DHO_STATIC_ROUTES:
2008 case DHO_TRAILER_ENCAPSULATION:
2009 case DHO_ARP_CACHE_TIMEOUT:
2010 case DHO_IEEE802_3_ENCAPSULATION:
2011 case DHO_DEFAULT_TCP_TTL:
2012 case DHO_TCP_KEEPALIVE_INTERVAL:
2013 case DHO_TCP_KEEPALIVE_GARBAGE:
2014 case DHO_VENDOR_ENCAPSULATED_OPTIONS:
2015 case DHO_NETBIOS_NODE_TYPE:
2016 case DHO_NETBIOS_SCOPE:
2017 case DHO_X_DISPLAY_MANAGER:
2018 case DHO_DHCP_REQUESTED_ADDRESS:
2019 case DHO_DHCP_LEASE_TIME:
2020 case DHO_DHCP_OPTION_OVERLOAD:
2021 case DHO_DHCP_MESSAGE_TYPE:
2022 case DHO_DHCP_PARAMETER_REQUEST_LIST:
2023 case DHO_DHCP_MESSAGE:
2024 case DHO_DHCP_MAX_MESSAGE_SIZE:
2025 case DHO_DHCP_RENEWAL_TIME:
2026 case DHO_DHCP_REBINDING_TIME:
2027 case DHO_DHCP_CLASS_IDENTIFIER:
2028 case DHO_DHCP_CLIENT_IDENTIFIER:
2029 case DHO_DHCP_USER_CLASS_ID:
2033 warning("unknown dhcp option value 0x%x", option);
2034 return (unknown_ok);
2039 res_hnok(const char *name)
2041 const char *dn = name;
2042 int pch = '.', ch = *dn++;
2045 while (ch != '\0') {
2050 } else if (pch == '.' || nch == '.' || nch == '\0') {
2053 } else if (!isalnum(ch) && ch != '-' && ch != '_')
2055 else if (ch == '_' && warn == 0) {
2056 warning("warning: hostname %s contains an "
2057 "underscore which violates RFC 952", name);
2065 /* Does buf consist only of dotted decimal ipv4 addrs?
2066 * return how many if so,
2067 * otherwise, return 0
2070 ipv4addrs(char * buf)
2075 while (inet_aton(buf, &jnk) == 1){
2077 while (*buf == '.' || isdigit(*buf))
2088 option_as_string(unsigned int code, unsigned char *data, int len)
2090 static char optbuf[32768]; /* XXX */
2092 int opleft = sizeof(optbuf);
2093 unsigned char *dp = data;
2096 error("option_as_string: bad code %d", code);
2098 for (; dp < data + len; dp++) {
2099 if (!isascii(*dp) || !isprint(*dp)) {
2100 if (dp + 1 != data + len || *dp != 0) {
2102 snprintf(op, opleft, "\\%03o", *dp);
2107 } else if (*dp == '"' || *dp == '\'' || *dp == '$' ||
2108 *dp == '`' || *dp == '\\') {
2122 warning("dhcp option too large");
2127 fork_privchld(int fd, int fd2)
2129 struct pollfd pfd[1];
2130 int nfds, pfail = 0;
2134 error("cannot fork");
2142 if (chdir("/") == -1)
2143 error("chdir(\"/\")");
2145 setproctitle("%s [priv]", ifi->name);
2147 dup2(nullfd, STDIN_FILENO);
2148 dup2(nullfd, STDOUT_FILENO);
2149 dup2(nullfd, STDERR_FILENO);
2155 pfd[0].events = POLLIN;
2156 if ((nfds = poll(pfd, 1, INFTIM)) == -1)
2158 error("poll error");
2161 * Handle temporary errors, but bail if they persist.
2163 if (nfds == 0 || !(pfd[0].revents & POLLIN)) {
2164 if (pfail > POLL_FAILURES)
2165 error("poll failed > %d times", POLL_FAILURES);
2166 sleep(pfail * POLL_FAILURE_WAIT);