1 /* $OpenBSD: src/sbin/dhclient/dhclient.c,v 1.146 2012/07/09 16:21:21 krw Exp $ */
4 * Copyright 2004 Henning Brauer <henning@openbsd.org>
5 * Copyright (c) 1995, 1996, 1997, 1998, 1999
6 * The Internet Software Consortium. All rights reserved.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
17 * 3. Neither the name of The Internet Software Consortium nor the names
18 * of its contributors may be used to endorse or promote products derived
19 * from this software without specific prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE INTERNET SOFTWARE CONSORTIUM AND
22 * CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
23 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
24 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
25 * DISCLAIMED. IN NO EVENT SHALL THE INTERNET SOFTWARE CONSORTIUM OR
26 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
27 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
28 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
29 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
30 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
31 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
32 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35 * This software has been written for the Internet Software Consortium
36 * by Ted Lemon <mellon@fugue.com> in cooperation with Vixie
37 * Enterprises. To learn more about the Internet Software Consortium,
38 * see ``http://www.vix.com/isc''. To learn more about Vixie
39 * Enterprises, see ``http://www.vix.com''.
41 * This client was substantially modified and enhanced by Elliot Poger
42 * for use on Linux while he was working on the MosquitoNet project at
45 * The current version owes much to Elliot's Linux enhancements, but
46 * was substantially reorganized and partially rewritten by Ted Lemon
47 * so as to use the same networking framework that the Internet Software
48 * Consortium DHCP server uses. Much system-specific configuration code
49 * was moved into a shell script so that as support for more operating
50 * systems is added, it will not be necessary to port and maintain
51 * system-specific configuration code to these operating systems - instead,
52 * the shell script can invoke the native tools to accomplish the same
55 #include <sys/ioctl.h>
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);
99 void get_ifname(char *, char *);
102 static FILE *leaseFile;
105 findproto(char *cp, int n)
112 for (i = 1; i; i <<= 1) {
114 sa = (struct sockaddr *)cp;
120 if (sa->sa_family == AF_INET)
122 if (sa->sa_family == AF_INET6)
135 get_ifa(char *cp, int n)
142 for (i = 1; i; i <<= 1)
144 sa = (struct sockaddr *)cp;
152 struct iaddr defaddr = { .len = 4 }; /* NULL is for silence warnings */
159 struct rt_msghdr *rtm;
160 struct if_msghdr *ifm;
161 struct ifa_msghdr *ifam;
162 struct if_announcemsghdr *ifan;
163 struct client_lease *l;
164 time_t t = time(NULL);
168 char *errmsg, buf[64];
171 n = read(routefd, &msg, sizeof(msg));
172 } while (n == -1 && errno == EINTR);
174 rtm = (struct rt_msghdr *)msg;
175 if (n < sizeof(rtm->rtm_msglen) || n < rtm->rtm_msglen ||
176 rtm->rtm_version != RTM_VERSION)
179 switch (rtm->rtm_type) {
181 ifam = (struct ifa_msghdr *)rtm;
182 if (ifam->ifam_index != ifi->index)
184 if (findproto((char *)(ifam + 1), ifam->ifam_addrs) != AF_INET)
186 sa = get_ifa((char *)(ifam + 1), ifam->ifam_addrs);
188 errmsg = "sa == NULL";
192 if ((a.len = sizeof(struct in_addr)) > sizeof(a.iabuf))
193 error("king bula sez: len mismatch");
194 memcpy(a.iabuf, &((struct sockaddr_in *)sa)->sin_addr, a.len);
195 if (addr_eq(a, defaddr))
198 /* state_panic() can try unexpired existing leases */
199 if (client->active && addr_eq(a, client->active->address))
201 for (l = client->leases; l != NULL; l = l->next)
202 if (addr_eq(a, l->address))
206 /* new addr is the one we set */
208 snprintf(buf, sizeof(buf), "%s: %s",
209 "new address not one we set", piaddr(a));
213 ifam = (struct ifa_msghdr *)rtm;
214 if (ifam->ifam_index != ifi->index)
216 if (findproto((char *)(ifam + 1), ifam->ifam_addrs) != AF_INET)
218 /* XXX check addrs like RTM_NEWADDR instead of this? */
219 if (scripttime == 0 || t < scripttime + 10)
221 errmsg = "interface address deleted";
224 ifm = (struct if_msghdr *)rtm;
225 if (ifm->ifm_index != ifi->index)
227 if ((rtm->rtm_flags & RTF_UP) == 0) {
228 errmsg = "interface down";
233 LINK_STATE_IS_UP(ifm->ifm_data.ifi_link_state) ? 1 : 0;
234 if (linkstat != ifi->linkstat) {
236 debug("link state %s -> %s",
237 ifi->linkstat ? "up" : "down",
238 linkstat ? "up" : "down");
240 ifi->linkstat = interface_status(ifi->name);
242 client->state = S_REBOOTING;
248 ifan = (struct if_announcemsghdr *)rtm;
249 if (ifan->ifan_what == IFAN_DEPARTURE &&
250 ifan->ifan_index == ifi->index) {
251 errmsg = "interface departure";
263 error("routehandler: %s", errmsg);
267 main(int argc, char *argv[])
269 int ch, fd, quiet = 0, i = 0, pipe_fd[2];
272 /* Initially, log errors to stderr as well as to syslogd. */
273 openlog(getprogname(), LOG_PID | LOG_NDELAY, DHCPD_LOG_FACILITY);
274 setlogmask(LOG_UPTO(LOG_INFO));
276 while ((ch = getopt(argc, argv, "c:dl:qu")) != -1)
279 path_dhclient_conf = optarg;
285 path_dhclient_db = optarg;
303 ifi = calloc(1, sizeof(*ifi));
306 client = calloc(1, sizeof(*client));
308 error("client calloc");
309 config = calloc(1, sizeof(*config));
311 error("config calloc");
313 get_ifname(ifi->name, argv[0]);
314 if (path_dhclient_db == NULL && asprintf(&path_dhclient_db, "%s.%s",
315 _PATH_DHCLIENT_DB, ifi->name) == -1)
324 memset(&sockaddr_broadcast, 0, sizeof(sockaddr_broadcast));
325 sockaddr_broadcast.sin_family = AF_INET;
326 sockaddr_broadcast.sin_port = htons(REMOTE_PORT);
327 sockaddr_broadcast.sin_addr.s_addr = INADDR_BROADCAST;
328 sockaddr_broadcast.sin_len = sizeof(sockaddr_broadcast);
329 inaddr_any.s_addr = INADDR_ANY;
333 if (interface_status(ifi->name) == 0) {
334 interface_link_forceup(ifi->name);
335 /* Give it up to 4 seconds of silent grace to find link */
340 while (!(ifi->linkstat = interface_status(ifi->name))) {
342 fprintf(stderr, "%s: no link ...", ifi->name);
344 fprintf(stderr, ".");
346 if (++i > config->link_timeout) {
347 fprintf(stderr, " sleeping\n");
353 fprintf(stderr, " got link\n");
356 if ((nullfd = open(_PATH_DEVNULL, O_RDWR, 0)) == -1)
357 error("cannot open %s: %m", _PATH_DEVNULL);
359 if ((pw = getpwnam("_dhcp")) == NULL)
360 error("no such user: _dhcp");
362 if (pipe(pipe_fd) == -1)
365 fork_privchld(pipe_fd[0], pipe_fd[1]);
370 if ((fd = open(path_dhclient_db, O_RDONLY|O_EXLOCK|O_CREAT, 0)) == -1)
371 error("can't open and lock %s: %m", path_dhclient_db);
372 read_client_leases();
373 if ((leaseFile = fopen(path_dhclient_db, "w")) == NULL)
374 error("can't open %s: %m", path_dhclient_db);
375 rewrite_client_leases();
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_REBOOTING;
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 /* Cancel all timeouts, since a link state change gets us here
453 and can happen anytime. */
456 /* If we don't remember an active lease, go straight to INIT. */
457 if (!client->active || client->active->is_bootp) {
458 client->state = S_INIT;
463 /* make_request doesn't initialize xid because it normally comes
464 from the DHCPDISCOVER, but we haven't sent a DHCPDISCOVER,
465 so pick an xid now. */
466 client->xid = arc4random();
468 /* Make a DHCPREQUEST packet, and set appropriate per-interface
470 make_request(client->active);
471 client->destination = iaddr_broadcast;
472 client->first_sending = cur_time;
473 client->interval = 0;
475 /* Send out the first DHCPREQUEST packet. */
480 * Called when a lease has completely expired and we've
481 * been unable to renew it.
486 /* Make a DHCPDISCOVER packet, and set appropriate per-interface
488 make_discover(client->active);
489 client->xid = client->packet.xid;
490 client->destination = iaddr_broadcast;
491 client->state = S_SELECTING;
492 client->first_sending = cur_time;
493 client->interval = 0;
495 /* Add an immediate timeout to cause the first DHCPDISCOVER packet
501 * state_selecting is called when one or more DHCPOFFER packets
502 * have been received and a configurable period of time has passed.
505 state_selecting(void)
507 struct client_lease *lp, *next, *picked;
509 /* Cancel state_selecting and send_discover timeouts, since either
510 one could have got us here. */
513 /* We have received one or more DHCPOFFER packets. Currently,
514 the only criterion by which we judge leases is whether or
515 not we get a response when we arp for them. */
517 for (lp = client->offered_leases; lp; lp = next) {
525 free_client_lease(lp);
528 client->offered_leases = NULL;
530 /* If we just tossed all the leases we were offered, go back
533 client->state = S_INIT;
539 /* If it was a BOOTREPLY, we can just take the address right now. */
540 if (!picked->options[DHO_DHCP_MESSAGE_TYPE].len) {
541 client->new = picked;
543 /* Make up some lease expiry times
544 XXX these should be configurable. */
545 client->new->expiry = cur_time + 12000;
546 client->new->renewal += cur_time + 8000;
547 client->new->rebind += cur_time + 10000;
549 client->state = S_REQUESTING;
551 /* Bind to the address we received. */
556 /* Go to the REQUESTING state. */
557 client->destination = iaddr_broadcast;
558 client->state = S_REQUESTING;
559 client->first_sending = cur_time;
560 client->interval = 0;
562 /* Make a DHCPREQUEST packet from the lease we picked. */
563 make_request(picked);
564 client->xid = client->packet.xid;
566 /* Toss the lease we picked - we'll get it back in a DHCPACK. */
567 free_client_lease(picked);
569 /* Add an immediate timeout to send the first DHCPREQUEST packet. */
574 dhcpack(struct iaddr client_addr, struct option_data *options)
576 struct client_lease *lease;
579 if (client->state != S_REBOOTING &&
580 client->state != S_REQUESTING &&
581 client->state != S_RENEWING &&
582 client->state != S_REBINDING)
586 lease = packet_to_lease(options);
588 note("packet_to_lease failed.");
594 /* Stop resending DHCPREQUEST. */
597 /* Figure out the lease time. */
598 if (client->new->options[DHO_DHCP_LEASE_TIME].data)
599 client->new->expiry =
600 getULong(client->new->options[DHO_DHCP_LEASE_TIME].data);
602 client->new->expiry = DEFAULT_LEASE_TIME;
603 /* A number that looks negative here is really just very large,
604 because the lease expiry offset is unsigned. */
605 if (client->new->expiry < 0)
606 client->new->expiry = TIME_MAX;
607 /* XXX should be fixed by resetting the client state */
608 if (client->new->expiry < 60)
609 client->new->expiry = 60;
611 /* Take the server-provided renewal time if there is one;
612 otherwise figure it out according to the spec. */
613 if (client->new->options[DHO_DHCP_RENEWAL_TIME].len)
614 client->new->renewal =
615 getULong(client->new->options[DHO_DHCP_RENEWAL_TIME].data);
617 client->new->renewal = client->new->expiry / 2;
619 /* Same deal with the rebind time. */
620 if (client->new->options[DHO_DHCP_REBINDING_TIME].len)
621 client->new->rebind =
622 getULong(client->new->options[DHO_DHCP_REBINDING_TIME].data);
624 client->new->rebind = client->new->renewal +
625 client->new->renewal / 2 + client->new->renewal / 4;
627 client->new->expiry += cur_time;
628 /* Lease lengths can never be negative. */
629 if (client->new->expiry < cur_time)
630 client->new->expiry = TIME_MAX;
631 client->new->renewal += cur_time;
632 if (client->new->renewal < cur_time)
633 client->new->renewal = TIME_MAX;
634 client->new->rebind += cur_time;
635 if (client->new->rebind < cur_time)
636 client->new->rebind = TIME_MAX;
644 /* Run the client script with the new parameters. */
645 script_init((client->state == S_REQUESTING ? "BOUND" :
646 (client->state == S_RENEWING ? "RENEW" :
647 (client->state == S_REBOOTING ? "REBOOT" : "REBIND"))));
648 if (client->active && client->state != S_REBOOTING)
649 script_write_params("old_", client->active);
650 script_write_params("new_", client->new);
653 /* Replace the old active lease with the new one. */
655 free_client_lease(client->active);
656 client->active = client->new;
659 /* Write out new leases file. */
660 rewrite_client_leases();
662 /* Set timeout to start the renewal process. */
663 set_timeout(client->active->renewal, state_bound);
665 note("bound to %s -- renewal in %ld seconds.",
666 piaddr(client->active->address),
667 client->active->renewal - cur_time);
668 client->state = S_BOUND;
669 reinitialize_interface();
674 * state_bound is called when we've successfully bound to a particular
675 * lease, but the renewal time on that lease has expired. We are
676 * expected to unicast a DHCPREQUEST to the server that gave us our
682 /* T1 has expired. */
683 make_request(client->active);
684 client->xid = client->packet.xid;
686 if (client->active->options[DHO_DHCP_SERVER_IDENTIFIER].len == 4) {
687 memcpy(client->destination.iabuf,
688 client->active->options[DHO_DHCP_SERVER_IDENTIFIER].data,
690 client->destination.len = 4;
692 client->destination = iaddr_broadcast;
694 client->first_sending = cur_time;
695 client->interval = 0;
696 client->state = S_RENEWING;
698 /* Send the first packet immediately. */
703 dhcpoffer(struct iaddr client_addr, struct option_data *options)
705 struct client_lease *lease, *lp;
708 char *name = options[DHO_DHCP_MESSAGE_TYPE].len ? "DHCPOFFER" :
712 if (client->state != S_SELECTING)
716 /* If this lease doesn't supply the minimum required parameters,
718 for (i = 0; config->required_options[i]; i++) {
719 if (!options[config->required_options[i]].len) {
720 note("%s isn't satisfactory.", name);
725 /* If we've already seen this lease, don't record it again. */
726 for (lease = client->offered_leases;
727 lease; lease = lease->next) {
728 if (lease->address.len == sizeof(client->packet.yiaddr) &&
729 !memcmp(lease->address.iabuf,
730 &client->packet.yiaddr, lease->address.len)) {
732 debug("%s already seen.", name);
738 lease = packet_to_lease(options);
740 note("packet_to_lease failed.");
744 /* If this lease was acquired through a BOOTREPLY, record that
746 if (!options[DHO_DHCP_MESSAGE_TYPE].len)
749 /* Figure out when we're supposed to stop selecting. */
750 stop_selecting = client->first_sending + config->select_interval;
752 /* If this is the lease we asked for, put it at the head of the
753 list, and don't mess with the arp request timeout. */
754 if (addr_eq(lease->address, client->requested_address)) {
755 lease->next = client->offered_leases;
756 client->offered_leases = lease;
758 /* Put the lease at the end of the list. */
760 if (!client->offered_leases)
761 client->offered_leases = lease;
763 for (lp = client->offered_leases; lp->next;
770 /* If the selecting interval has expired, go immediately to
771 state_selecting(). Otherwise, time out into
772 state_selecting at the select interval. */
773 if (stop_selecting <= cur_time)
776 set_timeout(stop_selecting, state_selecting);
781 * Allocate a client_lease structure and initialize it from the
782 * parameters in the specified packet.
784 struct client_lease *
785 packet_to_lease(struct option_data *options)
787 struct client_lease *lease;
790 lease = malloc(sizeof(struct client_lease));
793 warning("dhcpoffer: no memory to record lease.");
797 memset(lease, 0, sizeof(*lease));
799 /* Copy the lease options. */
800 for (i = 0; i < 256; i++) {
801 if (options[i].len) {
802 lease->options[i] = options[i];
803 options[i].data = NULL;
805 if (!check_option(lease, i)) {
806 warning("Invalid lease option - ignoring offer");
807 free_client_lease(lease);
813 lease->address.len = sizeof(client->packet.yiaddr);
814 memcpy(lease->address.iabuf, &client->packet.yiaddr,
817 /* If the server name was filled out, copy it. */
818 if ((!lease->options[DHO_DHCP_OPTION_OVERLOAD].len ||
819 !(lease->options[DHO_DHCP_OPTION_OVERLOAD].data[0] & 2)) &&
820 client->packet.sname[0]) {
821 lease->server_name = malloc(DHCP_SNAME_LEN + 1);
822 if (!lease->server_name) {
823 warning("dhcpoffer: no memory for server name.");
824 free_client_lease(lease);
827 memcpy(lease->server_name, client->packet.sname,
829 lease->server_name[DHCP_SNAME_LEN] = '\0';
830 if (!res_hnok(lease->server_name)) {
831 warning("Bogus server name %s", lease->server_name);
832 free(lease->server_name);
833 lease->server_name = NULL;
837 /* Ditto for the filename. */
838 if ((!lease->options[DHO_DHCP_OPTION_OVERLOAD].len ||
839 !(lease->options[DHO_DHCP_OPTION_OVERLOAD].data[0] & 1)) &&
840 client->packet.file[0]) {
841 /* Don't count on the NUL terminator. */
842 lease->filename = malloc(DHCP_FILE_LEN + 1);
843 if (!lease->filename) {
844 warning("dhcpoffer: no memory for filename.");
845 free_client_lease(lease);
848 memcpy(lease->filename, client->packet.file, DHCP_FILE_LEN);
849 lease->filename[DHCP_FILE_LEN] = '\0';
855 dhcpnak(struct iaddr client_addr, struct option_data *options)
858 if (client->state != S_REBOOTING &&
859 client->state != S_REQUESTING &&
860 client->state != S_RENEWING &&
861 client->state != S_REBINDING)
865 if (!client->active) {
866 note("DHCPNAK with no active lease.");
870 free_client_lease(client->active);
871 client->active = NULL;
873 /* Stop sending DHCPREQUEST packets... */
876 client->state = S_INIT;
881 * Send out a DHCPDISCOVER packet, and set a timeout to send out another
882 * one after the right interval has expired. If we don't get an offer by
883 * the time we reach the panic interval, call the panic function.
888 int interval, increase = 1;
890 /* Figure out how long it's been since we started transmitting. */
891 interval = cur_time - client->first_sending;
893 /* If we're past the panic timeout, call the script and tell it
894 we haven't found anything for this interface yet. */
895 if (interval > config->timeout) {
901 * If we're supposed to increase the interval, do so. If it's
902 * currently zero (i.e., we haven't sent any packets yet), set
903 * it to initial_interval; otherwise, add to it a random
904 * number between zero and two times itself. On average, this
905 * means that it will double with every transmission.
908 if (!client->interval)
909 client->interval = config->initial_interval;
911 client->interval += (arc4random() >> 2) %
912 (2 * client->interval);
915 /* Don't backoff past cutoff. */
916 if (client->interval > config->backoff_cutoff)
917 client->interval = ((config->backoff_cutoff / 2)
918 + ((arc4random() >> 2) %
919 config->backoff_cutoff));
920 } else if (!client->interval)
921 client->interval = config->initial_interval;
923 /* If the backoff would take us to the panic timeout, just use that
925 if (cur_time + client->interval >
926 client->first_sending + config->timeout)
927 client->interval = (client->first_sending +
928 config->timeout) - cur_time + 1;
930 /* Record the number of seconds since we started sending. */
931 if (interval < 65536)
932 client->packet.secs = htons(interval);
934 client->packet.secs = htons(65535);
935 client->secs = client->packet.secs;
937 note("DHCPDISCOVER on %s to %s port %d interval %ld",
938 ifi->name, inet_ntoa(sockaddr_broadcast.sin_addr),
939 ntohs(sockaddr_broadcast.sin_port), client->interval);
941 /* Send out a packet. */
942 send_packet(inaddr_any, &sockaddr_broadcast, NULL);
944 set_timeout(cur_time + client->interval, send_discover);
948 * state_panic gets called if we haven't received any offers in a preset
949 * amount of time. When this happens, we try to use existing leases
950 * that haven't yet expired, and failing that, we call the client script
951 * and hope it can do something.
956 struct client_lease *loop = client->active;
957 struct client_lease *lp;
959 note("No DHCPOFFERS received.");
961 /* We may not have an active lease, but we may have some
962 predefined leases that we can try. */
963 if (!client->active && client->leases)
966 /* Run through the list of leases and see if one can be used. */
967 while (client->active) {
968 if (client->active->expiry > cur_time) {
969 note("Trying recorded lease %s",
970 piaddr(client->active->address));
971 /* Run the client script with the existing
973 script_init("TIMEOUT");
974 script_write_params("new_", client->active);
976 /* If the old lease is still good and doesn't
977 yet need renewal, go into BOUND state and
978 timeout at the renewal time. */
981 client->active->renewal) {
982 client->state = S_BOUND;
983 note("bound: renewal in %ld seconds.",
984 client->active->renewal -
986 set_timeout(client->active->renewal,
989 client->state = S_BOUND;
990 note("bound: immediate renewal.");
993 reinitialize_interface();
999 /* If there are no other leases, give up. */
1000 if (!client->leases) {
1001 client->leases = client->active;
1002 client->active = NULL;
1007 /* Otherwise, put the active lease at the end of the
1008 lease list, and try another lease.. */
1009 for (lp = client->leases; lp->next; lp = lp->next)
1011 lp->next = client->active;
1013 lp->next->next = NULL;
1014 client->active = client->leases;
1015 client->leases = client->leases->next;
1017 /* If we already tried this lease, we've exhausted the
1018 set of leases, so we might as well give up for
1020 if (client->active == loop)
1023 loop = client->active;
1026 /* No leases were available, or what was available didn't work, so
1027 tell the shell script that we failed to allocate an address,
1028 and try again later. */
1029 note("No working leases in persistent database - sleeping.");
1030 script_init("FAIL");
1032 client->state = S_INIT;
1033 set_timeout(cur_time + config->retry_interval, state_init);
1040 struct sockaddr_in destination;
1041 struct in_addr from;
1044 /* Figure out how long it's been since we started transmitting. */
1045 interval = cur_time - client->first_sending;
1047 /* If we're in the INIT-REBOOT or REQUESTING state and we're
1048 past the reboot timeout, go to INIT and see if we can
1049 DISCOVER an address... */
1050 /* XXX In the INIT-REBOOT state, if we don't get an ACK, it
1051 means either that we're on a network with no DHCP server,
1052 or that our server is down. In the latter case, assuming
1053 that there is a backup DHCP server, DHCPDISCOVER will get
1054 us a new address, but we could also have successfully
1055 reused our old address. In the former case, we're hosed
1056 anyway. This is not a win-prone situation. */
1057 if ((client->state == S_REBOOTING ||
1058 client->state == S_REQUESTING) &&
1059 interval > config->reboot_timeout) {
1060 client->state = S_INIT;
1066 /* If the lease has expired, relinquish the address and go back
1067 to the INIT state. */
1068 if (client->state != S_REQUESTING &&
1069 cur_time > client->active->expiry) {
1070 /* Run the client script with the new parameters. */
1071 script_init("EXPIRE");
1072 script_write_params("old_", client->active);
1075 client->state = S_INIT;
1080 /* Do the exponential backoff... */
1081 if (!client->interval)
1082 client->interval = config->initial_interval;
1084 client->interval += ((arc4random() >> 2) %
1085 (2 * client->interval));
1087 /* Don't backoff past cutoff. */
1088 if (client->interval > config->backoff_cutoff)
1089 client->interval = ((config->backoff_cutoff / 2) +
1090 ((arc4random() >> 2) % client->interval));
1092 /* If the backoff would take us to the expiry time, just set the
1093 timeout to the expiry time. */
1094 if (client->state != S_REQUESTING && cur_time + client->interval >
1095 client->active->expiry)
1096 client->interval = client->active->expiry - cur_time + 1;
1098 /* If the lease T2 time has elapsed, or if we're not yet bound,
1099 broadcast the DHCPREQUEST rather than unicasting. */
1100 memset(&destination, 0, sizeof(destination));
1101 if (client->state == S_REQUESTING ||
1102 client->state == S_REBOOTING ||
1103 cur_time > client->active->rebind)
1104 destination.sin_addr.s_addr = INADDR_BROADCAST;
1106 memcpy(&destination.sin_addr.s_addr, client->destination.iabuf,
1107 sizeof(destination.sin_addr.s_addr));
1108 destination.sin_port = htons(REMOTE_PORT);
1109 destination.sin_family = AF_INET;
1110 destination.sin_len = sizeof(destination);
1112 if (client->state != S_REQUESTING)
1113 memcpy(&from, client->active->address.iabuf, sizeof(from));
1115 from.s_addr = INADDR_ANY;
1117 /* Record the number of seconds since we started sending. */
1118 if (client->state == S_REQUESTING)
1119 client->packet.secs = client->secs;
1121 if (interval < 65536)
1122 client->packet.secs = htons(interval);
1124 client->packet.secs = htons(65535);
1127 note("DHCPREQUEST on %s to %s port %d", ifi->name,
1128 inet_ntoa(destination.sin_addr), ntohs(destination.sin_port));
1130 /* Send out a packet. */
1131 send_packet(from, &destination, NULL);
1133 set_timeout(cur_time + client->interval, send_request);
1139 note("DHCPDECLINE on %s to %s port %d", ifi->name,
1140 inet_ntoa(sockaddr_broadcast.sin_addr),
1141 ntohs(sockaddr_broadcast.sin_port));
1143 /* Send out a packet. */
1144 send_packet(inaddr_any, &sockaddr_broadcast, NULL);
1148 make_discover(struct client_lease *lease)
1150 unsigned char discover = DHCPDISCOVER;
1151 struct option_data options[256];
1154 memset(options, 0, sizeof(options));
1155 memset(&client->packet, 0, sizeof(client->packet));
1157 /* Set DHCP_MESSAGE_TYPE to DHCPDISCOVER */
1158 i = DHO_DHCP_MESSAGE_TYPE;
1159 options[i].data = &discover;
1160 options[i].len = sizeof(discover);
1162 /* Request the options we want */
1163 i = DHO_DHCP_PARAMETER_REQUEST_LIST;
1164 options[i].data = config->requested_options;
1165 options[i].len = config->requested_option_count;
1167 /* If we had an address, try to get it again. */
1169 client->requested_address = lease->address;
1170 i = DHO_DHCP_REQUESTED_ADDRESS;
1171 options[i].data = lease->address.iabuf;
1172 options[i].len = lease->address.len;
1174 client->requested_address.len = 0;
1176 /* Send any options requested in the config file. */
1177 for (i = 0; i < 256; i++)
1178 if (!options[i].data &&
1179 config->send_options[i].data) {
1180 options[i].data = config->send_options[i].data;
1181 options[i].len = config->send_options[i].len;
1184 /* Set up the option buffer to fit in a minimal UDP packet. */
1185 i = cons_options(options);
1186 if (i == -1 || client->packet.options[i] != DHO_END)
1187 error("options do not fit in DHCPDISCOVER packet.");
1188 client->packet_length = DHCP_FIXED_NON_UDP+i+1;
1189 if (client->packet_length < BOOTP_MIN_LEN)
1190 client->packet_length = BOOTP_MIN_LEN;
1192 client->packet.op = BOOTREQUEST;
1193 client->packet.htype = ifi->hw_address.htype;
1194 client->packet.hlen = ifi->hw_address.hlen;
1195 client->packet.hops = 0;
1196 client->packet.xid = arc4random();
1197 client->packet.secs = 0; /* filled in by send_discover. */
1198 client->packet.flags = 0;
1200 memset(&client->packet.ciaddr, 0, sizeof(client->packet.ciaddr));
1201 memset(&client->packet.yiaddr, 0, sizeof(client->packet.yiaddr));
1202 memset(&client->packet.siaddr, 0, sizeof(client->packet.siaddr));
1203 memset(&client->packet.giaddr, 0, sizeof(client->packet.giaddr));
1204 memcpy(client->packet.chaddr, ifi->hw_address.haddr,
1205 ifi->hw_address.hlen);
1209 make_request(struct client_lease * lease)
1211 unsigned char request = DHCPREQUEST;
1212 struct option_data options[256];
1215 memset(options, 0, sizeof(options));
1216 memset(&client->packet, 0, sizeof(client->packet));
1218 /* Set DHCP_MESSAGE_TYPE to DHCPREQUEST */
1219 i = DHO_DHCP_MESSAGE_TYPE;
1220 options[i].data = &request;
1221 options[i].len = sizeof(request);
1223 /* Request the options we want */
1224 i = DHO_DHCP_PARAMETER_REQUEST_LIST;
1225 options[i].data = config->requested_options;
1226 options[i].len = config->requested_option_count;
1228 /* If we are requesting an address that hasn't yet been assigned
1229 to us, use the DHCP Requested Address option. */
1230 if (client->state == S_REQUESTING) {
1231 /* Send back the server identifier... */
1232 i = DHO_DHCP_SERVER_IDENTIFIER;
1233 options[i].data = lease->options[i].data;
1234 options[i].len = lease->options[i].len;
1236 if (client->state == S_REQUESTING ||
1237 client->state == S_REBOOTING) {
1238 client->requested_address = lease->address;
1239 i = DHO_DHCP_REQUESTED_ADDRESS;
1240 options[i].data = lease->address.iabuf;
1241 options[i].len = lease->address.len;
1243 client->requested_address.len = 0;
1245 /* Send any options requested in the config file. */
1246 for (i = 0; i < 256; i++)
1247 if (!options[i].data && config->send_options[i].data) {
1248 options[i].data = config->send_options[i].data;
1249 options[i].len = config->send_options[i].len;
1252 /* Set up the option buffer to fit in a minimal UDP packet. */
1253 i = cons_options(options);
1254 if (i == -1 || client->packet.options[i] != DHO_END)
1255 error("options do not fit in DHCPREQUEST packet.");
1256 client->packet_length = DHCP_FIXED_NON_UDP+i+1;
1257 if (client->packet_length < BOOTP_MIN_LEN)
1258 client->packet_length = BOOTP_MIN_LEN;
1260 client->packet.op = BOOTREQUEST;
1261 client->packet.htype = ifi->hw_address.htype;
1262 client->packet.hlen = ifi->hw_address.hlen;
1263 client->packet.hops = 0;
1264 client->packet.xid = client->xid;
1265 client->packet.secs = 0; /* Filled in by send_request. */
1266 client->packet.flags = 0;
1268 /* If we own the address we're requesting, put it in ciaddr;
1269 otherwise set ciaddr to zero. */
1270 if (client->state == S_BOUND ||
1271 client->state == S_RENEWING ||
1272 client->state == S_REBINDING) {
1273 memcpy(&client->packet.ciaddr,
1274 lease->address.iabuf, lease->address.len);
1276 memset(&client->packet.ciaddr, 0,
1277 sizeof(client->packet.ciaddr));
1280 memset(&client->packet.yiaddr, 0, sizeof(client->packet.yiaddr));
1281 memset(&client->packet.siaddr, 0, sizeof(client->packet.siaddr));
1282 memset(&client->packet.giaddr, 0, sizeof(client->packet.giaddr));
1283 memcpy(client->packet.chaddr, ifi->hw_address.haddr,
1284 ifi->hw_address.hlen);
1288 make_decline(struct client_lease *lease)
1290 struct option_data options[256];
1291 unsigned char decline = DHCPDECLINE;
1294 memset(options, 0, sizeof(options));
1295 memset(&client->packet, 0, sizeof(client->packet));
1297 /* Set DHCP_MESSAGE_TYPE to DHCPDECLINE */
1298 i = DHO_DHCP_MESSAGE_TYPE;
1299 options[i].data = &decline;
1300 options[i].len = sizeof(decline);
1302 /* Send back the server identifier... */
1303 i = DHO_DHCP_SERVER_IDENTIFIER;
1304 options[i].data = lease->options[i].data;
1305 options[i].len = lease->options[i].len;
1307 /* Send back the address we're declining. */
1308 i = DHO_DHCP_REQUESTED_ADDRESS;
1309 options[i].data = lease->address.iabuf;
1310 options[i].len = lease->address.len;
1312 /* Send the uid if the user supplied one. */
1313 i = DHO_DHCP_CLIENT_IDENTIFIER;
1314 if (config->send_options[i].len) {
1315 options[i].data = config->send_options[i].data;
1316 options[i].len = config->send_options[i].len;
1319 /* Set up the option buffer to fit in a minimal UDP packet. */
1320 i = cons_options(options);
1321 if (i == -1 || client->packet.options[i] != DHO_END)
1322 error("options do not fit in DHCPDECLINE packet.");
1323 client->packet_length = DHCP_FIXED_NON_UDP+i+1;
1324 if (client->packet_length < BOOTP_MIN_LEN)
1325 client->packet_length = BOOTP_MIN_LEN;
1327 client->packet.op = BOOTREQUEST;
1328 client->packet.htype = ifi->hw_address.htype;
1329 client->packet.hlen = ifi->hw_address.hlen;
1330 client->packet.hops = 0;
1331 client->packet.xid = client->xid;
1332 client->packet.secs = 0; /* Filled in by send_request. */
1333 client->packet.flags = 0;
1335 /* ciaddr must always be zero. */
1336 memset(&client->packet.ciaddr, 0, sizeof(client->packet.ciaddr));
1337 memset(&client->packet.yiaddr, 0, sizeof(client->packet.yiaddr));
1338 memset(&client->packet.siaddr, 0, sizeof(client->packet.siaddr));
1339 memset(&client->packet.giaddr, 0, sizeof(client->packet.giaddr));
1340 memcpy(client->packet.chaddr, ifi->hw_address.haddr,
1341 ifi->hw_address.hlen);
1345 free_client_lease(struct client_lease *lease)
1349 if (lease->server_name)
1350 free(lease->server_name);
1351 if (lease->filename)
1352 free(lease->filename);
1353 for (i = 0; i < 256; i++) {
1354 if (lease->options[i].len)
1355 free(lease->options[i].data);
1361 rewrite_client_leases(void)
1363 struct client_lease *lp;
1365 if (!leaseFile) /* XXX */
1366 error("lease file not open");
1371 for (lp = client->leases; lp; lp = lp->next) {
1372 if (client->active && addr_eq(lp->address,
1373 client->active->address))
1375 write_client_lease(lp);
1379 write_client_lease(client->active);
1382 ftruncate(fileno(leaseFile), ftello(leaseFile));
1383 fsync(fileno(leaseFile));
1387 write_client_lease(struct client_lease *lease)
1392 /* If the lease came from the config file, we don't need to stash
1393 a copy in the lease database. */
1394 if (lease->is_static)
1397 if (!leaseFile) /* XXX */
1398 error("lease file not open");
1400 fprintf(leaseFile, "lease {\n");
1401 if (lease->is_bootp)
1402 fprintf(leaseFile, " bootp;\n");
1403 fprintf(leaseFile, " interface \"%s\";\n", ifi->name);
1404 fprintf(leaseFile, " fixed-address %s;\n", piaddr(lease->address));
1405 if (lease->filename)
1406 fprintf(leaseFile, " filename \"%s\";\n", lease->filename);
1407 if (lease->server_name)
1408 fprintf(leaseFile, " server-name \"%s\";\n",
1409 lease->server_name);
1410 for (i = 0; i < 256; i++)
1411 if (lease->options[i].len)
1412 fprintf(leaseFile, " option %s %s;\n",
1413 dhcp_options[i].name,
1414 pretty_print_option(i, lease->options[i].data,
1415 lease->options[i].len, 1, 1));
1417 t = gmtime(&lease->renewal);
1418 fprintf(leaseFile, " renew %d %d/%d/%d %02d:%02d:%02d;\n",
1419 t->tm_wday, t->tm_year + 1900, t->tm_mon + 1, t->tm_mday,
1420 t->tm_hour, t->tm_min, t->tm_sec);
1421 t = gmtime(&lease->rebind);
1422 fprintf(leaseFile, " rebind %d %d/%d/%d %02d:%02d:%02d;\n",
1423 t->tm_wday, t->tm_year + 1900, t->tm_mon + 1, t->tm_mday,
1424 t->tm_hour, t->tm_min, t->tm_sec);
1425 t = gmtime(&lease->expiry);
1426 fprintf(leaseFile, " expire %d %d/%d/%d %02d:%02d:%02d;\n",
1427 t->tm_wday, t->tm_year + 1900, t->tm_mon + 1, t->tm_mday,
1428 t->tm_hour, t->tm_min, t->tm_sec);
1429 fprintf(leaseFile, "}\n");
1434 script_init(char *reason)
1437 struct imsg_hdr hdr;
1440 hdr.code = IMSG_SCRIPT_INIT;
1441 hdr.len = sizeof(struct imsg_hdr) + sizeof(size_t) + strlen(reason);
1442 buf = buf_open(hdr.len);
1444 buf_add(buf, &hdr, sizeof(hdr));
1445 len = strlen(reason);
1446 buf_add(buf, &len, sizeof(len));
1447 buf_add(buf, reason, len);
1449 buf_close(privfd, buf);
1453 priv_script_init(char *reason)
1455 client->scriptEnvsize = 100;
1456 if (client->scriptEnv == NULL)
1458 calloc(client->scriptEnvsize, sizeof(char *));
1459 if (client->scriptEnv == NULL)
1460 error("script_init: no memory for environment");
1462 client->scriptEnv[0] = strdup(CLIENT_PATH);
1463 if (client->scriptEnv[0] == NULL)
1464 error("script_init: no memory for environment");
1466 client->scriptEnv[1] = NULL;
1468 script_set_env("", "interface", ifi->name);
1470 script_set_env("", "reason", reason);
1474 priv_script_write_params(char *prefix, struct client_lease *lease)
1476 u_int8_t dbuf[1500];
1480 script_set_env(prefix, "ip_address", piaddr(lease->address));
1482 if (lease->options[DHO_SUBNET_MASK].len &&
1483 (lease->options[DHO_SUBNET_MASK].len <
1484 sizeof(lease->address.iabuf))) {
1485 struct iaddr netmask, subnet, broadcast;
1487 memcpy(netmask.iabuf, lease->options[DHO_SUBNET_MASK].data,
1488 lease->options[DHO_SUBNET_MASK].len);
1489 netmask.len = lease->options[DHO_SUBNET_MASK].len;
1491 subnet = subnet_number(lease->address, netmask);
1493 script_set_env(prefix, "network_number",
1495 if (!lease->options[DHO_BROADCAST_ADDRESS].len) {
1496 broadcast = broadcast_addr(subnet, netmask);
1498 script_set_env(prefix,
1499 "broadcast_address",
1505 if (lease->filename)
1506 script_set_env(prefix, "filename", lease->filename);
1507 if (lease->server_name)
1508 script_set_env(prefix, "server_name",
1509 lease->server_name);
1510 for (i = 0; i < 256; i++) {
1511 u_int8_t *dp = NULL;
1513 if (config->defaults[i].len) {
1514 if (lease->options[i].len) {
1515 switch (config->default_actions[i]) {
1516 case ACTION_DEFAULT:
1517 dp = lease->options[i].data;
1518 len = lease->options[i].len;
1520 case ACTION_SUPERSEDE:
1522 dp = config->defaults[i].data;
1523 len = config->defaults[i].len;
1525 case ACTION_PREPEND:
1526 len = config->defaults[i].len +
1527 lease->options[i].len;
1528 if (len >= sizeof(dbuf)) {
1529 warning("no space to %s %s",
1531 dhcp_options[i].name);
1536 config->defaults[i].data,
1537 config->defaults[i].len);
1539 config->defaults[i].len,
1540 lease->options[i].data,
1541 lease->options[i].len);
1545 len = config->defaults[i].len +
1546 lease->options[i].len;
1547 if (len >= sizeof(dbuf)) {
1548 warning("no space to %s %s",
1550 dhcp_options[i].name);
1554 memcpy(dp, lease->options[i].data,
1555 lease->options[i].len);
1556 memcpy(dp + lease->options[i].len,
1557 config->defaults[i].data,
1558 config->defaults[i].len);
1562 dp = config->defaults[i].data;
1563 len = config->defaults[i].len;
1565 } else if (lease->options[i].len) {
1566 len = lease->options[i].len;
1567 dp = lease->options[i].data;
1574 if (dhcp_option_ev_name(name, sizeof(name),
1576 script_set_env(prefix, name,
1577 pretty_print_option(i, dp, len, 0, 0));
1580 snprintf(tbuf, sizeof(tbuf), "%d", (int)lease->expiry);
1581 script_set_env(prefix, "expiry", tbuf);
1585 script_write_params(char *prefix, struct client_lease *lease)
1587 size_t fn_len = 0, sn_len = 0, pr_len = 0;
1588 struct imsg_hdr hdr;
1592 if (lease->filename != NULL)
1593 fn_len = strlen(lease->filename);
1594 if (lease->server_name != NULL)
1595 sn_len = strlen(lease->server_name);
1597 pr_len = strlen(prefix);
1599 hdr.code = IMSG_SCRIPT_WRITE_PARAMS;
1600 hdr.len = sizeof(hdr) + sizeof(struct client_lease) +
1601 sizeof(size_t) + fn_len + sizeof(size_t) + sn_len +
1602 sizeof(size_t) + pr_len;
1604 for (i = 0; i < 256; i++)
1605 hdr.len += sizeof(int) + lease->options[i].len;
1607 scripttime = time(NULL);
1609 buf = buf_open(hdr.len);
1611 buf_add(buf, &hdr, sizeof(hdr));
1612 buf_add(buf, lease, sizeof(struct client_lease));
1613 buf_add(buf, &fn_len, sizeof(fn_len));
1614 buf_add(buf, lease->filename, fn_len);
1615 buf_add(buf, &sn_len, sizeof(sn_len));
1616 buf_add(buf, lease->server_name, sn_len);
1617 buf_add(buf, &pr_len, sizeof(pr_len));
1618 buf_add(buf, prefix, pr_len);
1620 for (i = 0; i < 256; i++) {
1621 buf_add(buf, &lease->options[i].len,
1622 sizeof(lease->options[i].len));
1623 buf_add(buf, lease->options[i].data,
1624 lease->options[i].len);
1627 buf_close(privfd, buf);
1633 struct imsg_hdr hdr;
1637 scripttime = time(NULL);
1639 hdr.code = IMSG_SCRIPT_GO;
1640 hdr.len = sizeof(struct imsg_hdr);
1642 buf = buf_open(hdr.len);
1644 buf_add(buf, &hdr, sizeof(hdr));
1645 buf_close(privfd, buf);
1647 bzero(&hdr, sizeof(hdr));
1648 buf_read(privfd, &hdr, sizeof(hdr));
1649 if (hdr.code != IMSG_SCRIPT_GO_RET)
1650 error("unexpected msg type %u", hdr.code);
1651 if (hdr.len != sizeof(hdr) + sizeof(int))
1652 error("received corrupted message");
1653 buf_read(privfd, &ret, sizeof(ret));
1659 priv_script_go(void)
1661 char *scriptName, *argv[2], **envp;
1662 int pid, wpid, wstatus;
1664 scripttime = time(NULL);
1666 scriptName = config->script_name;
1667 envp = client->scriptEnv;
1669 argv[0] = scriptName;
1678 wpid = wait(&wstatus);
1679 } while (wpid != pid && wpid > 0);
1685 execve(scriptName, argv, envp);
1686 error("execve (%s, ...): %m", scriptName);
1691 return (WEXITSTATUS(wstatus));
1695 script_set_env(const char *prefix, const char *name, const char *value)
1699 namelen = strlen(name);
1701 for (i = 0; client->scriptEnv[i]; i++)
1702 if (strncmp(client->scriptEnv[i], name, namelen) == 0 &&
1703 client->scriptEnv[i][namelen] == '=')
1706 if (client->scriptEnv[i])
1707 /* Reuse the slot. */
1708 free(client->scriptEnv[i]);
1710 /* New variable. Expand if necessary. */
1711 if (i >= client->scriptEnvsize - 1) {
1712 char **newscriptEnv;
1713 int newscriptEnvsize = client->scriptEnvsize + 50;
1715 newscriptEnv = realloc(client->scriptEnv,
1717 if (newscriptEnv == NULL) {
1718 free(client->scriptEnv);
1719 client->scriptEnv = NULL;
1720 client->scriptEnvsize = 0;
1721 error("script_set_env: no memory for variable");
1723 client->scriptEnv = newscriptEnv;
1724 client->scriptEnvsize = newscriptEnvsize;
1726 /* need to set the NULL pointer at end of array beyond
1728 client->scriptEnv[i + 1] = NULL;
1730 /* Allocate space and format the variable in the appropriate slot. */
1731 client->scriptEnv[i] = malloc(strlen(prefix) + strlen(name) + 1 +
1733 if (client->scriptEnv[i] == NULL)
1734 error("script_set_env: no memory for variable assignment");
1736 /* No `` or $() command substitution allowed in environment values! */
1737 for (j = 0; j < strlen(value); j++)
1741 error("illegal character (%c) in value '%s'", value[j],
1745 snprintf(client->scriptEnv[i], strlen(prefix) + strlen(name) +
1746 1 + strlen(value) + 1, "%s%s=%s", prefix, name, value);
1750 script_flush_env(void)
1754 for (i = 0; client->scriptEnv[i]; i++) {
1755 free(client->scriptEnv[i]);
1756 client->scriptEnv[i] = NULL;
1758 client->scriptEnvsize = 0;
1762 dhcp_option_ev_name(char *buf, size_t buflen, const struct option *option)
1766 for (i = 0; option->name[i]; i++) {
1767 if (i + 1 == buflen)
1769 if (option->name[i] == '-')
1772 buf[i] = option->name[i];
1782 static int state = 0;
1784 if (no_daemon || state)
1789 /* Stop logging to stderr... */
1792 if (daemon(1, 0) == -1)
1795 /* we are chrooted, daemon(3) fails to open /dev/null */
1797 dup2(nullfd, STDIN_FILENO);
1798 dup2(nullfd, STDOUT_FILENO);
1799 dup2(nullfd, STDERR_FILENO);
1806 check_option(struct client_lease *l, int option)
1811 /* we use this, since this is what gets passed to dhclient-script */
1813 opbuf = pretty_print_option(option, l->options[option].data,
1814 l->options[option].len, 0, 0);
1816 sbuf = option_as_string(option, l->options[option].data,
1817 l->options[option].len);
1820 case DHO_SUBNET_MASK:
1821 case DHO_SWAP_SERVER:
1822 case DHO_BROADCAST_ADDRESS:
1823 case DHO_DHCP_SERVER_IDENTIFIER:
1824 case DHO_ROUTER_SOLICITATION_ADDRESS:
1825 case DHO_DHCP_REQUESTED_ADDRESS:
1826 if (ipv4addrs(opbuf) == 0) {
1827 warning("Invalid IP address in option %s: %s",
1828 dhcp_options[option].name, opbuf);
1831 if (l->options[option].len != 4) { /* RFC 2132 */
1832 warning("warning: Only 1 IP address allowed in "
1833 "%s option; length %d, must be 4",
1834 dhcp_options[option].name,
1835 l->options[option].len);
1836 l->options[option].len = 4;
1839 case DHO_TIME_SERVERS:
1840 case DHO_NAME_SERVERS:
1842 case DHO_DOMAIN_NAME_SERVERS:
1843 case DHO_LOG_SERVERS:
1844 case DHO_COOKIE_SERVERS:
1845 case DHO_LPR_SERVERS:
1846 case DHO_IMPRESS_SERVERS:
1847 case DHO_RESOURCE_LOCATION_SERVERS:
1848 case DHO_NIS_SERVERS:
1849 case DHO_NTP_SERVERS:
1850 case DHO_NETBIOS_NAME_SERVERS:
1851 case DHO_NETBIOS_DD_SERVER:
1852 case DHO_FONT_SERVERS:
1853 if (ipv4addrs(opbuf) == 0) {
1854 warning("Invalid IP address in option %s: %s",
1855 dhcp_options[option].name, opbuf);
1860 case DHO_DOMAIN_NAME:
1861 case DHO_NIS_DOMAIN:
1862 if (!res_hnok(sbuf)) {
1863 warning("Bogus Host Name option %d: %s (%s)", option,
1865 l->options[option].len = 0;
1866 free(l->options[option].data);
1870 case DHO_TIME_OFFSET:
1872 case DHO_MERIT_DUMP:
1874 case DHO_EXTENSIONS_PATH:
1875 case DHO_IP_FORWARDING:
1876 case DHO_NON_LOCAL_SOURCE_ROUTING:
1877 case DHO_POLICY_FILTER:
1878 case DHO_MAX_DGRAM_REASSEMBLY:
1879 case DHO_DEFAULT_IP_TTL:
1880 case DHO_PATH_MTU_AGING_TIMEOUT:
1881 case DHO_PATH_MTU_PLATEAU_TABLE:
1882 case DHO_INTERFACE_MTU:
1883 case DHO_ALL_SUBNETS_LOCAL:
1884 case DHO_PERFORM_MASK_DISCOVERY:
1885 case DHO_MASK_SUPPLIER:
1886 case DHO_ROUTER_DISCOVERY:
1887 case DHO_STATIC_ROUTES:
1888 case DHO_TRAILER_ENCAPSULATION:
1889 case DHO_ARP_CACHE_TIMEOUT:
1890 case DHO_IEEE802_3_ENCAPSULATION:
1891 case DHO_DEFAULT_TCP_TTL:
1892 case DHO_TCP_KEEPALIVE_INTERVAL:
1893 case DHO_TCP_KEEPALIVE_GARBAGE:
1894 case DHO_VENDOR_ENCAPSULATED_OPTIONS:
1895 case DHO_NETBIOS_NODE_TYPE:
1896 case DHO_NETBIOS_SCOPE:
1897 case DHO_X_DISPLAY_MANAGER:
1898 case DHO_DHCP_LEASE_TIME:
1899 case DHO_DHCP_OPTION_OVERLOAD:
1900 case DHO_DHCP_MESSAGE_TYPE:
1901 case DHO_DHCP_PARAMETER_REQUEST_LIST:
1902 case DHO_DHCP_MESSAGE:
1903 case DHO_DHCP_MAX_MESSAGE_SIZE:
1904 case DHO_DHCP_RENEWAL_TIME:
1905 case DHO_DHCP_REBINDING_TIME:
1906 case DHO_DHCP_CLASS_IDENTIFIER:
1907 case DHO_DHCP_CLIENT_IDENTIFIER:
1908 case DHO_DHCP_USER_CLASS_ID:
1909 case DHO_TFTP_SERVER:
1914 warning("unknown dhcp option value 0x%x", option);
1915 return (unknown_ok);
1920 res_hnok(const char *name)
1922 const char *dn = name;
1923 int pch = '.', ch = *dn++;
1926 while (ch != '\0') {
1931 } else if (pch == '.' || nch == '.' || nch == '\0') {
1934 } else if (!isalnum(ch) && ch != '-' && ch != '_')
1936 else if (ch == '_' && warn == 0) {
1937 warning("warning: hostname %s contains an "
1938 "underscore which violates RFC 952", name);
1946 /* Does buf consist only of dotted decimal ipv4 addrs?
1947 * return how many if so,
1948 * otherwise, return 0
1951 ipv4addrs(char * buf)
1956 while (inet_aton(buf, &jnk) == 1){
1958 while (*buf == '.' || isdigit(*buf))
1969 option_as_string(unsigned int code, unsigned char *data, int len)
1971 static char optbuf[32768]; /* XXX */
1973 int opleft = sizeof(optbuf);
1974 unsigned char *dp = data;
1977 error("option_as_string: bad code %d", code);
1979 for (; dp < data + len; dp++) {
1980 if (!isascii(*dp) || !isprint(*dp)) {
1981 if (dp + 1 != data + len || *dp != 0) {
1983 snprintf(op, opleft, "\\%03o", *dp);
1988 } else if (*dp == '"' || *dp == '\'' || *dp == '$' ||
1989 *dp == '`' || *dp == '\\') {
2003 warning("dhcp option too large");
2008 fork_privchld(int fd, int fd2)
2010 struct pollfd pfd[1];
2011 int nfds, pfail = 0;
2015 error("cannot fork");
2023 if (chdir("/") == -1)
2024 error("chdir(\"/\")");
2026 setproctitle("%s [priv]", ifi->name);
2028 dup2(nullfd, STDIN_FILENO);
2029 dup2(nullfd, STDOUT_FILENO);
2030 dup2(nullfd, STDERR_FILENO);
2036 pfd[0].events = POLLIN;
2037 if ((nfds = poll(pfd, 1, INFTIM)) == -1)
2039 error("poll error");
2042 * Handle temporary errors, but bail if they persist.
2044 if (nfds == 0 || !(pfd[0].revents & POLLIN)) {
2045 if (pfail > POLL_FAILURES)
2046 error("poll failed > %d times", POLL_FAILURES);
2047 sleep(pfail * POLL_FAILURE_WAIT);
2057 get_ifname(char *ifname, char *arg)
2059 struct ifgroupreq ifgr;
2060 struct ifg_req *ifg;
2063 if (!strcmp(arg, "egress")) {
2064 s = socket(AF_INET, SOCK_DGRAM, 0);
2066 error("socket error");
2067 bzero(&ifgr, sizeof(ifgr));
2068 strlcpy(ifgr.ifgr_name, "egress", sizeof(ifgr.ifgr_name));
2069 if (ioctl(s, SIOCGIFGMEMB, (caddr_t)&ifgr) == -1) {
2070 if (errno == ENOENT)
2071 error("no interface in group egress found");
2072 error("ioctl SIOCGIFGMEMB: %m");
2074 len = ifgr.ifgr_len;
2075 if ((ifgr.ifgr_groups = calloc(1, len)) == NULL)
2076 error("get_ifname");
2077 if (ioctl(s, SIOCGIFGMEMB, (caddr_t)&ifgr) == -1)
2078 error("ioctl SIOCGIFGMEMB: %m");
2081 for (ifg = ifgr.ifgr_groups;
2082 ifg && len >= sizeof(struct ifg_req); ifg++) {
2083 len -= sizeof(struct ifg_req);
2085 error("too many interfaces in group egress");
2086 arg = ifg->ifgrq_member;
2089 if (strlcpy(ifi->name, arg, IFNAMSIZ) >= IFNAMSIZ)
2090 error("Interface name too long: %m");
2092 free(ifgr.ifgr_groups);
2094 } else if (strlcpy(ifi->name, arg, IFNAMSIZ) >= IFNAMSIZ)
2095 error("Interface name too long");