1 /* $OpenBSD: src/sbin/dhclient/dhclient.c,v 1.126 2009/05/20 20:37:43 thib 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 */
162 struct rt_msghdr *rtm;
163 struct if_msghdr *ifm;
164 struct ifa_msghdr *ifam;
165 struct if_announcemsghdr *ifan;
166 struct client_lease *l;
167 time_t t = time(NULL);
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);
192 if ((a.len = sizeof(struct in_addr)) > sizeof(a.iabuf))
193 error("king bula sez: len mismatch");
194 memcpy(a.iabuf, &((struct sockaddr_in *)sa)->sin_addr, a.len);
195 if (addr_eq(a, defaddr))
198 for (l = client->active; l != NULL; l = l->next)
199 if (addr_eq(a, l->address))
202 if (l != NULL || (client->alias &&
203 addr_eq(a, client->alias->address)))
204 /* new addr is the one we set */
209 ifam = (struct ifa_msghdr *)rtm;
210 if (ifam->ifam_index != ifi->index)
212 if (findproto((char *)(ifam + 1), ifam->ifam_addrs) != AF_INET)
214 if (scripttime == 0 || t < scripttime + 10)
218 ifm = (struct if_msghdr *)rtm;
219 if (ifm->ifm_index != ifi->index)
221 if ((rtm->rtm_flags & RTF_UP) == 0)
225 LINK_STATE_IS_UP(ifm->ifm_data.ifi_link_state) ? 1 : 0;
226 if (linkstat != ifi->linkstat) {
227 debug("link state %s -> %s",
228 ifi->linkstat ? "up" : "down",
229 linkstat ? "up" : "down");
230 ifi->linkstat = interface_link_status(ifi->name);
232 client->state = S_INIT;
238 ifan = (struct if_announcemsghdr *)rtm;
239 if (ifan->ifan_what == IFAN_DEPARTURE &&
240 ifan->ifan_index == ifi->index)
249 script_init("FAIL", NULL);
251 script_write_params("alias_", client->alias);
257 main(int argc, char *argv[])
259 int ch, fd, quiet = 0, i = 0, pipe_fd[2];
262 /* Initially, log errors to stderr as well as to syslogd. */
263 openlog(getprogname(), LOG_PID | LOG_NDELAY, DHCPD_LOG_FACILITY);
264 setlogmask(LOG_UPTO(LOG_INFO));
266 while ((ch = getopt(argc, argv, "c:dl:qu")) != -1)
269 path_dhclient_conf = optarg;
275 path_dhclient_db = optarg;
293 ifi = calloc(1, sizeof(*ifi));
296 client = calloc(1, sizeof(*client));
298 error("client calloc");
299 config = calloc(1, sizeof(*config));
301 error("config calloc");
303 if (strlcpy(ifi->name, argv[0], IFNAMSIZ) >= IFNAMSIZ)
304 error("Interface name too long");
305 if (path_dhclient_db == NULL && asprintf(&path_dhclient_db, "%s.%s",
306 _PATH_DHCLIENT_DB, ifi->name) == -1)
315 memset(&sockaddr_broadcast, 0, sizeof(sockaddr_broadcast));
316 sockaddr_broadcast.sin_family = AF_INET;
317 sockaddr_broadcast.sin_port = htons(REMOTE_PORT);
318 sockaddr_broadcast.sin_addr.s_addr = INADDR_BROADCAST;
319 sockaddr_broadcast.sin_len = sizeof(sockaddr_broadcast);
320 inaddr_any.s_addr = INADDR_ANY;
324 if (interface_status(ifi->name) == 0) {
325 interface_link_forceup(ifi->name);
326 /* Give it up to 4 seconds of silent grace to find link */
331 while (!(ifi->linkstat = interface_link_status(ifi->name))) {
333 fprintf(stderr, "%s: no link ...", ifi->name);
335 fprintf(stderr, ".");
337 if (++i > config->link_timeout) {
338 fprintf(stderr, " sleeping\n");
344 fprintf(stderr, " got link\n");
347 if ((nullfd = open(_PATH_DEVNULL, O_RDWR, 0)) == -1)
348 error("cannot open %s: %m", _PATH_DEVNULL);
350 if ((pw = getpwnam("_dhcp")) == NULL)
351 error("no such user: _dhcp");
353 if (pipe(pipe_fd) == -1)
356 fork_privchld(pipe_fd[0], pipe_fd[1]);
361 if ((fd = open(path_dhclient_db, O_RDONLY|O_EXLOCK|O_CREAT, 0)) == -1)
362 error("can't open and lock %s: %m", path_dhclient_db);
363 read_client_leases();
364 if ((leaseFile = fopen(path_dhclient_db, "w")) == NULL)
365 error("can't open %s: %m", path_dhclient_db);
366 rewrite_client_leases();
369 priv_script_init("PREINIT", NULL);
371 priv_script_write_params("alias_", client->alias);
374 if ((routefd = socket(PF_ROUTE, SOCK_RAW, 0)) == -1)
375 error("socket(PF_ROUTE, SOCK_RAW): %m");
377 /* set up the interface */
378 discover_interface();
380 if (chroot(_PATH_VAREMPTY) == -1)
382 if (chdir("/") == -1)
383 error("chdir(\"/\")");
385 if (setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) == -1)
387 if (setgroups(1, &pw->pw_gid) == -1)
389 if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) == -1)
394 setproctitle("%s", ifi->name);
397 client->state = S_INIT;
411 fprintf(stderr, "usage: %s [-dqu] [-c file] [-l file] interface\n",
419 * Each routine is called from the dhclient_state_machine() in one of
421 * -> entering INIT state
422 * -> recvpacket_flag == 0: timeout in this state
423 * -> otherwise: received a packet in this state
425 * Return conditions as handled by dhclient_state_machine():
426 * Returns 1, sendpacket_flag = 1: send packet, reset timer.
427 * Returns 1, sendpacket_flag = 0: just reset the timer (wait for a milestone).
428 * Returns 0: finish the nap which was interrupted for no good reason.
430 * Several per-interface variables are used to keep track of the process:
431 * active_lease: the lease that is being used on the interface
432 * (null pointer if not configured yet).
433 * offered_leases: leases corresponding to DHCPOFFER messages that have
434 * been sent to us by DHCP servers.
435 * acked_leases: leases corresponding to DHCPACK messages that have been
436 * sent to us by DHCP servers.
437 * sendpacket: DHCP packet we're trying to send.
438 * destination: IP address to send sendpacket to
439 * In addition, there are several relevant per-lease variables.
440 * T1_expiry, T2_expiry, lease_expiry: lease milestones
441 * In the active lease, these control the process of renewing the lease;
442 * In leases on the acked_leases list, this simply determines when we
443 * can no longer legitimately use the lease.
448 /* If we don't remember an active lease, go straight to INIT. */
449 if (!client->active || client->active->is_bootp) {
454 /* We are in the rebooting state. */
455 client->state = S_REBOOTING;
457 /* make_request doesn't initialize xid because it normally comes
458 from the DHCPDISCOVER, but we haven't sent a DHCPDISCOVER,
459 so pick an xid now. */
460 client->xid = arc4random();
462 /* Make a DHCPREQUEST packet, and set appropriate per-interface
464 make_request(client->active);
465 client->destination = iaddr_broadcast;
466 client->first_sending = cur_time;
467 client->interval = config->initial_interval;
469 /* Zap the medium list... */
470 client->medium = NULL;
472 /* Send out the first DHCPREQUEST packet. */
477 * Called when a lease has completely expired and we've
478 * been unable to renew it.
483 /* Make a DHCPDISCOVER packet, and set appropriate per-interface
485 make_discover(client->active);
486 client->xid = client->packet.xid;
487 client->destination = iaddr_broadcast;
488 client->state = S_SELECTING;
489 client->first_sending = cur_time;
490 client->interval = config->initial_interval;
492 /* Add an immediate timeout to cause the first DHCPDISCOVER packet
498 * state_selecting is called when one or more DHCPOFFER packets
499 * have been received and a configurable period of time has passed.
502 state_selecting(void)
504 struct client_lease *lp, *next, *picked;
506 /* Cancel state_selecting and send_discover timeouts, since either
507 one could have got us here. */
508 cancel_timeout(state_selecting);
509 cancel_timeout(send_discover);
511 /* We have received one or more DHCPOFFER packets. Currently,
512 the only criterion by which we judge leases is whether or
513 not we get a response when we arp for them. */
515 for (lp = client->offered_leases; lp; lp = next) {
518 /* Check to see if we got an ARPREPLY for the address
519 in this particular lease. */
521 script_init("ARPCHECK", lp->medium);
522 script_write_params("check_", lp);
524 /* If the ARPCHECK code detects another
525 machine using the offered address, it exits
526 nonzero. We need to send a DHCPDECLINE and
537 free_client_lease(lp);
540 client->offered_leases = NULL;
542 /* If we just tossed all the leases we were offered, go back
545 client->state = S_INIT;
550 /* If it was a BOOTREPLY, we can just take the address right now. */
551 if (!picked->options[DHO_DHCP_MESSAGE_TYPE].len) {
552 client->new = picked;
554 /* Make up some lease expiry times
555 XXX these should be configurable. */
556 client->new->expiry = cur_time + 12000;
557 client->new->renewal += cur_time + 8000;
558 client->new->rebind += cur_time + 10000;
560 client->state = S_REQUESTING;
562 /* Bind to the address we received. */
567 /* Go to the REQUESTING state. */
568 client->destination = iaddr_broadcast;
569 client->state = S_REQUESTING;
570 client->first_sending = cur_time;
571 client->interval = config->initial_interval;
573 /* Make a DHCPREQUEST packet from the lease we picked. */
574 make_request(picked);
575 client->xid = client->packet.xid;
577 /* Toss the lease we picked - we'll get it back in a DHCPACK. */
578 free_client_lease(picked);
580 /* Add an immediate timeout to send the first DHCPREQUEST packet. */
585 dhcpack(struct iaddr client_addr, struct option_data *options)
587 struct client_lease *lease;
590 if (client->state != S_REBOOTING &&
591 client->state != S_REQUESTING &&
592 client->state != S_RENEWING &&
593 client->state != S_REBINDING)
597 lease = packet_to_lease(options);
599 note("packet_to_lease failed.");
605 /* Stop resending DHCPREQUEST. */
606 cancel_timeout(send_request);
608 /* Figure out the lease time. */
609 if (client->new->options[DHO_DHCP_LEASE_TIME].data)
610 client->new->expiry =
611 getULong(client->new->options[DHO_DHCP_LEASE_TIME].data);
613 client->new->expiry = DEFAULT_LEASE_TIME;
614 /* A number that looks negative here is really just very large,
615 because the lease expiry offset is unsigned. */
616 if (client->new->expiry < 0)
617 client->new->expiry = TIME_MAX;
618 /* XXX should be fixed by resetting the client state */
619 if (client->new->expiry < 60)
620 client->new->expiry = 60;
622 /* Take the server-provided renewal time if there is one;
623 otherwise figure it out according to the spec. */
624 if (client->new->options[DHO_DHCP_RENEWAL_TIME].len)
625 client->new->renewal =
626 getULong(client->new->options[DHO_DHCP_RENEWAL_TIME].data);
628 client->new->renewal = client->new->expiry / 2;
630 /* Same deal with the rebind time. */
631 if (client->new->options[DHO_DHCP_REBINDING_TIME].len)
632 client->new->rebind =
633 getULong(client->new->options[DHO_DHCP_REBINDING_TIME].data);
635 client->new->rebind = client->new->renewal +
636 client->new->renewal / 2 + client->new->renewal / 4;
638 client->new->expiry += cur_time;
639 /* Lease lengths can never be negative. */
640 if (client->new->expiry < cur_time)
641 client->new->expiry = TIME_MAX;
642 client->new->renewal += cur_time;
643 if (client->new->renewal < cur_time)
644 client->new->renewal = TIME_MAX;
645 client->new->rebind += cur_time;
646 if (client->new->rebind < cur_time)
647 client->new->rebind = TIME_MAX;
655 /* Remember the medium. */
656 client->new->medium = client->medium;
658 /* Write out the new lease. */
659 write_client_lease(client->new, 0);
661 /* Run the client script with the new parameters. */
662 script_init((client->state == S_REQUESTING ? "BOUND" :
663 (client->state == S_RENEWING ? "RENEW" :
664 (client->state == S_REBOOTING ? "REBOOT" : "REBIND"))),
665 client->new->medium);
666 if (client->active && client->state != S_REBOOTING)
667 script_write_params("old_", client->active);
668 script_write_params("new_", client->new);
670 script_write_params("alias_", client->alias);
673 /* Replace the old active lease with the new one. */
675 free_client_lease(client->active);
676 client->active = client->new;
679 /* Set up a timeout to start the renewal process. */
680 add_timeout(client->active->renewal, state_bound);
682 note("bound to %s -- renewal in %ld seconds.",
683 piaddr(client->active->address),
684 client->active->renewal - cur_time);
685 client->state = S_BOUND;
686 reinitialize_interface();
691 * state_bound is called when we've successfully bound to a particular
692 * lease, but the renewal time on that lease has expired. We are
693 * expected to unicast a DHCPREQUEST to the server that gave us our
699 /* T1 has expired. */
700 make_request(client->active);
701 client->xid = client->packet.xid;
703 if (client->active->options[DHO_DHCP_SERVER_IDENTIFIER].len == 4) {
704 memcpy(client->destination.iabuf,
705 client->active->options[DHO_DHCP_SERVER_IDENTIFIER].data,
707 client->destination.len = 4;
709 client->destination = iaddr_broadcast;
711 client->first_sending = cur_time;
712 client->interval = config->initial_interval;
713 client->state = S_RENEWING;
715 /* Send the first packet immediately. */
720 dhcpoffer(struct iaddr client_addr, struct option_data *options)
722 struct client_lease *lease, *lp;
724 int arp_timeout_needed, stop_selecting;
725 char *name = options[DHO_DHCP_MESSAGE_TYPE].len ? "DHCPOFFER" :
729 if (client->state != S_SELECTING)
733 /* If this lease doesn't supply the minimum required parameters,
735 for (i = 0; config->required_options[i]; i++) {
736 if (!options[config->required_options[i]].len) {
737 note("%s isn't satisfactory.", name);
742 /* If we've already seen this lease, don't record it again. */
743 for (lease = client->offered_leases;
744 lease; lease = lease->next) {
745 if (lease->address.len == sizeof(client->packet.yiaddr) &&
746 !memcmp(lease->address.iabuf,
747 &client->packet.yiaddr, lease->address.len)) {
748 debug("%s already seen.", name);
753 lease = packet_to_lease(options);
755 note("packet_to_lease failed.");
759 /* If this lease was acquired through a BOOTREPLY, record that
761 if (!options[DHO_DHCP_MESSAGE_TYPE].len)
764 /* Record the medium under which this lease was offered. */
765 lease->medium = client->medium;
767 /* Send out an ARP Request for the offered IP address. */
768 script_init("ARPSEND", lease->medium);
769 script_write_params("check_", lease);
770 /* If the script can't send an ARP request without waiting,
771 we'll be waiting when we do the ARPCHECK, so don't wait now. */
773 arp_timeout_needed = 0;
775 arp_timeout_needed = 2;
777 /* Figure out when we're supposed to stop selecting. */
778 stop_selecting = client->first_sending + config->select_interval;
780 /* If this is the lease we asked for, put it at the head of the
781 list, and don't mess with the arp request timeout. */
782 if (lease->address.len == client->requested_address.len &&
783 !memcmp(lease->address.iabuf,
784 client->requested_address.iabuf,
785 client->requested_address.len)) {
786 lease->next = client->offered_leases;
787 client->offered_leases = lease;
789 /* If we already have an offer, and arping for this
790 offer would take us past the selection timeout,
791 then don't extend the timeout - just hope for the
793 if (client->offered_leases &&
794 (cur_time + arp_timeout_needed) > stop_selecting)
795 arp_timeout_needed = 0;
797 /* Put the lease at the end of the list. */
799 if (!client->offered_leases)
800 client->offered_leases = lease;
802 for (lp = client->offered_leases; lp->next;
809 /* If we're supposed to stop selecting before we've had time
810 to wait for the ARPREPLY, add some delay to wait for
812 if (stop_selecting - cur_time < arp_timeout_needed)
813 stop_selecting = cur_time + arp_timeout_needed;
815 /* If the selecting interval has expired, go immediately to
816 state_selecting(). Otherwise, time out into
817 state_selecting at the select interval. */
818 if (stop_selecting <= 0)
821 add_timeout(stop_selecting, state_selecting);
822 cancel_timeout(send_discover);
827 * Allocate a client_lease structure and initialize it from the
828 * parameters in the specified packet.
830 struct client_lease *
831 packet_to_lease(struct option_data *options)
833 struct client_lease *lease;
836 lease = malloc(sizeof(struct client_lease));
839 warning("dhcpoffer: no memory to record lease.");
843 memset(lease, 0, sizeof(*lease));
845 /* Copy the lease options. */
846 for (i = 0; i < 256; i++) {
847 if (options[i].len) {
848 lease->options[i] = options[i];
849 options[i].data = NULL;
851 if (!check_option(lease, i)) {
852 warning("Invalid lease option - ignoring offer");
853 free_client_lease(lease);
859 lease->address.len = sizeof(client->packet.yiaddr);
860 memcpy(lease->address.iabuf, &client->packet.yiaddr,
863 /* If the server name was filled out, copy it. */
864 if ((!lease->options[DHO_DHCP_OPTION_OVERLOAD].len ||
865 !(lease->options[DHO_DHCP_OPTION_OVERLOAD].data[0] & 2)) &&
866 client->packet.sname[0]) {
867 lease->server_name = malloc(DHCP_SNAME_LEN + 1);
868 if (!lease->server_name) {
869 warning("dhcpoffer: no memory for server name.");
870 free_client_lease(lease);
873 memcpy(lease->server_name, client->packet.sname,
875 lease->server_name[DHCP_SNAME_LEN] = '\0';
876 if (!res_hnok(lease->server_name)) {
877 warning("Bogus server name %s", lease->server_name);
878 free(lease->server_name);
879 lease->server_name = NULL;
883 /* Ditto for the filename. */
884 if ((!lease->options[DHO_DHCP_OPTION_OVERLOAD].len ||
885 !(lease->options[DHO_DHCP_OPTION_OVERLOAD].data[0] & 1)) &&
886 client->packet.file[0]) {
887 /* Don't count on the NUL terminator. */
888 lease->filename = malloc(DHCP_FILE_LEN + 1);
889 if (!lease->filename) {
890 warning("dhcpoffer: no memory for filename.");
891 free_client_lease(lease);
894 memcpy(lease->filename, client->packet.file, DHCP_FILE_LEN);
895 lease->filename[DHCP_FILE_LEN] = '\0';
901 dhcpnak(struct iaddr client_addr, struct option_data *options)
904 if (client->state != S_REBOOTING &&
905 client->state != S_REQUESTING &&
906 client->state != S_RENEWING &&
907 client->state != S_REBINDING)
911 if (!client->active) {
912 note("DHCPNAK with no active lease.");
916 free_client_lease(client->active);
917 client->active = NULL;
919 /* Stop sending DHCPREQUEST packets... */
920 cancel_timeout(send_request);
922 client->state = S_INIT;
927 * Send out a DHCPDISCOVER packet, and set a timeout to send out another
928 * one after the right interval has expired. If we don't get an offer by
929 * the time we reach the panic interval, call the panic function.
934 int interval, increase = 1;
936 /* Figure out how long it's been since we started transmitting. */
937 interval = cur_time - client->first_sending;
939 /* If we're past the panic timeout, call the script and tell it
940 we haven't found anything for this interface yet. */
941 if (interval > config->timeout) {
946 /* If we're selecting media, try the whole list before doing
947 the exponential backoff, but if we've already received an
948 offer, stop looping, because we obviously have it right. */
949 if (!client->offered_leases && config->media) {
952 if (client->medium) {
953 client->medium = client->medium->next;
956 if (!client->medium) {
958 error("No valid media types for %s!", ifi->name);
959 client->medium = config->media;
963 note("Trying medium \"%s\" %d", client->medium->string,
965 script_init("MEDIUM", client->medium);
971 * If we're supposed to increase the interval, do so. If it's
972 * currently zero (i.e., we haven't sent any packets yet), set
973 * it to initial_interval; otherwise, add to it a random
974 * number between zero and two times itself. On average, this
975 * means that it will double with every transmission.
978 if (!client->interval)
979 client->interval = config->initial_interval;
981 client->interval += (arc4random() >> 2) %
982 (2 * client->interval);
985 /* Don't backoff past cutoff. */
986 if (client->interval > config->backoff_cutoff)
987 client->interval = ((config->backoff_cutoff / 2)
988 + ((arc4random() >> 2) %
989 config->backoff_cutoff));
990 } else if (!client->interval)
991 client->interval = config->initial_interval;
993 /* If the backoff would take us to the panic timeout, just use that
995 if (cur_time + client->interval >
996 client->first_sending + config->timeout)
997 client->interval = (client->first_sending +
998 config->timeout) - cur_time + 1;
1000 /* Record the number of seconds since we started sending. */
1001 if (interval < 65536)
1002 client->packet.secs = htons(interval);
1004 client->packet.secs = htons(65535);
1005 client->secs = client->packet.secs;
1007 note("DHCPDISCOVER on %s to %s port %d interval %ld",
1008 ifi->name, inet_ntoa(sockaddr_broadcast.sin_addr),
1009 ntohs(sockaddr_broadcast.sin_port), client->interval);
1011 /* Send out a packet. */
1012 send_packet(inaddr_any, &sockaddr_broadcast, NULL);
1014 add_timeout(cur_time + client->interval, send_discover);
1018 * state_panic gets called if we haven't received any offers in a preset
1019 * amount of time. When this happens, we try to use existing leases
1020 * that haven't yet expired, and failing that, we call the client script
1021 * and hope it can do something.
1026 struct client_lease *loop = client->active;
1027 struct client_lease *lp;
1029 note("No DHCPOFFERS received.");
1031 /* We may not have an active lease, but we may have some
1032 predefined leases that we can try. */
1033 if (!client->active && client->leases)
1036 /* Run through the list of leases and see if one can be used. */
1037 while (client->active) {
1038 if (client->active->expiry > cur_time) {
1039 note("Trying recorded lease %s",
1040 piaddr(client->active->address));
1041 /* Run the client script with the existing
1043 script_init("TIMEOUT",
1044 client->active->medium);
1045 script_write_params("new_", client->active);
1047 script_write_params("alias_",
1050 /* If the old lease is still good and doesn't
1051 yet need renewal, go into BOUND state and
1052 timeout at the renewal time. */
1055 client->active->renewal) {
1056 client->state = S_BOUND;
1057 note("bound: renewal in %ld seconds.",
1058 client->active->renewal -
1060 add_timeout(client->active->renewal,
1063 client->state = S_BOUND;
1064 note("bound: immediate renewal.");
1067 reinitialize_interface();
1073 /* If there are no other leases, give up. */
1074 if (!client->leases) {
1075 client->leases = client->active;
1076 client->active = NULL;
1081 /* Otherwise, put the active lease at the end of the
1082 lease list, and try another lease.. */
1083 for (lp = client->leases; lp->next; lp = lp->next)
1085 lp->next = client->active;
1087 lp->next->next = NULL;
1088 client->active = client->leases;
1089 client->leases = client->leases->next;
1091 /* If we already tried this lease, we've exhausted the
1092 set of leases, so we might as well give up for
1094 if (client->active == loop)
1097 loop = client->active;
1100 /* No leases were available, or what was available didn't work, so
1101 tell the shell script that we failed to allocate an address,
1102 and try again later. */
1103 note("No working leases in persistent database - sleeping.");
1104 script_init("FAIL", NULL);
1106 script_write_params("alias_", client->alias);
1108 client->state = S_INIT;
1109 add_timeout(cur_time + config->retry_interval, state_init);
1116 struct sockaddr_in destination;
1117 struct in_addr from;
1120 /* Figure out how long it's been since we started transmitting. */
1121 interval = cur_time - client->first_sending;
1123 /* If we're in the INIT-REBOOT or REQUESTING state and we're
1124 past the reboot timeout, go to INIT and see if we can
1125 DISCOVER an address... */
1126 /* XXX In the INIT-REBOOT state, if we don't get an ACK, it
1127 means either that we're on a network with no DHCP server,
1128 or that our server is down. In the latter case, assuming
1129 that there is a backup DHCP server, DHCPDISCOVER will get
1130 us a new address, but we could also have successfully
1131 reused our old address. In the former case, we're hosed
1132 anyway. This is not a win-prone situation. */
1133 if ((client->state == S_REBOOTING ||
1134 client->state == S_REQUESTING) &&
1135 interval > config->reboot_timeout) {
1137 client->state = S_INIT;
1138 cancel_timeout(send_request);
1143 /* If we're in the reboot state, make sure the media is set up
1145 if (client->state == S_REBOOTING &&
1147 client->active->medium) {
1148 script_init("MEDIUM", client->active->medium);
1150 /* If the medium we chose won't fly, go to INIT state. */
1154 /* Record the medium. */
1155 client->medium = client->active->medium;
1158 /* If the lease has expired, relinquish the address and go back
1159 to the INIT state. */
1160 if (client->state != S_REQUESTING &&
1161 cur_time > client->active->expiry) {
1162 /* Run the client script with the new parameters. */
1163 script_init("EXPIRE", NULL);
1164 script_write_params("old_", client->active);
1166 script_write_params("alias_", client->alias);
1169 /* Now do a preinit on the interface so that we can
1170 discover a new address. */
1171 script_init("PREINIT", NULL);
1173 script_write_params("alias_", client->alias);
1176 client->state = S_INIT;
1181 /* Do the exponential backoff... */
1182 if (!client->interval)
1183 client->interval = config->initial_interval;
1185 client->interval += ((arc4random() >> 2) %
1186 (2 * client->interval));
1188 /* Don't backoff past cutoff. */
1189 if (client->interval > config->backoff_cutoff)
1190 client->interval = ((config->backoff_cutoff / 2) +
1191 ((arc4random() >> 2) % client->interval));
1193 /* If the backoff would take us to the expiry time, just set the
1194 timeout to the expiry time. */
1195 if (client->state != S_REQUESTING && cur_time + client->interval >
1196 client->active->expiry)
1197 client->interval = client->active->expiry - cur_time + 1;
1199 /* If the lease T2 time has elapsed, or if we're not yet bound,
1200 broadcast the DHCPREQUEST rather than unicasting. */
1201 memset(&destination, 0, sizeof(destination));
1202 if (client->state == S_REQUESTING ||
1203 client->state == S_REBOOTING ||
1204 cur_time > client->active->rebind)
1205 destination.sin_addr.s_addr = INADDR_BROADCAST;
1207 memcpy(&destination.sin_addr.s_addr, client->destination.iabuf,
1208 sizeof(destination.sin_addr.s_addr));
1209 destination.sin_port = htons(REMOTE_PORT);
1210 destination.sin_family = AF_INET;
1211 destination.sin_len = sizeof(destination);
1213 if (client->state != S_REQUESTING)
1214 memcpy(&from, client->active->address.iabuf, sizeof(from));
1216 from.s_addr = INADDR_ANY;
1218 /* Record the number of seconds since we started sending. */
1219 if (client->state == S_REQUESTING)
1220 client->packet.secs = client->secs;
1222 if (interval < 65536)
1223 client->packet.secs = htons(interval);
1225 client->packet.secs = htons(65535);
1228 note("DHCPREQUEST on %s to %s port %d", ifi->name,
1229 inet_ntoa(destination.sin_addr), ntohs(destination.sin_port));
1231 /* Send out a packet. */
1232 send_packet(from, &destination, NULL);
1234 add_timeout(cur_time + client->interval, send_request);
1240 note("DHCPDECLINE on %s to %s port %d", ifi->name,
1241 inet_ntoa(sockaddr_broadcast.sin_addr),
1242 ntohs(sockaddr_broadcast.sin_port));
1244 /* Send out a packet. */
1245 send_packet(inaddr_any, &sockaddr_broadcast, NULL);
1249 make_discover(struct client_lease *lease)
1251 unsigned char discover = DHCPDISCOVER;
1252 struct option_data options[256];
1255 memset(options, 0, sizeof(options));
1256 memset(&client->packet, 0, sizeof(client->packet));
1258 /* Set DHCP_MESSAGE_TYPE to DHCPDISCOVER */
1259 i = DHO_DHCP_MESSAGE_TYPE;
1260 options[i].data = &discover;
1261 options[i].len = sizeof(discover);
1263 /* Request the options we want */
1264 i = DHO_DHCP_PARAMETER_REQUEST_LIST;
1265 options[i].data = config->requested_options;
1266 options[i].len = config->requested_option_count;
1268 /* If we had an address, try to get it again. */
1270 client->requested_address = lease->address;
1271 i = DHO_DHCP_REQUESTED_ADDRESS;
1272 options[i].data = lease->address.iabuf;
1273 options[i].len = lease->address.len;
1275 client->requested_address.len = 0;
1277 /* Send any options requested in the config file. */
1278 for (i = 0; i < 256; i++)
1279 if (!options[i].data &&
1280 config->send_options[i].data) {
1281 options[i].data = config->send_options[i].data;
1282 options[i].len = config->send_options[i].len;
1285 /* Set up the option buffer to fit in a minimal UDP packet. */
1286 i = cons_options(client->packet.options, 576 - DHCP_FIXED_LEN,
1288 if (i == -1 || client->packet.options[i] != DHO_END)
1289 error("options do not fit in DHCPDISCOVER packet.");
1290 client->packet_length = DHCP_FIXED_NON_UDP+i+1;
1291 if (client->packet_length < BOOTP_MIN_LEN)
1292 client->packet_length = BOOTP_MIN_LEN;
1294 client->packet.op = BOOTREQUEST;
1295 client->packet.htype = ifi->hw_address.htype;
1296 client->packet.hlen = ifi->hw_address.hlen;
1297 client->packet.hops = 0;
1298 client->packet.xid = arc4random();
1299 client->packet.secs = 0; /* filled in by send_discover. */
1300 client->packet.flags = 0;
1302 memset(&client->packet.ciaddr, 0, sizeof(client->packet.ciaddr));
1303 memset(&client->packet.yiaddr, 0, sizeof(client->packet.yiaddr));
1304 memset(&client->packet.siaddr, 0, sizeof(client->packet.siaddr));
1305 memset(&client->packet.giaddr, 0, sizeof(client->packet.giaddr));
1306 memcpy(client->packet.chaddr, ifi->hw_address.haddr,
1307 ifi->hw_address.hlen);
1311 make_request(struct client_lease * lease)
1313 unsigned char request = DHCPREQUEST;
1314 struct option_data options[256];
1317 memset(options, 0, sizeof(options));
1318 memset(&client->packet, 0, sizeof(client->packet));
1320 /* Set DHCP_MESSAGE_TYPE to DHCPREQUEST */
1321 i = DHO_DHCP_MESSAGE_TYPE;
1322 options[i].data = &request;
1323 options[i].len = sizeof(request);
1325 /* Request the options we want */
1326 i = DHO_DHCP_PARAMETER_REQUEST_LIST;
1327 options[i].data = config->requested_options;
1328 options[i].len = config->requested_option_count;
1330 /* If we are requesting an address that hasn't yet been assigned
1331 to us, use the DHCP Requested Address option. */
1332 if (client->state == S_REQUESTING) {
1333 /* Send back the server identifier... */
1334 i = DHO_DHCP_SERVER_IDENTIFIER;
1335 options[i].data = lease->options[i].data;
1336 options[i].len = lease->options[i].len;
1338 if (client->state == S_REQUESTING ||
1339 client->state == S_REBOOTING) {
1340 client->requested_address = lease->address;
1341 i = DHO_DHCP_REQUESTED_ADDRESS;
1342 options[i].data = lease->address.iabuf;
1343 options[i].len = lease->address.len;
1345 client->requested_address.len = 0;
1347 /* Send any options requested in the config file. */
1348 for (i = 0; i < 256; i++)
1349 if (!options[i].data && config->send_options[i].data) {
1350 options[i].data = config->send_options[i].data;
1351 options[i].len = config->send_options[i].len;
1354 /* Set up the option buffer to fit in a minimal UDP packet. */
1355 i = cons_options(client->packet.options, 576 - DHCP_FIXED_LEN,
1357 if (i == -1 || client->packet.options[i] != DHO_END)
1358 error("options do not fit in DHCPREQUEST packet.");
1359 client->packet_length = DHCP_FIXED_NON_UDP+i+1;
1360 if (client->packet_length < BOOTP_MIN_LEN)
1361 client->packet_length = BOOTP_MIN_LEN;
1363 client->packet.op = BOOTREQUEST;
1364 client->packet.htype = ifi->hw_address.htype;
1365 client->packet.hlen = ifi->hw_address.hlen;
1366 client->packet.hops = 0;
1367 client->packet.xid = client->xid;
1368 client->packet.secs = 0; /* Filled in by send_request. */
1369 client->packet.flags = 0;
1371 /* If we own the address we're requesting, put it in ciaddr;
1372 otherwise set ciaddr to zero. */
1373 if (client->state == S_BOUND ||
1374 client->state == S_RENEWING ||
1375 client->state == S_REBINDING) {
1376 memcpy(&client->packet.ciaddr,
1377 lease->address.iabuf, lease->address.len);
1379 memset(&client->packet.ciaddr, 0,
1380 sizeof(client->packet.ciaddr));
1383 memset(&client->packet.yiaddr, 0, sizeof(client->packet.yiaddr));
1384 memset(&client->packet.siaddr, 0, sizeof(client->packet.siaddr));
1385 memset(&client->packet.giaddr, 0, sizeof(client->packet.giaddr));
1386 memcpy(client->packet.chaddr, ifi->hw_address.haddr,
1387 ifi->hw_address.hlen);
1391 make_decline(struct client_lease *lease)
1393 struct option_data options[256];
1394 unsigned char decline = DHCPDECLINE;
1397 memset(options, 0, sizeof(options));
1398 memset(&client->packet, 0, sizeof(client->packet));
1400 /* Set DHCP_MESSAGE_TYPE to DHCPDECLINE */
1401 i = DHO_DHCP_MESSAGE_TYPE;
1402 options[i].data = &decline;
1403 options[i].len = sizeof(decline);
1405 /* Send back the server identifier... */
1406 i = DHO_DHCP_SERVER_IDENTIFIER;
1407 options[i].data = lease->options[i].data;
1408 options[i].len = lease->options[i].len;
1410 /* Send back the address we're declining. */
1411 i = DHO_DHCP_REQUESTED_ADDRESS;
1412 options[i].data = lease->address.iabuf;
1413 options[i].len = lease->address.len;
1415 /* Send the uid if the user supplied one. */
1416 i = DHO_DHCP_CLIENT_IDENTIFIER;
1417 if (config->send_options[i].len) {
1418 options[i].data = config->send_options[i].data;
1419 options[i].len = config->send_options[i].len;
1422 /* Set up the option buffer to fit in a minimal UDP packet. */
1423 i = cons_options(client->packet.options, 576 - DHCP_FIXED_LEN,
1425 if (i == -1 || client->packet.options[i] != DHO_END)
1426 error("options do not fit in DHCPDECLINE packet.");
1427 client->packet_length = DHCP_FIXED_NON_UDP+i+1;
1428 if (client->packet_length < BOOTP_MIN_LEN)
1429 client->packet_length = BOOTP_MIN_LEN;
1431 client->packet.op = BOOTREQUEST;
1432 client->packet.htype = ifi->hw_address.htype;
1433 client->packet.hlen = ifi->hw_address.hlen;
1434 client->packet.hops = 0;
1435 client->packet.xid = client->xid;
1436 client->packet.secs = 0; /* Filled in by send_request. */
1437 client->packet.flags = 0;
1439 /* ciaddr must always be zero. */
1440 memset(&client->packet.ciaddr, 0, sizeof(client->packet.ciaddr));
1441 memset(&client->packet.yiaddr, 0, sizeof(client->packet.yiaddr));
1442 memset(&client->packet.siaddr, 0, sizeof(client->packet.siaddr));
1443 memset(&client->packet.giaddr, 0, sizeof(client->packet.giaddr));
1444 memcpy(client->packet.chaddr, ifi->hw_address.haddr,
1445 ifi->hw_address.hlen);
1449 free_client_lease(struct client_lease *lease)
1453 if (lease->server_name)
1454 free(lease->server_name);
1455 if (lease->filename)
1456 free(lease->filename);
1457 for (i = 0; i < 256; i++) {
1458 if (lease->options[i].len)
1459 free(lease->options[i].data);
1465 rewrite_client_leases(void)
1467 struct client_lease *lp;
1469 if (!leaseFile) /* XXX */
1470 error("lease file not open");
1475 for (lp = client->leases; lp; lp = lp->next)
1476 write_client_lease(lp, 1);
1478 write_client_lease(client->active, 1);
1481 ftruncate(fileno(leaseFile), ftello(leaseFile));
1482 fsync(fileno(leaseFile));
1486 write_client_lease(struct client_lease *lease, int rewrite)
1488 static int leases_written;
1493 if (leases_written++ > 20) {
1494 rewrite_client_leases();
1499 /* If the lease came from the config file, we don't need to stash
1500 a copy in the lease database. */
1501 if (lease->is_static)
1504 if (!leaseFile) /* XXX */
1505 error("lease file not open");
1507 fprintf(leaseFile, "lease {\n");
1508 if (lease->is_bootp)
1509 fprintf(leaseFile, " bootp;\n");
1510 fprintf(leaseFile, " interface \"%s\";\n", ifi->name);
1511 fprintf(leaseFile, " fixed-address %s;\n", piaddr(lease->address));
1512 if (lease->filename)
1513 fprintf(leaseFile, " filename \"%s\";\n", lease->filename);
1514 if (lease->server_name)
1515 fprintf(leaseFile, " server-name \"%s\";\n",
1516 lease->server_name);
1518 fprintf(leaseFile, " medium \"%s\";\n", lease->medium->string);
1519 for (i = 0; i < 256; i++)
1520 if (lease->options[i].len)
1521 fprintf(leaseFile, " option %s %s;\n",
1522 dhcp_options[i].name,
1523 pretty_print_option(i, lease->options[i].data,
1524 lease->options[i].len, 1, 1));
1526 t = gmtime(&lease->renewal);
1527 fprintf(leaseFile, " renew %d %d/%d/%d %02d:%02d:%02d;\n",
1528 t->tm_wday, t->tm_year + 1900, t->tm_mon + 1, t->tm_mday,
1529 t->tm_hour, t->tm_min, t->tm_sec);
1530 t = gmtime(&lease->rebind);
1531 fprintf(leaseFile, " rebind %d %d/%d/%d %02d:%02d:%02d;\n",
1532 t->tm_wday, t->tm_year + 1900, t->tm_mon + 1, t->tm_mday,
1533 t->tm_hour, t->tm_min, t->tm_sec);
1534 t = gmtime(&lease->expiry);
1535 fprintf(leaseFile, " expire %d %d/%d/%d %02d:%02d:%02d;\n",
1536 t->tm_wday, t->tm_year + 1900, t->tm_mon + 1, t->tm_mday,
1537 t->tm_hour, t->tm_min, t->tm_sec);
1538 fprintf(leaseFile, "}\n");
1543 script_init(char *reason, struct string_list *medium)
1545 size_t len, mediumlen = 0;
1546 struct imsg_hdr hdr;
1549 if (medium != NULL && medium->string != NULL)
1550 mediumlen = strlen(medium->string);
1552 hdr.code = IMSG_SCRIPT_INIT;
1553 hdr.len = sizeof(struct imsg_hdr) +
1554 sizeof(size_t) + mediumlen +
1555 sizeof(size_t) + strlen(reason);
1557 buf = buf_open(hdr.len);
1559 buf_add(buf, &hdr, sizeof(hdr));
1560 buf_add(buf, &mediumlen, sizeof(mediumlen));
1562 buf_add(buf, medium->string, mediumlen);
1563 len = strlen(reason);
1564 buf_add(buf, &len, sizeof(len));
1565 buf_add(buf, reason, len);
1567 buf_close(privfd, buf);
1571 priv_script_init(char *reason, char *medium)
1573 client->scriptEnvsize = 100;
1574 if (client->scriptEnv == NULL)
1576 calloc(client->scriptEnvsize, sizeof(char *));
1577 if (client->scriptEnv == NULL)
1578 error("script_init: no memory for environment");
1580 client->scriptEnv[0] = strdup(CLIENT_PATH);
1581 if (client->scriptEnv[0] == NULL)
1582 error("script_init: no memory for environment");
1584 client->scriptEnv[1] = NULL;
1586 script_set_env("", "interface", ifi->name);
1589 script_set_env("", "medium", medium);
1591 script_set_env("", "reason", reason);
1595 priv_script_write_params(char *prefix, struct client_lease *lease)
1597 u_int8_t dbuf[1500];
1601 script_set_env(prefix, "ip_address", piaddr(lease->address));
1603 if (lease->options[DHO_SUBNET_MASK].len &&
1604 (lease->options[DHO_SUBNET_MASK].len <
1605 sizeof(lease->address.iabuf))) {
1606 struct iaddr netmask, subnet, broadcast;
1608 memcpy(netmask.iabuf, lease->options[DHO_SUBNET_MASK].data,
1609 lease->options[DHO_SUBNET_MASK].len);
1610 netmask.len = lease->options[DHO_SUBNET_MASK].len;
1612 subnet = subnet_number(lease->address, netmask);
1614 script_set_env(prefix, "network_number",
1616 if (!lease->options[DHO_BROADCAST_ADDRESS].len) {
1617 broadcast = broadcast_addr(subnet, netmask);
1619 script_set_env(prefix,
1620 "broadcast_address",
1626 if (lease->filename)
1627 script_set_env(prefix, "filename", lease->filename);
1628 if (lease->server_name)
1629 script_set_env(prefix, "server_name",
1630 lease->server_name);
1631 for (i = 0; i < 256; i++) {
1632 u_int8_t *dp = NULL;
1634 if (config->defaults[i].len) {
1635 if (lease->options[i].len) {
1636 switch (config->default_actions[i]) {
1637 case ACTION_DEFAULT:
1638 dp = lease->options[i].data;
1639 len = lease->options[i].len;
1641 case ACTION_SUPERSEDE:
1643 dp = config->defaults[i].data;
1644 len = config->defaults[i].len;
1646 case ACTION_PREPEND:
1647 len = config->defaults[i].len +
1648 lease->options[i].len;
1649 if (len > sizeof(dbuf)) {
1650 warning("no space to %s %s",
1652 dhcp_options[i].name);
1657 config->defaults[i].data,
1658 config->defaults[i].len);
1660 config->defaults[i].len,
1661 lease->options[i].data,
1662 lease->options[i].len);
1666 len = config->defaults[i].len +
1667 lease->options[i].len;
1668 if (len > sizeof(dbuf)) {
1669 warning("no space to %s %s",
1671 dhcp_options[i].name);
1675 memcpy(dp, lease->options[i].data,
1676 lease->options[i].len);
1677 memcpy(dp + lease->options[i].len,
1678 config->defaults[i].data,
1679 config->defaults[i].len);
1683 dp = config->defaults[i].data;
1684 len = config->defaults[i].len;
1686 } else if (lease->options[i].len) {
1687 len = lease->options[i].len;
1688 dp = lease->options[i].data;
1695 if (dhcp_option_ev_name(name, sizeof(name),
1697 script_set_env(prefix, name,
1698 pretty_print_option(i, dp, len, 0, 0));
1701 snprintf(tbuf, sizeof(tbuf), "%d", (int)lease->expiry);
1702 script_set_env(prefix, "expiry", tbuf);
1706 script_write_params(char *prefix, struct client_lease *lease)
1708 size_t fn_len = 0, sn_len = 0, pr_len = 0;
1709 struct imsg_hdr hdr;
1713 if (lease->filename != NULL)
1714 fn_len = strlen(lease->filename);
1715 if (lease->server_name != NULL)
1716 sn_len = strlen(lease->server_name);
1718 pr_len = strlen(prefix);
1720 hdr.code = IMSG_SCRIPT_WRITE_PARAMS;
1721 hdr.len = sizeof(hdr) + sizeof(struct client_lease) +
1722 sizeof(size_t) + fn_len + sizeof(size_t) + sn_len +
1723 sizeof(size_t) + pr_len;
1725 for (i = 0; i < 256; i++)
1726 hdr.len += sizeof(int) + lease->options[i].len;
1728 scripttime = time(NULL);
1730 buf = buf_open(hdr.len);
1732 buf_add(buf, &hdr, sizeof(hdr));
1733 buf_add(buf, lease, sizeof(struct client_lease));
1734 buf_add(buf, &fn_len, sizeof(fn_len));
1735 buf_add(buf, lease->filename, fn_len);
1736 buf_add(buf, &sn_len, sizeof(sn_len));
1737 buf_add(buf, lease->server_name, sn_len);
1738 buf_add(buf, &pr_len, sizeof(pr_len));
1739 buf_add(buf, prefix, pr_len);
1741 for (i = 0; i < 256; i++) {
1742 buf_add(buf, &lease->options[i].len,
1743 sizeof(lease->options[i].len));
1744 buf_add(buf, lease->options[i].data,
1745 lease->options[i].len);
1748 buf_close(privfd, buf);
1754 struct imsg_hdr hdr;
1758 scripttime = time(NULL);
1760 hdr.code = IMSG_SCRIPT_GO;
1761 hdr.len = sizeof(struct imsg_hdr);
1763 buf = buf_open(hdr.len);
1765 buf_add(buf, &hdr, sizeof(hdr));
1766 buf_close(privfd, buf);
1768 bzero(&hdr, sizeof(hdr));
1769 buf_read(privfd, &hdr, sizeof(hdr));
1770 if (hdr.code != IMSG_SCRIPT_GO_RET)
1771 error("unexpected msg type %u", hdr.code);
1772 if (hdr.len != sizeof(hdr) + sizeof(int))
1773 error("received corrupted message");
1774 buf_read(privfd, &ret, sizeof(ret));
1780 priv_script_go(void)
1782 char *scriptName, *argv[2], **envp;
1783 int pid, wpid, wstatus;
1785 scripttime = time(NULL);
1787 scriptName = config->script_name;
1788 envp = client->scriptEnv;
1790 argv[0] = scriptName;
1799 wpid = wait(&wstatus);
1800 } while (wpid != pid && wpid > 0);
1806 execve(scriptName, argv, envp);
1807 error("execve (%s, ...): %m", scriptName);
1812 return (WEXITSTATUS(wstatus));
1816 script_set_env(const char *prefix, const char *name, const char *value)
1820 namelen = strlen(name);
1822 for (i = 0; client->scriptEnv[i]; i++)
1823 if (strncmp(client->scriptEnv[i], name, namelen) == 0 &&
1824 client->scriptEnv[i][namelen] == '=')
1827 if (client->scriptEnv[i])
1828 /* Reuse the slot. */
1829 free(client->scriptEnv[i]);
1831 /* New variable. Expand if necessary. */
1832 if (i >= client->scriptEnvsize - 1) {
1833 char **newscriptEnv;
1834 int newscriptEnvsize = client->scriptEnvsize + 50;
1836 newscriptEnv = realloc(client->scriptEnv,
1838 if (newscriptEnv == NULL) {
1839 free(client->scriptEnv);
1840 client->scriptEnv = NULL;
1841 client->scriptEnvsize = 0;
1842 error("script_set_env: no memory for variable");
1844 client->scriptEnv = newscriptEnv;
1845 client->scriptEnvsize = newscriptEnvsize;
1847 /* need to set the NULL pointer at end of array beyond
1849 client->scriptEnv[i + 1] = NULL;
1851 /* Allocate space and format the variable in the appropriate slot. */
1852 client->scriptEnv[i] = malloc(strlen(prefix) + strlen(name) + 1 +
1854 if (client->scriptEnv[i] == NULL)
1855 error("script_set_env: no memory for variable assignment");
1857 /* No `` or $() command substitution allowed in environment values! */
1858 for (j = 0; j < strlen(value); j++)
1862 error("illegal character (%c) in value '%s'", value[j],
1866 snprintf(client->scriptEnv[i], strlen(prefix) + strlen(name) +
1867 1 + strlen(value) + 1, "%s%s=%s", prefix, name, value);
1871 script_flush_env(void)
1875 for (i = 0; client->scriptEnv[i]; i++) {
1876 free(client->scriptEnv[i]);
1877 client->scriptEnv[i] = NULL;
1879 client->scriptEnvsize = 0;
1883 dhcp_option_ev_name(char *buf, size_t buflen, const struct option *option)
1887 for (i = 0; option->name[i]; i++) {
1888 if (i + 1 == buflen)
1890 if (option->name[i] == '-')
1893 buf[i] = option->name[i];
1903 static int state = 0;
1905 if (no_daemon || state)
1910 /* Stop logging to stderr... */
1913 if (daemon(1, 0) == -1)
1916 /* we are chrooted, daemon(3) fails to open /dev/null */
1918 dup2(nullfd, STDIN_FILENO);
1919 dup2(nullfd, STDOUT_FILENO);
1920 dup2(nullfd, STDERR_FILENO);
1927 check_option(struct client_lease *l, int option)
1932 /* we use this, since this is what gets passed to dhclient-script */
1934 opbuf = pretty_print_option(option, l->options[option].data,
1935 l->options[option].len, 0, 0);
1937 sbuf = option_as_string(option, l->options[option].data,
1938 l->options[option].len);
1941 case DHO_SUBNET_MASK:
1942 case DHO_TIME_SERVERS:
1943 case DHO_NAME_SERVERS:
1945 case DHO_DOMAIN_NAME_SERVERS:
1946 case DHO_LOG_SERVERS:
1947 case DHO_COOKIE_SERVERS:
1948 case DHO_LPR_SERVERS:
1949 case DHO_IMPRESS_SERVERS:
1950 case DHO_RESOURCE_LOCATION_SERVERS:
1951 case DHO_SWAP_SERVER:
1952 case DHO_BROADCAST_ADDRESS:
1953 case DHO_NIS_SERVERS:
1954 case DHO_NTP_SERVERS:
1955 case DHO_NETBIOS_NAME_SERVERS:
1956 case DHO_NETBIOS_DD_SERVER:
1957 case DHO_FONT_SERVERS:
1958 case DHO_DHCP_SERVER_IDENTIFIER:
1959 if (!ipv4addrs(opbuf)) {
1960 warning("Invalid IP address in option: %s", opbuf);
1965 case DHO_DOMAIN_NAME:
1966 case DHO_NIS_DOMAIN:
1967 if (!res_hnok(sbuf)) {
1968 warning("Bogus Host Name option %d: %s (%s)", option,
1970 l->options[option].len = 0;
1971 free(l->options[option].data);
1975 case DHO_TIME_OFFSET:
1977 case DHO_MERIT_DUMP:
1979 case DHO_EXTENSIONS_PATH:
1980 case DHO_IP_FORWARDING:
1981 case DHO_NON_LOCAL_SOURCE_ROUTING:
1982 case DHO_POLICY_FILTER:
1983 case DHO_MAX_DGRAM_REASSEMBLY:
1984 case DHO_DEFAULT_IP_TTL:
1985 case DHO_PATH_MTU_AGING_TIMEOUT:
1986 case DHO_PATH_MTU_PLATEAU_TABLE:
1987 case DHO_INTERFACE_MTU:
1988 case DHO_ALL_SUBNETS_LOCAL:
1989 case DHO_PERFORM_MASK_DISCOVERY:
1990 case DHO_MASK_SUPPLIER:
1991 case DHO_ROUTER_DISCOVERY:
1992 case DHO_ROUTER_SOLICITATION_ADDRESS:
1993 case DHO_STATIC_ROUTES:
1994 case DHO_TRAILER_ENCAPSULATION:
1995 case DHO_ARP_CACHE_TIMEOUT:
1996 case DHO_IEEE802_3_ENCAPSULATION:
1997 case DHO_DEFAULT_TCP_TTL:
1998 case DHO_TCP_KEEPALIVE_INTERVAL:
1999 case DHO_TCP_KEEPALIVE_GARBAGE:
2000 case DHO_VENDOR_ENCAPSULATED_OPTIONS:
2001 case DHO_NETBIOS_NODE_TYPE:
2002 case DHO_NETBIOS_SCOPE:
2003 case DHO_X_DISPLAY_MANAGER:
2004 case DHO_DHCP_REQUESTED_ADDRESS:
2005 case DHO_DHCP_LEASE_TIME:
2006 case DHO_DHCP_OPTION_OVERLOAD:
2007 case DHO_DHCP_MESSAGE_TYPE:
2008 case DHO_DHCP_PARAMETER_REQUEST_LIST:
2009 case DHO_DHCP_MESSAGE:
2010 case DHO_DHCP_MAX_MESSAGE_SIZE:
2011 case DHO_DHCP_RENEWAL_TIME:
2012 case DHO_DHCP_REBINDING_TIME:
2013 case DHO_DHCP_CLASS_IDENTIFIER:
2014 case DHO_DHCP_CLIENT_IDENTIFIER:
2015 case DHO_DHCP_USER_CLASS_ID:
2019 warning("unknown dhcp option value 0x%x", option);
2020 return (unknown_ok);
2025 res_hnok(const char *name)
2027 const char *dn = name;
2028 int pch = '.', ch = *dn++;
2031 while (ch != '\0') {
2036 } else if (pch == '.' || nch == '.' || nch == '\0') {
2039 } else if (!isalnum(ch) && ch != '-' && ch != '_')
2041 else if (ch == '_' && warn == 0) {
2042 warning("warning: hostname %s contains an "
2043 "underscore which violates RFC 952", name);
2051 /* Does buf consist only of dotted decimal ipv4 addrs?
2052 * return how many if so,
2053 * otherwise, return 0
2056 ipv4addrs(char * buf)
2061 while (inet_aton(buf, &jnk) == 1){
2063 while (*buf == '.' || isdigit(*buf))
2074 option_as_string(unsigned int code, unsigned char *data, int len)
2076 static char optbuf[32768]; /* XXX */
2078 int opleft = sizeof(optbuf);
2079 unsigned char *dp = data;
2082 error("option_as_string: bad code %d", code);
2084 for (; dp < data + len; dp++) {
2085 if (!isascii(*dp) || !isprint(*dp)) {
2086 if (dp + 1 != data + len || *dp != 0) {
2088 snprintf(op, opleft, "\\%03o", *dp);
2093 } else if (*dp == '"' || *dp == '\'' || *dp == '$' ||
2094 *dp == '`' || *dp == '\\') {
2108 warning("dhcp option too large");
2113 fork_privchld(int fd, int fd2)
2115 struct pollfd pfd[1];
2116 int nfds, pfail = 0;
2120 error("cannot fork");
2128 if (chdir("/") == -1)
2129 error("chdir(\"/\")");
2131 setproctitle("%s [priv]", ifi->name);
2133 dup2(nullfd, STDIN_FILENO);
2134 dup2(nullfd, STDOUT_FILENO);
2135 dup2(nullfd, STDERR_FILENO);
2141 pfd[0].events = POLLIN;
2142 if ((nfds = poll(pfd, 1, INFTIM)) == -1)
2144 error("poll error");
2147 * Handle temporary errors, but bail if they persist.
2149 if (nfds == 0 || !(pfd[0].revents & POLLIN)) {
2150 if (pfail > POLL_FAILURES)
2151 error("poll failed > %d times", POLL_FAILURES);
2152 sleep(pfail * POLL_FAILURE_WAIT);