1 /* $OpenBSD: dhclient.c,v 1.118 2008/05/09 05:19:14 reyk Exp $ */
2 /* $DragonFly: src/sbin/dhclient/dhclient.c,v 1.2 2008/09/10 10:01:18 matthias Exp $ */
5 * Copyright 2004 Henning Brauer <henning@openbsd.org>
6 * Copyright (c) 1995, 1996, 1997, 1998, 1999
7 * The Internet Software Consortium. All rights reserved.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. Neither the name of The Internet Software Consortium nor the names
19 * of its contributors may be used to endorse or promote products derived
20 * from this software without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE INTERNET SOFTWARE CONSORTIUM AND
23 * CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
24 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
25 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
26 * DISCLAIMED. IN NO EVENT SHALL THE INTERNET SOFTWARE CONSORTIUM OR
27 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
28 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
29 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
30 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
31 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
32 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
33 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 * This software has been written for the Internet Software Consortium
37 * by Ted Lemon <mellon@fugue.com> in cooperation with Vixie
38 * Enterprises. To learn more about the Internet Software Consortium,
39 * see ``http://www.vix.com/isc''. To learn more about Vixie
40 * Enterprises, see ``http://www.vix.com''.
42 * This client was substantially modified and enhanced by Elliot Poger
43 * for use on Linux while he was working on the MosquitoNet project at
46 * The current version owes much to Elliot's Linux enhancements, but
47 * was substantially reorganized and partially rewritten by Ted Lemon
48 * so as to use the same networking framework that the Internet Software
49 * Consortium DHCP server uses. Much system-specific configuration code
50 * was moved into a shell script so that as support for more operating
51 * systems is added, it will not be necessary to port and maintain
52 * system-specific configuration code to these operating systems - instead,
53 * the shell script can invoke the native tools to accomplish the same
65 #define CLIENT_PATH "PATH=/usr/bin:/usr/sbin:/bin:/sbin"
66 #define DEFAULT_LEASE_TIME 43200 /* 12 hours... */
67 #define TIME_MAX 2147483647
68 #define POLL_FAILURES 10
69 #define POLL_FAILURE_WAIT 1 /* Back off multiplier (seconds) */
73 char *path_dhclient_conf = _PATH_DHCLIENT_CONF;
74 char *path_dhclient_db = NULL;
83 struct iaddr iaddr_broadcast = { 4, { 255, 255, 255, 255 } };
84 struct in_addr inaddr_any;
85 struct sockaddr_in sockaddr_broadcast;
87 struct interface_info *ifi;
88 struct client_state *client;
89 struct client_config *config;
91 int findproto(char *, int);
92 struct sockaddr *get_ifa(char *, int);
94 int check_option(struct client_lease *l, int option);
95 int ipv4addrs(char * buf);
96 int res_hnok(const char *dn);
97 char *option_as_string(unsigned int code, unsigned char *data, int len);
98 int fork_privchld(int, int);
101 ((a) > 0 ? (1 + (((a) - 1) | (sizeof(long) - 1))) : sizeof(long))
102 #define ADVANCE(x, n) (x += ROUNDUP((n)->sa_len))
105 static FILE *leaseFile;
108 findproto(char *cp, int n)
115 for (i = 1; i; i <<= 1) {
117 sa = (struct sockaddr *)cp;
123 if (sa->sa_family == AF_INET)
125 if (sa->sa_family == AF_INET6)
138 get_ifa(char *cp, int n)
145 for (i = 1; i; i <<= 1)
147 sa = (struct sockaddr *)cp;
155 struct iaddr defaddr = { .len = 4 }; /* NULL is for silence warnings */
163 struct rt_msghdr *rtm;
164 struct if_msghdr *ifm;
165 struct ifa_msghdr *ifam;
166 struct if_announcemsghdr *ifan;
167 struct client_lease *l;
168 time_t t = time(NULL);
174 * Read one message non-blocking, ignore signals.
177 n = read(routefd, &msg, sizeof(msg));
178 } while (n == -1 && errno == EINTR);
181 * No operation if no messages ready or the message is
182 * not sized properly.
184 rtm = (struct rt_msghdr *)msg;
185 if (n < sizeof(rtm->rtm_msglen) || n < rtm->rtm_msglen ||
186 rtm->rtm_version != RTM_VERSION) {
191 * Process the message.
193 switch (rtm->rtm_type) {
195 ifam = (struct ifa_msghdr *)rtm;
196 if (ifam->ifam_index != ifi->index)
198 if (findproto((char *)(ifam + 1), ifam->ifam_addrs) != AF_INET)
200 sa = get_ifa((char *)(ifam + 1), ifam->ifam_addrs);
202 warning("RTM_NEWADDR: No IFA");
206 if ((a.len = sizeof(struct in_addr)) > sizeof(a.iabuf))
207 error("king bula sez: len mismatch");
208 memcpy(a.iabuf, &((struct sockaddr_in *)sa)->sin_addr, a.len);
209 if (addr_eq(a, defaddr))
212 for (l = client->active; l != NULL; l = l->next)
213 if (addr_eq(a, l->address))
216 if (l != NULL || (client->alias &&
217 addr_eq(a, client->alias->address)))
218 /* new addr is the one we set */
221 warning("RTM_NEWADDR: Our IFA not found");
224 ifam = (struct ifa_msghdr *)rtm;
225 if (ifam->ifam_index != ifi->index)
227 if (findproto((char *)(ifam + 1), ifam->ifam_addrs) != AF_INET)
229 if (scripttime == 0 || t < scripttime + 10)
231 warning("RTM_DELADDR: Third-party %d", (int)(t - scripttime));
234 ifm = (struct if_msghdr *)rtm;
235 if (ifm->ifm_index != ifi->index)
237 if ((rtm->rtm_flags & RTF_UP) == 0) {
238 warning("RTM_IFINFO: Interface not up");
243 LINK_STATE_IS_UP(ifm->ifm_data.ifi_link_state) ? 1 : 0;
244 if (linkstat != ifi->linkstat) {
245 debug("link state %s -> %s",
246 ifi->linkstat ? "up" : "down",
247 linkstat ? "up" : "down");
248 ifi->linkstat = interface_link_status(ifi->name);
250 client->state = S_INIT;
256 ifan = (struct if_announcemsghdr *)rtm;
257 if (ifan->ifan_what == IFAN_DEPARTURE &&
258 ifan->ifan_index == ifi->index) {
259 warning("RTM_IFANNOUNCE: Interface departure");
269 script_init("FAIL", NULL);
271 script_write_params("alias_", client->alias);
277 main(int argc, char *argv[])
279 int ch, fd, quiet = 0, i = 0, pipe_fd[2];
282 /* Initially, log errors to stderr as well as to syslogd. */
283 openlog(getprogname(), LOG_PID | LOG_NDELAY, DHCPD_LOG_FACILITY);
284 setlogmask(LOG_UPTO(LOG_INFO));
286 while ((ch = getopt(argc, argv, "c:dl:qu")) != -1)
289 path_dhclient_conf = optarg;
295 path_dhclient_db = optarg;
313 ifi = calloc(1, sizeof(*ifi));
316 client = calloc(1, sizeof(*client));
318 error("client calloc");
319 config = calloc(1, sizeof(*config));
321 error("config calloc");
323 if (strlcpy(ifi->name, argv[0], IFNAMSIZ) >= IFNAMSIZ)
324 error("Interface name too long");
325 if (path_dhclient_db == NULL && asprintf(&path_dhclient_db, "%s.%s",
326 _PATH_DHCLIENT_DB, ifi->name) == -1)
335 memset(&sockaddr_broadcast, 0, sizeof(sockaddr_broadcast));
336 sockaddr_broadcast.sin_family = AF_INET;
337 sockaddr_broadcast.sin_port = htons(REMOTE_PORT);
338 sockaddr_broadcast.sin_addr.s_addr = INADDR_BROADCAST;
339 sockaddr_broadcast.sin_len = sizeof(sockaddr_broadcast);
340 inaddr_any.s_addr = INADDR_ANY;
344 if (interface_status(ifi->name) == 0) {
345 interface_link_forceup(ifi->name);
346 /* Give it up to 4 seconds of silent grace to find link */
351 while (!(ifi->linkstat = interface_link_status(ifi->name))) {
353 fprintf(stderr, "%s: no link ...", ifi->name);
355 fprintf(stderr, ".");
357 if (++i > config->link_timeout) {
358 fprintf(stderr, " sleeping\n");
364 fprintf(stderr, " got link\n");
367 if ((nullfd = open(_PATH_DEVNULL, O_RDWR, 0)) == -1)
368 error("cannot open %s: %m", _PATH_DEVNULL);
370 if ((pw = getpwnam("_dhcp")) == NULL) {
371 warning("no such user: _dhcp, falling back to \"nobody\"");
372 if ((pw = getpwnam("nobody")) == NULL)
373 error("no such user: nobody");
376 if (pipe(pipe_fd) == -1)
379 fork_privchld(pipe_fd[0], pipe_fd[1]);
384 if ((fd = open(path_dhclient_db, O_RDONLY|O_EXLOCK|O_CREAT, 0)) == -1)
385 error("can't open and lock %s: %m", path_dhclient_db);
386 read_client_leases();
387 if ((leaseFile = fopen(path_dhclient_db, "w")) == NULL)
388 error("can't open %s: %m", path_dhclient_db);
389 rewrite_client_leases();
392 priv_script_init("PREINIT", NULL);
394 priv_script_write_params("alias_", client->alias);
397 if ((routefd = socket(PF_ROUTE, SOCK_RAW, 0)) == -1)
398 error("socket(PF_ROUTE, SOCK_RAW): %m");
400 /* set up the interface */
401 discover_interface();
403 if (chroot(_PATH_VAREMPTY) == -1)
405 if (chdir("/") == -1)
406 error("chdir(\"/\")");
408 if (setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) == -1)
410 if (setgroups(1, &pw->pw_gid) == -1)
412 if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) == -1)
417 setproctitle("%s", ifi->name);
420 client->state = S_INIT;
434 fprintf(stderr, "usage: %s [-dqu] [-c file] [-l file] interface\n",
442 * Each routine is called from the dhclient_state_machine() in one of
444 * -> entering INIT state
445 * -> recvpacket_flag == 0: timeout in this state
446 * -> otherwise: received a packet in this state
448 * Return conditions as handled by dhclient_state_machine():
449 * Returns 1, sendpacket_flag = 1: send packet, reset timer.
450 * Returns 1, sendpacket_flag = 0: just reset the timer (wait for a milestone).
451 * Returns 0: finish the nap which was interrupted for no good reason.
453 * Several per-interface variables are used to keep track of the process:
454 * active_lease: the lease that is being used on the interface
455 * (null pointer if not configured yet).
456 * offered_leases: leases corresponding to DHCPOFFER messages that have
457 * been sent to us by DHCP servers.
458 * acked_leases: leases corresponding to DHCPACK messages that have been
459 * sent to us by DHCP servers.
460 * sendpacket: DHCP packet we're trying to send.
461 * destination: IP address to send sendpacket to
462 * In addition, there are several relevant per-lease variables.
463 * T1_expiry, T2_expiry, lease_expiry: lease milestones
464 * In the active lease, these control the process of renewing the lease;
465 * In leases on the acked_leases list, this simply determines when we
466 * can no longer legitimately use the lease.
471 /* If we don't remember an active lease, go straight to INIT. */
472 if (!client->active || client->active->is_bootp) {
477 /* We are in the rebooting state. */
478 client->state = S_REBOOTING;
480 /* make_request doesn't initialize xid because it normally comes
481 from the DHCPDISCOVER, but we haven't sent a DHCPDISCOVER,
482 so pick an xid now. */
483 client->xid = arc4random();
485 /* Make a DHCPREQUEST packet, and set appropriate per-interface
487 make_request(client->active);
488 client->destination = iaddr_broadcast;
489 client->first_sending = cur_time;
490 client->interval = config->initial_interval;
492 /* Zap the medium list... */
493 client->medium = NULL;
495 /* Send out the first DHCPREQUEST packet. */
500 * Called when a lease has completely expired and we've
501 * been unable to renew it.
506 /* Make a DHCPDISCOVER packet, and set appropriate per-interface
508 make_discover(client->active);
509 client->xid = client->packet.xid;
510 client->destination = iaddr_broadcast;
511 client->state = S_SELECTING;
512 client->first_sending = cur_time;
513 client->interval = config->initial_interval;
515 /* Add an immediate timeout to cause the first DHCPDISCOVER packet
521 * state_selecting is called when one or more DHCPOFFER packets
522 * have been received and a configurable period of time has passed.
525 state_selecting(void)
527 struct client_lease *lp, *next, *picked;
529 /* Cancel state_selecting and send_discover timeouts, since either
530 one could have got us here. */
531 cancel_timeout(state_selecting);
532 cancel_timeout(send_discover);
534 /* We have received one or more DHCPOFFER packets. Currently,
535 the only criterion by which we judge leases is whether or
536 not we get a response when we arp for them. */
538 for (lp = client->offered_leases; lp; lp = next) {
541 /* Check to see if we got an ARPREPLY for the address
542 in this particular lease. */
544 script_init("ARPCHECK", lp->medium);
545 script_write_params("check_", lp);
547 /* If the ARPCHECK code detects another
548 machine using the offered address, it exits
549 nonzero. We need to send a DHCPDECLINE and
560 free_client_lease(lp);
563 client->offered_leases = NULL;
565 /* If we just tossed all the leases we were offered, go back
568 client->state = S_INIT;
573 /* If it was a BOOTREPLY, we can just take the address right now. */
574 if (!picked->options[DHO_DHCP_MESSAGE_TYPE].len) {
575 client->new = picked;
577 /* Make up some lease expiry times
578 XXX these should be configurable. */
579 client->new->expiry = cur_time + 12000;
580 client->new->renewal += cur_time + 8000;
581 client->new->rebind += cur_time + 10000;
583 client->state = S_REQUESTING;
585 /* Bind to the address we received. */
590 /* Go to the REQUESTING state. */
591 client->destination = iaddr_broadcast;
592 client->state = S_REQUESTING;
593 client->first_sending = cur_time;
594 client->interval = config->initial_interval;
596 /* Make a DHCPREQUEST packet from the lease we picked. */
597 make_request(picked);
598 client->xid = client->packet.xid;
600 /* Toss the lease we picked - we'll get it back in a DHCPACK. */
601 free_client_lease(picked);
603 /* Add an immediate timeout to send the first DHCPREQUEST packet. */
608 dhcpack(struct iaddr client_addr, struct option_data *options)
610 struct client_lease *lease;
612 if (client->xid != client->packet.xid)
615 if (client->state != S_REBOOTING &&
616 client->state != S_REQUESTING &&
617 client->state != S_RENEWING &&
618 client->state != S_REBINDING)
621 note("DHCPACK from %s", piaddr(client_addr));
623 lease = packet_to_lease(options);
625 note("packet_to_lease failed.");
631 /* Stop resending DHCPREQUEST. */
632 cancel_timeout(send_request);
634 /* Figure out the lease time. */
635 if (client->new->options[DHO_DHCP_LEASE_TIME].data)
636 client->new->expiry =
637 getULong(client->new->options[DHO_DHCP_LEASE_TIME].data);
639 client->new->expiry = DEFAULT_LEASE_TIME;
640 /* A number that looks negative here is really just very large,
641 because the lease expiry offset is unsigned. */
642 if (client->new->expiry < 0)
643 client->new->expiry = TIME_MAX;
644 /* XXX should be fixed by resetting the client state */
645 if (client->new->expiry < 60)
646 client->new->expiry = 60;
648 /* Take the server-provided renewal time if there is one;
649 otherwise figure it out according to the spec. */
650 if (client->new->options[DHO_DHCP_RENEWAL_TIME].len)
651 client->new->renewal =
652 getULong(client->new->options[DHO_DHCP_RENEWAL_TIME].data);
654 client->new->renewal = client->new->expiry / 2;
656 /* Same deal with the rebind time. */
657 if (client->new->options[DHO_DHCP_REBINDING_TIME].len)
658 client->new->rebind =
659 getULong(client->new->options[DHO_DHCP_REBINDING_TIME].data);
661 client->new->rebind = client->new->renewal +
662 client->new->renewal / 2 + client->new->renewal / 4;
664 client->new->expiry += cur_time;
665 /* Lease lengths can never be negative. */
666 if (client->new->expiry < cur_time)
667 client->new->expiry = TIME_MAX;
668 client->new->renewal += cur_time;
669 if (client->new->renewal < cur_time)
670 client->new->renewal = TIME_MAX;
671 client->new->rebind += cur_time;
672 if (client->new->rebind < cur_time)
673 client->new->rebind = TIME_MAX;
681 /* Remember the medium. */
682 client->new->medium = client->medium;
684 /* Write out the new lease. */
685 write_client_lease(client->new, 0);
687 /* Run the client script with the new parameters. */
688 script_init((client->state == S_REQUESTING ? "BOUND" :
689 (client->state == S_RENEWING ? "RENEW" :
690 (client->state == S_REBOOTING ? "REBOOT" : "REBIND"))),
691 client->new->medium);
692 if (client->active && client->state != S_REBOOTING)
693 script_write_params("old_", client->active);
694 script_write_params("new_", client->new);
696 script_write_params("alias_", client->alias);
699 /* Replace the old active lease with the new one. */
701 free_client_lease(client->active);
702 client->active = client->new;
705 /* Set up a timeout to start the renewal process. */
706 add_timeout(client->active->renewal, state_bound);
708 note("bound to %s -- renewal in %ld seconds.",
709 piaddr(client->active->address),
710 client->active->renewal - cur_time);
711 client->state = S_BOUND;
712 reinitialize_interface();
717 * state_bound is called when we've successfully bound to a particular
718 * lease, but the renewal time on that lease has expired. We are
719 * expected to unicast a DHCPREQUEST to the server that gave us our
725 /* T1 has expired. */
726 make_request(client->active);
727 client->xid = client->packet.xid;
729 if (client->active->options[DHO_DHCP_SERVER_IDENTIFIER].len == 4) {
730 memcpy(client->destination.iabuf,
731 client->active->options[DHO_DHCP_SERVER_IDENTIFIER].data,
733 client->destination.len = 4;
735 client->destination = iaddr_broadcast;
737 client->first_sending = cur_time;
738 client->interval = config->initial_interval;
739 client->state = S_RENEWING;
741 /* Send the first packet immediately. */
746 dhcpoffer(struct iaddr client_addr, struct option_data *options)
748 struct client_lease *lease, *lp;
750 int arp_timeout_needed, stop_selecting;
751 char *name = options[DHO_DHCP_MESSAGE_TYPE].len ? "DHCPOFFER" :
754 if (client->xid != client->packet.xid)
757 if (client->state != S_SELECTING)
760 note("%s from %s", name, piaddr(client_addr));
762 /* If this lease doesn't supply the minimum required parameters,
764 for (i = 0; config->required_options[i]; i++) {
765 if (!options[config->required_options[i]].len) {
766 note("%s isn't satisfactory.", name);
771 /* If we've already seen this lease, don't record it again. */
772 for (lease = client->offered_leases;
773 lease; lease = lease->next) {
774 if (lease->address.len == sizeof(client->packet.yiaddr) &&
775 !memcmp(lease->address.iabuf,
776 &client->packet.yiaddr, lease->address.len)) {
777 debug("%s already seen.", name);
782 lease = packet_to_lease(options);
784 note("packet_to_lease failed.");
788 /* If this lease was acquired through a BOOTREPLY, record that
790 if (!options[DHO_DHCP_MESSAGE_TYPE].len)
793 /* Record the medium under which this lease was offered. */
794 lease->medium = client->medium;
796 /* Send out an ARP Request for the offered IP address. */
797 script_init("ARPSEND", lease->medium);
798 script_write_params("check_", lease);
799 /* If the script can't send an ARP request without waiting,
800 we'll be waiting when we do the ARPCHECK, so don't wait now. */
802 arp_timeout_needed = 0;
804 arp_timeout_needed = 2;
806 /* Figure out when we're supposed to stop selecting. */
807 stop_selecting = client->first_sending + config->select_interval;
809 /* If this is the lease we asked for, put it at the head of the
810 list, and don't mess with the arp request timeout. */
811 if (lease->address.len == client->requested_address.len &&
812 !memcmp(lease->address.iabuf,
813 client->requested_address.iabuf,
814 client->requested_address.len)) {
815 lease->next = client->offered_leases;
816 client->offered_leases = lease;
818 /* If we already have an offer, and arping for this
819 offer would take us past the selection timeout,
820 then don't extend the timeout - just hope for the
822 if (client->offered_leases &&
823 (cur_time + arp_timeout_needed) > stop_selecting)
824 arp_timeout_needed = 0;
826 /* Put the lease at the end of the list. */
828 if (!client->offered_leases)
829 client->offered_leases = lease;
831 for (lp = client->offered_leases; lp->next;
838 /* If we're supposed to stop selecting before we've had time
839 to wait for the ARPREPLY, add some delay to wait for
841 if (stop_selecting - cur_time < arp_timeout_needed)
842 stop_selecting = cur_time + arp_timeout_needed;
844 /* If the selecting interval has expired, go immediately to
845 state_selecting(). Otherwise, time out into
846 state_selecting at the select interval. */
847 if (stop_selecting <= 0)
850 add_timeout(stop_selecting, state_selecting);
851 cancel_timeout(send_discover);
856 * Allocate a client_lease structure and initialize it from the
857 * parameters in the specified packet.
859 struct client_lease *
860 packet_to_lease(struct option_data *options)
862 struct client_lease *lease;
865 lease = malloc(sizeof(struct client_lease));
868 warning("dhcpoffer: no memory to record lease.");
872 memset(lease, 0, sizeof(*lease));
874 /* Copy the lease options. */
875 for (i = 0; i < 256; i++) {
876 if (options[i].len) {
877 lease->options[i] = options[i];
878 options[i].data = NULL;
880 if (!check_option(lease, i)) {
881 warning("Invalid lease option - ignoring offer");
882 free_client_lease(lease);
888 lease->address.len = sizeof(client->packet.yiaddr);
889 memcpy(lease->address.iabuf, &client->packet.yiaddr,
892 /* If the server name was filled out, copy it. */
893 if ((!lease->options[DHO_DHCP_OPTION_OVERLOAD].len ||
894 !(lease->options[DHO_DHCP_OPTION_OVERLOAD].data[0] & 2)) &&
895 client->packet.sname[0]) {
896 lease->server_name = malloc(DHCP_SNAME_LEN + 1);
897 if (!lease->server_name) {
898 warning("dhcpoffer: no memory for server name.");
899 free_client_lease(lease);
902 memcpy(lease->server_name, client->packet.sname,
904 lease->server_name[DHCP_SNAME_LEN] = '\0';
905 if (!res_hnok(lease->server_name)) {
906 warning("Bogus server name %s", lease->server_name);
907 free(lease->server_name);
908 lease->server_name = NULL;
912 /* Ditto for the filename. */
913 if ((!lease->options[DHO_DHCP_OPTION_OVERLOAD].len ||
914 !(lease->options[DHO_DHCP_OPTION_OVERLOAD].data[0] & 1)) &&
915 client->packet.file[0]) {
916 /* Don't count on the NUL terminator. */
917 lease->filename = malloc(DHCP_FILE_LEN + 1);
918 if (!lease->filename) {
919 warning("dhcpoffer: no memory for filename.");
920 free_client_lease(lease);
923 memcpy(lease->filename, client->packet.file, DHCP_FILE_LEN);
924 lease->filename[DHCP_FILE_LEN] = '\0';
930 dhcpnak(struct iaddr client_addr, struct option_data *options)
932 if (client->xid != client->packet.xid)
935 if (client->state != S_REBOOTING &&
936 client->state != S_REQUESTING &&
937 client->state != S_RENEWING &&
938 client->state != S_REBINDING)
941 note("DHCPNAK from %s", piaddr(client_addr));
943 if (!client->active) {
944 note("DHCPNAK with no active lease.");
948 free_client_lease(client->active);
949 client->active = NULL;
951 /* Stop sending DHCPREQUEST packets... */
952 cancel_timeout(send_request);
954 client->state = S_INIT;
959 * Send out a DHCPDISCOVER packet, and set a timeout to send out another
960 * one after the right interval has expired. If we don't get an offer by
961 * the time we reach the panic interval, call the panic function.
966 int interval, increase = 1;
968 /* Figure out how long it's been since we started transmitting. */
969 interval = cur_time - client->first_sending;
971 /* If we're past the panic timeout, call the script and tell it
972 we haven't found anything for this interface yet. */
973 if (interval > config->timeout) {
978 /* If we're selecting media, try the whole list before doing
979 the exponential backoff, but if we've already received an
980 offer, stop looping, because we obviously have it right. */
981 if (!client->offered_leases && config->media) {
984 if (client->medium) {
985 client->medium = client->medium->next;
988 if (!client->medium) {
990 error("No valid media types for %s!", ifi->name);
991 client->medium = config->media;
995 note("Trying medium \"%s\" %d", client->medium->string,
997 script_init("MEDIUM", client->medium);
1003 * If we're supposed to increase the interval, do so. If it's
1004 * currently zero (i.e., we haven't sent any packets yet), set
1005 * it to initial_interval; otherwise, add to it a random
1006 * number between zero and two times itself. On average, this
1007 * means that it will double with every transmission.
1010 if (!client->interval)
1011 client->interval = config->initial_interval;
1013 client->interval += (arc4random() >> 2) %
1014 (2 * client->interval);
1017 /* Don't backoff past cutoff. */
1018 if (client->interval > config->backoff_cutoff)
1019 client->interval = ((config->backoff_cutoff / 2)
1020 + ((arc4random() >> 2) %
1021 config->backoff_cutoff));
1022 } else if (!client->interval)
1023 client->interval = config->initial_interval;
1025 /* If the backoff would take us to the panic timeout, just use that
1027 if (cur_time + client->interval >
1028 client->first_sending + config->timeout)
1029 client->interval = (client->first_sending +
1030 config->timeout) - cur_time + 1;
1032 /* Record the number of seconds since we started sending. */
1033 if (interval < 65536)
1034 client->packet.secs = htons(interval);
1036 client->packet.secs = htons(65535);
1037 client->secs = client->packet.secs;
1039 note("DHCPDISCOVER on %s to %s port %d interval %ld",
1040 ifi->name, inet_ntoa(sockaddr_broadcast.sin_addr),
1041 ntohs(sockaddr_broadcast.sin_port), client->interval);
1043 /* Send out a packet. */
1044 send_packet(inaddr_any, &sockaddr_broadcast, NULL);
1046 add_timeout(cur_time + client->interval, send_discover);
1050 * state_panic gets called if we haven't received any offers in a preset
1051 * amount of time. When this happens, we try to use existing leases
1052 * that haven't yet expired, and failing that, we call the client script
1053 * and hope it can do something.
1058 struct client_lease *loop = client->active;
1059 struct client_lease *lp;
1061 note("No DHCPOFFERS received.");
1063 /* We may not have an active lease, but we may have some
1064 predefined leases that we can try. */
1065 if (!client->active && client->leases)
1068 /* Run through the list of leases and see if one can be used. */
1069 while (client->active) {
1070 if (client->active->expiry > cur_time) {
1071 note("Trying recorded lease %s",
1072 piaddr(client->active->address));
1073 /* Run the client script with the existing
1075 script_init("TIMEOUT",
1076 client->active->medium);
1077 script_write_params("new_", client->active);
1079 script_write_params("alias_",
1082 /* If the old lease is still good and doesn't
1083 yet need renewal, go into BOUND state and
1084 timeout at the renewal time. */
1087 client->active->renewal) {
1088 client->state = S_BOUND;
1089 note("bound: renewal in %ld seconds.",
1090 client->active->renewal -
1092 add_timeout(client->active->renewal,
1095 client->state = S_BOUND;
1096 note("bound: immediate renewal.");
1099 reinitialize_interface();
1105 /* If there are no other leases, give up. */
1106 if (!client->leases) {
1107 client->leases = client->active;
1108 client->active = NULL;
1113 /* Otherwise, put the active lease at the end of the
1114 lease list, and try another lease.. */
1115 for (lp = client->leases; lp->next; lp = lp->next)
1117 lp->next = client->active;
1119 lp->next->next = NULL;
1120 client->active = client->leases;
1121 client->leases = client->leases->next;
1123 /* If we already tried this lease, we've exhausted the
1124 set of leases, so we might as well give up for
1126 if (client->active == loop)
1129 loop = client->active;
1132 /* No leases were available, or what was available didn't work, so
1133 tell the shell script that we failed to allocate an address,
1134 and try again later. */
1135 note("No working leases in persistent database - sleeping.");
1136 script_init("FAIL", NULL);
1138 script_write_params("alias_", client->alias);
1140 client->state = S_INIT;
1141 add_timeout(cur_time + config->retry_interval, state_init);
1148 struct sockaddr_in destination;
1149 struct in_addr from;
1152 /* Figure out how long it's been since we started transmitting. */
1153 interval = cur_time - client->first_sending;
1155 /* If we're in the INIT-REBOOT or REQUESTING state and we're
1156 past the reboot timeout, go to INIT and see if we can
1157 DISCOVER an address... */
1158 /* XXX In the INIT-REBOOT state, if we don't get an ACK, it
1159 means either that we're on a network with no DHCP server,
1160 or that our server is down. In the latter case, assuming
1161 that there is a backup DHCP server, DHCPDISCOVER will get
1162 us a new address, but we could also have successfully
1163 reused our old address. In the former case, we're hosed
1164 anyway. This is not a win-prone situation. */
1165 if ((client->state == S_REBOOTING ||
1166 client->state == S_REQUESTING) &&
1167 interval > config->reboot_timeout) {
1169 client->state = S_INIT;
1170 cancel_timeout(send_request);
1175 /* If we're in the reboot state, make sure the media is set up
1177 if (client->state == S_REBOOTING &&
1179 client->active->medium) {
1180 script_init("MEDIUM", client->active->medium);
1182 /* If the medium we chose won't fly, go to INIT state. */
1186 /* Record the medium. */
1187 client->medium = client->active->medium;
1190 /* If the lease has expired, relinquish the address and go back
1191 to the INIT state. */
1192 if (client->state != S_REQUESTING &&
1193 cur_time > client->active->expiry) {
1194 /* Run the client script with the new parameters. */
1195 script_init("EXPIRE", NULL);
1196 script_write_params("old_", client->active);
1198 script_write_params("alias_", client->alias);
1201 /* Now do a preinit on the interface so that we can
1202 discover a new address. */
1203 script_init("PREINIT", NULL);
1205 script_write_params("alias_", client->alias);
1208 client->state = S_INIT;
1213 /* Do the exponential backoff... */
1214 if (!client->interval)
1215 client->interval = config->initial_interval;
1217 client->interval += ((arc4random() >> 2) %
1218 (2 * client->interval));
1220 /* Don't backoff past cutoff. */
1221 if (client->interval > config->backoff_cutoff)
1222 client->interval = ((config->backoff_cutoff / 2) +
1223 ((arc4random() >> 2) % client->interval));
1225 /* If the backoff would take us to the expiry time, just set the
1226 timeout to the expiry time. */
1227 if (client->state != S_REQUESTING && cur_time + client->interval >
1228 client->active->expiry)
1229 client->interval = client->active->expiry - cur_time + 1;
1231 /* If the lease T2 time has elapsed, or if we're not yet bound,
1232 broadcast the DHCPREQUEST rather than unicasting. */
1233 memset(&destination, 0, sizeof(destination));
1234 if (client->state == S_REQUESTING ||
1235 client->state == S_REBOOTING ||
1236 cur_time > client->active->rebind)
1237 destination.sin_addr.s_addr = INADDR_BROADCAST;
1239 memcpy(&destination.sin_addr.s_addr, client->destination.iabuf,
1240 sizeof(destination.sin_addr.s_addr));
1241 destination.sin_port = htons(REMOTE_PORT);
1242 destination.sin_family = AF_INET;
1243 destination.sin_len = sizeof(destination);
1245 if (client->state != S_REQUESTING)
1246 memcpy(&from, client->active->address.iabuf, sizeof(from));
1248 from.s_addr = INADDR_ANY;
1250 /* Record the number of seconds since we started sending. */
1251 if (client->state == S_REQUESTING)
1252 client->packet.secs = client->secs;
1254 if (interval < 65536)
1255 client->packet.secs = htons(interval);
1257 client->packet.secs = htons(65535);
1260 note("DHCPREQUEST on %s to %s port %d", ifi->name,
1261 inet_ntoa(destination.sin_addr), ntohs(destination.sin_port));
1263 /* Send out a packet. */
1264 send_packet(from, &destination, NULL);
1266 add_timeout(cur_time + client->interval, send_request);
1272 note("DHCPDECLINE on %s to %s port %d", ifi->name,
1273 inet_ntoa(sockaddr_broadcast.sin_addr),
1274 ntohs(sockaddr_broadcast.sin_port));
1276 /* Send out a packet. */
1277 send_packet(inaddr_any, &sockaddr_broadcast, NULL);
1281 make_discover(struct client_lease *lease)
1283 unsigned char discover = DHCPDISCOVER;
1284 struct option_data options[256];
1287 memset(options, 0, sizeof(options));
1288 memset(&client->packet, 0, sizeof(client->packet));
1290 /* Set DHCP_MESSAGE_TYPE to DHCPDISCOVER */
1291 i = DHO_DHCP_MESSAGE_TYPE;
1292 options[i].data = &discover;
1293 options[i].len = sizeof(discover);
1295 /* Request the options we want */
1296 i = DHO_DHCP_PARAMETER_REQUEST_LIST;
1297 options[i].data = config->requested_options;
1298 options[i].len = config->requested_option_count;
1300 /* If we had an address, try to get it again. */
1302 client->requested_address = lease->address;
1303 i = DHO_DHCP_REQUESTED_ADDRESS;
1304 options[i].data = lease->address.iabuf;
1305 options[i].len = lease->address.len;
1307 client->requested_address.len = 0;
1309 /* Send any options requested in the config file. */
1310 for (i = 0; i < 256; i++)
1311 if (!options[i].data &&
1312 config->send_options[i].data) {
1313 options[i].data = config->send_options[i].data;
1314 options[i].len = config->send_options[i].len;
1317 /* Set up the option buffer to fit in a minimal UDP packet. */
1318 i = cons_options(client->packet.options, 576 - DHCP_FIXED_LEN,
1320 if (i == -1 || client->packet.options[i] != DHO_END)
1321 error("options do not fit in DHCPDISCOVER packet.");
1322 client->packet_length = DHCP_FIXED_NON_UDP+i+1;
1323 if (client->packet_length < BOOTP_MIN_LEN)
1324 client->packet_length = BOOTP_MIN_LEN;
1326 client->packet.op = BOOTREQUEST;
1327 client->packet.htype = ifi->hw_address.htype;
1328 client->packet.hlen = ifi->hw_address.hlen;
1329 client->packet.hops = 0;
1330 client->packet.xid = arc4random();
1331 client->packet.secs = 0; /* filled in by send_discover. */
1332 client->packet.flags = 0;
1334 memset(&client->packet.ciaddr, 0, sizeof(client->packet.ciaddr));
1335 memset(&client->packet.yiaddr, 0, sizeof(client->packet.yiaddr));
1336 memset(&client->packet.siaddr, 0, sizeof(client->packet.siaddr));
1337 memset(&client->packet.giaddr, 0, sizeof(client->packet.giaddr));
1338 memcpy(client->packet.chaddr, ifi->hw_address.haddr,
1339 ifi->hw_address.hlen);
1343 make_request(struct client_lease * lease)
1345 unsigned char request = DHCPREQUEST;
1346 struct option_data options[256];
1349 memset(options, 0, sizeof(options));
1350 memset(&client->packet, 0, sizeof(client->packet));
1352 /* Set DHCP_MESSAGE_TYPE to DHCPREQUEST */
1353 i = DHO_DHCP_MESSAGE_TYPE;
1354 options[i].data = &request;
1355 options[i].len = sizeof(request);
1357 /* Request the options we want */
1358 i = DHO_DHCP_PARAMETER_REQUEST_LIST;
1359 options[i].data = config->requested_options;
1360 options[i].len = config->requested_option_count;
1362 /* If we are requesting an address that hasn't yet been assigned
1363 to us, use the DHCP Requested Address option. */
1364 if (client->state == S_REQUESTING) {
1365 /* Send back the server identifier... */
1366 i = DHO_DHCP_SERVER_IDENTIFIER;
1367 options[i].data = lease->options[i].data;
1368 options[i].len = lease->options[i].len;
1370 if (client->state == S_REQUESTING ||
1371 client->state == S_REBOOTING) {
1372 client->requested_address = lease->address;
1373 i = DHO_DHCP_REQUESTED_ADDRESS;
1374 options[i].data = lease->address.iabuf;
1375 options[i].len = lease->address.len;
1377 client->requested_address.len = 0;
1379 /* Send any options requested in the config file. */
1380 for (i = 0; i < 256; i++)
1381 if (!options[i].data && config->send_options[i].data) {
1382 options[i].data = config->send_options[i].data;
1383 options[i].len = config->send_options[i].len;
1386 /* Set up the option buffer to fit in a minimal UDP packet. */
1387 i = cons_options(client->packet.options, 576 - DHCP_FIXED_LEN,
1389 if (i == -1 || client->packet.options[i] != DHO_END)
1390 error("options do not fit in DHCPREQUEST packet.");
1391 client->packet_length = DHCP_FIXED_NON_UDP+i+1;
1392 if (client->packet_length < BOOTP_MIN_LEN)
1393 client->packet_length = BOOTP_MIN_LEN;
1395 client->packet.op = BOOTREQUEST;
1396 client->packet.htype = ifi->hw_address.htype;
1397 client->packet.hlen = ifi->hw_address.hlen;
1398 client->packet.hops = 0;
1399 client->packet.xid = client->xid;
1400 client->packet.secs = 0; /* Filled in by send_request. */
1401 client->packet.flags = 0;
1403 /* If we own the address we're requesting, put it in ciaddr;
1404 otherwise set ciaddr to zero. */
1405 if (client->state == S_BOUND ||
1406 client->state == S_RENEWING ||
1407 client->state == S_REBINDING) {
1408 memcpy(&client->packet.ciaddr,
1409 lease->address.iabuf, lease->address.len);
1411 memset(&client->packet.ciaddr, 0,
1412 sizeof(client->packet.ciaddr));
1415 memset(&client->packet.yiaddr, 0, sizeof(client->packet.yiaddr));
1416 memset(&client->packet.siaddr, 0, sizeof(client->packet.siaddr));
1417 memset(&client->packet.giaddr, 0, sizeof(client->packet.giaddr));
1418 memcpy(client->packet.chaddr, ifi->hw_address.haddr,
1419 ifi->hw_address.hlen);
1423 make_decline(struct client_lease *lease)
1425 struct option_data options[256];
1426 unsigned char decline = DHCPDECLINE;
1429 memset(options, 0, sizeof(options));
1430 memset(&client->packet, 0, sizeof(client->packet));
1432 /* Set DHCP_MESSAGE_TYPE to DHCPDECLINE */
1433 i = DHO_DHCP_MESSAGE_TYPE;
1434 options[i].data = &decline;
1435 options[i].len = sizeof(decline);
1437 /* Send back the server identifier... */
1438 i = DHO_DHCP_SERVER_IDENTIFIER;
1439 options[i].data = lease->options[i].data;
1440 options[i].len = lease->options[i].len;
1442 /* Send back the address we're declining. */
1443 i = DHO_DHCP_REQUESTED_ADDRESS;
1444 options[i].data = lease->address.iabuf;
1445 options[i].len = lease->address.len;
1447 /* Send the uid if the user supplied one. */
1448 i = DHO_DHCP_CLIENT_IDENTIFIER;
1449 if (config->send_options[i].len) {
1450 options[i].data = config->send_options[i].data;
1451 options[i].len = config->send_options[i].len;
1454 /* Set up the option buffer to fit in a minimal UDP packet. */
1455 i = cons_options(client->packet.options, 576 - DHCP_FIXED_LEN,
1457 if (i == -1 || client->packet.options[i] != DHO_END)
1458 error("options do not fit in DHCPDECLINE packet.");
1459 client->packet_length = DHCP_FIXED_NON_UDP+i+1;
1460 if (client->packet_length < BOOTP_MIN_LEN)
1461 client->packet_length = BOOTP_MIN_LEN;
1463 client->packet.op = BOOTREQUEST;
1464 client->packet.htype = ifi->hw_address.htype;
1465 client->packet.hlen = ifi->hw_address.hlen;
1466 client->packet.hops = 0;
1467 client->packet.xid = client->xid;
1468 client->packet.secs = 0; /* Filled in by send_request. */
1469 client->packet.flags = 0;
1471 /* ciaddr must always be zero. */
1472 memset(&client->packet.ciaddr, 0, sizeof(client->packet.ciaddr));
1473 memset(&client->packet.yiaddr, 0, sizeof(client->packet.yiaddr));
1474 memset(&client->packet.siaddr, 0, sizeof(client->packet.siaddr));
1475 memset(&client->packet.giaddr, 0, sizeof(client->packet.giaddr));
1476 memcpy(client->packet.chaddr, ifi->hw_address.haddr,
1477 ifi->hw_address.hlen);
1481 free_client_lease(struct client_lease *lease)
1485 if (lease->server_name)
1486 free(lease->server_name);
1487 if (lease->filename)
1488 free(lease->filename);
1489 for (i = 0; i < 256; i++) {
1490 if (lease->options[i].len)
1491 free(lease->options[i].data);
1497 rewrite_client_leases(void)
1499 struct client_lease *lp;
1501 if (!leaseFile) /* XXX */
1502 error("lease file not open");
1507 for (lp = client->leases; lp; lp = lp->next)
1508 write_client_lease(lp, 1);
1510 write_client_lease(client->active, 1);
1513 ftruncate(fileno(leaseFile), ftello(leaseFile));
1514 fsync(fileno(leaseFile));
1518 write_client_lease(struct client_lease *lease, int rewrite)
1520 static int leases_written;
1525 if (leases_written++ > 20) {
1526 rewrite_client_leases();
1531 /* If the lease came from the config file, we don't need to stash
1532 a copy in the lease database. */
1533 if (lease->is_static)
1536 if (!leaseFile) /* XXX */
1537 error("lease file not open");
1539 fprintf(leaseFile, "lease {\n");
1540 if (lease->is_bootp)
1541 fprintf(leaseFile, " bootp;\n");
1542 fprintf(leaseFile, " interface \"%s\";\n", ifi->name);
1543 fprintf(leaseFile, " fixed-address %s;\n", piaddr(lease->address));
1544 if (lease->filename)
1545 fprintf(leaseFile, " filename \"%s\";\n", lease->filename);
1546 if (lease->server_name)
1547 fprintf(leaseFile, " server-name \"%s\";\n",
1548 lease->server_name);
1550 fprintf(leaseFile, " medium \"%s\";\n", lease->medium->string);
1551 for (i = 0; i < 256; i++)
1552 if (lease->options[i].len)
1553 fprintf(leaseFile, " option %s %s;\n",
1554 dhcp_options[i].name,
1555 pretty_print_option(i, lease->options[i].data,
1556 lease->options[i].len, 1, 1));
1558 t = gmtime(&lease->renewal);
1559 fprintf(leaseFile, " renew %d %d/%d/%d %02d:%02d:%02d;\n",
1560 t->tm_wday, t->tm_year + 1900, t->tm_mon + 1, t->tm_mday,
1561 t->tm_hour, t->tm_min, t->tm_sec);
1562 t = gmtime(&lease->rebind);
1563 fprintf(leaseFile, " rebind %d %d/%d/%d %02d:%02d:%02d;\n",
1564 t->tm_wday, t->tm_year + 1900, t->tm_mon + 1, t->tm_mday,
1565 t->tm_hour, t->tm_min, t->tm_sec);
1566 t = gmtime(&lease->expiry);
1567 fprintf(leaseFile, " expire %d %d/%d/%d %02d:%02d:%02d;\n",
1568 t->tm_wday, t->tm_year + 1900, t->tm_mon + 1, t->tm_mday,
1569 t->tm_hour, t->tm_min, t->tm_sec);
1570 fprintf(leaseFile, "}\n");
1575 script_init(char *reason, struct string_list *medium)
1577 size_t len, mediumlen = 0;
1578 struct imsg_hdr hdr;
1581 if (medium != NULL && medium->string != NULL)
1582 mediumlen = strlen(medium->string);
1584 hdr.code = IMSG_SCRIPT_INIT;
1585 hdr.len = sizeof(struct imsg_hdr) +
1586 sizeof(size_t) + mediumlen +
1587 sizeof(size_t) + strlen(reason);
1589 buf = buf_open(hdr.len);
1591 buf_add(buf, &hdr, sizeof(hdr));
1592 buf_add(buf, &mediumlen, sizeof(mediumlen));
1594 buf_add(buf, medium->string, mediumlen);
1595 len = strlen(reason);
1596 buf_add(buf, &len, sizeof(len));
1597 buf_add(buf, reason, len);
1599 buf_close(privfd, buf);
1603 priv_script_init(char *reason, char *medium)
1605 client->scriptEnvsize = 100;
1606 if (client->scriptEnv == NULL)
1608 calloc(client->scriptEnvsize, sizeof(char *));
1609 if (client->scriptEnv == NULL)
1610 error("script_init: no memory for environment");
1612 client->scriptEnv[0] = strdup(CLIENT_PATH);
1613 if (client->scriptEnv[0] == NULL)
1614 error("script_init: no memory for environment");
1616 client->scriptEnv[1] = NULL;
1618 script_set_env("", "interface", ifi->name);
1621 script_set_env("", "medium", medium);
1623 script_set_env("", "reason", reason);
1627 priv_script_write_params(char *prefix, struct client_lease *lease)
1629 u_int8_t dbuf[1500];
1633 script_set_env(prefix, "ip_address", piaddr(lease->address));
1635 if (lease->options[DHO_SUBNET_MASK].len &&
1636 (lease->options[DHO_SUBNET_MASK].len <
1637 sizeof(lease->address.iabuf))) {
1638 struct iaddr netmask, subnet, broadcast;
1640 memcpy(netmask.iabuf, lease->options[DHO_SUBNET_MASK].data,
1641 lease->options[DHO_SUBNET_MASK].len);
1642 netmask.len = lease->options[DHO_SUBNET_MASK].len;
1644 subnet = subnet_number(lease->address, netmask);
1646 script_set_env(prefix, "network_number",
1648 if (!lease->options[DHO_BROADCAST_ADDRESS].len) {
1649 broadcast = broadcast_addr(subnet, netmask);
1651 script_set_env(prefix,
1652 "broadcast_address",
1658 if (lease->filename)
1659 script_set_env(prefix, "filename", lease->filename);
1660 if (lease->server_name)
1661 script_set_env(prefix, "server_name",
1662 lease->server_name);
1663 for (i = 0; i < 256; i++) {
1664 u_int8_t *dp = NULL;
1666 if (config->defaults[i].len) {
1667 if (lease->options[i].len) {
1668 switch (config->default_actions[i]) {
1669 case ACTION_DEFAULT:
1670 dp = lease->options[i].data;
1671 len = lease->options[i].len;
1673 case ACTION_SUPERSEDE:
1675 dp = config->defaults[i].data;
1676 len = config->defaults[i].len;
1678 case ACTION_PREPEND:
1679 len = config->defaults[i].len +
1680 lease->options[i].len;
1681 if (len > sizeof(dbuf)) {
1682 warning("no space to %s %s",
1684 dhcp_options[i].name);
1689 config->defaults[i].data,
1690 config->defaults[i].len);
1692 config->defaults[i].len,
1693 lease->options[i].data,
1694 lease->options[i].len);
1698 len = config->defaults[i].len +
1699 lease->options[i].len;
1700 if (len > sizeof(dbuf)) {
1701 warning("no space to %s %s",
1703 dhcp_options[i].name);
1707 memcpy(dp, lease->options[i].data,
1708 lease->options[i].len);
1709 memcpy(dp + lease->options[i].len,
1710 config->defaults[i].data,
1711 config->defaults[i].len);
1715 dp = config->defaults[i].data;
1716 len = config->defaults[i].len;
1718 } else if (lease->options[i].len) {
1719 len = lease->options[i].len;
1720 dp = lease->options[i].data;
1727 if (dhcp_option_ev_name(name, sizeof(name),
1729 script_set_env(prefix, name,
1730 pretty_print_option(i, dp, len, 0, 0));
1733 snprintf(tbuf, sizeof(tbuf), "%d", (int)lease->expiry);
1734 script_set_env(prefix, "expiry", tbuf);
1738 script_write_params(char *prefix, struct client_lease *lease)
1740 size_t fn_len = 0, sn_len = 0, pr_len = 0;
1741 struct imsg_hdr hdr;
1745 if (lease->filename != NULL)
1746 fn_len = strlen(lease->filename);
1747 if (lease->server_name != NULL)
1748 sn_len = strlen(lease->server_name);
1750 pr_len = strlen(prefix);
1752 hdr.code = IMSG_SCRIPT_WRITE_PARAMS;
1753 hdr.len = sizeof(hdr) + sizeof(struct client_lease) +
1754 sizeof(size_t) + fn_len + sizeof(size_t) + sn_len +
1755 sizeof(size_t) + pr_len;
1757 for (i = 0; i < 256; i++)
1758 hdr.len += sizeof(int) + lease->options[i].len;
1760 scripttime = time(NULL);
1762 buf = buf_open(hdr.len);
1764 buf_add(buf, &hdr, sizeof(hdr));
1765 buf_add(buf, lease, sizeof(struct client_lease));
1766 buf_add(buf, &fn_len, sizeof(fn_len));
1767 buf_add(buf, lease->filename, fn_len);
1768 buf_add(buf, &sn_len, sizeof(sn_len));
1769 buf_add(buf, lease->server_name, sn_len);
1770 buf_add(buf, &pr_len, sizeof(pr_len));
1771 buf_add(buf, prefix, pr_len);
1773 for (i = 0; i < 256; i++) {
1774 buf_add(buf, &lease->options[i].len,
1775 sizeof(lease->options[i].len));
1776 buf_add(buf, lease->options[i].data,
1777 lease->options[i].len);
1780 buf_close(privfd, buf);
1786 struct imsg_hdr hdr;
1790 scripttime = time(NULL);
1792 hdr.code = IMSG_SCRIPT_GO;
1793 hdr.len = sizeof(struct imsg_hdr);
1795 buf = buf_open(hdr.len);
1797 buf_add(buf, &hdr, sizeof(hdr));
1798 buf_close(privfd, buf);
1800 bzero(&hdr, sizeof(hdr));
1801 buf_read(privfd, &hdr, sizeof(hdr));
1802 if (hdr.code != IMSG_SCRIPT_GO_RET)
1803 error("unexpected msg type %u", hdr.code);
1804 if (hdr.len != sizeof(hdr) + sizeof(int))
1805 error("received corrupted message");
1806 buf_read(privfd, &ret, sizeof(ret));
1812 priv_script_go(void)
1814 char *scriptName, *argv[2], **envp;
1815 int pid, wpid, wstatus;
1817 scripttime = time(NULL);
1819 scriptName = config->script_name;
1820 envp = client->scriptEnv;
1822 argv[0] = scriptName;
1831 wpid = wait(&wstatus);
1832 } while (wpid != pid && wpid > 0);
1838 execve(scriptName, argv, envp);
1839 error("execve (%s, ...): %m", scriptName);
1844 return (WEXITSTATUS(wstatus));
1848 script_set_env(const char *prefix, const char *name, const char *value)
1852 namelen = strlen(name);
1854 for (i = 0; client->scriptEnv[i]; i++)
1855 if (strncmp(client->scriptEnv[i], name, namelen) == 0 &&
1856 client->scriptEnv[i][namelen] == '=')
1859 if (client->scriptEnv[i])
1860 /* Reuse the slot. */
1861 free(client->scriptEnv[i]);
1863 /* New variable. Expand if necessary. */
1864 if (i >= client->scriptEnvsize - 1) {
1865 char **newscriptEnv;
1866 int newscriptEnvsize = client->scriptEnvsize + 50;
1868 newscriptEnv = realloc(client->scriptEnv,
1870 if (newscriptEnv == NULL) {
1871 free(client->scriptEnv);
1872 client->scriptEnv = NULL;
1873 client->scriptEnvsize = 0;
1874 error("script_set_env: no memory for variable");
1876 client->scriptEnv = newscriptEnv;
1877 client->scriptEnvsize = newscriptEnvsize;
1879 /* need to set the NULL pointer at end of array beyond
1881 client->scriptEnv[i + 1] = NULL;
1883 /* Allocate space and format the variable in the appropriate slot. */
1884 client->scriptEnv[i] = malloc(strlen(prefix) + strlen(name) + 1 +
1886 if (client->scriptEnv[i] == NULL)
1887 error("script_set_env: no memory for variable assignment");
1889 /* No `` or $() command substitution allowed in environment values! */
1890 for (j = 0; j < strlen(value); j++)
1894 error("illegal character (%c) in value '%s'", value[j],
1898 snprintf(client->scriptEnv[i], strlen(prefix) + strlen(name) +
1899 1 + strlen(value) + 1, "%s%s=%s", prefix, name, value);
1903 script_flush_env(void)
1907 for (i = 0; client->scriptEnv[i]; i++) {
1908 free(client->scriptEnv[i]);
1909 client->scriptEnv[i] = NULL;
1911 client->scriptEnvsize = 0;
1915 dhcp_option_ev_name(char *buf, size_t buflen, const struct option *option)
1919 for (i = 0; option->name[i]; i++) {
1920 if (i + 1 == buflen)
1922 if (option->name[i] == '-')
1925 buf[i] = option->name[i];
1935 static int state = 0;
1937 if (no_daemon || state)
1942 /* Stop logging to stderr... */
1945 if (daemon(1, 0) == -1)
1948 /* we are chrooted, daemon(3) fails to open /dev/null */
1950 dup2(nullfd, STDIN_FILENO);
1951 dup2(nullfd, STDOUT_FILENO);
1952 dup2(nullfd, STDERR_FILENO);
1959 check_option(struct client_lease *l, int option)
1964 /* we use this, since this is what gets passed to dhclient-script */
1966 opbuf = pretty_print_option(option, l->options[option].data,
1967 l->options[option].len, 0, 0);
1969 sbuf = option_as_string(option, l->options[option].data,
1970 l->options[option].len);
1973 case DHO_SUBNET_MASK:
1974 case DHO_TIME_SERVERS:
1975 case DHO_NAME_SERVERS:
1977 case DHO_DOMAIN_NAME_SERVERS:
1978 case DHO_LOG_SERVERS:
1979 case DHO_COOKIE_SERVERS:
1980 case DHO_LPR_SERVERS:
1981 case DHO_IMPRESS_SERVERS:
1982 case DHO_RESOURCE_LOCATION_SERVERS:
1983 case DHO_SWAP_SERVER:
1984 case DHO_BROADCAST_ADDRESS:
1985 case DHO_NIS_SERVERS:
1986 case DHO_NTP_SERVERS:
1987 case DHO_NETBIOS_NAME_SERVERS:
1988 case DHO_NETBIOS_DD_SERVER:
1989 case DHO_FONT_SERVERS:
1990 case DHO_DHCP_SERVER_IDENTIFIER:
1991 if (!ipv4addrs(opbuf)) {
1992 warning("Invalid IP address in option: %s", opbuf);
1997 case DHO_DOMAIN_NAME:
1998 case DHO_NIS_DOMAIN:
1999 if (!res_hnok(sbuf)) {
2000 warning("Bogus Host Name option %d: %s (%s)", option,
2002 l->options[option].len = 0;
2003 free(l->options[option].data);
2007 case DHO_TIME_OFFSET:
2009 case DHO_MERIT_DUMP:
2011 case DHO_EXTENSIONS_PATH:
2012 case DHO_IP_FORWARDING:
2013 case DHO_NON_LOCAL_SOURCE_ROUTING:
2014 case DHO_POLICY_FILTER:
2015 case DHO_MAX_DGRAM_REASSEMBLY:
2016 case DHO_DEFAULT_IP_TTL:
2017 case DHO_PATH_MTU_AGING_TIMEOUT:
2018 case DHO_PATH_MTU_PLATEAU_TABLE:
2019 case DHO_INTERFACE_MTU:
2020 case DHO_ALL_SUBNETS_LOCAL:
2021 case DHO_PERFORM_MASK_DISCOVERY:
2022 case DHO_MASK_SUPPLIER:
2023 case DHO_ROUTER_DISCOVERY:
2024 case DHO_ROUTER_SOLICITATION_ADDRESS:
2025 case DHO_STATIC_ROUTES:
2026 case DHO_TRAILER_ENCAPSULATION:
2027 case DHO_ARP_CACHE_TIMEOUT:
2028 case DHO_IEEE802_3_ENCAPSULATION:
2029 case DHO_DEFAULT_TCP_TTL:
2030 case DHO_TCP_KEEPALIVE_INTERVAL:
2031 case DHO_TCP_KEEPALIVE_GARBAGE:
2032 case DHO_VENDOR_ENCAPSULATED_OPTIONS:
2033 case DHO_NETBIOS_NODE_TYPE:
2034 case DHO_NETBIOS_SCOPE:
2035 case DHO_X_DISPLAY_MANAGER:
2036 case DHO_DHCP_REQUESTED_ADDRESS:
2037 case DHO_DHCP_LEASE_TIME:
2038 case DHO_DHCP_OPTION_OVERLOAD:
2039 case DHO_DHCP_MESSAGE_TYPE:
2040 case DHO_DHCP_PARAMETER_REQUEST_LIST:
2041 case DHO_DHCP_MESSAGE:
2042 case DHO_DHCP_MAX_MESSAGE_SIZE:
2043 case DHO_DHCP_RENEWAL_TIME:
2044 case DHO_DHCP_REBINDING_TIME:
2045 case DHO_DHCP_CLASS_IDENTIFIER:
2046 case DHO_DHCP_CLIENT_IDENTIFIER:
2047 case DHO_DHCP_USER_CLASS_ID:
2051 warning("unknown dhcp option value 0x%x", option);
2052 return (unknown_ok);
2057 res_hnok(const char *name)
2059 const char *dn = name;
2060 int pch = '.', ch = *dn++;
2063 while (ch != '\0') {
2068 } else if (pch == '.' || nch == '.' || nch == '\0') {
2071 } else if (!isalnum(ch) && ch != '-' && ch != '_')
2073 else if (ch == '_' && warn == 0) {
2074 warning("warning: hostname %s contains an "
2075 "underscore which violates RFC 952", name);
2083 /* Does buf consist only of dotted decimal ipv4 addrs?
2084 * return how many if so,
2085 * otherwise, return 0
2088 ipv4addrs(char * buf)
2093 while (inet_aton(buf, &jnk) == 1){
2095 while (*buf == '.' || isdigit(*buf))
2106 option_as_string(unsigned int code, unsigned char *data, int len)
2108 static char optbuf[32768]; /* XXX */
2110 int opleft = sizeof(optbuf);
2111 unsigned char *dp = data;
2114 error("option_as_string: bad code %d", code);
2116 for (; dp < data + len; dp++) {
2117 if (!isascii(*dp) || !isprint(*dp)) {
2118 if (dp + 1 != data + len || *dp != 0) {
2120 snprintf(op, opleft, "\\%03o", *dp);
2125 } else if (*dp == '"' || *dp == '\'' || *dp == '$' ||
2126 *dp == '`' || *dp == '\\') {
2140 warning("dhcp option too large");
2145 fork_privchld(int fd, int fd2)
2147 struct pollfd pfd[1];
2148 int nfds, pfail = 0;
2152 error("cannot fork");
2160 if (chdir("/") == -1)
2161 error("chdir(\"/\")");
2163 setproctitle("%s [priv]", ifi->name);
2165 dup2(nullfd, STDIN_FILENO);
2166 dup2(nullfd, STDOUT_FILENO);
2167 dup2(nullfd, STDERR_FILENO);
2173 pfd[0].events = POLLIN;
2174 if ((nfds = poll(pfd, 1, INFTIM)) == -1)
2176 error("poll error");
2179 * Handle temporary errors, but bail if they persist.
2181 if (nfds == 0 || !(pfd[0].revents & POLLIN)) {
2182 if (pfail > POLL_FAILURES)
2183 error("poll failed > %d times", POLL_FAILURES);
2184 sleep(pfail * POLL_FAILURE_WAIT);