1 /* $OpenBSD: src/sbin/dhclient/dhclient.c,v 1.130 2009/06/12 20:07:35 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 (lease->address.len == client->requested_address.len &&
800 !memcmp(lease->address.iabuf,
801 client->requested_address.iabuf,
802 client->requested_address.len)) {
803 lease->next = client->offered_leases;
804 client->offered_leases = lease;
806 /* If we already have an offer, and arping for this
807 offer would take us past the selection timeout,
808 then don't extend the timeout - just hope for the
810 if (client->offered_leases &&
811 (cur_time + arp_timeout_needed) > stop_selecting)
812 arp_timeout_needed = 0;
814 /* Put the lease at the end of the list. */
816 if (!client->offered_leases)
817 client->offered_leases = lease;
819 for (lp = client->offered_leases; lp->next;
826 /* If we're supposed to stop selecting before we've had time
827 to wait for the ARPREPLY, add some delay to wait for
829 if (stop_selecting - cur_time < arp_timeout_needed)
830 stop_selecting = cur_time + arp_timeout_needed;
832 /* If the selecting interval has expired, go immediately to
833 state_selecting(). Otherwise, time out into
834 state_selecting at the select interval. */
835 if (stop_selecting <= 0)
838 add_timeout(stop_selecting, state_selecting);
839 cancel_timeout(send_discover);
844 * Allocate a client_lease structure and initialize it from the
845 * parameters in the specified packet.
847 struct client_lease *
848 packet_to_lease(struct option_data *options)
850 struct client_lease *lease;
853 lease = malloc(sizeof(struct client_lease));
856 warning("dhcpoffer: no memory to record lease.");
860 memset(lease, 0, sizeof(*lease));
862 /* Copy the lease options. */
863 for (i = 0; i < 256; i++) {
864 if (options[i].len) {
865 lease->options[i] = options[i];
866 options[i].data = NULL;
868 if (!check_option(lease, i)) {
869 warning("Invalid lease option - ignoring offer");
870 free_client_lease(lease);
876 lease->address.len = sizeof(client->packet.yiaddr);
877 memcpy(lease->address.iabuf, &client->packet.yiaddr,
880 /* If the server name was filled out, copy it. */
881 if ((!lease->options[DHO_DHCP_OPTION_OVERLOAD].len ||
882 !(lease->options[DHO_DHCP_OPTION_OVERLOAD].data[0] & 2)) &&
883 client->packet.sname[0]) {
884 lease->server_name = malloc(DHCP_SNAME_LEN + 1);
885 if (!lease->server_name) {
886 warning("dhcpoffer: no memory for server name.");
887 free_client_lease(lease);
890 memcpy(lease->server_name, client->packet.sname,
892 lease->server_name[DHCP_SNAME_LEN] = '\0';
893 if (!res_hnok(lease->server_name)) {
894 warning("Bogus server name %s", lease->server_name);
895 free(lease->server_name);
896 lease->server_name = NULL;
900 /* Ditto for the filename. */
901 if ((!lease->options[DHO_DHCP_OPTION_OVERLOAD].len ||
902 !(lease->options[DHO_DHCP_OPTION_OVERLOAD].data[0] & 1)) &&
903 client->packet.file[0]) {
904 /* Don't count on the NUL terminator. */
905 lease->filename = malloc(DHCP_FILE_LEN + 1);
906 if (!lease->filename) {
907 warning("dhcpoffer: no memory for filename.");
908 free_client_lease(lease);
911 memcpy(lease->filename, client->packet.file, DHCP_FILE_LEN);
912 lease->filename[DHCP_FILE_LEN] = '\0';
918 dhcpnak(struct iaddr client_addr, struct option_data *options)
921 if (client->state != S_REBOOTING &&
922 client->state != S_REQUESTING &&
923 client->state != S_RENEWING &&
924 client->state != S_REBINDING)
928 if (!client->active) {
929 note("DHCPNAK with no active lease.");
933 free_client_lease(client->active);
934 client->active = NULL;
936 /* Stop sending DHCPREQUEST packets... */
937 cancel_timeout(send_request);
939 client->state = S_INIT;
944 * Send out a DHCPDISCOVER packet, and set a timeout to send out another
945 * one after the right interval has expired. If we don't get an offer by
946 * the time we reach the panic interval, call the panic function.
951 int interval, increase = 1;
953 /* Figure out how long it's been since we started transmitting. */
954 interval = cur_time - client->first_sending;
956 /* If we're past the panic timeout, call the script and tell it
957 we haven't found anything for this interface yet. */
958 if (interval > config->timeout) {
963 /* If we're selecting media, try the whole list before doing
964 the exponential backoff, but if we've already received an
965 offer, stop looping, because we obviously have it right. */
966 if (!client->offered_leases && config->media) {
969 if (client->medium) {
970 client->medium = client->medium->next;
973 if (!client->medium) {
975 error("No valid media types for %s!", ifi->name);
976 client->medium = config->media;
980 note("Trying medium \"%s\" %d", client->medium->string,
982 script_init("MEDIUM", client->medium);
988 * If we're supposed to increase the interval, do so. If it's
989 * currently zero (i.e., we haven't sent any packets yet), set
990 * it to initial_interval; otherwise, add to it a random
991 * number between zero and two times itself. On average, this
992 * means that it will double with every transmission.
995 if (!client->interval)
996 client->interval = config->initial_interval;
998 client->interval += (arc4random() >> 2) %
999 (2 * client->interval);
1002 /* Don't backoff past cutoff. */
1003 if (client->interval > config->backoff_cutoff)
1004 client->interval = ((config->backoff_cutoff / 2)
1005 + ((arc4random() >> 2) %
1006 config->backoff_cutoff));
1007 } else if (!client->interval)
1008 client->interval = config->initial_interval;
1010 /* If the backoff would take us to the panic timeout, just use that
1012 if (cur_time + client->interval >
1013 client->first_sending + config->timeout)
1014 client->interval = (client->first_sending +
1015 config->timeout) - cur_time + 1;
1017 /* Record the number of seconds since we started sending. */
1018 if (interval < 65536)
1019 client->packet.secs = htons(interval);
1021 client->packet.secs = htons(65535);
1022 client->secs = client->packet.secs;
1024 note("DHCPDISCOVER on %s to %s port %d interval %ld",
1025 ifi->name, inet_ntoa(sockaddr_broadcast.sin_addr),
1026 ntohs(sockaddr_broadcast.sin_port), client->interval);
1028 /* Send out a packet. */
1029 send_packet(inaddr_any, &sockaddr_broadcast, NULL);
1031 add_timeout(cur_time + client->interval, send_discover);
1035 * state_panic gets called if we haven't received any offers in a preset
1036 * amount of time. When this happens, we try to use existing leases
1037 * that haven't yet expired, and failing that, we call the client script
1038 * and hope it can do something.
1043 struct client_lease *loop = client->active;
1044 struct client_lease *lp;
1046 note("No DHCPOFFERS received.");
1048 /* We may not have an active lease, but we may have some
1049 predefined leases that we can try. */
1050 if (!client->active && client->leases)
1053 /* Run through the list of leases and see if one can be used. */
1054 while (client->active) {
1055 if (client->active->expiry > cur_time) {
1056 note("Trying recorded lease %s",
1057 piaddr(client->active->address));
1058 /* Run the client script with the existing
1060 script_init("TIMEOUT",
1061 client->active->medium);
1062 script_write_params("new_", client->active);
1064 script_write_params("alias_",
1067 /* If the old lease is still good and doesn't
1068 yet need renewal, go into BOUND state and
1069 timeout at the renewal time. */
1072 client->active->renewal) {
1073 client->state = S_BOUND;
1074 note("bound: renewal in %ld seconds.",
1075 client->active->renewal -
1077 add_timeout(client->active->renewal,
1080 client->state = S_BOUND;
1081 note("bound: immediate renewal.");
1084 reinitialize_interface();
1090 /* If there are no other leases, give up. */
1091 if (!client->leases) {
1092 client->leases = client->active;
1093 client->active = NULL;
1098 /* Otherwise, put the active lease at the end of the
1099 lease list, and try another lease.. */
1100 for (lp = client->leases; lp->next; lp = lp->next)
1102 lp->next = client->active;
1104 lp->next->next = NULL;
1105 client->active = client->leases;
1106 client->leases = client->leases->next;
1108 /* If we already tried this lease, we've exhausted the
1109 set of leases, so we might as well give up for
1111 if (client->active == loop)
1114 loop = client->active;
1117 /* No leases were available, or what was available didn't work, so
1118 tell the shell script that we failed to allocate an address,
1119 and try again later. */
1120 note("No working leases in persistent database - sleeping.");
1121 script_init("FAIL", NULL);
1123 script_write_params("alias_", client->alias);
1125 client->state = S_INIT;
1126 add_timeout(cur_time + config->retry_interval, state_init);
1133 struct sockaddr_in destination;
1134 struct in_addr from;
1137 /* Figure out how long it's been since we started transmitting. */
1138 interval = cur_time - client->first_sending;
1140 /* If we're in the INIT-REBOOT or REQUESTING state and we're
1141 past the reboot timeout, go to INIT and see if we can
1142 DISCOVER an address... */
1143 /* XXX In the INIT-REBOOT state, if we don't get an ACK, it
1144 means either that we're on a network with no DHCP server,
1145 or that our server is down. In the latter case, assuming
1146 that there is a backup DHCP server, DHCPDISCOVER will get
1147 us a new address, but we could also have successfully
1148 reused our old address. In the former case, we're hosed
1149 anyway. This is not a win-prone situation. */
1150 if ((client->state == S_REBOOTING ||
1151 client->state == S_REQUESTING) &&
1152 interval > config->reboot_timeout) {
1154 client->state = S_INIT;
1155 cancel_timeout(send_request);
1160 /* If we're in the reboot state, make sure the media is set up
1162 if (client->state == S_REBOOTING &&
1164 client->active->medium) {
1165 script_init("MEDIUM", client->active->medium);
1167 /* If the medium we chose won't fly, go to INIT state. */
1171 /* Record the medium. */
1172 client->medium = client->active->medium;
1175 /* If the lease has expired, relinquish the address and go back
1176 to the INIT state. */
1177 if (client->state != S_REQUESTING &&
1178 cur_time > client->active->expiry) {
1179 /* Run the client script with the new parameters. */
1180 script_init("EXPIRE", NULL);
1181 script_write_params("old_", client->active);
1183 script_write_params("alias_", client->alias);
1186 /* Now do a preinit on the interface so that we can
1187 discover a new address. */
1188 script_init("PREINIT", NULL);
1190 script_write_params("alias_", client->alias);
1193 client->state = S_INIT;
1198 /* Do the exponential backoff... */
1199 if (!client->interval)
1200 client->interval = config->initial_interval;
1202 client->interval += ((arc4random() >> 2) %
1203 (2 * client->interval));
1205 /* Don't backoff past cutoff. */
1206 if (client->interval > config->backoff_cutoff)
1207 client->interval = ((config->backoff_cutoff / 2) +
1208 ((arc4random() >> 2) % client->interval));
1210 /* If the backoff would take us to the expiry time, just set the
1211 timeout to the expiry time. */
1212 if (client->state != S_REQUESTING && cur_time + client->interval >
1213 client->active->expiry)
1214 client->interval = client->active->expiry - cur_time + 1;
1216 /* If the lease T2 time has elapsed, or if we're not yet bound,
1217 broadcast the DHCPREQUEST rather than unicasting. */
1218 memset(&destination, 0, sizeof(destination));
1219 if (client->state == S_REQUESTING ||
1220 client->state == S_REBOOTING ||
1221 cur_time > client->active->rebind)
1222 destination.sin_addr.s_addr = INADDR_BROADCAST;
1224 memcpy(&destination.sin_addr.s_addr, client->destination.iabuf,
1225 sizeof(destination.sin_addr.s_addr));
1226 destination.sin_port = htons(REMOTE_PORT);
1227 destination.sin_family = AF_INET;
1228 destination.sin_len = sizeof(destination);
1230 if (client->state != S_REQUESTING)
1231 memcpy(&from, client->active->address.iabuf, sizeof(from));
1233 from.s_addr = INADDR_ANY;
1235 /* Record the number of seconds since we started sending. */
1236 if (client->state == S_REQUESTING)
1237 client->packet.secs = client->secs;
1239 if (interval < 65536)
1240 client->packet.secs = htons(interval);
1242 client->packet.secs = htons(65535);
1245 note("DHCPREQUEST on %s to %s port %d", ifi->name,
1246 inet_ntoa(destination.sin_addr), ntohs(destination.sin_port));
1248 /* Send out a packet. */
1249 send_packet(from, &destination, NULL);
1251 add_timeout(cur_time + client->interval, send_request);
1257 note("DHCPDECLINE on %s to %s port %d", ifi->name,
1258 inet_ntoa(sockaddr_broadcast.sin_addr),
1259 ntohs(sockaddr_broadcast.sin_port));
1261 /* Send out a packet. */
1262 send_packet(inaddr_any, &sockaddr_broadcast, NULL);
1266 make_discover(struct client_lease *lease)
1268 unsigned char discover = DHCPDISCOVER;
1269 struct option_data options[256];
1272 memset(options, 0, sizeof(options));
1273 memset(&client->packet, 0, sizeof(client->packet));
1275 /* Set DHCP_MESSAGE_TYPE to DHCPDISCOVER */
1276 i = DHO_DHCP_MESSAGE_TYPE;
1277 options[i].data = &discover;
1278 options[i].len = sizeof(discover);
1280 /* Request the options we want */
1281 i = DHO_DHCP_PARAMETER_REQUEST_LIST;
1282 options[i].data = config->requested_options;
1283 options[i].len = config->requested_option_count;
1285 /* If we had an address, try to get it again. */
1287 client->requested_address = lease->address;
1288 i = DHO_DHCP_REQUESTED_ADDRESS;
1289 options[i].data = lease->address.iabuf;
1290 options[i].len = lease->address.len;
1292 client->requested_address.len = 0;
1294 /* Send any options requested in the config file. */
1295 for (i = 0; i < 256; i++)
1296 if (!options[i].data &&
1297 config->send_options[i].data) {
1298 options[i].data = config->send_options[i].data;
1299 options[i].len = config->send_options[i].len;
1302 /* Set up the option buffer to fit in a minimal UDP packet. */
1303 i = cons_options(client->packet.options, 576 - DHCP_FIXED_LEN,
1305 if (i == -1 || client->packet.options[i] != DHO_END)
1306 error("options do not fit in DHCPDISCOVER packet.");
1307 client->packet_length = DHCP_FIXED_NON_UDP+i+1;
1308 if (client->packet_length < BOOTP_MIN_LEN)
1309 client->packet_length = BOOTP_MIN_LEN;
1311 client->packet.op = BOOTREQUEST;
1312 client->packet.htype = ifi->hw_address.htype;
1313 client->packet.hlen = ifi->hw_address.hlen;
1314 client->packet.hops = 0;
1315 client->packet.xid = arc4random();
1316 client->packet.secs = 0; /* filled in by send_discover. */
1317 client->packet.flags = 0;
1319 memset(&client->packet.ciaddr, 0, sizeof(client->packet.ciaddr));
1320 memset(&client->packet.yiaddr, 0, sizeof(client->packet.yiaddr));
1321 memset(&client->packet.siaddr, 0, sizeof(client->packet.siaddr));
1322 memset(&client->packet.giaddr, 0, sizeof(client->packet.giaddr));
1323 memcpy(client->packet.chaddr, ifi->hw_address.haddr,
1324 ifi->hw_address.hlen);
1328 make_request(struct client_lease * lease)
1330 unsigned char request = DHCPREQUEST;
1331 struct option_data options[256];
1334 memset(options, 0, sizeof(options));
1335 memset(&client->packet, 0, sizeof(client->packet));
1337 /* Set DHCP_MESSAGE_TYPE to DHCPREQUEST */
1338 i = DHO_DHCP_MESSAGE_TYPE;
1339 options[i].data = &request;
1340 options[i].len = sizeof(request);
1342 /* Request the options we want */
1343 i = DHO_DHCP_PARAMETER_REQUEST_LIST;
1344 options[i].data = config->requested_options;
1345 options[i].len = config->requested_option_count;
1347 /* If we are requesting an address that hasn't yet been assigned
1348 to us, use the DHCP Requested Address option. */
1349 if (client->state == S_REQUESTING) {
1350 /* Send back the server identifier... */
1351 i = DHO_DHCP_SERVER_IDENTIFIER;
1352 options[i].data = lease->options[i].data;
1353 options[i].len = lease->options[i].len;
1355 if (client->state == S_REQUESTING ||
1356 client->state == S_REBOOTING) {
1357 client->requested_address = lease->address;
1358 i = DHO_DHCP_REQUESTED_ADDRESS;
1359 options[i].data = lease->address.iabuf;
1360 options[i].len = lease->address.len;
1362 client->requested_address.len = 0;
1364 /* Send any options requested in the config file. */
1365 for (i = 0; i < 256; i++)
1366 if (!options[i].data && config->send_options[i].data) {
1367 options[i].data = config->send_options[i].data;
1368 options[i].len = config->send_options[i].len;
1371 /* Set up the option buffer to fit in a minimal UDP packet. */
1372 i = cons_options(client->packet.options, 576 - DHCP_FIXED_LEN,
1374 if (i == -1 || client->packet.options[i] != DHO_END)
1375 error("options do not fit in DHCPREQUEST packet.");
1376 client->packet_length = DHCP_FIXED_NON_UDP+i+1;
1377 if (client->packet_length < BOOTP_MIN_LEN)
1378 client->packet_length = BOOTP_MIN_LEN;
1380 client->packet.op = BOOTREQUEST;
1381 client->packet.htype = ifi->hw_address.htype;
1382 client->packet.hlen = ifi->hw_address.hlen;
1383 client->packet.hops = 0;
1384 client->packet.xid = client->xid;
1385 client->packet.secs = 0; /* Filled in by send_request. */
1386 client->packet.flags = 0;
1388 /* If we own the address we're requesting, put it in ciaddr;
1389 otherwise set ciaddr to zero. */
1390 if (client->state == S_BOUND ||
1391 client->state == S_RENEWING ||
1392 client->state == S_REBINDING) {
1393 memcpy(&client->packet.ciaddr,
1394 lease->address.iabuf, lease->address.len);
1396 memset(&client->packet.ciaddr, 0,
1397 sizeof(client->packet.ciaddr));
1400 memset(&client->packet.yiaddr, 0, sizeof(client->packet.yiaddr));
1401 memset(&client->packet.siaddr, 0, sizeof(client->packet.siaddr));
1402 memset(&client->packet.giaddr, 0, sizeof(client->packet.giaddr));
1403 memcpy(client->packet.chaddr, ifi->hw_address.haddr,
1404 ifi->hw_address.hlen);
1408 make_decline(struct client_lease *lease)
1410 struct option_data options[256];
1411 unsigned char decline = DHCPDECLINE;
1414 memset(options, 0, sizeof(options));
1415 memset(&client->packet, 0, sizeof(client->packet));
1417 /* Set DHCP_MESSAGE_TYPE to DHCPDECLINE */
1418 i = DHO_DHCP_MESSAGE_TYPE;
1419 options[i].data = &decline;
1420 options[i].len = sizeof(decline);
1422 /* Send back the server identifier... */
1423 i = DHO_DHCP_SERVER_IDENTIFIER;
1424 options[i].data = lease->options[i].data;
1425 options[i].len = lease->options[i].len;
1427 /* Send back the address we're declining. */
1428 i = DHO_DHCP_REQUESTED_ADDRESS;
1429 options[i].data = lease->address.iabuf;
1430 options[i].len = lease->address.len;
1432 /* Send the uid if the user supplied one. */
1433 i = DHO_DHCP_CLIENT_IDENTIFIER;
1434 if (config->send_options[i].len) {
1435 options[i].data = config->send_options[i].data;
1436 options[i].len = config->send_options[i].len;
1439 /* Set up the option buffer to fit in a minimal UDP packet. */
1440 i = cons_options(client->packet.options, 576 - DHCP_FIXED_LEN,
1442 if (i == -1 || client->packet.options[i] != DHO_END)
1443 error("options do not fit in DHCPDECLINE packet.");
1444 client->packet_length = DHCP_FIXED_NON_UDP+i+1;
1445 if (client->packet_length < BOOTP_MIN_LEN)
1446 client->packet_length = BOOTP_MIN_LEN;
1448 client->packet.op = BOOTREQUEST;
1449 client->packet.htype = ifi->hw_address.htype;
1450 client->packet.hlen = ifi->hw_address.hlen;
1451 client->packet.hops = 0;
1452 client->packet.xid = client->xid;
1453 client->packet.secs = 0; /* Filled in by send_request. */
1454 client->packet.flags = 0;
1456 /* ciaddr must always be zero. */
1457 memset(&client->packet.ciaddr, 0, sizeof(client->packet.ciaddr));
1458 memset(&client->packet.yiaddr, 0, sizeof(client->packet.yiaddr));
1459 memset(&client->packet.siaddr, 0, sizeof(client->packet.siaddr));
1460 memset(&client->packet.giaddr, 0, sizeof(client->packet.giaddr));
1461 memcpy(client->packet.chaddr, ifi->hw_address.haddr,
1462 ifi->hw_address.hlen);
1466 free_client_lease(struct client_lease *lease)
1470 if (lease->server_name)
1471 free(lease->server_name);
1472 if (lease->filename)
1473 free(lease->filename);
1474 for (i = 0; i < 256; i++) {
1475 if (lease->options[i].len)
1476 free(lease->options[i].data);
1482 rewrite_client_leases(void)
1484 struct client_lease *lp;
1486 if (!leaseFile) /* XXX */
1487 error("lease file not open");
1492 for (lp = client->leases; lp; lp = lp->next)
1493 write_client_lease(lp, 1);
1495 write_client_lease(client->active, 1);
1498 ftruncate(fileno(leaseFile), ftello(leaseFile));
1499 fsync(fileno(leaseFile));
1503 write_client_lease(struct client_lease *lease, int rewrite)
1505 static int leases_written;
1510 if (leases_written++ > 20) {
1511 rewrite_client_leases();
1516 /* If the lease came from the config file, we don't need to stash
1517 a copy in the lease database. */
1518 if (lease->is_static)
1521 if (!leaseFile) /* XXX */
1522 error("lease file not open");
1524 fprintf(leaseFile, "lease {\n");
1525 if (lease->is_bootp)
1526 fprintf(leaseFile, " bootp;\n");
1527 fprintf(leaseFile, " interface \"%s\";\n", ifi->name);
1528 fprintf(leaseFile, " fixed-address %s;\n", piaddr(lease->address));
1529 if (lease->filename)
1530 fprintf(leaseFile, " filename \"%s\";\n", lease->filename);
1531 if (lease->server_name)
1532 fprintf(leaseFile, " server-name \"%s\";\n",
1533 lease->server_name);
1535 fprintf(leaseFile, " medium \"%s\";\n", lease->medium->string);
1536 for (i = 0; i < 256; i++)
1537 if (lease->options[i].len)
1538 fprintf(leaseFile, " option %s %s;\n",
1539 dhcp_options[i].name,
1540 pretty_print_option(i, lease->options[i].data,
1541 lease->options[i].len, 1, 1));
1543 t = gmtime(&lease->renewal);
1544 fprintf(leaseFile, " renew %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->rebind);
1548 fprintf(leaseFile, " rebind %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 t = gmtime(&lease->expiry);
1552 fprintf(leaseFile, " expire %d %d/%d/%d %02d:%02d:%02d;\n",
1553 t->tm_wday, t->tm_year + 1900, t->tm_mon + 1, t->tm_mday,
1554 t->tm_hour, t->tm_min, t->tm_sec);
1555 fprintf(leaseFile, "}\n");
1560 script_init(char *reason, struct string_list *medium)
1562 size_t len, mediumlen = 0;
1563 struct imsg_hdr hdr;
1566 if (medium != NULL && medium->string != NULL)
1567 mediumlen = strlen(medium->string);
1569 hdr.code = IMSG_SCRIPT_INIT;
1570 hdr.len = sizeof(struct imsg_hdr) +
1571 sizeof(size_t) + mediumlen +
1572 sizeof(size_t) + strlen(reason);
1574 buf = buf_open(hdr.len);
1576 buf_add(buf, &hdr, sizeof(hdr));
1577 buf_add(buf, &mediumlen, sizeof(mediumlen));
1579 buf_add(buf, medium->string, mediumlen);
1580 len = strlen(reason);
1581 buf_add(buf, &len, sizeof(len));
1582 buf_add(buf, reason, len);
1584 buf_close(privfd, buf);
1588 priv_script_init(char *reason, char *medium)
1590 client->scriptEnvsize = 100;
1591 if (client->scriptEnv == NULL)
1593 calloc(client->scriptEnvsize, sizeof(char *));
1594 if (client->scriptEnv == NULL)
1595 error("script_init: no memory for environment");
1597 client->scriptEnv[0] = strdup(CLIENT_PATH);
1598 if (client->scriptEnv[0] == NULL)
1599 error("script_init: no memory for environment");
1601 client->scriptEnv[1] = NULL;
1603 script_set_env("", "interface", ifi->name);
1606 script_set_env("", "medium", medium);
1608 script_set_env("", "reason", reason);
1612 priv_script_write_params(char *prefix, struct client_lease *lease)
1614 u_int8_t dbuf[1500];
1618 script_set_env(prefix, "ip_address", piaddr(lease->address));
1620 if (lease->options[DHO_SUBNET_MASK].len &&
1621 (lease->options[DHO_SUBNET_MASK].len <
1622 sizeof(lease->address.iabuf))) {
1623 struct iaddr netmask, subnet, broadcast;
1625 memcpy(netmask.iabuf, lease->options[DHO_SUBNET_MASK].data,
1626 lease->options[DHO_SUBNET_MASK].len);
1627 netmask.len = lease->options[DHO_SUBNET_MASK].len;
1629 subnet = subnet_number(lease->address, netmask);
1631 script_set_env(prefix, "network_number",
1633 if (!lease->options[DHO_BROADCAST_ADDRESS].len) {
1634 broadcast = broadcast_addr(subnet, netmask);
1636 script_set_env(prefix,
1637 "broadcast_address",
1643 if (lease->filename)
1644 script_set_env(prefix, "filename", lease->filename);
1645 if (lease->server_name)
1646 script_set_env(prefix, "server_name",
1647 lease->server_name);
1648 for (i = 0; i < 256; i++) {
1649 u_int8_t *dp = NULL;
1651 if (config->defaults[i].len) {
1652 if (lease->options[i].len) {
1653 switch (config->default_actions[i]) {
1654 case ACTION_DEFAULT:
1655 dp = lease->options[i].data;
1656 len = lease->options[i].len;
1658 case ACTION_SUPERSEDE:
1660 dp = config->defaults[i].data;
1661 len = config->defaults[i].len;
1663 case ACTION_PREPEND:
1664 len = config->defaults[i].len +
1665 lease->options[i].len;
1666 if (len > sizeof(dbuf)) {
1667 warning("no space to %s %s",
1669 dhcp_options[i].name);
1674 config->defaults[i].data,
1675 config->defaults[i].len);
1677 config->defaults[i].len,
1678 lease->options[i].data,
1679 lease->options[i].len);
1683 len = config->defaults[i].len +
1684 lease->options[i].len;
1685 if (len > sizeof(dbuf)) {
1686 warning("no space to %s %s",
1688 dhcp_options[i].name);
1692 memcpy(dp, lease->options[i].data,
1693 lease->options[i].len);
1694 memcpy(dp + lease->options[i].len,
1695 config->defaults[i].data,
1696 config->defaults[i].len);
1700 dp = config->defaults[i].data;
1701 len = config->defaults[i].len;
1703 } else if (lease->options[i].len) {
1704 len = lease->options[i].len;
1705 dp = lease->options[i].data;
1712 if (dhcp_option_ev_name(name, sizeof(name),
1714 script_set_env(prefix, name,
1715 pretty_print_option(i, dp, len, 0, 0));
1718 snprintf(tbuf, sizeof(tbuf), "%d", (int)lease->expiry);
1719 script_set_env(prefix, "expiry", tbuf);
1723 script_write_params(char *prefix, struct client_lease *lease)
1725 size_t fn_len = 0, sn_len = 0, pr_len = 0;
1726 struct imsg_hdr hdr;
1730 if (lease->filename != NULL)
1731 fn_len = strlen(lease->filename);
1732 if (lease->server_name != NULL)
1733 sn_len = strlen(lease->server_name);
1735 pr_len = strlen(prefix);
1737 hdr.code = IMSG_SCRIPT_WRITE_PARAMS;
1738 hdr.len = sizeof(hdr) + sizeof(struct client_lease) +
1739 sizeof(size_t) + fn_len + sizeof(size_t) + sn_len +
1740 sizeof(size_t) + pr_len;
1742 for (i = 0; i < 256; i++)
1743 hdr.len += sizeof(int) + lease->options[i].len;
1745 scripttime = time(NULL);
1747 buf = buf_open(hdr.len);
1749 buf_add(buf, &hdr, sizeof(hdr));
1750 buf_add(buf, lease, sizeof(struct client_lease));
1751 buf_add(buf, &fn_len, sizeof(fn_len));
1752 buf_add(buf, lease->filename, fn_len);
1753 buf_add(buf, &sn_len, sizeof(sn_len));
1754 buf_add(buf, lease->server_name, sn_len);
1755 buf_add(buf, &pr_len, sizeof(pr_len));
1756 buf_add(buf, prefix, pr_len);
1758 for (i = 0; i < 256; i++) {
1759 buf_add(buf, &lease->options[i].len,
1760 sizeof(lease->options[i].len));
1761 buf_add(buf, lease->options[i].data,
1762 lease->options[i].len);
1765 buf_close(privfd, buf);
1771 struct imsg_hdr hdr;
1775 scripttime = time(NULL);
1777 hdr.code = IMSG_SCRIPT_GO;
1778 hdr.len = sizeof(struct imsg_hdr);
1780 buf = buf_open(hdr.len);
1782 buf_add(buf, &hdr, sizeof(hdr));
1783 buf_close(privfd, buf);
1785 bzero(&hdr, sizeof(hdr));
1786 buf_read(privfd, &hdr, sizeof(hdr));
1787 if (hdr.code != IMSG_SCRIPT_GO_RET)
1788 error("unexpected msg type %u", hdr.code);
1789 if (hdr.len != sizeof(hdr) + sizeof(int))
1790 error("received corrupted message");
1791 buf_read(privfd, &ret, sizeof(ret));
1797 priv_script_go(void)
1799 char *scriptName, *argv[2], **envp;
1800 int pid, wpid, wstatus;
1802 scripttime = time(NULL);
1804 scriptName = config->script_name;
1805 envp = client->scriptEnv;
1807 argv[0] = scriptName;
1816 wpid = wait(&wstatus);
1817 } while (wpid != pid && wpid > 0);
1823 execve(scriptName, argv, envp);
1824 error("execve (%s, ...): %m", scriptName);
1829 return (WEXITSTATUS(wstatus));
1833 script_set_env(const char *prefix, const char *name, const char *value)
1837 namelen = strlen(name);
1839 for (i = 0; client->scriptEnv[i]; i++)
1840 if (strncmp(client->scriptEnv[i], name, namelen) == 0 &&
1841 client->scriptEnv[i][namelen] == '=')
1844 if (client->scriptEnv[i])
1845 /* Reuse the slot. */
1846 free(client->scriptEnv[i]);
1848 /* New variable. Expand if necessary. */
1849 if (i >= client->scriptEnvsize - 1) {
1850 char **newscriptEnv;
1851 int newscriptEnvsize = client->scriptEnvsize + 50;
1853 newscriptEnv = realloc(client->scriptEnv,
1855 if (newscriptEnv == NULL) {
1856 free(client->scriptEnv);
1857 client->scriptEnv = NULL;
1858 client->scriptEnvsize = 0;
1859 error("script_set_env: no memory for variable");
1861 client->scriptEnv = newscriptEnv;
1862 client->scriptEnvsize = newscriptEnvsize;
1864 /* need to set the NULL pointer at end of array beyond
1866 client->scriptEnv[i + 1] = NULL;
1868 /* Allocate space and format the variable in the appropriate slot. */
1869 client->scriptEnv[i] = malloc(strlen(prefix) + strlen(name) + 1 +
1871 if (client->scriptEnv[i] == NULL)
1872 error("script_set_env: no memory for variable assignment");
1874 /* No `` or $() command substitution allowed in environment values! */
1875 for (j = 0; j < strlen(value); j++)
1879 error("illegal character (%c) in value '%s'", value[j],
1883 snprintf(client->scriptEnv[i], strlen(prefix) + strlen(name) +
1884 1 + strlen(value) + 1, "%s%s=%s", prefix, name, value);
1888 script_flush_env(void)
1892 for (i = 0; client->scriptEnv[i]; i++) {
1893 free(client->scriptEnv[i]);
1894 client->scriptEnv[i] = NULL;
1896 client->scriptEnvsize = 0;
1900 dhcp_option_ev_name(char *buf, size_t buflen, const struct option *option)
1904 for (i = 0; option->name[i]; i++) {
1905 if (i + 1 == buflen)
1907 if (option->name[i] == '-')
1910 buf[i] = option->name[i];
1920 static int state = 0;
1922 if (no_daemon || state)
1927 /* Stop logging to stderr... */
1930 if (daemon(1, 0) == -1)
1933 /* we are chrooted, daemon(3) fails to open /dev/null */
1935 dup2(nullfd, STDIN_FILENO);
1936 dup2(nullfd, STDOUT_FILENO);
1937 dup2(nullfd, STDERR_FILENO);
1944 check_option(struct client_lease *l, int option)
1949 /* we use this, since this is what gets passed to dhclient-script */
1951 opbuf = pretty_print_option(option, l->options[option].data,
1952 l->options[option].len, 0, 0);
1954 sbuf = option_as_string(option, l->options[option].data,
1955 l->options[option].len);
1958 case DHO_SUBNET_MASK:
1959 case DHO_TIME_SERVERS:
1960 case DHO_NAME_SERVERS:
1962 case DHO_DOMAIN_NAME_SERVERS:
1963 case DHO_LOG_SERVERS:
1964 case DHO_COOKIE_SERVERS:
1965 case DHO_LPR_SERVERS:
1966 case DHO_IMPRESS_SERVERS:
1967 case DHO_RESOURCE_LOCATION_SERVERS:
1968 case DHO_SWAP_SERVER:
1969 case DHO_BROADCAST_ADDRESS:
1970 case DHO_NIS_SERVERS:
1971 case DHO_NTP_SERVERS:
1972 case DHO_NETBIOS_NAME_SERVERS:
1973 case DHO_NETBIOS_DD_SERVER:
1974 case DHO_FONT_SERVERS:
1975 case DHO_DHCP_SERVER_IDENTIFIER:
1976 if (!ipv4addrs(opbuf)) {
1977 warning("Invalid IP address in option: %s", opbuf);
1982 case DHO_DOMAIN_NAME:
1983 case DHO_NIS_DOMAIN:
1984 if (!res_hnok(sbuf)) {
1985 warning("Bogus Host Name option %d: %s (%s)", option,
1987 l->options[option].len = 0;
1988 free(l->options[option].data);
1992 case DHO_TIME_OFFSET:
1994 case DHO_MERIT_DUMP:
1996 case DHO_EXTENSIONS_PATH:
1997 case DHO_IP_FORWARDING:
1998 case DHO_NON_LOCAL_SOURCE_ROUTING:
1999 case DHO_POLICY_FILTER:
2000 case DHO_MAX_DGRAM_REASSEMBLY:
2001 case DHO_DEFAULT_IP_TTL:
2002 case DHO_PATH_MTU_AGING_TIMEOUT:
2003 case DHO_PATH_MTU_PLATEAU_TABLE:
2004 case DHO_INTERFACE_MTU:
2005 case DHO_ALL_SUBNETS_LOCAL:
2006 case DHO_PERFORM_MASK_DISCOVERY:
2007 case DHO_MASK_SUPPLIER:
2008 case DHO_ROUTER_DISCOVERY:
2009 case DHO_ROUTER_SOLICITATION_ADDRESS:
2010 case DHO_STATIC_ROUTES:
2011 case DHO_TRAILER_ENCAPSULATION:
2012 case DHO_ARP_CACHE_TIMEOUT:
2013 case DHO_IEEE802_3_ENCAPSULATION:
2014 case DHO_DEFAULT_TCP_TTL:
2015 case DHO_TCP_KEEPALIVE_INTERVAL:
2016 case DHO_TCP_KEEPALIVE_GARBAGE:
2017 case DHO_VENDOR_ENCAPSULATED_OPTIONS:
2018 case DHO_NETBIOS_NODE_TYPE:
2019 case DHO_NETBIOS_SCOPE:
2020 case DHO_X_DISPLAY_MANAGER:
2021 case DHO_DHCP_REQUESTED_ADDRESS:
2022 case DHO_DHCP_LEASE_TIME:
2023 case DHO_DHCP_OPTION_OVERLOAD:
2024 case DHO_DHCP_MESSAGE_TYPE:
2025 case DHO_DHCP_PARAMETER_REQUEST_LIST:
2026 case DHO_DHCP_MESSAGE:
2027 case DHO_DHCP_MAX_MESSAGE_SIZE:
2028 case DHO_DHCP_RENEWAL_TIME:
2029 case DHO_DHCP_REBINDING_TIME:
2030 case DHO_DHCP_CLASS_IDENTIFIER:
2031 case DHO_DHCP_CLIENT_IDENTIFIER:
2032 case DHO_DHCP_USER_CLASS_ID:
2036 warning("unknown dhcp option value 0x%x", option);
2037 return (unknown_ok);
2042 res_hnok(const char *name)
2044 const char *dn = name;
2045 int pch = '.', ch = *dn++;
2048 while (ch != '\0') {
2053 } else if (pch == '.' || nch == '.' || nch == '\0') {
2056 } else if (!isalnum(ch) && ch != '-' && ch != '_')
2058 else if (ch == '_' && warn == 0) {
2059 warning("warning: hostname %s contains an "
2060 "underscore which violates RFC 952", name);
2068 /* Does buf consist only of dotted decimal ipv4 addrs?
2069 * return how many if so,
2070 * otherwise, return 0
2073 ipv4addrs(char * buf)
2078 while (inet_aton(buf, &jnk) == 1){
2080 while (*buf == '.' || isdigit(*buf))
2091 option_as_string(unsigned int code, unsigned char *data, int len)
2093 static char optbuf[32768]; /* XXX */
2095 int opleft = sizeof(optbuf);
2096 unsigned char *dp = data;
2099 error("option_as_string: bad code %d", code);
2101 for (; dp < data + len; dp++) {
2102 if (!isascii(*dp) || !isprint(*dp)) {
2103 if (dp + 1 != data + len || *dp != 0) {
2105 snprintf(op, opleft, "\\%03o", *dp);
2110 } else if (*dp == '"' || *dp == '\'' || *dp == '$' ||
2111 *dp == '`' || *dp == '\\') {
2125 warning("dhcp option too large");
2130 fork_privchld(int fd, int fd2)
2132 struct pollfd pfd[1];
2133 int nfds, pfail = 0;
2137 error("cannot fork");
2145 if (chdir("/") == -1)
2146 error("chdir(\"/\")");
2148 setproctitle("%s [priv]", ifi->name);
2150 dup2(nullfd, STDIN_FILENO);
2151 dup2(nullfd, STDOUT_FILENO);
2152 dup2(nullfd, STDERR_FILENO);
2158 pfd[0].events = POLLIN;
2159 if ((nfds = poll(pfd, 1, INFTIM)) == -1)
2161 error("poll error");
2164 * Handle temporary errors, but bail if they persist.
2166 if (nfds == 0 || !(pfd[0].revents & POLLIN)) {
2167 if (pfail > POLL_FAILURES)
2168 error("poll failed > %d times", POLL_FAILURES);
2169 sleep(pfail * POLL_FAILURE_WAIT);