1 /* $OpenBSD: src/sbin/dhclient/dhclient.c,v 1.140 2011/04/17 20:06:08 phessler 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 *);
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 */
162 struct rt_msghdr *rtm;
163 struct if_msghdr *ifm;
164 struct ifa_msghdr *ifam;
165 struct if_announcemsghdr *ifan;
166 struct client_lease *l;
167 time_t t = time(NULL);
171 char *errmsg, buf[64];
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);
191 errmsg = "sa == NULL";
195 if ((a.len = sizeof(struct in_addr)) > sizeof(a.iabuf))
196 error("king bula sez: len mismatch");
197 memcpy(a.iabuf, &((struct sockaddr_in *)sa)->sin_addr, a.len);
198 if (addr_eq(a, defaddr))
201 /* state_panic() can try unexpired existing leases */
202 if (client->active && addr_eq(a, client->active->address))
204 for (l = client->leases; l != NULL; l = l->next)
205 if (addr_eq(a, l->address))
209 /* new addr is the one we set */
211 snprintf(buf, sizeof(buf), "%s: %s",
212 "new address not one we set", piaddr(a));
216 ifam = (struct ifa_msghdr *)rtm;
217 if (ifam->ifam_index != ifi->index)
219 if (findproto((char *)(ifam + 1), ifam->ifam_addrs) != AF_INET)
221 /* XXX check addrs like RTM_NEWADDR instead of this? */
222 if (scripttime == 0 || t < scripttime + 10)
224 errmsg = "interface address deleted";
227 ifm = (struct if_msghdr *)rtm;
228 if (ifm->ifm_index != ifi->index)
230 if ((rtm->rtm_flags & RTF_UP) == 0) {
231 errmsg = "interface down";
236 LINK_STATE_IS_UP(ifm->ifm_data.ifi_link_state) ? 1 : 0;
237 if (linkstat != ifi->linkstat) {
239 debug("link state %s -> %s",
240 ifi->linkstat ? "up" : "down",
241 linkstat ? "up" : "down");
243 ifi->linkstat = interface_link_status(ifi->name);
245 client->state = S_INIT;
251 ifan = (struct if_announcemsghdr *)rtm;
252 if (ifan->ifan_what == IFAN_DEPARTURE &&
253 ifan->ifan_index == ifi->index) {
254 errmsg = "interface departure";
266 error("routehandler: %s", errmsg);
270 main(int argc, char *argv[])
272 int ch, fd, quiet = 0, i = 0, pipe_fd[2];
275 /* Initially, log errors to stderr as well as to syslogd. */
276 openlog(getprogname(), LOG_PID | LOG_NDELAY, DHCPD_LOG_FACILITY);
277 setlogmask(LOG_UPTO(LOG_INFO));
279 while ((ch = getopt(argc, argv, "c:dl:qu")) != -1)
282 path_dhclient_conf = optarg;
288 path_dhclient_db = optarg;
306 ifi = calloc(1, sizeof(*ifi));
309 client = calloc(1, sizeof(*client));
311 error("client calloc");
312 config = calloc(1, sizeof(*config));
314 error("config calloc");
316 get_ifname(ifi->name, argv[0]);
317 if (path_dhclient_db == NULL && asprintf(&path_dhclient_db, "%s.%s",
318 _PATH_DHCLIENT_DB, ifi->name) == -1)
327 memset(&sockaddr_broadcast, 0, sizeof(sockaddr_broadcast));
328 sockaddr_broadcast.sin_family = AF_INET;
329 sockaddr_broadcast.sin_port = htons(REMOTE_PORT);
330 sockaddr_broadcast.sin_addr.s_addr = INADDR_BROADCAST;
331 sockaddr_broadcast.sin_len = sizeof(sockaddr_broadcast);
332 inaddr_any.s_addr = INADDR_ANY;
336 if (interface_status(ifi->name) == 0) {
337 interface_link_forceup(ifi->name);
338 /* Give it up to 4 seconds of silent grace to find link */
343 while (!(ifi->linkstat = interface_link_status(ifi->name))) {
345 fprintf(stderr, "%s: no link ...", ifi->name);
347 fprintf(stderr, ".");
349 if (++i > config->link_timeout) {
350 fprintf(stderr, " sleeping\n");
356 fprintf(stderr, " got link\n");
359 if ((nullfd = open(_PATH_DEVNULL, O_RDWR, 0)) == -1)
360 error("cannot open %s: %m", _PATH_DEVNULL);
362 if ((pw = getpwnam("_dhcp")) == NULL)
363 error("no such user: _dhcp");
365 if (pipe(pipe_fd) == -1)
368 fork_privchld(pipe_fd[0], pipe_fd[1]);
373 if ((fd = open(path_dhclient_db, O_RDONLY|O_EXLOCK|O_CREAT, 0)) == -1)
374 error("can't open and lock %s: %m", path_dhclient_db);
375 read_client_leases();
376 if ((leaseFile = fopen(path_dhclient_db, "w")) == NULL)
377 error("can't open %s: %m", path_dhclient_db);
378 rewrite_client_leases();
381 if ((routefd = socket(PF_ROUTE, SOCK_RAW, 0)) == -1)
382 error("socket(PF_ROUTE, SOCK_RAW): %m");
384 /* set up the interface */
385 discover_interface();
387 if (chroot(_PATH_VAREMPTY) == -1)
389 if (chdir("/") == -1)
390 error("chdir(\"/\")");
392 if (setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) == -1)
394 if (setgroups(1, &pw->pw_gid) == -1)
396 if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) == -1)
401 setproctitle("%s", ifi->name);
404 client->state = S_INIT;
418 fprintf(stderr, "usage: %s [-dqu] [-c file] [-l file] interface\n",
426 * Each routine is called from the dhclient_state_machine() in one of
428 * -> entering INIT state
429 * -> recvpacket_flag == 0: timeout in this state
430 * -> otherwise: received a packet in this state
432 * Return conditions as handled by dhclient_state_machine():
433 * Returns 1, sendpacket_flag = 1: send packet, reset timer.
434 * Returns 1, sendpacket_flag = 0: just reset the timer (wait for a milestone).
435 * Returns 0: finish the nap which was interrupted for no good reason.
437 * Several per-interface variables are used to keep track of the process:
438 * active_lease: the lease that is being used on the interface
439 * (null pointer if not configured yet).
440 * offered_leases: leases corresponding to DHCPOFFER messages that have
441 * been sent to us by DHCP servers.
442 * acked_leases: leases corresponding to DHCPACK messages that have been
443 * sent to us by DHCP servers.
444 * sendpacket: DHCP packet we're trying to send.
445 * destination: IP address to send sendpacket to
446 * In addition, there are several relevant per-lease variables.
447 * T1_expiry, T2_expiry, lease_expiry: lease milestones
448 * In the active lease, these control the process of renewing the lease;
449 * In leases on the acked_leases list, this simply determines when we
450 * can no longer legitimately use the lease.
455 /* If we don't remember an active lease, go straight to INIT. */
456 if (!client->active || client->active->is_bootp) {
461 /* We are in the rebooting state. */
462 client->state = S_REBOOTING;
464 /* make_request doesn't initialize xid because it normally comes
465 from the DHCPDISCOVER, but we haven't sent a DHCPDISCOVER,
466 so pick an xid now. */
467 client->xid = arc4random();
469 /* Make a DHCPREQUEST packet, and set appropriate per-interface
471 make_request(client->active);
472 client->destination = iaddr_broadcast;
473 client->first_sending = cur_time;
474 client->interval = 0;
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 = 0;
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) {
527 free_client_lease(lp);
530 client->offered_leases = NULL;
532 /* If we just tossed all the leases we were offered, go back
535 client->state = S_INIT;
541 /* If it was a BOOTREPLY, we can just take the address right now. */
542 if (!picked->options[DHO_DHCP_MESSAGE_TYPE].len) {
543 client->new = picked;
545 /* Make up some lease expiry times
546 XXX these should be configurable. */
547 client->new->expiry = cur_time + 12000;
548 client->new->renewal += cur_time + 8000;
549 client->new->rebind += cur_time + 10000;
551 client->state = S_REQUESTING;
553 /* Bind to the address we received. */
558 /* Go to the REQUESTING state. */
559 client->destination = iaddr_broadcast;
560 client->state = S_REQUESTING;
561 client->first_sending = cur_time;
562 client->interval = 0;
564 /* Make a DHCPREQUEST packet from the lease we picked. */
565 make_request(picked);
566 client->xid = client->packet.xid;
568 /* Toss the lease we picked - we'll get it back in a DHCPACK. */
569 free_client_lease(picked);
571 /* Add an immediate timeout to send the first DHCPREQUEST packet. */
576 dhcpack(struct iaddr client_addr, struct option_data *options)
578 struct client_lease *lease;
581 if (client->state != S_REBOOTING &&
582 client->state != S_REQUESTING &&
583 client->state != S_RENEWING &&
584 client->state != S_REBINDING)
588 lease = packet_to_lease(options);
590 note("packet_to_lease failed.");
596 /* Stop resending DHCPREQUEST. */
597 cancel_timeout(send_request);
599 /* Figure out the lease time. */
600 if (client->new->options[DHO_DHCP_LEASE_TIME].data)
601 client->new->expiry =
602 getULong(client->new->options[DHO_DHCP_LEASE_TIME].data);
604 client->new->expiry = DEFAULT_LEASE_TIME;
605 /* A number that looks negative here is really just very large,
606 because the lease expiry offset is unsigned. */
607 if (client->new->expiry < 0)
608 client->new->expiry = TIME_MAX;
609 /* XXX should be fixed by resetting the client state */
610 if (client->new->expiry < 60)
611 client->new->expiry = 60;
613 /* Take the server-provided renewal time if there is one;
614 otherwise figure it out according to the spec. */
615 if (client->new->options[DHO_DHCP_RENEWAL_TIME].len)
616 client->new->renewal =
617 getULong(client->new->options[DHO_DHCP_RENEWAL_TIME].data);
619 client->new->renewal = client->new->expiry / 2;
621 /* Same deal with the rebind time. */
622 if (client->new->options[DHO_DHCP_REBINDING_TIME].len)
623 client->new->rebind =
624 getULong(client->new->options[DHO_DHCP_REBINDING_TIME].data);
626 client->new->rebind = client->new->renewal +
627 client->new->renewal / 2 + client->new->renewal / 4;
629 client->new->expiry += cur_time;
630 /* Lease lengths can never be negative. */
631 if (client->new->expiry < cur_time)
632 client->new->expiry = TIME_MAX;
633 client->new->renewal += cur_time;
634 if (client->new->renewal < cur_time)
635 client->new->renewal = TIME_MAX;
636 client->new->rebind += cur_time;
637 if (client->new->rebind < cur_time)
638 client->new->rebind = TIME_MAX;
646 /* Write out the new lease. */
647 write_client_lease(client->new, 0);
649 /* Run the client script with the new parameters. */
650 script_init((client->state == S_REQUESTING ? "BOUND" :
651 (client->state == S_RENEWING ? "RENEW" :
652 (client->state == S_REBOOTING ? "REBOOT" : "REBIND"))));
653 if (client->active && client->state != S_REBOOTING)
654 script_write_params("old_", client->active);
655 script_write_params("new_", client->new);
658 /* Replace the old active lease with the new one. */
660 free_client_lease(client->active);
661 client->active = client->new;
664 /* Set up a timeout to start the renewal process. */
665 add_timeout(client->active->renewal, state_bound);
667 note("bound to %s -- renewal in %ld seconds.",
668 piaddr(client->active->address),
669 client->active->renewal - cur_time);
670 client->state = S_BOUND;
671 reinitialize_interface();
676 * state_bound is called when we've successfully bound to a particular
677 * lease, but the renewal time on that lease has expired. We are
678 * expected to unicast a DHCPREQUEST to the server that gave us our
684 /* T1 has expired. */
685 make_request(client->active);
686 client->xid = client->packet.xid;
688 if (client->active->options[DHO_DHCP_SERVER_IDENTIFIER].len == 4) {
689 memcpy(client->destination.iabuf,
690 client->active->options[DHO_DHCP_SERVER_IDENTIFIER].data,
692 client->destination.len = 4;
694 client->destination = iaddr_broadcast;
696 client->first_sending = cur_time;
697 client->interval = 0;
698 client->state = S_RENEWING;
700 /* Send the first packet immediately. */
705 dhcpoffer(struct iaddr client_addr, struct option_data *options)
707 struct client_lease *lease, *lp;
710 char *name = options[DHO_DHCP_MESSAGE_TYPE].len ? "DHCPOFFER" :
714 if (client->state != S_SELECTING)
718 /* If this lease doesn't supply the minimum required parameters,
720 for (i = 0; config->required_options[i]; i++) {
721 if (!options[config->required_options[i]].len) {
722 note("%s isn't satisfactory.", name);
727 /* If we've already seen this lease, don't record it again. */
728 for (lease = client->offered_leases;
729 lease; lease = lease->next) {
730 if (lease->address.len == sizeof(client->packet.yiaddr) &&
731 !memcmp(lease->address.iabuf,
732 &client->packet.yiaddr, lease->address.len)) {
734 debug("%s already seen.", name);
740 lease = packet_to_lease(options);
742 note("packet_to_lease failed.");
746 /* If this lease was acquired through a BOOTREPLY, record that
748 if (!options[DHO_DHCP_MESSAGE_TYPE].len)
751 /* Figure out when we're supposed to stop selecting. */
752 stop_selecting = client->first_sending + config->select_interval;
754 /* If this is the lease we asked for, put it at the head of the
755 list, and don't mess with the arp request timeout. */
756 if (addr_eq(lease->address, client->requested_address)) {
757 lease->next = client->offered_leases;
758 client->offered_leases = lease;
760 /* Put the lease at the end of the list. */
762 if (!client->offered_leases)
763 client->offered_leases = lease;
765 for (lp = client->offered_leases; lp->next;
772 /* If the selecting interval has expired, go immediately to
773 state_selecting(). Otherwise, time out into
774 state_selecting at the select interval. */
775 if (stop_selecting <= cur_time)
778 add_timeout(stop_selecting, state_selecting);
779 cancel_timeout(send_discover);
784 * Allocate a client_lease structure and initialize it from the
785 * parameters in the specified packet.
787 struct client_lease *
788 packet_to_lease(struct option_data *options)
790 struct client_lease *lease;
793 lease = malloc(sizeof(struct client_lease));
796 warning("dhcpoffer: no memory to record lease.");
800 memset(lease, 0, sizeof(*lease));
802 /* Copy the lease options. */
803 for (i = 0; i < 256; i++) {
804 if (options[i].len) {
805 lease->options[i] = options[i];
806 options[i].data = NULL;
808 if (!check_option(lease, i)) {
809 warning("Invalid lease option - ignoring offer");
810 free_client_lease(lease);
816 lease->address.len = sizeof(client->packet.yiaddr);
817 memcpy(lease->address.iabuf, &client->packet.yiaddr,
820 /* If the server name was filled out, copy it. */
821 if ((!lease->options[DHO_DHCP_OPTION_OVERLOAD].len ||
822 !(lease->options[DHO_DHCP_OPTION_OVERLOAD].data[0] & 2)) &&
823 client->packet.sname[0]) {
824 lease->server_name = malloc(DHCP_SNAME_LEN + 1);
825 if (!lease->server_name) {
826 warning("dhcpoffer: no memory for server name.");
827 free_client_lease(lease);
830 memcpy(lease->server_name, client->packet.sname,
832 lease->server_name[DHCP_SNAME_LEN] = '\0';
833 if (!res_hnok(lease->server_name)) {
834 warning("Bogus server name %s", lease->server_name);
835 free(lease->server_name);
836 lease->server_name = NULL;
840 /* Ditto for the filename. */
841 if ((!lease->options[DHO_DHCP_OPTION_OVERLOAD].len ||
842 !(lease->options[DHO_DHCP_OPTION_OVERLOAD].data[0] & 1)) &&
843 client->packet.file[0]) {
844 /* Don't count on the NUL terminator. */
845 lease->filename = malloc(DHCP_FILE_LEN + 1);
846 if (!lease->filename) {
847 warning("dhcpoffer: no memory for filename.");
848 free_client_lease(lease);
851 memcpy(lease->filename, client->packet.file, DHCP_FILE_LEN);
852 lease->filename[DHCP_FILE_LEN] = '\0';
858 dhcpnak(struct iaddr client_addr, struct option_data *options)
861 if (client->state != S_REBOOTING &&
862 client->state != S_REQUESTING &&
863 client->state != S_RENEWING &&
864 client->state != S_REBINDING)
868 if (!client->active) {
869 note("DHCPNAK with no active lease.");
873 free_client_lease(client->active);
874 client->active = NULL;
876 /* Stop sending DHCPREQUEST packets... */
877 cancel_timeout(send_request);
879 client->state = S_INIT;
884 * Send out a DHCPDISCOVER packet, and set a timeout to send out another
885 * one after the right interval has expired. If we don't get an offer by
886 * the time we reach the panic interval, call the panic function.
891 int interval, increase = 1;
893 /* Figure out how long it's been since we started transmitting. */
894 interval = cur_time - client->first_sending;
896 /* If we're past the panic timeout, call the script and tell it
897 we haven't found anything for this interface yet. */
898 if (interval > config->timeout) {
904 * If we're supposed to increase the interval, do so. If it's
905 * currently zero (i.e., we haven't sent any packets yet), set
906 * it to initial_interval; otherwise, add to it a random
907 * number between zero and two times itself. On average, this
908 * means that it will double with every transmission.
911 if (!client->interval)
912 client->interval = config->initial_interval;
914 client->interval += (arc4random() >> 2) %
915 (2 * client->interval);
918 /* Don't backoff past cutoff. */
919 if (client->interval > config->backoff_cutoff)
920 client->interval = ((config->backoff_cutoff / 2)
921 + ((arc4random() >> 2) %
922 config->backoff_cutoff));
923 } else if (!client->interval)
924 client->interval = config->initial_interval;
926 /* If the backoff would take us to the panic timeout, just use that
928 if (cur_time + client->interval >
929 client->first_sending + config->timeout)
930 client->interval = (client->first_sending +
931 config->timeout) - cur_time + 1;
933 /* Record the number of seconds since we started sending. */
934 if (interval < 65536)
935 client->packet.secs = htons(interval);
937 client->packet.secs = htons(65535);
938 client->secs = client->packet.secs;
940 note("DHCPDISCOVER on %s to %s port %d interval %ld",
941 ifi->name, inet_ntoa(sockaddr_broadcast.sin_addr),
942 ntohs(sockaddr_broadcast.sin_port), client->interval);
944 /* Send out a packet. */
945 send_packet(inaddr_any, &sockaddr_broadcast, NULL);
947 add_timeout(cur_time + client->interval, send_discover);
951 * state_panic gets called if we haven't received any offers in a preset
952 * amount of time. When this happens, we try to use existing leases
953 * that haven't yet expired, and failing that, we call the client script
954 * and hope it can do something.
959 struct client_lease *loop = client->active;
960 struct client_lease *lp;
962 note("No DHCPOFFERS received.");
964 /* We may not have an active lease, but we may have some
965 predefined leases that we can try. */
966 if (!client->active && client->leases)
969 /* Run through the list of leases and see if one can be used. */
970 while (client->active) {
971 if (client->active->expiry > cur_time) {
972 note("Trying recorded lease %s",
973 piaddr(client->active->address));
974 /* Run the client script with the existing
976 script_init("TIMEOUT");
977 script_write_params("new_", client->active);
979 /* If the old lease is still good and doesn't
980 yet need renewal, go into BOUND state and
981 timeout at the renewal time. */
984 client->active->renewal) {
985 client->state = S_BOUND;
986 note("bound: renewal in %ld seconds.",
987 client->active->renewal -
989 add_timeout(client->active->renewal,
992 client->state = S_BOUND;
993 note("bound: immediate renewal.");
996 reinitialize_interface();
1002 /* If there are no other leases, give up. */
1003 if (!client->leases) {
1004 client->leases = client->active;
1005 client->active = NULL;
1010 /* Otherwise, put the active lease at the end of the
1011 lease list, and try another lease.. */
1012 for (lp = client->leases; lp->next; lp = lp->next)
1014 lp->next = client->active;
1016 lp->next->next = NULL;
1017 client->active = client->leases;
1018 client->leases = client->leases->next;
1020 /* If we already tried this lease, we've exhausted the
1021 set of leases, so we might as well give up for
1023 if (client->active == loop)
1026 loop = client->active;
1029 /* No leases were available, or what was available didn't work, so
1030 tell the shell script that we failed to allocate an address,
1031 and try again later. */
1032 note("No working leases in persistent database - sleeping.");
1033 script_init("FAIL");
1035 client->state = S_INIT;
1036 add_timeout(cur_time + config->retry_interval, state_init);
1043 struct sockaddr_in destination;
1044 struct in_addr from;
1047 /* Figure out how long it's been since we started transmitting. */
1048 interval = cur_time - client->first_sending;
1050 /* If we're in the INIT-REBOOT or REQUESTING state and we're
1051 past the reboot timeout, go to INIT and see if we can
1052 DISCOVER an address... */
1053 /* XXX In the INIT-REBOOT state, if we don't get an ACK, it
1054 means either that we're on a network with no DHCP server,
1055 or that our server is down. In the latter case, assuming
1056 that there is a backup DHCP server, DHCPDISCOVER will get
1057 us a new address, but we could also have successfully
1058 reused our old address. In the former case, we're hosed
1059 anyway. This is not a win-prone situation. */
1060 if ((client->state == S_REBOOTING ||
1061 client->state == S_REQUESTING) &&
1062 interval > config->reboot_timeout) {
1063 client->state = S_INIT;
1064 cancel_timeout(send_request);
1069 /* If the lease has expired, relinquish the address and go back
1070 to the INIT state. */
1071 if (client->state != S_REQUESTING &&
1072 cur_time > client->active->expiry) {
1073 /* Run the client script with the new parameters. */
1074 script_init("EXPIRE");
1075 script_write_params("old_", client->active);
1078 client->state = S_INIT;
1083 /* Do the exponential backoff... */
1084 if (!client->interval)
1085 client->interval = config->initial_interval;
1087 client->interval += ((arc4random() >> 2) %
1088 (2 * client->interval));
1090 /* Don't backoff past cutoff. */
1091 if (client->interval > config->backoff_cutoff)
1092 client->interval = ((config->backoff_cutoff / 2) +
1093 ((arc4random() >> 2) % client->interval));
1095 /* If the backoff would take us to the expiry time, just set the
1096 timeout to the expiry time. */
1097 if (client->state != S_REQUESTING && cur_time + client->interval >
1098 client->active->expiry)
1099 client->interval = client->active->expiry - cur_time + 1;
1101 /* If the lease T2 time has elapsed, or if we're not yet bound,
1102 broadcast the DHCPREQUEST rather than unicasting. */
1103 memset(&destination, 0, sizeof(destination));
1104 if (client->state == S_REQUESTING ||
1105 client->state == S_REBOOTING ||
1106 cur_time > client->active->rebind)
1107 destination.sin_addr.s_addr = INADDR_BROADCAST;
1109 memcpy(&destination.sin_addr.s_addr, client->destination.iabuf,
1110 sizeof(destination.sin_addr.s_addr));
1111 destination.sin_port = htons(REMOTE_PORT);
1112 destination.sin_family = AF_INET;
1113 destination.sin_len = sizeof(destination);
1115 if (client->state != S_REQUESTING)
1116 memcpy(&from, client->active->address.iabuf, sizeof(from));
1118 from.s_addr = INADDR_ANY;
1120 /* Record the number of seconds since we started sending. */
1121 if (client->state == S_REQUESTING)
1122 client->packet.secs = client->secs;
1124 if (interval < 65536)
1125 client->packet.secs = htons(interval);
1127 client->packet.secs = htons(65535);
1130 note("DHCPREQUEST on %s to %s port %d", ifi->name,
1131 inet_ntoa(destination.sin_addr), ntohs(destination.sin_port));
1133 /* Send out a packet. */
1134 send_packet(from, &destination, NULL);
1136 add_timeout(cur_time + client->interval, send_request);
1142 note("DHCPDECLINE on %s to %s port %d", ifi->name,
1143 inet_ntoa(sockaddr_broadcast.sin_addr),
1144 ntohs(sockaddr_broadcast.sin_port));
1146 /* Send out a packet. */
1147 send_packet(inaddr_any, &sockaddr_broadcast, NULL);
1151 make_discover(struct client_lease *lease)
1153 unsigned char discover = DHCPDISCOVER;
1154 struct option_data options[256];
1157 memset(options, 0, sizeof(options));
1158 memset(&client->packet, 0, sizeof(client->packet));
1160 /* Set DHCP_MESSAGE_TYPE to DHCPDISCOVER */
1161 i = DHO_DHCP_MESSAGE_TYPE;
1162 options[i].data = &discover;
1163 options[i].len = sizeof(discover);
1165 /* Request the options we want */
1166 i = DHO_DHCP_PARAMETER_REQUEST_LIST;
1167 options[i].data = config->requested_options;
1168 options[i].len = config->requested_option_count;
1170 /* If we had an address, try to get it again. */
1172 client->requested_address = lease->address;
1173 i = DHO_DHCP_REQUESTED_ADDRESS;
1174 options[i].data = lease->address.iabuf;
1175 options[i].len = lease->address.len;
1177 client->requested_address.len = 0;
1179 /* Send any options requested in the config file. */
1180 for (i = 0; i < 256; i++)
1181 if (!options[i].data &&
1182 config->send_options[i].data) {
1183 options[i].data = config->send_options[i].data;
1184 options[i].len = config->send_options[i].len;
1187 /* Set up the option buffer to fit in a minimal UDP packet. */
1188 i = cons_options(client->packet.options, 576 - DHCP_FIXED_LEN,
1190 if (i == -1 || client->packet.options[i] != DHO_END)
1191 error("options do not fit in DHCPDISCOVER packet.");
1192 client->packet_length = DHCP_FIXED_NON_UDP+i+1;
1193 if (client->packet_length < BOOTP_MIN_LEN)
1194 client->packet_length = BOOTP_MIN_LEN;
1196 client->packet.op = BOOTREQUEST;
1197 client->packet.htype = ifi->hw_address.htype;
1198 client->packet.hlen = ifi->hw_address.hlen;
1199 client->packet.hops = 0;
1200 client->packet.xid = arc4random();
1201 client->packet.secs = 0; /* filled in by send_discover. */
1202 client->packet.flags = 0;
1204 memset(&client->packet.ciaddr, 0, sizeof(client->packet.ciaddr));
1205 memset(&client->packet.yiaddr, 0, sizeof(client->packet.yiaddr));
1206 memset(&client->packet.siaddr, 0, sizeof(client->packet.siaddr));
1207 memset(&client->packet.giaddr, 0, sizeof(client->packet.giaddr));
1208 memcpy(client->packet.chaddr, ifi->hw_address.haddr,
1209 ifi->hw_address.hlen);
1213 make_request(struct client_lease * lease)
1215 unsigned char request = DHCPREQUEST;
1216 struct option_data options[256];
1219 memset(options, 0, sizeof(options));
1220 memset(&client->packet, 0, sizeof(client->packet));
1222 /* Set DHCP_MESSAGE_TYPE to DHCPREQUEST */
1223 i = DHO_DHCP_MESSAGE_TYPE;
1224 options[i].data = &request;
1225 options[i].len = sizeof(request);
1227 /* Request the options we want */
1228 i = DHO_DHCP_PARAMETER_REQUEST_LIST;
1229 options[i].data = config->requested_options;
1230 options[i].len = config->requested_option_count;
1232 /* If we are requesting an address that hasn't yet been assigned
1233 to us, use the DHCP Requested Address option. */
1234 if (client->state == S_REQUESTING) {
1235 /* Send back the server identifier... */
1236 i = DHO_DHCP_SERVER_IDENTIFIER;
1237 options[i].data = lease->options[i].data;
1238 options[i].len = lease->options[i].len;
1240 if (client->state == S_REQUESTING ||
1241 client->state == S_REBOOTING) {
1242 client->requested_address = lease->address;
1243 i = DHO_DHCP_REQUESTED_ADDRESS;
1244 options[i].data = lease->address.iabuf;
1245 options[i].len = lease->address.len;
1247 client->requested_address.len = 0;
1249 /* Send any options requested in the config file. */
1250 for (i = 0; i < 256; i++)
1251 if (!options[i].data && config->send_options[i].data) {
1252 options[i].data = config->send_options[i].data;
1253 options[i].len = config->send_options[i].len;
1256 /* Set up the option buffer to fit in a minimal UDP packet. */
1257 i = cons_options(client->packet.options, 576 - DHCP_FIXED_LEN,
1259 if (i == -1 || client->packet.options[i] != DHO_END)
1260 error("options do not fit in DHCPREQUEST packet.");
1261 client->packet_length = DHCP_FIXED_NON_UDP+i+1;
1262 if (client->packet_length < BOOTP_MIN_LEN)
1263 client->packet_length = BOOTP_MIN_LEN;
1265 client->packet.op = BOOTREQUEST;
1266 client->packet.htype = ifi->hw_address.htype;
1267 client->packet.hlen = ifi->hw_address.hlen;
1268 client->packet.hops = 0;
1269 client->packet.xid = client->xid;
1270 client->packet.secs = 0; /* Filled in by send_request. */
1271 client->packet.flags = 0;
1273 /* If we own the address we're requesting, put it in ciaddr;
1274 otherwise set ciaddr to zero. */
1275 if (client->state == S_BOUND ||
1276 client->state == S_RENEWING ||
1277 client->state == S_REBINDING) {
1278 memcpy(&client->packet.ciaddr,
1279 lease->address.iabuf, lease->address.len);
1281 memset(&client->packet.ciaddr, 0,
1282 sizeof(client->packet.ciaddr));
1285 memset(&client->packet.yiaddr, 0, sizeof(client->packet.yiaddr));
1286 memset(&client->packet.siaddr, 0, sizeof(client->packet.siaddr));
1287 memset(&client->packet.giaddr, 0, sizeof(client->packet.giaddr));
1288 memcpy(client->packet.chaddr, ifi->hw_address.haddr,
1289 ifi->hw_address.hlen);
1293 make_decline(struct client_lease *lease)
1295 struct option_data options[256];
1296 unsigned char decline = DHCPDECLINE;
1299 memset(options, 0, sizeof(options));
1300 memset(&client->packet, 0, sizeof(client->packet));
1302 /* Set DHCP_MESSAGE_TYPE to DHCPDECLINE */
1303 i = DHO_DHCP_MESSAGE_TYPE;
1304 options[i].data = &decline;
1305 options[i].len = sizeof(decline);
1307 /* Send back the server identifier... */
1308 i = DHO_DHCP_SERVER_IDENTIFIER;
1309 options[i].data = lease->options[i].data;
1310 options[i].len = lease->options[i].len;
1312 /* Send back the address we're declining. */
1313 i = DHO_DHCP_REQUESTED_ADDRESS;
1314 options[i].data = lease->address.iabuf;
1315 options[i].len = lease->address.len;
1317 /* Send the uid if the user supplied one. */
1318 i = DHO_DHCP_CLIENT_IDENTIFIER;
1319 if (config->send_options[i].len) {
1320 options[i].data = config->send_options[i].data;
1321 options[i].len = config->send_options[i].len;
1324 /* Set up the option buffer to fit in a minimal UDP packet. */
1325 i = cons_options(client->packet.options, 576 - DHCP_FIXED_LEN,
1327 if (i == -1 || client->packet.options[i] != DHO_END)
1328 error("options do not fit in DHCPDECLINE packet.");
1329 client->packet_length = DHCP_FIXED_NON_UDP+i+1;
1330 if (client->packet_length < BOOTP_MIN_LEN)
1331 client->packet_length = BOOTP_MIN_LEN;
1333 client->packet.op = BOOTREQUEST;
1334 client->packet.htype = ifi->hw_address.htype;
1335 client->packet.hlen = ifi->hw_address.hlen;
1336 client->packet.hops = 0;
1337 client->packet.xid = client->xid;
1338 client->packet.secs = 0; /* Filled in by send_request. */
1339 client->packet.flags = 0;
1341 /* ciaddr must always be zero. */
1342 memset(&client->packet.ciaddr, 0, sizeof(client->packet.ciaddr));
1343 memset(&client->packet.yiaddr, 0, sizeof(client->packet.yiaddr));
1344 memset(&client->packet.siaddr, 0, sizeof(client->packet.siaddr));
1345 memset(&client->packet.giaddr, 0, sizeof(client->packet.giaddr));
1346 memcpy(client->packet.chaddr, ifi->hw_address.haddr,
1347 ifi->hw_address.hlen);
1351 free_client_lease(struct client_lease *lease)
1355 if (lease->server_name)
1356 free(lease->server_name);
1357 if (lease->filename)
1358 free(lease->filename);
1359 for (i = 0; i < 256; i++) {
1360 if (lease->options[i].len)
1361 free(lease->options[i].data);
1367 rewrite_client_leases(void)
1369 struct client_lease *lp;
1371 if (!leaseFile) /* XXX */
1372 error("lease file not open");
1377 for (lp = client->leases; lp; lp = lp->next)
1378 write_client_lease(lp, 1);
1380 write_client_lease(client->active, 1);
1383 ftruncate(fileno(leaseFile), ftello(leaseFile));
1384 fsync(fileno(leaseFile));
1388 write_client_lease(struct client_lease *lease, int rewrite)
1390 static int leases_written;
1395 if (leases_written++ > 20) {
1396 rewrite_client_leases();
1401 /* If the lease came from the config file, we don't need to stash
1402 a copy in the lease database. */
1403 if (lease->is_static)
1406 if (!leaseFile) /* XXX */
1407 error("lease file not open");
1409 fprintf(leaseFile, "lease {\n");
1410 if (lease->is_bootp)
1411 fprintf(leaseFile, " bootp;\n");
1412 fprintf(leaseFile, " interface \"%s\";\n", ifi->name);
1413 fprintf(leaseFile, " fixed-address %s;\n", piaddr(lease->address));
1414 if (lease->filename)
1415 fprintf(leaseFile, " filename \"%s\";\n", lease->filename);
1416 if (lease->server_name)
1417 fprintf(leaseFile, " server-name \"%s\";\n",
1418 lease->server_name);
1419 for (i = 0; i < 256; i++)
1420 if (lease->options[i].len)
1421 fprintf(leaseFile, " option %s %s;\n",
1422 dhcp_options[i].name,
1423 pretty_print_option(i, lease->options[i].data,
1424 lease->options[i].len, 1, 1));
1426 t = gmtime(&lease->renewal);
1427 fprintf(leaseFile, " renew %d %d/%d/%d %02d:%02d:%02d;\n",
1428 t->tm_wday, t->tm_year + 1900, t->tm_mon + 1, t->tm_mday,
1429 t->tm_hour, t->tm_min, t->tm_sec);
1430 t = gmtime(&lease->rebind);
1431 fprintf(leaseFile, " rebind %d %d/%d/%d %02d:%02d:%02d;\n",
1432 t->tm_wday, t->tm_year + 1900, t->tm_mon + 1, t->tm_mday,
1433 t->tm_hour, t->tm_min, t->tm_sec);
1434 t = gmtime(&lease->expiry);
1435 fprintf(leaseFile, " expire %d %d/%d/%d %02d:%02d:%02d;\n",
1436 t->tm_wday, t->tm_year + 1900, t->tm_mon + 1, t->tm_mday,
1437 t->tm_hour, t->tm_min, t->tm_sec);
1438 fprintf(leaseFile, "}\n");
1443 script_init(char *reason)
1446 struct imsg_hdr hdr;
1449 hdr.code = IMSG_SCRIPT_INIT;
1450 hdr.len = sizeof(struct imsg_hdr) + sizeof(size_t) + strlen(reason);
1451 buf = buf_open(hdr.len);
1453 buf_add(buf, &hdr, sizeof(hdr));
1454 len = strlen(reason);
1455 buf_add(buf, &len, sizeof(len));
1456 buf_add(buf, reason, len);
1458 buf_close(privfd, buf);
1462 priv_script_init(char *reason)
1464 client->scriptEnvsize = 100;
1465 if (client->scriptEnv == NULL)
1467 calloc(client->scriptEnvsize, sizeof(char *));
1468 if (client->scriptEnv == NULL)
1469 error("script_init: no memory for environment");
1471 client->scriptEnv[0] = strdup(CLIENT_PATH);
1472 if (client->scriptEnv[0] == NULL)
1473 error("script_init: no memory for environment");
1475 client->scriptEnv[1] = NULL;
1477 script_set_env("", "interface", ifi->name);
1479 script_set_env("", "reason", reason);
1483 priv_script_write_params(char *prefix, struct client_lease *lease)
1485 u_int8_t dbuf[1500];
1489 script_set_env(prefix, "ip_address", piaddr(lease->address));
1491 if (lease->options[DHO_SUBNET_MASK].len &&
1492 (lease->options[DHO_SUBNET_MASK].len <
1493 sizeof(lease->address.iabuf))) {
1494 struct iaddr netmask, subnet, broadcast;
1496 memcpy(netmask.iabuf, lease->options[DHO_SUBNET_MASK].data,
1497 lease->options[DHO_SUBNET_MASK].len);
1498 netmask.len = lease->options[DHO_SUBNET_MASK].len;
1500 subnet = subnet_number(lease->address, netmask);
1502 script_set_env(prefix, "network_number",
1504 if (!lease->options[DHO_BROADCAST_ADDRESS].len) {
1505 broadcast = broadcast_addr(subnet, netmask);
1507 script_set_env(prefix,
1508 "broadcast_address",
1514 if (lease->filename)
1515 script_set_env(prefix, "filename", lease->filename);
1516 if (lease->server_name)
1517 script_set_env(prefix, "server_name",
1518 lease->server_name);
1519 for (i = 0; i < 256; i++) {
1520 u_int8_t *dp = NULL;
1522 if (config->defaults[i].len) {
1523 if (lease->options[i].len) {
1524 switch (config->default_actions[i]) {
1525 case ACTION_DEFAULT:
1526 dp = lease->options[i].data;
1527 len = lease->options[i].len;
1529 case ACTION_SUPERSEDE:
1531 dp = config->defaults[i].data;
1532 len = config->defaults[i].len;
1534 case ACTION_PREPEND:
1535 len = config->defaults[i].len +
1536 lease->options[i].len;
1537 if (len >= sizeof(dbuf)) {
1538 warning("no space to %s %s",
1540 dhcp_options[i].name);
1545 config->defaults[i].data,
1546 config->defaults[i].len);
1548 config->defaults[i].len,
1549 lease->options[i].data,
1550 lease->options[i].len);
1554 len = config->defaults[i].len +
1555 lease->options[i].len;
1556 if (len >= sizeof(dbuf)) {
1557 warning("no space to %s %s",
1559 dhcp_options[i].name);
1563 memcpy(dp, lease->options[i].data,
1564 lease->options[i].len);
1565 memcpy(dp + lease->options[i].len,
1566 config->defaults[i].data,
1567 config->defaults[i].len);
1571 dp = config->defaults[i].data;
1572 len = config->defaults[i].len;
1574 } else if (lease->options[i].len) {
1575 len = lease->options[i].len;
1576 dp = lease->options[i].data;
1583 if (dhcp_option_ev_name(name, sizeof(name),
1585 script_set_env(prefix, name,
1586 pretty_print_option(i, dp, len, 0, 0));
1589 snprintf(tbuf, sizeof(tbuf), "%d", (int)lease->expiry);
1590 script_set_env(prefix, "expiry", tbuf);
1594 script_write_params(char *prefix, struct client_lease *lease)
1596 size_t fn_len = 0, sn_len = 0, pr_len = 0;
1597 struct imsg_hdr hdr;
1601 if (lease->filename != NULL)
1602 fn_len = strlen(lease->filename);
1603 if (lease->server_name != NULL)
1604 sn_len = strlen(lease->server_name);
1606 pr_len = strlen(prefix);
1608 hdr.code = IMSG_SCRIPT_WRITE_PARAMS;
1609 hdr.len = sizeof(hdr) + sizeof(struct client_lease) +
1610 sizeof(size_t) + fn_len + sizeof(size_t) + sn_len +
1611 sizeof(size_t) + pr_len;
1613 for (i = 0; i < 256; i++)
1614 hdr.len += sizeof(int) + lease->options[i].len;
1616 scripttime = time(NULL);
1618 buf = buf_open(hdr.len);
1620 buf_add(buf, &hdr, sizeof(hdr));
1621 buf_add(buf, lease, sizeof(struct client_lease));
1622 buf_add(buf, &fn_len, sizeof(fn_len));
1623 buf_add(buf, lease->filename, fn_len);
1624 buf_add(buf, &sn_len, sizeof(sn_len));
1625 buf_add(buf, lease->server_name, sn_len);
1626 buf_add(buf, &pr_len, sizeof(pr_len));
1627 buf_add(buf, prefix, pr_len);
1629 for (i = 0; i < 256; i++) {
1630 buf_add(buf, &lease->options[i].len,
1631 sizeof(lease->options[i].len));
1632 buf_add(buf, lease->options[i].data,
1633 lease->options[i].len);
1636 buf_close(privfd, buf);
1642 struct imsg_hdr hdr;
1646 scripttime = time(NULL);
1648 hdr.code = IMSG_SCRIPT_GO;
1649 hdr.len = sizeof(struct imsg_hdr);
1651 buf = buf_open(hdr.len);
1653 buf_add(buf, &hdr, sizeof(hdr));
1654 buf_close(privfd, buf);
1656 bzero(&hdr, sizeof(hdr));
1657 buf_read(privfd, &hdr, sizeof(hdr));
1658 if (hdr.code != IMSG_SCRIPT_GO_RET)
1659 error("unexpected msg type %u", hdr.code);
1660 if (hdr.len != sizeof(hdr) + sizeof(int))
1661 error("received corrupted message");
1662 buf_read(privfd, &ret, sizeof(ret));
1668 priv_script_go(void)
1670 char *scriptName, *argv[2], **envp;
1671 int pid, wpid, wstatus;
1673 scripttime = time(NULL);
1675 scriptName = config->script_name;
1676 envp = client->scriptEnv;
1678 argv[0] = scriptName;
1687 wpid = wait(&wstatus);
1688 } while (wpid != pid && wpid > 0);
1694 execve(scriptName, argv, envp);
1695 error("execve (%s, ...): %m", scriptName);
1700 return (WEXITSTATUS(wstatus));
1704 script_set_env(const char *prefix, const char *name, const char *value)
1708 namelen = strlen(name);
1710 for (i = 0; client->scriptEnv[i]; i++)
1711 if (strncmp(client->scriptEnv[i], name, namelen) == 0 &&
1712 client->scriptEnv[i][namelen] == '=')
1715 if (client->scriptEnv[i])
1716 /* Reuse the slot. */
1717 free(client->scriptEnv[i]);
1719 /* New variable. Expand if necessary. */
1720 if (i >= client->scriptEnvsize - 1) {
1721 char **newscriptEnv;
1722 int newscriptEnvsize = client->scriptEnvsize + 50;
1724 newscriptEnv = realloc(client->scriptEnv,
1726 if (newscriptEnv == NULL) {
1727 free(client->scriptEnv);
1728 client->scriptEnv = NULL;
1729 client->scriptEnvsize = 0;
1730 error("script_set_env: no memory for variable");
1732 client->scriptEnv = newscriptEnv;
1733 client->scriptEnvsize = newscriptEnvsize;
1735 /* need to set the NULL pointer at end of array beyond
1737 client->scriptEnv[i + 1] = NULL;
1739 /* Allocate space and format the variable in the appropriate slot. */
1740 client->scriptEnv[i] = malloc(strlen(prefix) + strlen(name) + 1 +
1742 if (client->scriptEnv[i] == NULL)
1743 error("script_set_env: no memory for variable assignment");
1745 /* No `` or $() command substitution allowed in environment values! */
1746 for (j = 0; j < strlen(value); j++)
1750 error("illegal character (%c) in value '%s'", value[j],
1754 snprintf(client->scriptEnv[i], strlen(prefix) + strlen(name) +
1755 1 + strlen(value) + 1, "%s%s=%s", prefix, name, value);
1759 script_flush_env(void)
1763 for (i = 0; client->scriptEnv[i]; i++) {
1764 free(client->scriptEnv[i]);
1765 client->scriptEnv[i] = NULL;
1767 client->scriptEnvsize = 0;
1771 dhcp_option_ev_name(char *buf, size_t buflen, const struct option *option)
1775 for (i = 0; option->name[i]; i++) {
1776 if (i + 1 == buflen)
1778 if (option->name[i] == '-')
1781 buf[i] = option->name[i];
1791 static int state = 0;
1793 if (no_daemon || state)
1798 /* Stop logging to stderr... */
1801 if (daemon(1, 0) == -1)
1804 /* we are chrooted, daemon(3) fails to open /dev/null */
1806 dup2(nullfd, STDIN_FILENO);
1807 dup2(nullfd, STDOUT_FILENO);
1808 dup2(nullfd, STDERR_FILENO);
1815 check_option(struct client_lease *l, int option)
1820 /* we use this, since this is what gets passed to dhclient-script */
1822 opbuf = pretty_print_option(option, l->options[option].data,
1823 l->options[option].len, 0, 0);
1825 sbuf = option_as_string(option, l->options[option].data,
1826 l->options[option].len);
1829 case DHO_SUBNET_MASK:
1830 case DHO_SWAP_SERVER:
1831 case DHO_BROADCAST_ADDRESS:
1832 case DHO_DHCP_SERVER_IDENTIFIER:
1833 case DHO_ROUTER_SOLICITATION_ADDRESS:
1834 case DHO_DHCP_REQUESTED_ADDRESS:
1835 if (ipv4addrs(opbuf) == 0) {
1836 warning("Invalid IP address in option %s: %s",
1837 dhcp_options[option].name, opbuf);
1840 if (l->options[option].len != 4) { /* RFC 2132 */
1841 warning("warning: Only 1 IP address allowed in "
1842 "%s option; length %d, must be 4",
1843 dhcp_options[option].name,
1844 l->options[option].len);
1845 l->options[option].len = 4;
1848 case DHO_TIME_SERVERS:
1849 case DHO_NAME_SERVERS:
1851 case DHO_DOMAIN_NAME_SERVERS:
1852 case DHO_LOG_SERVERS:
1853 case DHO_COOKIE_SERVERS:
1854 case DHO_LPR_SERVERS:
1855 case DHO_IMPRESS_SERVERS:
1856 case DHO_RESOURCE_LOCATION_SERVERS:
1857 case DHO_NIS_SERVERS:
1858 case DHO_NTP_SERVERS:
1859 case DHO_NETBIOS_NAME_SERVERS:
1860 case DHO_NETBIOS_DD_SERVER:
1861 case DHO_FONT_SERVERS:
1862 if (ipv4addrs(opbuf) == 0) {
1863 warning("Invalid IP address in option %s: %s",
1864 dhcp_options[option].name, opbuf);
1869 case DHO_DOMAIN_NAME:
1870 case DHO_NIS_DOMAIN:
1871 if (!res_hnok(sbuf)) {
1872 warning("Bogus Host Name option %d: %s (%s)", option,
1874 l->options[option].len = 0;
1875 free(l->options[option].data);
1879 case DHO_TIME_OFFSET:
1881 case DHO_MERIT_DUMP:
1883 case DHO_EXTENSIONS_PATH:
1884 case DHO_IP_FORWARDING:
1885 case DHO_NON_LOCAL_SOURCE_ROUTING:
1886 case DHO_POLICY_FILTER:
1887 case DHO_MAX_DGRAM_REASSEMBLY:
1888 case DHO_DEFAULT_IP_TTL:
1889 case DHO_PATH_MTU_AGING_TIMEOUT:
1890 case DHO_PATH_MTU_PLATEAU_TABLE:
1891 case DHO_INTERFACE_MTU:
1892 case DHO_ALL_SUBNETS_LOCAL:
1893 case DHO_PERFORM_MASK_DISCOVERY:
1894 case DHO_MASK_SUPPLIER:
1895 case DHO_ROUTER_DISCOVERY:
1896 case DHO_STATIC_ROUTES:
1897 case DHO_TRAILER_ENCAPSULATION:
1898 case DHO_ARP_CACHE_TIMEOUT:
1899 case DHO_IEEE802_3_ENCAPSULATION:
1900 case DHO_DEFAULT_TCP_TTL:
1901 case DHO_TCP_KEEPALIVE_INTERVAL:
1902 case DHO_TCP_KEEPALIVE_GARBAGE:
1903 case DHO_VENDOR_ENCAPSULATED_OPTIONS:
1904 case DHO_NETBIOS_NODE_TYPE:
1905 case DHO_NETBIOS_SCOPE:
1906 case DHO_X_DISPLAY_MANAGER:
1907 case DHO_DHCP_LEASE_TIME:
1908 case DHO_DHCP_OPTION_OVERLOAD:
1909 case DHO_DHCP_MESSAGE_TYPE:
1910 case DHO_DHCP_PARAMETER_REQUEST_LIST:
1911 case DHO_DHCP_MESSAGE:
1912 case DHO_DHCP_MAX_MESSAGE_SIZE:
1913 case DHO_DHCP_RENEWAL_TIME:
1914 case DHO_DHCP_REBINDING_TIME:
1915 case DHO_DHCP_CLASS_IDENTIFIER:
1916 case DHO_DHCP_CLIENT_IDENTIFIER:
1917 case DHO_DHCP_USER_CLASS_ID:
1918 case DHO_TFTP_SERVER:
1923 warning("unknown dhcp option value 0x%x", option);
1924 return (unknown_ok);
1929 res_hnok(const char *name)
1931 const char *dn = name;
1932 int pch = '.', ch = *dn++;
1935 while (ch != '\0') {
1940 } else if (pch == '.' || nch == '.' || nch == '\0') {
1943 } else if (!isalnum(ch) && ch != '-' && ch != '_')
1945 else if (ch == '_' && warn == 0) {
1946 warning("warning: hostname %s contains an "
1947 "underscore which violates RFC 952", name);
1955 /* Does buf consist only of dotted decimal ipv4 addrs?
1956 * return how many if so,
1957 * otherwise, return 0
1960 ipv4addrs(char * buf)
1965 while (inet_aton(buf, &jnk) == 1){
1967 while (*buf == '.' || isdigit(*buf))
1978 option_as_string(unsigned int code, unsigned char *data, int len)
1980 static char optbuf[32768]; /* XXX */
1982 int opleft = sizeof(optbuf);
1983 unsigned char *dp = data;
1986 error("option_as_string: bad code %d", code);
1988 for (; dp < data + len; dp++) {
1989 if (!isascii(*dp) || !isprint(*dp)) {
1990 if (dp + 1 != data + len || *dp != 0) {
1992 snprintf(op, opleft, "\\%03o", *dp);
1997 } else if (*dp == '"' || *dp == '\'' || *dp == '$' ||
1998 *dp == '`' || *dp == '\\') {
2012 warning("dhcp option too large");
2017 fork_privchld(int fd, int fd2)
2019 struct pollfd pfd[1];
2020 int nfds, pfail = 0;
2024 error("cannot fork");
2032 if (chdir("/") == -1)
2033 error("chdir(\"/\")");
2035 setproctitle("%s [priv]", ifi->name);
2037 dup2(nullfd, STDIN_FILENO);
2038 dup2(nullfd, STDOUT_FILENO);
2039 dup2(nullfd, STDERR_FILENO);
2045 pfd[0].events = POLLIN;
2046 if ((nfds = poll(pfd, 1, INFTIM)) == -1)
2048 error("poll error");
2051 * Handle temporary errors, but bail if they persist.
2053 if (nfds == 0 || !(pfd[0].revents & POLLIN)) {
2054 if (pfail > POLL_FAILURES)
2055 error("poll failed > %d times", POLL_FAILURES);
2056 sleep(pfail * POLL_FAILURE_WAIT);
2066 get_ifname(char *ifname, char *arg)
2068 struct ifgroupreq ifgr;
2069 struct ifg_req *ifg;
2072 if (!strcmp(arg, "egress")) {
2073 s = socket(AF_INET, SOCK_DGRAM, 0);
2075 error("socket error");
2076 bzero(&ifgr, sizeof(ifgr));
2077 strlcpy(ifgr.ifgr_name, "egress", sizeof(ifgr.ifgr_name));
2078 if (ioctl(s, SIOCGIFGMEMB, (caddr_t)&ifgr) == -1) {
2079 if (errno == ENOENT)
2080 error("no interface in group egress found");
2081 error("ioctl SIOCGIFGMEMB: %m");
2083 len = ifgr.ifgr_len;
2084 if ((ifgr.ifgr_groups = calloc(1, len)) == NULL)
2085 error("get_ifname");
2086 if (ioctl(s, SIOCGIFGMEMB, (caddr_t)&ifgr) == -1)
2087 error("ioctl SIOCGIFGMEMB: %m");
2090 for (ifg = ifgr.ifgr_groups;
2091 ifg && len >= sizeof(struct ifg_req); ifg++) {
2092 len -= sizeof(struct ifg_req);
2094 error("too many interfaces in group egress");
2095 arg = ifg->ifgrq_member;
2098 if (strlcpy(ifi->name, arg, IFNAMSIZ) >= IFNAMSIZ)
2099 error("Interface name too long: %m");
2101 free(ifgr.ifgr_groups);
2103 } else if (strlcpy(ifi->name, arg, IFNAMSIZ) >= IFNAMSIZ)
2104 error("Interface name too long");