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