1 /* $OpenBSD: dhclient.c,v 1.63 2005/02/06 17:10:13 krw Exp $ */
4 * SPDX-License-Identifier: BSD-3-Clause
6 * Copyright 2004 Henning Brauer <henning@openbsd.org>
7 * Copyright (c) 1995, 1996, 1997, 1998, 1999
8 * The Internet Software Consortium. All rights reserved.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 * 3. Neither the name of The Internet Software Consortium nor the names
20 * of its contributors may be used to endorse or promote products derived
21 * from this software without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE INTERNET SOFTWARE CONSORTIUM AND
24 * CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
25 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
26 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
27 * DISCLAIMED. IN NO EVENT SHALL THE INTERNET SOFTWARE CONSORTIUM OR
28 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
29 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
30 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
31 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
32 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
33 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
34 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
37 * This software has been written for the Internet Software Consortium
38 * by Ted Lemon <mellon@fugue.com> in cooperation with Vixie
39 * Enterprises. To learn more about the Internet Software Consortium,
40 * see ``http://www.vix.com/isc''. To learn more about Vixie
41 * Enterprises, see ``http://www.vix.com''.
43 * This client was substantially modified and enhanced by Elliot Poger
44 * for use on Linux while he was working on the MosquitoNet project at
47 * The current version owes much to Elliot's Linux enhancements, but
48 * was substantially reorganized and partially rewritten by Ted Lemon
49 * so as to use the same networking framework that the Internet Software
50 * Consortium DHCP server uses. Much system-specific configuration code
51 * was moved into a shell script so that as support for more operating
52 * systems is added, it will not be necessary to port and maintain
53 * system-specific configuration code to these operating systems - instead,
54 * the shell script can invoke the native tools to accomplish the same
58 #include <sys/cdefs.h>
59 __FBSDID("$FreeBSD$");
64 #include <sys/capsicum.h>
65 #include <sys/endian.h>
67 #include <capsicum_helpers.h>
70 #include <net80211/ieee80211_freebsd.h>
73 #ifndef _PATH_VAREMPTY
74 #define _PATH_VAREMPTY "/var/empty"
78 #define hyphenchar(c) ((c) == 0x2d)
79 #define bslashchar(c) ((c) == 0x5c)
80 #define periodchar(c) ((c) == PERIOD)
81 #define asterchar(c) ((c) == 0x2a)
82 #define alphachar(c) (((c) >= 0x41 && (c) <= 0x5a) || \
83 ((c) >= 0x61 && (c) <= 0x7a))
84 #define digitchar(c) ((c) >= 0x30 && (c) <= 0x39)
85 #define whitechar(c) ((c) == ' ' || (c) == '\t')
87 #define borderchar(c) (alphachar(c) || digitchar(c))
88 #define middlechar(c) (borderchar(c) || hyphenchar(c))
89 #define domainchar(c) ((c) > 0x20 && (c) < 0x7f)
91 #define CLIENT_PATH "PATH=/usr/bin:/usr/sbin:/bin:/sbin"
93 cap_channel_t *capsyslog;
96 static time_t default_lease_time = 43200; /* 12 hours... */
98 const char *path_dhclient_conf = _PATH_DHCLIENT_CONF;
99 char *path_dhclient_db = NULL;
103 static int nullfd = -1;
105 static char hostname[_POSIX_HOST_NAME_MAX + 1];
107 static struct iaddr iaddr_broadcast = { 4, { 255, 255, 255, 255 } };
108 static struct in_addr inaddr_any, inaddr_broadcast;
110 static char *path_dhclient_pidfile;
111 struct pidfh *pidfile;
114 * ASSERT_STATE() does nothing now; it used to be
115 * assert (state_is == state_shouldbe).
117 #define ASSERT_STATE(state_is, state_shouldbe) {}
120 * We need to check that the expiry, renewal and rebind times are not beyond
121 * the end of time (~2038 when a 32-bit time_t is being used).
123 #define TIME_MAX ((((time_t) 1 << (sizeof(time_t) * CHAR_BIT - 2)) - 1) * 2 + 1)
126 static int no_daemon;
127 static int unknown_ok = 1;
130 struct interface_info *ifi;
132 int findproto(char *, int);
133 struct sockaddr *get_ifa(char *, int);
134 void routehandler(struct protocol *);
136 int check_option(struct client_lease *l, int option);
137 int check_classless_option(unsigned char *data, int len);
138 int ipv4addrs(const char * buf);
139 int res_hnok(const char *dn);
140 int check_search(const char *srch);
141 const char *option_as_string(unsigned int code, unsigned char *data, int len);
142 int fork_privchld(int, int);
145 ((a) > 0 ? (1 + (((a) - 1) | (sizeof(long) - 1))) : sizeof(long))
146 #define ADVANCE(x, n) (x += ROUNDUP((n)->sa_len))
148 /* Minimum MTU is 68 as per RFC791, p. 24 */
151 static time_t scripttime;
154 findproto(char *cp, int n)
161 for (i = 1; i; i <<= 1) {
163 sa = (struct sockaddr *)cp;
169 if (sa->sa_family == AF_INET)
171 if (sa->sa_family == AF_INET6)
184 get_ifa(char *cp, int n)
191 for (i = 1; i; i <<= 1)
193 sa = (struct sockaddr *)cp;
202 static struct iaddr defaddr = { .len = 4 };
203 static uint8_t curbssid[6];
208 struct interface_info *_ifi = arg;
211 * Clear existing state.
213 if (_ifi->client->active != NULL) {
214 script_init("EXPIRE", NULL);
215 script_write_params("old_",
216 _ifi->client->active);
217 if (_ifi->client->alias)
218 script_write_params("alias_",
219 _ifi->client->alias);
222 _ifi->client->state = S_INIT;
226 routehandler(struct protocol *p __unused)
228 char msg[2048], *addr;
229 struct rt_msghdr *rtm;
230 struct if_msghdr *ifm;
231 struct ifa_msghdr *ifam;
232 struct if_announcemsghdr *ifan;
233 struct ieee80211_join_event *jev;
234 struct client_lease *l;
235 time_t t = time(NULL);
236 struct sockaddr_in *sa;
241 n = read(routefd, &msg, sizeof(msg));
242 rtm = (struct rt_msghdr *)msg;
243 if (n < (ssize_t)sizeof(rtm->rtm_msglen) ||
244 n < (ssize_t)rtm->rtm_msglen ||
245 rtm->rtm_version != RTM_VERSION)
248 switch (rtm->rtm_type) {
251 ifam = (struct ifa_msghdr *)rtm;
253 if (ifam->ifam_index != ifi->index)
255 if (findproto((char *)(ifam + 1), ifam->ifam_addrs) != AF_INET)
257 if (scripttime == 0 || t < scripttime + 10)
260 sa = (struct sockaddr_in*)get_ifa((char *)(ifam + 1), ifam->ifam_addrs);
264 if ((a.len = sizeof(struct in_addr)) > sizeof(a.iabuf))
265 error("king bula sez: len mismatch");
266 memcpy(a.iabuf, &sa->sin_addr, a.len);
267 if (addr_eq(a, defaddr))
270 for (l = ifi->client->active; l != NULL; l = l->next)
271 if (addr_eq(a, l->address))
274 if (l == NULL) /* added/deleted addr is not the one we set */
277 addr = inet_ntoa(sa->sin_addr);
278 if (rtm->rtm_type == RTM_NEWADDR) {
280 * XXX: If someone other than us adds our address,
281 * should we assume they are taking over from us,
282 * delete the lease record, and exit without modifying
285 warning("My address (%s) was re-added", addr);
287 warning("My address (%s) was deleted, dhclient exiting",
293 ifm = (struct if_msghdr *)rtm;
294 if (ifm->ifm_index != ifi->index)
296 if ((rtm->rtm_flags & RTF_UP) == 0) {
297 warning("Interface %s is down, dhclient exiting",
301 linkstat = interface_link_status(ifi->name);
302 if (linkstat != ifi->linkstat) {
303 debug("%s link state %s -> %s", ifi->name,
304 ifi->linkstat ? "up" : "down",
305 linkstat ? "up" : "down");
306 ifi->linkstat = linkstat;
312 ifan = (struct if_announcemsghdr *)rtm;
313 if (ifan->ifan_what == IFAN_DEPARTURE &&
314 ifan->ifan_index == ifi->index) {
315 warning("Interface %s is gone, dhclient exiting",
321 ifan = (struct if_announcemsghdr *)rtm;
322 if (ifan->ifan_index != ifi->index)
324 switch (ifan->ifan_what) {
325 case RTM_IEEE80211_ASSOC:
326 case RTM_IEEE80211_REASSOC:
328 * Use assoc/reassoc event to kick state machine
329 * in case we roam. Otherwise fall back to the
330 * normal state machine just like a wired network.
332 jev = (struct ieee80211_join_event *) &ifan[1];
333 if (memcmp(curbssid, jev->iev_addr, 6)) {
337 memcpy(curbssid, jev->iev_addr, 6);
347 script_init("FAIL", NULL);
348 if (ifi->client->alias)
349 script_write_params("alias_", ifi->client->alias);
352 pidfile_remove(pidfile);
359 cap_channel_t *casper;
363 error("unable to start casper");
365 capsyslog = cap_service_open(casper, "system.syslog");
367 if (capsyslog == NULL)
368 error("unable to open system.syslog service");
372 main(int argc, char *argv[])
374 int ch, fd, quiet = 0, i = 0;
376 int immediate_daemon = 0;
383 /* Initially, log errors to stderr as well as to syslogd. */
384 cap_openlog(capsyslog, getprogname(), LOG_PID | LOG_NDELAY, DHCPD_LOG_FACILITY);
385 cap_setlogmask(capsyslog, LOG_UPTO(LOG_DEBUG));
387 while ((ch = getopt(argc, argv, "bc:dl:p:qu")) != -1)
390 immediate_daemon = 1;
393 path_dhclient_conf = optarg;
399 path_dhclient_db = optarg;
402 path_dhclient_pidfile = optarg;
420 if (path_dhclient_pidfile == NULL) {
421 asprintf(&path_dhclient_pidfile,
422 "%sdhclient.%s.pid", _PATH_VARRUN, *argv);
423 if (path_dhclient_pidfile == NULL)
426 pidfile = pidfile_open(path_dhclient_pidfile, 0644, &otherpid);
427 if (pidfile == NULL) {
429 error("dhclient already running, pid: %d.", otherpid);
431 error("dhclient already running.");
432 warning("Cannot open or create pidfile: %m");
435 if ((ifi = calloc(1, sizeof(struct interface_info))) == NULL)
437 if (strlcpy(ifi->name, argv[0], IFNAMSIZ) >= IFNAMSIZ)
438 error("Interface name too long");
439 if (path_dhclient_db == NULL && asprintf(&path_dhclient_db, "%s.%s",
440 _PATH_DHCLIENT_DB, ifi->name) == -1)
449 inaddr_broadcast.s_addr = INADDR_BROADCAST;
450 inaddr_any.s_addr = INADDR_ANY;
454 /* The next bit is potentially very time-consuming, so write out
455 the pidfile right away. We will write it out again with the
456 correct pid after daemonizing. */
458 pidfile_write(pidfile);
460 if (!interface_link_status(ifi->name)) {
461 fprintf(stderr, "%s: no link ...", ifi->name);
464 while (!interface_link_status(ifi->name)) {
465 fprintf(stderr, ".");
468 fprintf(stderr, " giving up\n");
473 fprintf(stderr, " got link\n");
477 if ((nullfd = open(_PATH_DEVNULL, O_RDWR, 0)) == -1)
478 error("cannot open %s: %m", _PATH_DEVNULL);
480 if ((pw = getpwnam("_dhcp")) == NULL) {
481 warning("no such user: _dhcp, falling back to \"nobody\"");
482 if ((pw = getpwnam("nobody")) == NULL)
483 error("no such user: nobody");
487 * Obtain hostname before entering capability mode - it won't be
488 * possible then, as reading kern.hostname is not permitted.
490 if (gethostname(hostname, sizeof(hostname)) < 0)
493 priv_script_init("PREINIT", NULL);
494 if (ifi->client->alias)
495 priv_script_write_params("alias_", ifi->client->alias);
498 /* set up the interface */
499 discover_interfaces(ifi);
501 if (pipe(pipe_fd) == -1)
504 fork_privchld(pipe_fd[0], pipe_fd[1]);
513 cap_rights_init(&rights, CAP_READ, CAP_WRITE);
514 if (cap_rights_limit(privfd, &rights) < 0 && errno != ENOSYS)
515 error("can't limit private descriptor: %m");
517 if ((fd = open(path_dhclient_db, O_RDONLY|O_EXLOCK|O_CREAT, 0)) == -1)
518 error("can't open and lock %s: %m", path_dhclient_db);
519 read_client_leases();
520 rewrite_client_leases();
523 if ((routefd = socket(PF_ROUTE, SOCK_RAW, 0)) != -1)
524 add_protocol("AF_ROUTE", routefd, routehandler, ifi);
525 if (shutdown(routefd, SHUT_WR) < 0)
526 error("can't shutdown route socket: %m");
527 cap_rights_init(&rights, CAP_EVENT, CAP_READ);
528 if (cap_rights_limit(routefd, &rights) < 0 && errno != ENOSYS)
529 error("can't limit route socket: %m");
531 if (chroot(_PATH_VAREMPTY) == -1)
533 if (chdir("/") == -1)
534 error("chdir(\"/\")");
536 if (setgroups(1, &pw->pw_gid) ||
537 setegid(pw->pw_gid) || setgid(pw->pw_gid) ||
538 seteuid(pw->pw_uid) || setuid(pw->pw_uid))
539 error("can't drop privileges: %m");
543 setproctitle("%s", ifi->name);
545 if (caph_enter_casper() < 0)
546 error("can't enter capability mode: %m");
548 if (immediate_daemon)
551 ifi->client->state = S_INIT;
554 bootp_packet_handler = do_packet;
566 fprintf(stderr, "usage: %s [-bdqu] ", getprogname());
567 fprintf(stderr, "[-c conffile] [-l leasefile] interface\n");
574 * Each routine is called from the dhclient_state_machine() in one of
576 * -> entering INIT state
577 * -> recvpacket_flag == 0: timeout in this state
578 * -> otherwise: received a packet in this state
580 * Return conditions as handled by dhclient_state_machine():
581 * Returns 1, sendpacket_flag = 1: send packet, reset timer.
582 * Returns 1, sendpacket_flag = 0: just reset the timer (wait for a milestone).
583 * Returns 0: finish the nap which was interrupted for no good reason.
585 * Several per-interface variables are used to keep track of the process:
586 * active_lease: the lease that is being used on the interface
587 * (null pointer if not configured yet).
588 * offered_leases: leases corresponding to DHCPOFFER messages that have
589 * been sent to us by DHCP servers.
590 * acked_leases: leases corresponding to DHCPACK messages that have been
591 * sent to us by DHCP servers.
592 * sendpacket: DHCP packet we're trying to send.
593 * destination: IP address to send sendpacket to
594 * In addition, there are several relevant per-lease variables.
595 * T1_expiry, T2_expiry, lease_expiry: lease milestones
596 * In the active lease, these control the process of renewing the lease;
597 * In leases on the acked_leases list, this simply determines when we
598 * can no longer legitimately use the lease.
602 state_reboot(void *ipp)
604 struct interface_info *ip = ipp;
606 /* If we don't remember an active lease, go straight to INIT. */
607 if (!ip->client->active || ip->client->active->is_bootp) {
612 /* We are in the rebooting state. */
613 ip->client->state = S_REBOOTING;
615 /* make_request doesn't initialize xid because it normally comes
616 from the DHCPDISCOVER, but we haven't sent a DHCPDISCOVER,
617 so pick an xid now. */
618 ip->client->xid = arc4random();
620 /* Make a DHCPREQUEST packet, and set appropriate per-interface
622 make_request(ip, ip->client->active);
623 ip->client->destination = iaddr_broadcast;
624 ip->client->first_sending = cur_time;
625 ip->client->interval = ip->client->config->initial_interval;
627 /* Zap the medium list... */
628 ip->client->medium = NULL;
630 /* Send out the first DHCPREQUEST packet. */
635 * Called when a lease has completely expired and we've
636 * been unable to renew it.
639 state_init(void *ipp)
641 struct interface_info *ip = ipp;
643 ASSERT_STATE(state, S_INIT);
645 /* Make a DHCPDISCOVER packet, and set appropriate per-interface
647 make_discover(ip, ip->client->active);
648 ip->client->xid = ip->client->packet.xid;
649 ip->client->destination = iaddr_broadcast;
650 ip->client->state = S_SELECTING;
651 ip->client->first_sending = cur_time;
652 ip->client->interval = ip->client->config->initial_interval;
654 /* Add an immediate timeout to cause the first DHCPDISCOVER packet
660 * state_selecting is called when one or more DHCPOFFER packets
661 * have been received and a configurable period of time has passed.
664 state_selecting(void *ipp)
666 struct interface_info *ip = ipp;
667 struct client_lease *lp, *next, *picked;
669 ASSERT_STATE(state, S_SELECTING);
671 /* Cancel state_selecting and send_discover timeouts, since either
672 one could have got us here. */
673 cancel_timeout(state_selecting, ip);
674 cancel_timeout(send_discover, ip);
676 /* We have received one or more DHCPOFFER packets. Currently,
677 the only criterion by which we judge leases is whether or
678 not we get a response when we arp for them. */
680 for (lp = ip->client->offered_leases; lp; lp = next) {
683 /* Check to see if we got an ARPREPLY for the address
684 in this particular lease. */
686 script_init("ARPCHECK", lp->medium);
687 script_write_params("check_", lp);
689 /* If the ARPCHECK code detects another
690 machine using the offered address, it exits
691 nonzero. We need to send a DHCPDECLINE and
694 make_decline(ip, lp);
702 free_client_lease(lp);
705 ip->client->offered_leases = NULL;
707 /* If we just tossed all the leases we were offered, go back
710 ip->client->state = S_INIT;
715 /* If it was a BOOTREPLY, we can just take the address right now. */
716 if (!picked->options[DHO_DHCP_MESSAGE_TYPE].len) {
717 ip->client->new = picked;
719 /* Make up some lease expiry times
720 XXX these should be configurable. */
721 ip->client->new->expiry = cur_time + 12000;
722 ip->client->new->renewal += cur_time + 8000;
723 ip->client->new->rebind += cur_time + 10000;
725 ip->client->state = S_REQUESTING;
727 /* Bind to the address we received. */
732 /* Go to the REQUESTING state. */
733 ip->client->destination = iaddr_broadcast;
734 ip->client->state = S_REQUESTING;
735 ip->client->first_sending = cur_time;
736 ip->client->interval = ip->client->config->initial_interval;
738 /* Make a DHCPREQUEST packet from the lease we picked. */
739 make_request(ip, picked);
740 ip->client->xid = ip->client->packet.xid;
742 /* Toss the lease we picked - we'll get it back in a DHCPACK. */
743 free_client_lease(picked);
745 /* Add an immediate timeout to send the first DHCPREQUEST packet. */
749 /* state_requesting is called when we receive a DHCPACK message after
750 having sent out one or more DHCPREQUEST packets. */
753 dhcpack(struct packet *packet)
755 struct interface_info *ip = packet->interface;
756 struct client_lease *lease;
758 /* If we're not receptive to an offer right now, or if the offer
759 has an unrecognizable transaction id, then just drop it. */
760 if (packet->interface->client->xid != packet->raw->xid ||
761 (packet->interface->hw_address.hlen != packet->raw->hlen) ||
762 (memcmp(packet->interface->hw_address.haddr,
763 packet->raw->chaddr, packet->raw->hlen)))
766 if (ip->client->state != S_REBOOTING &&
767 ip->client->state != S_REQUESTING &&
768 ip->client->state != S_RENEWING &&
769 ip->client->state != S_REBINDING)
772 note("DHCPACK from %s", piaddr(packet->client_addr));
774 lease = packet_to_lease(packet);
776 note("packet_to_lease failed.");
780 ip->client->new = lease;
782 /* Stop resending DHCPREQUEST. */
783 cancel_timeout(send_request, ip);
785 /* Figure out the lease time. */
786 if (ip->client->config->default_actions[DHO_DHCP_LEASE_TIME] ==
788 ip->client->new->expiry = getULong(
789 ip->client->config->defaults[DHO_DHCP_LEASE_TIME].data);
790 else if (ip->client->new->options[DHO_DHCP_LEASE_TIME].data)
791 ip->client->new->expiry = getULong(
792 ip->client->new->options[DHO_DHCP_LEASE_TIME].data);
794 ip->client->new->expiry = default_lease_time;
795 /* A number that looks negative here is really just very large,
796 because the lease expiry offset is unsigned. Also make sure that
797 the addition of cur_time below does not overflow (a 32 bit) time_t. */
798 if (ip->client->new->expiry < 0 ||
799 ip->client->new->expiry > TIME_MAX - cur_time)
800 ip->client->new->expiry = TIME_MAX - cur_time;
801 /* XXX should be fixed by resetting the client state */
802 if (ip->client->new->expiry < 60)
803 ip->client->new->expiry = 60;
805 /* Unless overridden in the config, take the server-provided renewal
806 * time if there is one. Otherwise figure it out according to the spec.
807 * Also make sure the renewal time does not exceed the expiry time.
809 if (ip->client->config->default_actions[DHO_DHCP_RENEWAL_TIME] ==
811 ip->client->new->renewal = getULong(
812 ip->client->config->defaults[DHO_DHCP_RENEWAL_TIME].data);
813 else if (ip->client->new->options[DHO_DHCP_RENEWAL_TIME].len)
814 ip->client->new->renewal = getULong(
815 ip->client->new->options[DHO_DHCP_RENEWAL_TIME].data);
817 ip->client->new->renewal = ip->client->new->expiry / 2;
818 if (ip->client->new->renewal < 0 ||
819 ip->client->new->renewal > ip->client->new->expiry / 2)
820 ip->client->new->renewal = ip->client->new->expiry / 2;
822 /* Same deal with the rebind time. */
823 if (ip->client->config->default_actions[DHO_DHCP_REBINDING_TIME] ==
825 ip->client->new->rebind = getULong(
826 ip->client->config->defaults[DHO_DHCP_REBINDING_TIME].data);
827 else if (ip->client->new->options[DHO_DHCP_REBINDING_TIME].len)
828 ip->client->new->rebind = getULong(
829 ip->client->new->options[DHO_DHCP_REBINDING_TIME].data);
831 ip->client->new->rebind = ip->client->new->renewal / 4 * 7;
832 if (ip->client->new->rebind < 0 ||
833 ip->client->new->rebind > ip->client->new->renewal / 4 * 7)
834 ip->client->new->rebind = ip->client->new->renewal / 4 * 7;
836 /* Convert the time offsets into seconds-since-the-epoch */
837 ip->client->new->expiry += cur_time;
838 ip->client->new->renewal += cur_time;
839 ip->client->new->rebind += cur_time;
845 bind_lease(struct interface_info *ip)
847 struct option_data *opt;
849 /* Remember the medium. */
850 ip->client->new->medium = ip->client->medium;
852 opt = &ip->client->new->options[DHO_INTERFACE_MTU];
853 if (opt->len == sizeof(u_int16_t)) {
855 bool supersede = (ip->client->config->default_actions[DHO_INTERFACE_MTU] ==
859 mtu = getUShort(ip->client->config->defaults[DHO_INTERFACE_MTU].data);
861 mtu = be16dec(opt->data);
864 /* Treat 0 like a user intentionally doesn't want to change MTU and,
865 * therefore, warning is not needed */
866 if (!supersede || mtu != 0)
867 warning("mtu size %u < %d: ignored", (unsigned)mtu, MIN_MTU);
869 interface_set_mtu_unpriv(privfd, mtu);
873 /* Write out the new lease. */
874 write_client_lease(ip, ip->client->new, 0);
876 /* Run the client script with the new parameters. */
877 script_init((ip->client->state == S_REQUESTING ? "BOUND" :
878 (ip->client->state == S_RENEWING ? "RENEW" :
879 (ip->client->state == S_REBOOTING ? "REBOOT" : "REBIND"))),
880 ip->client->new->medium);
881 if (ip->client->active && ip->client->state != S_REBOOTING)
882 script_write_params("old_", ip->client->active);
883 script_write_params("new_", ip->client->new);
884 if (ip->client->alias)
885 script_write_params("alias_", ip->client->alias);
888 /* Replace the old active lease with the new one. */
889 if (ip->client->active)
890 free_client_lease(ip->client->active);
891 ip->client->active = ip->client->new;
892 ip->client->new = NULL;
894 /* Set up a timeout to start the renewal process. */
895 add_timeout(ip->client->active->renewal, state_bound, ip);
897 note("bound to %s -- renewal in %d seconds.",
898 piaddr(ip->client->active->address),
899 (int)(ip->client->active->renewal - cur_time));
900 ip->client->state = S_BOUND;
901 reinitialize_interfaces();
906 * state_bound is called when we've successfully bound to a particular
907 * lease, but the renewal time on that lease has expired. We are
908 * expected to unicast a DHCPREQUEST to the server that gave us our
912 state_bound(void *ipp)
914 struct interface_info *ip = ipp;
916 ASSERT_STATE(state, S_BOUND);
918 /* T1 has expired. */
919 make_request(ip, ip->client->active);
920 ip->client->xid = ip->client->packet.xid;
922 if (ip->client->active->options[DHO_DHCP_SERVER_IDENTIFIER].len == 4) {
923 memcpy(ip->client->destination.iabuf, ip->client->active->
924 options[DHO_DHCP_SERVER_IDENTIFIER].data, 4);
925 ip->client->destination.len = 4;
927 ip->client->destination = iaddr_broadcast;
929 ip->client->first_sending = cur_time;
930 ip->client->interval = ip->client->config->initial_interval;
931 ip->client->state = S_RENEWING;
933 /* Send the first packet immediately. */
938 bootp(struct packet *packet)
940 struct iaddrlist *ap;
942 if (packet->raw->op != BOOTREPLY)
945 /* If there's a reject list, make sure this packet's sender isn't
947 for (ap = packet->interface->client->config->reject_list;
949 if (addr_eq(packet->client_addr, ap->addr)) {
950 note("BOOTREPLY from %s rejected.", piaddr(ap->addr));
958 dhcp(struct packet *packet)
960 struct iaddrlist *ap;
961 void (*handler)(struct packet *);
964 switch (packet->packet_type) {
981 /* If there's a reject list, make sure this packet's sender isn't
983 for (ap = packet->interface->client->config->reject_list;
985 if (addr_eq(packet->client_addr, ap->addr)) {
986 note("%s from %s rejected.", type, piaddr(ap->addr));
994 dhcpoffer(struct packet *packet)
996 struct interface_info *ip = packet->interface;
997 struct client_lease *lease, *lp;
999 int arp_timeout_needed, stop_selecting;
1000 const char *name = packet->options[DHO_DHCP_MESSAGE_TYPE].len ?
1001 "DHCPOFFER" : "BOOTREPLY";
1003 /* If we're not receptive to an offer right now, or if the offer
1004 has an unrecognizable transaction id, then just drop it. */
1005 if (ip->client->state != S_SELECTING ||
1006 packet->interface->client->xid != packet->raw->xid ||
1007 (packet->interface->hw_address.hlen != packet->raw->hlen) ||
1008 (memcmp(packet->interface->hw_address.haddr,
1009 packet->raw->chaddr, packet->raw->hlen)))
1012 note("%s from %s", name, piaddr(packet->client_addr));
1015 /* If this lease doesn't supply the minimum required parameters,
1017 for (i = 0; ip->client->config->required_options[i]; i++) {
1018 if (!packet->options[ip->client->config->
1019 required_options[i]].len) {
1020 note("%s isn't satisfactory.", name);
1025 /* If we've already seen this lease, don't record it again. */
1026 for (lease = ip->client->offered_leases;
1027 lease; lease = lease->next) {
1028 if (lease->address.len == sizeof(packet->raw->yiaddr) &&
1029 !memcmp(lease->address.iabuf,
1030 &packet->raw->yiaddr, lease->address.len)) {
1031 debug("%s already seen.", name);
1036 lease = packet_to_lease(packet);
1038 note("packet_to_lease failed.");
1042 /* If this lease was acquired through a BOOTREPLY, record that
1044 if (!packet->options[DHO_DHCP_MESSAGE_TYPE].len)
1045 lease->is_bootp = 1;
1047 /* Record the medium under which this lease was offered. */
1048 lease->medium = ip->client->medium;
1050 /* Send out an ARP Request for the offered IP address. */
1051 script_init("ARPSEND", lease->medium);
1052 script_write_params("check_", lease);
1053 /* If the script can't send an ARP request without waiting,
1054 we'll be waiting when we do the ARPCHECK, so don't wait now. */
1056 arp_timeout_needed = 0;
1058 arp_timeout_needed = 2;
1060 /* Figure out when we're supposed to stop selecting. */
1062 ip->client->first_sending + ip->client->config->select_interval;
1064 /* If this is the lease we asked for, put it at the head of the
1065 list, and don't mess with the arp request timeout. */
1066 if (lease->address.len == ip->client->requested_address.len &&
1067 !memcmp(lease->address.iabuf,
1068 ip->client->requested_address.iabuf,
1069 ip->client->requested_address.len)) {
1070 lease->next = ip->client->offered_leases;
1071 ip->client->offered_leases = lease;
1073 /* If we already have an offer, and arping for this
1074 offer would take us past the selection timeout,
1075 then don't extend the timeout - just hope for the
1077 if (ip->client->offered_leases &&
1078 (cur_time + arp_timeout_needed) > stop_selecting)
1079 arp_timeout_needed = 0;
1081 /* Put the lease at the end of the list. */
1083 if (!ip->client->offered_leases)
1084 ip->client->offered_leases = lease;
1086 for (lp = ip->client->offered_leases; lp->next;
1093 /* If we're supposed to stop selecting before we've had time
1094 to wait for the ARPREPLY, add some delay to wait for
1096 if (stop_selecting - cur_time < arp_timeout_needed)
1097 stop_selecting = cur_time + arp_timeout_needed;
1099 /* If the selecting interval has expired, go immediately to
1100 state_selecting(). Otherwise, time out into
1101 state_selecting at the select interval. */
1102 if (stop_selecting <= 0)
1103 state_selecting(ip);
1105 add_timeout(stop_selecting, state_selecting, ip);
1106 cancel_timeout(send_discover, ip);
1110 /* Allocate a client_lease structure and initialize it from the parameters
1111 in the specified packet. */
1113 struct client_lease *
1114 packet_to_lease(struct packet *packet)
1116 struct client_lease *lease;
1119 lease = malloc(sizeof(struct client_lease));
1122 warning("dhcpoffer: no memory to record lease.");
1126 memset(lease, 0, sizeof(*lease));
1128 /* Copy the lease options. */
1129 for (i = 0; i < 256; i++) {
1130 if (packet->options[i].len) {
1131 lease->options[i].data =
1132 malloc(packet->options[i].len + 1);
1133 if (!lease->options[i].data) {
1134 warning("dhcpoffer: no memory for option %d", i);
1135 free_client_lease(lease);
1138 memcpy(lease->options[i].data,
1139 packet->options[i].data,
1140 packet->options[i].len);
1141 lease->options[i].len =
1142 packet->options[i].len;
1143 lease->options[i].data[lease->options[i].len] =
1146 if (!check_option(lease,i)) {
1147 /* ignore a bogus lease offer */
1148 warning("Invalid lease option - ignoring offer");
1149 free_client_lease(lease);
1155 lease->address.len = sizeof(packet->raw->yiaddr);
1156 memcpy(lease->address.iabuf, &packet->raw->yiaddr, lease->address.len);
1158 lease->nextserver.len = sizeof(packet->raw->siaddr);
1159 memcpy(lease->nextserver.iabuf, &packet->raw->siaddr, lease->nextserver.len);
1161 /* If the server name was filled out, copy it.
1162 Do not attempt to validate the server name as a host name.
1163 RFC 2131 merely states that sname is NUL-terminated (which do
1164 do not assume) and that it is the server's host name. Since
1165 the ISC client and server allow arbitrary characters, we do
1167 if ((!packet->options[DHO_DHCP_OPTION_OVERLOAD].len ||
1168 !(packet->options[DHO_DHCP_OPTION_OVERLOAD].data[0] & 2)) &&
1169 packet->raw->sname[0]) {
1170 lease->server_name = malloc(DHCP_SNAME_LEN + 1);
1171 if (!lease->server_name) {
1172 warning("dhcpoffer: no memory for server name.");
1173 free_client_lease(lease);
1176 memcpy(lease->server_name, packet->raw->sname, DHCP_SNAME_LEN);
1177 lease->server_name[DHCP_SNAME_LEN]='\0';
1180 /* Ditto for the filename. */
1181 if ((!packet->options[DHO_DHCP_OPTION_OVERLOAD].len ||
1182 !(packet->options[DHO_DHCP_OPTION_OVERLOAD].data[0] & 1)) &&
1183 packet->raw->file[0]) {
1184 /* Don't count on the NUL terminator. */
1185 lease->filename = malloc(DHCP_FILE_LEN + 1);
1186 if (!lease->filename) {
1187 warning("dhcpoffer: no memory for filename.");
1188 free_client_lease(lease);
1191 memcpy(lease->filename, packet->raw->file, DHCP_FILE_LEN);
1192 lease->filename[DHCP_FILE_LEN]='\0';
1198 dhcpnak(struct packet *packet)
1200 struct interface_info *ip = packet->interface;
1202 /* If we're not receptive to an offer right now, or if the offer
1203 has an unrecognizable transaction id, then just drop it. */
1204 if (packet->interface->client->xid != packet->raw->xid ||
1205 (packet->interface->hw_address.hlen != packet->raw->hlen) ||
1206 (memcmp(packet->interface->hw_address.haddr,
1207 packet->raw->chaddr, packet->raw->hlen)))
1210 if (ip->client->state != S_REBOOTING &&
1211 ip->client->state != S_REQUESTING &&
1212 ip->client->state != S_RENEWING &&
1213 ip->client->state != S_REBINDING)
1216 note("DHCPNAK from %s", piaddr(packet->client_addr));
1218 if (!ip->client->active) {
1219 note("DHCPNAK with no active lease.\n");
1223 free_client_lease(ip->client->active);
1224 ip->client->active = NULL;
1226 /* Stop sending DHCPREQUEST packets... */
1227 cancel_timeout(send_request, ip);
1229 ip->client->state = S_INIT;
1233 /* Send out a DHCPDISCOVER packet, and set a timeout to send out another
1234 one after the right interval has expired. If we don't get an offer by
1235 the time we reach the panic interval, call the panic function. */
1238 send_discover(void *ipp)
1240 struct interface_info *ip = ipp;
1241 int interval, increase = 1;
1243 /* Figure out how long it's been since we started transmitting. */
1244 interval = cur_time - ip->client->first_sending;
1246 /* If we're past the panic timeout, call the script and tell it
1247 we haven't found anything for this interface yet. */
1248 if (interval > ip->client->config->timeout) {
1253 /* If we're selecting media, try the whole list before doing
1254 the exponential backoff, but if we've already received an
1255 offer, stop looping, because we obviously have it right. */
1256 if (!ip->client->offered_leases &&
1257 ip->client->config->media) {
1260 if (ip->client->medium) {
1261 ip->client->medium = ip->client->medium->next;
1264 if (!ip->client->medium) {
1266 error("No valid media types for %s!", ip->name);
1267 ip->client->medium = ip->client->config->media;
1271 note("Trying medium \"%s\" %d", ip->client->medium->string,
1273 script_init("MEDIUM", ip->client->medium);
1279 * If we're supposed to increase the interval, do so. If it's
1280 * currently zero (i.e., we haven't sent any packets yet), set
1281 * it to one; otherwise, add to it a random number between zero
1282 * and two times itself. On average, this means that it will
1283 * double with every transmission.
1286 if (!ip->client->interval)
1287 ip->client->interval =
1288 ip->client->config->initial_interval;
1290 ip->client->interval += (arc4random() >> 2) %
1291 (2 * ip->client->interval);
1294 /* Don't backoff past cutoff. */
1295 if (ip->client->interval >
1296 ip->client->config->backoff_cutoff)
1297 ip->client->interval =
1298 ((ip->client->config->backoff_cutoff / 2)
1299 + ((arc4random() >> 2) %
1300 ip->client->config->backoff_cutoff));
1301 } else if (!ip->client->interval)
1302 ip->client->interval =
1303 ip->client->config->initial_interval;
1305 /* If the backoff would take us to the panic timeout, just use that
1307 if (cur_time + ip->client->interval >
1308 ip->client->first_sending + ip->client->config->timeout)
1309 ip->client->interval =
1310 (ip->client->first_sending +
1311 ip->client->config->timeout) - cur_time + 1;
1313 /* Record the number of seconds since we started sending. */
1314 if (interval < 65536)
1315 ip->client->packet.secs = htons(interval);
1317 ip->client->packet.secs = htons(65535);
1318 ip->client->secs = ip->client->packet.secs;
1320 note("DHCPDISCOVER on %s to %s port %d interval %d",
1321 ip->name, inet_ntoa(inaddr_broadcast), REMOTE_PORT,
1322 (int)ip->client->interval);
1324 /* Send out a packet. */
1325 send_packet_unpriv(privfd, &ip->client->packet,
1326 ip->client->packet_length, inaddr_any, inaddr_broadcast);
1328 add_timeout(cur_time + ip->client->interval, send_discover, ip);
1332 * state_panic gets called if we haven't received any offers in a preset
1333 * amount of time. When this happens, we try to use existing leases
1334 * that haven't yet expired, and failing that, we call the client script
1335 * and hope it can do something.
1338 state_panic(void *ipp)
1340 struct interface_info *ip = ipp;
1341 struct client_lease *loop = ip->client->active;
1342 struct client_lease *lp;
1344 note("No DHCPOFFERS received.");
1346 /* We may not have an active lease, but we may have some
1347 predefined leases that we can try. */
1348 if (!ip->client->active && ip->client->leases)
1351 /* Run through the list of leases and see if one can be used. */
1352 while (ip->client->active) {
1353 if (ip->client->active->expiry > cur_time) {
1354 note("Trying recorded lease %s",
1355 piaddr(ip->client->active->address));
1356 /* Run the client script with the existing
1358 script_init("TIMEOUT",
1359 ip->client->active->medium);
1360 script_write_params("new_", ip->client->active);
1361 if (ip->client->alias)
1362 script_write_params("alias_",
1365 /* If the old lease is still good and doesn't
1366 yet need renewal, go into BOUND state and
1367 timeout at the renewal time. */
1370 ip->client->active->renewal) {
1371 ip->client->state = S_BOUND;
1372 note("bound: renewal in %d seconds.",
1373 (int)(ip->client->active->renewal -
1376 ip->client->active->renewal,
1379 ip->client->state = S_BOUND;
1380 note("bound: immediate renewal.");
1383 reinitialize_interfaces();
1389 /* If there are no other leases, give up. */
1390 if (!ip->client->leases) {
1391 ip->client->leases = ip->client->active;
1392 ip->client->active = NULL;
1397 /* Otherwise, put the active lease at the end of the
1398 lease list, and try another lease.. */
1399 for (lp = ip->client->leases; lp->next; lp = lp->next)
1401 lp->next = ip->client->active;
1403 lp->next->next = NULL;
1404 ip->client->active = ip->client->leases;
1405 ip->client->leases = ip->client->leases->next;
1407 /* If we already tried this lease, we've exhausted the
1408 set of leases, so we might as well give up for
1410 if (ip->client->active == loop)
1413 loop = ip->client->active;
1416 /* No leases were available, or what was available didn't work, so
1417 tell the shell script that we failed to allocate an address,
1418 and try again later. */
1419 note("No working leases in persistent database - sleeping.\n");
1420 script_init("FAIL", NULL);
1421 if (ip->client->alias)
1422 script_write_params("alias_", ip->client->alias);
1424 ip->client->state = S_INIT;
1425 add_timeout(cur_time + ip->client->config->retry_interval, state_init,
1431 send_request(void *ipp)
1433 struct interface_info *ip = ipp;
1434 struct in_addr from, to;
1437 /* Figure out how long it's been since we started transmitting. */
1438 interval = cur_time - ip->client->first_sending;
1440 /* If we're in the INIT-REBOOT or REQUESTING state and we're
1441 past the reboot timeout, go to INIT and see if we can
1442 DISCOVER an address... */
1443 /* XXX In the INIT-REBOOT state, if we don't get an ACK, it
1444 means either that we're on a network with no DHCP server,
1445 or that our server is down. In the latter case, assuming
1446 that there is a backup DHCP server, DHCPDISCOVER will get
1447 us a new address, but we could also have successfully
1448 reused our old address. In the former case, we're hosed
1449 anyway. This is not a win-prone situation. */
1450 if ((ip->client->state == S_REBOOTING ||
1451 ip->client->state == S_REQUESTING) &&
1452 interval > ip->client->config->reboot_timeout) {
1454 ip->client->state = S_INIT;
1455 cancel_timeout(send_request, ip);
1460 /* If we're in the reboot state, make sure the media is set up
1462 if (ip->client->state == S_REBOOTING &&
1463 !ip->client->medium &&
1464 ip->client->active->medium ) {
1465 script_init("MEDIUM", ip->client->active->medium);
1467 /* If the medium we chose won't fly, go to INIT state. */
1471 /* Record the medium. */
1472 ip->client->medium = ip->client->active->medium;
1475 /* If the lease has expired, relinquish the address and go back
1476 to the INIT state. */
1477 if (ip->client->state != S_REQUESTING &&
1478 cur_time > ip->client->active->expiry) {
1479 /* Run the client script with the new parameters. */
1480 script_init("EXPIRE", NULL);
1481 script_write_params("old_", ip->client->active);
1482 if (ip->client->alias)
1483 script_write_params("alias_", ip->client->alias);
1486 /* Now do a preinit on the interface so that we can
1487 discover a new address. */
1488 script_init("PREINIT", NULL);
1489 if (ip->client->alias)
1490 script_write_params("alias_", ip->client->alias);
1493 ip->client->state = S_INIT;
1498 /* Do the exponential backoff... */
1499 if (!ip->client->interval)
1500 ip->client->interval = ip->client->config->initial_interval;
1502 ip->client->interval += ((arc4random() >> 2) %
1503 (2 * ip->client->interval));
1505 /* Don't backoff past cutoff. */
1506 if (ip->client->interval >
1507 ip->client->config->backoff_cutoff)
1508 ip->client->interval =
1509 ((ip->client->config->backoff_cutoff / 2) +
1510 ((arc4random() >> 2) % ip->client->interval));
1512 /* If the backoff would take us to the expiry time, just set the
1513 timeout to the expiry time. */
1514 if (ip->client->state != S_REQUESTING &&
1515 cur_time + ip->client->interval >
1516 ip->client->active->expiry)
1517 ip->client->interval =
1518 ip->client->active->expiry - cur_time + 1;
1520 /* If the lease T2 time has elapsed, or if we're not yet bound,
1521 broadcast the DHCPREQUEST rather than unicasting. */
1522 if (ip->client->state == S_REQUESTING ||
1523 ip->client->state == S_REBOOTING ||
1524 cur_time > ip->client->active->rebind)
1525 to.s_addr = INADDR_BROADCAST;
1527 memcpy(&to.s_addr, ip->client->destination.iabuf,
1530 if (ip->client->state != S_REQUESTING &&
1531 ip->client->state != S_REBOOTING)
1532 memcpy(&from, ip->client->active->address.iabuf,
1535 from.s_addr = INADDR_ANY;
1537 /* Record the number of seconds since we started sending. */
1538 if (ip->client->state == S_REQUESTING)
1539 ip->client->packet.secs = ip->client->secs;
1541 if (interval < 65536)
1542 ip->client->packet.secs = htons(interval);
1544 ip->client->packet.secs = htons(65535);
1547 note("DHCPREQUEST on %s to %s port %d", ip->name, inet_ntoa(to),
1550 /* Send out a packet. */
1551 send_packet_unpriv(privfd, &ip->client->packet,
1552 ip->client->packet_length, from, to);
1554 add_timeout(cur_time + ip->client->interval, send_request, ip);
1558 send_decline(void *ipp)
1560 struct interface_info *ip = ipp;
1562 note("DHCPDECLINE on %s to %s port %d", ip->name,
1563 inet_ntoa(inaddr_broadcast), REMOTE_PORT);
1565 /* Send out a packet. */
1566 send_packet_unpriv(privfd, &ip->client->packet,
1567 ip->client->packet_length, inaddr_any, inaddr_broadcast);
1571 make_discover(struct interface_info *ip, struct client_lease *lease)
1573 unsigned char discover = DHCPDISCOVER;
1574 struct tree_cache *options[256];
1575 struct tree_cache option_elements[256];
1578 memset(option_elements, 0, sizeof(option_elements));
1579 memset(options, 0, sizeof(options));
1580 memset(&ip->client->packet, 0, sizeof(ip->client->packet));
1582 /* Set DHCP_MESSAGE_TYPE to DHCPDISCOVER */
1583 i = DHO_DHCP_MESSAGE_TYPE;
1584 options[i] = &option_elements[i];
1585 options[i]->value = &discover;
1586 options[i]->len = sizeof(discover);
1587 options[i]->buf_size = sizeof(discover);
1588 options[i]->timeout = 0xFFFFFFFF;
1590 /* Request the options we want */
1591 i = DHO_DHCP_PARAMETER_REQUEST_LIST;
1592 options[i] = &option_elements[i];
1593 options[i]->value = ip->client->config->requested_options;
1594 options[i]->len = ip->client->config->requested_option_count;
1595 options[i]->buf_size =
1596 ip->client->config->requested_option_count;
1597 options[i]->timeout = 0xFFFFFFFF;
1599 /* If we had an address, try to get it again. */
1601 ip->client->requested_address = lease->address;
1602 i = DHO_DHCP_REQUESTED_ADDRESS;
1603 options[i] = &option_elements[i];
1604 options[i]->value = lease->address.iabuf;
1605 options[i]->len = lease->address.len;
1606 options[i]->buf_size = lease->address.len;
1607 options[i]->timeout = 0xFFFFFFFF;
1609 ip->client->requested_address.len = 0;
1611 /* Send any options requested in the config file. */
1612 for (i = 0; i < 256; i++)
1614 ip->client->config->send_options[i].data) {
1615 options[i] = &option_elements[i];
1617 ip->client->config->send_options[i].data;
1619 ip->client->config->send_options[i].len;
1620 options[i]->buf_size =
1621 ip->client->config->send_options[i].len;
1622 options[i]->timeout = 0xFFFFFFFF;
1625 /* send host name if not set via config file. */
1626 if (!options[DHO_HOST_NAME]) {
1627 if (hostname[0] != '\0') {
1629 char* posDot = strchr(hostname, '.');
1631 len = posDot - hostname;
1633 len = strlen(hostname);
1634 options[DHO_HOST_NAME] = &option_elements[DHO_HOST_NAME];
1635 options[DHO_HOST_NAME]->value = hostname;
1636 options[DHO_HOST_NAME]->len = len;
1637 options[DHO_HOST_NAME]->buf_size = len;
1638 options[DHO_HOST_NAME]->timeout = 0xFFFFFFFF;
1642 /* set unique client identifier */
1643 char client_ident[sizeof(ip->hw_address.haddr) + 1];
1644 if (!options[DHO_DHCP_CLIENT_IDENTIFIER]) {
1645 int hwlen = (ip->hw_address.hlen < sizeof(client_ident)-1) ?
1646 ip->hw_address.hlen : sizeof(client_ident)-1;
1647 client_ident[0] = ip->hw_address.htype;
1648 memcpy(&client_ident[1], ip->hw_address.haddr, hwlen);
1649 options[DHO_DHCP_CLIENT_IDENTIFIER] = &option_elements[DHO_DHCP_CLIENT_IDENTIFIER];
1650 options[DHO_DHCP_CLIENT_IDENTIFIER]->value = client_ident;
1651 options[DHO_DHCP_CLIENT_IDENTIFIER]->len = hwlen+1;
1652 options[DHO_DHCP_CLIENT_IDENTIFIER]->buf_size = hwlen+1;
1653 options[DHO_DHCP_CLIENT_IDENTIFIER]->timeout = 0xFFFFFFFF;
1656 /* Set up the option buffer... */
1657 ip->client->packet_length = cons_options(NULL, &ip->client->packet, 0,
1658 options, 0, 0, 0, NULL, 0);
1659 if (ip->client->packet_length < BOOTP_MIN_LEN)
1660 ip->client->packet_length = BOOTP_MIN_LEN;
1662 ip->client->packet.op = BOOTREQUEST;
1663 ip->client->packet.htype = ip->hw_address.htype;
1664 ip->client->packet.hlen = ip->hw_address.hlen;
1665 ip->client->packet.hops = 0;
1666 ip->client->packet.xid = arc4random();
1667 ip->client->packet.secs = 0; /* filled in by send_discover. */
1668 ip->client->packet.flags = 0;
1670 memset(&(ip->client->packet.ciaddr),
1671 0, sizeof(ip->client->packet.ciaddr));
1672 memset(&(ip->client->packet.yiaddr),
1673 0, sizeof(ip->client->packet.yiaddr));
1674 memset(&(ip->client->packet.siaddr),
1675 0, sizeof(ip->client->packet.siaddr));
1676 memset(&(ip->client->packet.giaddr),
1677 0, sizeof(ip->client->packet.giaddr));
1678 memcpy(ip->client->packet.chaddr,
1679 ip->hw_address.haddr, ip->hw_address.hlen);
1684 make_request(struct interface_info *ip, struct client_lease * lease)
1686 unsigned char request = DHCPREQUEST;
1687 struct tree_cache *options[256];
1688 struct tree_cache option_elements[256];
1691 memset(options, 0, sizeof(options));
1692 memset(&ip->client->packet, 0, sizeof(ip->client->packet));
1694 /* Set DHCP_MESSAGE_TYPE to DHCPREQUEST */
1695 i = DHO_DHCP_MESSAGE_TYPE;
1696 options[i] = &option_elements[i];
1697 options[i]->value = &request;
1698 options[i]->len = sizeof(request);
1699 options[i]->buf_size = sizeof(request);
1700 options[i]->timeout = 0xFFFFFFFF;
1702 /* Request the options we want */
1703 i = DHO_DHCP_PARAMETER_REQUEST_LIST;
1704 options[i] = &option_elements[i];
1705 options[i]->value = ip->client->config->requested_options;
1706 options[i]->len = ip->client->config->requested_option_count;
1707 options[i]->buf_size =
1708 ip->client->config->requested_option_count;
1709 options[i]->timeout = 0xFFFFFFFF;
1711 /* If we are requesting an address that hasn't yet been assigned
1712 to us, use the DHCP Requested Address option. */
1713 if (ip->client->state == S_REQUESTING) {
1714 /* Send back the server identifier... */
1715 i = DHO_DHCP_SERVER_IDENTIFIER;
1716 options[i] = &option_elements[i];
1717 options[i]->value = lease->options[i].data;
1718 options[i]->len = lease->options[i].len;
1719 options[i]->buf_size = lease->options[i].len;
1720 options[i]->timeout = 0xFFFFFFFF;
1722 if (ip->client->state == S_REQUESTING ||
1723 ip->client->state == S_REBOOTING) {
1724 ip->client->requested_address = lease->address;
1725 i = DHO_DHCP_REQUESTED_ADDRESS;
1726 options[i] = &option_elements[i];
1727 options[i]->value = lease->address.iabuf;
1728 options[i]->len = lease->address.len;
1729 options[i]->buf_size = lease->address.len;
1730 options[i]->timeout = 0xFFFFFFFF;
1732 ip->client->requested_address.len = 0;
1734 /* Send any options requested in the config file. */
1735 for (i = 0; i < 256; i++)
1737 ip->client->config->send_options[i].data) {
1738 options[i] = &option_elements[i];
1740 ip->client->config->send_options[i].data;
1742 ip->client->config->send_options[i].len;
1743 options[i]->buf_size =
1744 ip->client->config->send_options[i].len;
1745 options[i]->timeout = 0xFFFFFFFF;
1748 /* send host name if not set via config file. */
1749 if (!options[DHO_HOST_NAME]) {
1750 if (hostname[0] != '\0') {
1752 char* posDot = strchr(hostname, '.');
1754 len = posDot - hostname;
1756 len = strlen(hostname);
1757 options[DHO_HOST_NAME] = &option_elements[DHO_HOST_NAME];
1758 options[DHO_HOST_NAME]->value = hostname;
1759 options[DHO_HOST_NAME]->len = len;
1760 options[DHO_HOST_NAME]->buf_size = len;
1761 options[DHO_HOST_NAME]->timeout = 0xFFFFFFFF;
1765 /* set unique client identifier */
1766 char client_ident[sizeof(struct hardware)];
1767 if (!options[DHO_DHCP_CLIENT_IDENTIFIER]) {
1768 int hwlen = (ip->hw_address.hlen < sizeof(client_ident)-1) ?
1769 ip->hw_address.hlen : sizeof(client_ident)-1;
1770 client_ident[0] = ip->hw_address.htype;
1771 memcpy(&client_ident[1], ip->hw_address.haddr, hwlen);
1772 options[DHO_DHCP_CLIENT_IDENTIFIER] = &option_elements[DHO_DHCP_CLIENT_IDENTIFIER];
1773 options[DHO_DHCP_CLIENT_IDENTIFIER]->value = client_ident;
1774 options[DHO_DHCP_CLIENT_IDENTIFIER]->len = hwlen+1;
1775 options[DHO_DHCP_CLIENT_IDENTIFIER]->buf_size = hwlen+1;
1776 options[DHO_DHCP_CLIENT_IDENTIFIER]->timeout = 0xFFFFFFFF;
1779 /* Set up the option buffer... */
1780 ip->client->packet_length = cons_options(NULL, &ip->client->packet, 0,
1781 options, 0, 0, 0, NULL, 0);
1782 if (ip->client->packet_length < BOOTP_MIN_LEN)
1783 ip->client->packet_length = BOOTP_MIN_LEN;
1785 ip->client->packet.op = BOOTREQUEST;
1786 ip->client->packet.htype = ip->hw_address.htype;
1787 ip->client->packet.hlen = ip->hw_address.hlen;
1788 ip->client->packet.hops = 0;
1789 ip->client->packet.xid = ip->client->xid;
1790 ip->client->packet.secs = 0; /* Filled in by send_request. */
1792 /* If we own the address we're requesting, put it in ciaddr;
1793 otherwise set ciaddr to zero. */
1794 if (ip->client->state == S_BOUND ||
1795 ip->client->state == S_RENEWING ||
1796 ip->client->state == S_REBINDING) {
1797 memcpy(&ip->client->packet.ciaddr,
1798 lease->address.iabuf, lease->address.len);
1799 ip->client->packet.flags = 0;
1801 memset(&ip->client->packet.ciaddr, 0,
1802 sizeof(ip->client->packet.ciaddr));
1803 ip->client->packet.flags = 0;
1806 memset(&ip->client->packet.yiaddr, 0,
1807 sizeof(ip->client->packet.yiaddr));
1808 memset(&ip->client->packet.siaddr, 0,
1809 sizeof(ip->client->packet.siaddr));
1810 memset(&ip->client->packet.giaddr, 0,
1811 sizeof(ip->client->packet.giaddr));
1812 memcpy(ip->client->packet.chaddr,
1813 ip->hw_address.haddr, ip->hw_address.hlen);
1817 make_decline(struct interface_info *ip, struct client_lease *lease)
1819 struct tree_cache *options[256], message_type_tree;
1820 struct tree_cache requested_address_tree;
1821 struct tree_cache server_id_tree, client_id_tree;
1822 unsigned char decline = DHCPDECLINE;
1825 memset(options, 0, sizeof(options));
1826 memset(&ip->client->packet, 0, sizeof(ip->client->packet));
1828 /* Set DHCP_MESSAGE_TYPE to DHCPDECLINE */
1829 i = DHO_DHCP_MESSAGE_TYPE;
1830 options[i] = &message_type_tree;
1831 options[i]->value = &decline;
1832 options[i]->len = sizeof(decline);
1833 options[i]->buf_size = sizeof(decline);
1834 options[i]->timeout = 0xFFFFFFFF;
1836 /* Send back the server identifier... */
1837 i = DHO_DHCP_SERVER_IDENTIFIER;
1838 options[i] = &server_id_tree;
1839 options[i]->value = lease->options[i].data;
1840 options[i]->len = lease->options[i].len;
1841 options[i]->buf_size = lease->options[i].len;
1842 options[i]->timeout = 0xFFFFFFFF;
1844 /* Send back the address we're declining. */
1845 i = DHO_DHCP_REQUESTED_ADDRESS;
1846 options[i] = &requested_address_tree;
1847 options[i]->value = lease->address.iabuf;
1848 options[i]->len = lease->address.len;
1849 options[i]->buf_size = lease->address.len;
1850 options[i]->timeout = 0xFFFFFFFF;
1852 /* Send the uid if the user supplied one. */
1853 i = DHO_DHCP_CLIENT_IDENTIFIER;
1854 if (ip->client->config->send_options[i].len) {
1855 options[i] = &client_id_tree;
1856 options[i]->value = ip->client->config->send_options[i].data;
1857 options[i]->len = ip->client->config->send_options[i].len;
1858 options[i]->buf_size = ip->client->config->send_options[i].len;
1859 options[i]->timeout = 0xFFFFFFFF;
1863 /* Set up the option buffer... */
1864 ip->client->packet_length = cons_options(NULL, &ip->client->packet, 0,
1865 options, 0, 0, 0, NULL, 0);
1866 if (ip->client->packet_length < BOOTP_MIN_LEN)
1867 ip->client->packet_length = BOOTP_MIN_LEN;
1869 ip->client->packet.op = BOOTREQUEST;
1870 ip->client->packet.htype = ip->hw_address.htype;
1871 ip->client->packet.hlen = ip->hw_address.hlen;
1872 ip->client->packet.hops = 0;
1873 ip->client->packet.xid = ip->client->xid;
1874 ip->client->packet.secs = 0; /* Filled in by send_request. */
1875 ip->client->packet.flags = 0;
1877 /* ciaddr must always be zero. */
1878 memset(&ip->client->packet.ciaddr, 0,
1879 sizeof(ip->client->packet.ciaddr));
1880 memset(&ip->client->packet.yiaddr, 0,
1881 sizeof(ip->client->packet.yiaddr));
1882 memset(&ip->client->packet.siaddr, 0,
1883 sizeof(ip->client->packet.siaddr));
1884 memset(&ip->client->packet.giaddr, 0,
1885 sizeof(ip->client->packet.giaddr));
1886 memcpy(ip->client->packet.chaddr,
1887 ip->hw_address.haddr, ip->hw_address.hlen);
1891 free_client_lease(struct client_lease *lease)
1895 if (lease->server_name)
1896 free(lease->server_name);
1897 if (lease->filename)
1898 free(lease->filename);
1899 for (i = 0; i < 256; i++) {
1900 if (lease->options[i].len)
1901 free(lease->options[i].data);
1906 static FILE *leaseFile;
1909 rewrite_client_leases(void)
1911 struct client_lease *lp;
1912 cap_rights_t rights;
1915 leaseFile = fopen(path_dhclient_db, "w");
1917 error("can't create %s: %m", path_dhclient_db);
1918 cap_rights_init(&rights, CAP_FCNTL, CAP_FSTAT, CAP_FSYNC,
1919 CAP_FTRUNCATE, CAP_SEEK, CAP_WRITE);
1920 if (cap_rights_limit(fileno(leaseFile), &rights) < 0 &&
1922 error("can't limit lease descriptor: %m");
1924 if (cap_fcntls_limit(fileno(leaseFile), CAP_FCNTL_GETFL) < 0 &&
1926 error("can't limit lease descriptor fcntls: %m");
1933 for (lp = ifi->client->leases; lp; lp = lp->next)
1934 write_client_lease(ifi, lp, 1);
1935 if (ifi->client->active)
1936 write_client_lease(ifi, ifi->client->active, 1);
1939 ftruncate(fileno(leaseFile), ftello(leaseFile));
1940 fsync(fileno(leaseFile));
1944 write_client_lease(struct interface_info *ip, struct client_lease *lease,
1947 static int leases_written;
1952 if (leases_written++ > 20) {
1953 rewrite_client_leases();
1958 /* If the lease came from the config file, we don't need to stash
1959 a copy in the lease database. */
1960 if (lease->is_static)
1963 if (!leaseFile) { /* XXX */
1964 leaseFile = fopen(path_dhclient_db, "w");
1966 error("can't create %s: %m", path_dhclient_db);
1969 fprintf(leaseFile, "lease {\n");
1970 if (lease->is_bootp)
1971 fprintf(leaseFile, " bootp;\n");
1972 fprintf(leaseFile, " interface \"%s\";\n", ip->name);
1973 fprintf(leaseFile, " fixed-address %s;\n", piaddr(lease->address));
1974 if (lease->nextserver.len == sizeof(inaddr_any) &&
1975 0 != memcmp(lease->nextserver.iabuf, &inaddr_any,
1976 sizeof(inaddr_any)))
1977 fprintf(leaseFile, " next-server %s;\n",
1978 piaddr(lease->nextserver));
1979 if (lease->filename)
1980 fprintf(leaseFile, " filename \"%s\";\n", lease->filename);
1981 if (lease->server_name)
1982 fprintf(leaseFile, " server-name \"%s\";\n",
1983 lease->server_name);
1985 fprintf(leaseFile, " medium \"%s\";\n", lease->medium->string);
1986 for (i = 0; i < 256; i++)
1987 if (lease->options[i].len)
1988 fprintf(leaseFile, " option %s %s;\n",
1989 dhcp_options[i].name,
1990 pretty_print_option(i, lease->options[i].data,
1991 lease->options[i].len, 1, 1));
1993 t = gmtime(&lease->renewal);
1994 fprintf(leaseFile, " renew %d %d/%d/%d %02d:%02d:%02d;\n",
1995 t->tm_wday, t->tm_year + 1900, t->tm_mon + 1, t->tm_mday,
1996 t->tm_hour, t->tm_min, t->tm_sec);
1997 t = gmtime(&lease->rebind);
1998 fprintf(leaseFile, " rebind %d %d/%d/%d %02d:%02d:%02d;\n",
1999 t->tm_wday, t->tm_year + 1900, t->tm_mon + 1, t->tm_mday,
2000 t->tm_hour, t->tm_min, t->tm_sec);
2001 t = gmtime(&lease->expiry);
2002 fprintf(leaseFile, " expire %d %d/%d/%d %02d:%02d:%02d;\n",
2003 t->tm_wday, t->tm_year + 1900, t->tm_mon + 1, t->tm_mday,
2004 t->tm_hour, t->tm_min, t->tm_sec);
2005 fprintf(leaseFile, "}\n");
2010 script_init(const char *reason, struct string_list *medium)
2012 size_t len, mediumlen = 0;
2013 struct imsg_hdr hdr;
2017 if (medium != NULL && medium->string != NULL)
2018 mediumlen = strlen(medium->string);
2020 hdr.code = IMSG_SCRIPT_INIT;
2021 hdr.len = sizeof(struct imsg_hdr) +
2022 sizeof(size_t) + mediumlen +
2023 sizeof(size_t) + strlen(reason);
2025 if ((buf = buf_open(hdr.len)) == NULL)
2026 error("buf_open: %m");
2029 errs += buf_add(buf, &hdr, sizeof(hdr));
2030 errs += buf_add(buf, &mediumlen, sizeof(mediumlen));
2032 errs += buf_add(buf, medium->string, mediumlen);
2033 len = strlen(reason);
2034 errs += buf_add(buf, &len, sizeof(len));
2035 errs += buf_add(buf, reason, len);
2038 error("buf_add: %m");
2040 if (buf_close(privfd, buf) == -1)
2041 error("buf_close: %m");
2045 priv_script_init(const char *reason, char *medium)
2047 struct interface_info *ip = ifi;
2050 ip->client->scriptEnvsize = 100;
2051 if (ip->client->scriptEnv == NULL)
2052 ip->client->scriptEnv =
2053 malloc(ip->client->scriptEnvsize * sizeof(char *));
2054 if (ip->client->scriptEnv == NULL)
2055 error("script_init: no memory for environment");
2057 ip->client->scriptEnv[0] = strdup(CLIENT_PATH);
2058 if (ip->client->scriptEnv[0] == NULL)
2059 error("script_init: no memory for environment");
2061 ip->client->scriptEnv[1] = NULL;
2063 script_set_env(ip->client, "", "interface", ip->name);
2066 script_set_env(ip->client, "", "medium", medium);
2068 script_set_env(ip->client, "", "reason", reason);
2073 priv_script_write_params(const char *prefix, struct client_lease *lease)
2075 struct interface_info *ip = ifi;
2076 u_int8_t dbuf[1500], *dp = NULL;
2081 script_set_env(ip->client, prefix, "ip_address",
2082 piaddr(lease->address));
2084 if (ip->client->config->default_actions[DHO_SUBNET_MASK] ==
2086 dp = ip->client->config->defaults[DHO_SUBNET_MASK].data;
2087 len = ip->client->config->defaults[DHO_SUBNET_MASK].len;
2089 dp = lease->options[DHO_SUBNET_MASK].data;
2090 len = lease->options[DHO_SUBNET_MASK].len;
2092 if (len && (len < sizeof(lease->address.iabuf))) {
2093 struct iaddr netmask, subnet, broadcast;
2095 memcpy(netmask.iabuf, dp, len);
2097 subnet = subnet_number(lease->address, netmask);
2099 script_set_env(ip->client, prefix, "network_number",
2101 if (!lease->options[DHO_BROADCAST_ADDRESS].len) {
2102 broadcast = broadcast_addr(subnet, netmask);
2104 script_set_env(ip->client, prefix,
2105 "broadcast_address",
2111 if (lease->filename)
2112 script_set_env(ip->client, prefix, "filename", lease->filename);
2113 if (lease->server_name)
2114 script_set_env(ip->client, prefix, "server_name",
2115 lease->server_name);
2116 for (i = 0; i < 256; i++) {
2119 if (ip->client->config->defaults[i].len) {
2120 if (lease->options[i].len) {
2122 ip->client->config->default_actions[i]) {
2123 case ACTION_DEFAULT:
2124 dp = lease->options[i].data;
2125 len = lease->options[i].len;
2127 case ACTION_SUPERSEDE:
2130 config->defaults[i].data;
2132 config->defaults[i].len;
2134 case ACTION_PREPEND:
2136 config->defaults[i].len +
2137 lease->options[i].len;
2138 if (len >= sizeof(dbuf)) {
2139 warning("no space to %s %s",
2141 dhcp_options[i].name);
2147 config->defaults[i].data,
2149 config->defaults[i].len);
2150 memcpy(dp + ip->client->
2151 config->defaults[i].len,
2152 lease->options[i].data,
2153 lease->options[i].len);
2158 * When we append, we assume that we're
2159 * appending to text. Some MS servers
2160 * include a NUL byte at the end of
2161 * the search string provided.
2164 config->defaults[i].len +
2165 lease->options[i].len;
2166 if (len >= sizeof(dbuf)) {
2167 warning("no space to %s %s",
2169 dhcp_options[i].name);
2173 lease->options[i].data,
2174 lease->options[i].len);
2175 for (dp = dbuf + lease->options[i].len;
2176 dp > dbuf; dp--, len--)
2181 config->defaults[i].data,
2183 config->defaults[i].len);
2189 config->defaults[i].data;
2191 config->defaults[i].len;
2193 } else if (lease->options[i].len) {
2194 len = lease->options[i].len;
2195 dp = lease->options[i].data;
2202 if (dhcp_option_ev_name(name, sizeof(name),
2204 script_set_env(ip->client, prefix, name,
2205 pretty_print_option(i, dp, len, 0, 0));
2208 snprintf(tbuf, sizeof(tbuf), "%d", (int)lease->expiry);
2209 script_set_env(ip->client, prefix, "expiry", tbuf);
2213 script_write_params(const char *prefix, struct client_lease *lease)
2215 size_t fn_len = 0, sn_len = 0, pr_len = 0;
2216 struct imsg_hdr hdr;
2220 if (lease->filename != NULL)
2221 fn_len = strlen(lease->filename);
2222 if (lease->server_name != NULL)
2223 sn_len = strlen(lease->server_name);
2225 pr_len = strlen(prefix);
2227 hdr.code = IMSG_SCRIPT_WRITE_PARAMS;
2228 hdr.len = sizeof(hdr) + sizeof(*lease) +
2229 sizeof(fn_len) + fn_len + sizeof(sn_len) + sn_len +
2230 sizeof(pr_len) + pr_len;
2232 for (i = 0; i < 256; i++) {
2233 hdr.len += sizeof(lease->options[i].len);
2234 hdr.len += lease->options[i].len;
2237 scripttime = time(NULL);
2239 if ((buf = buf_open(hdr.len)) == NULL)
2240 error("buf_open: %m");
2243 errs += buf_add(buf, &hdr, sizeof(hdr));
2244 errs += buf_add(buf, lease, sizeof(*lease));
2245 errs += buf_add(buf, &fn_len, sizeof(fn_len));
2246 errs += buf_add(buf, lease->filename, fn_len);
2247 errs += buf_add(buf, &sn_len, sizeof(sn_len));
2248 errs += buf_add(buf, lease->server_name, sn_len);
2249 errs += buf_add(buf, &pr_len, sizeof(pr_len));
2250 errs += buf_add(buf, prefix, pr_len);
2252 for (i = 0; i < 256; i++) {
2253 errs += buf_add(buf, &lease->options[i].len,
2254 sizeof(lease->options[i].len));
2255 errs += buf_add(buf, lease->options[i].data,
2256 lease->options[i].len);
2260 error("buf_add: %m");
2262 if (buf_close(privfd, buf) == -1)
2263 error("buf_close: %m");
2269 struct imsg_hdr hdr;
2273 hdr.code = IMSG_SCRIPT_GO;
2274 hdr.len = sizeof(struct imsg_hdr);
2276 if ((buf = buf_open(hdr.len)) == NULL)
2277 error("buf_open: %m");
2279 if (buf_add(buf, &hdr, sizeof(hdr)))
2280 error("buf_add: %m");
2282 if (buf_close(privfd, buf) == -1)
2283 error("buf_close: %m");
2285 bzero(&hdr, sizeof(hdr));
2286 buf_read(privfd, &hdr, sizeof(hdr));
2287 if (hdr.code != IMSG_SCRIPT_GO_RET)
2288 error("unexpected msg type %u", hdr.code);
2289 if (hdr.len != sizeof(hdr) + sizeof(int))
2290 error("received corrupted message");
2291 buf_read(privfd, &ret, sizeof(ret));
2293 scripttime = time(NULL);
2299 priv_script_go(void)
2301 char *scriptName, *argv[2], **envp, *epp[3], reason[] = "REASON=NBI";
2302 static char client_path[] = CLIENT_PATH;
2303 struct interface_info *ip = ifi;
2304 int pid, wpid, wstatus;
2306 scripttime = time(NULL);
2309 scriptName = ip->client->config->script_name;
2310 envp = ip->client->scriptEnv;
2312 scriptName = top_level_config.script_name;
2314 epp[1] = client_path;
2319 argv[0] = scriptName;
2328 wpid = wait(&wstatus);
2329 } while (wpid != pid && wpid > 0);
2335 execve(scriptName, argv, envp);
2336 error("execve (%s, ...): %m", scriptName);
2340 script_flush_env(ip->client);
2342 return (wstatus & 0xff);
2346 script_set_env(struct client_state *client, const char *prefix,
2347 const char *name, const char *value)
2352 /* No `` or $() command substitution allowed in environment values! */
2353 for (j=0; j < strlen(value); j++)
2357 warning("illegal character (%c) in value '%s'",
2359 /* Ignore this option */
2363 namelen = strlen(name);
2365 for (i = 0; client->scriptEnv[i]; i++)
2366 if (strncmp(client->scriptEnv[i], name, namelen) == 0 &&
2367 client->scriptEnv[i][namelen] == '=')
2370 if (client->scriptEnv[i])
2371 /* Reuse the slot. */
2372 free(client->scriptEnv[i]);
2374 /* New variable. Expand if necessary. */
2375 if (i >= client->scriptEnvsize - 1) {
2376 char **newscriptEnv;
2377 int newscriptEnvsize = client->scriptEnvsize + 50;
2379 newscriptEnv = realloc(client->scriptEnv,
2381 if (newscriptEnv == NULL) {
2382 free(client->scriptEnv);
2383 client->scriptEnv = NULL;
2384 client->scriptEnvsize = 0;
2385 error("script_set_env: no memory for variable");
2387 client->scriptEnv = newscriptEnv;
2388 client->scriptEnvsize = newscriptEnvsize;
2390 /* need to set the NULL pointer at end of array beyond
2392 client->scriptEnv[i + 1] = NULL;
2394 /* Allocate space and format the variable in the appropriate slot. */
2395 client->scriptEnv[i] = malloc(strlen(prefix) + strlen(name) + 1 +
2397 if (client->scriptEnv[i] == NULL)
2398 error("script_set_env: no memory for variable assignment");
2399 snprintf(client->scriptEnv[i], strlen(prefix) + strlen(name) +
2400 1 + strlen(value) + 1, "%s%s=%s", prefix, name, value);
2404 script_flush_env(struct client_state *client)
2408 for (i = 0; client->scriptEnv[i]; i++) {
2409 free(client->scriptEnv[i]);
2410 client->scriptEnv[i] = NULL;
2412 client->scriptEnvsize = 0;
2416 dhcp_option_ev_name(char *buf, size_t buflen, struct option *option)
2420 for (i = 0; option->name[i]; i++) {
2421 if (i + 1 == buflen)
2423 if (option->name[i] == '-')
2426 buf[i] = option->name[i];
2436 static int state = 0;
2437 cap_rights_t rights;
2439 if (no_daemon || state)
2444 /* Stop logging to stderr... */
2447 if (daemonfd(-1, nullfd) == -1)
2450 cap_rights_init(&rights);
2452 if (pidfile != NULL) {
2453 pidfile_write(pidfile);
2454 if (cap_rights_limit(pidfile_fileno(pidfile), &rights) < 0 &&
2456 error("can't limit pidfile descriptor: %m");
2465 if (cap_rights_limit(STDIN_FILENO, &rights) < 0 && errno != ENOSYS)
2466 error("can't limit stdin: %m");
2467 cap_rights_init(&rights, CAP_WRITE);
2468 if (cap_rights_limit(STDOUT_FILENO, &rights) < 0 && errno != ENOSYS)
2469 error("can't limit stdout: %m");
2470 if (cap_rights_limit(STDERR_FILENO, &rights) < 0 && errno != ENOSYS)
2471 error("can't limit stderr: %m");
2475 check_option(struct client_lease *l, int option)
2480 /* we use this, since this is what gets passed to dhclient-script */
2482 opbuf = pretty_print_option(option, l->options[option].data,
2483 l->options[option].len, 0, 0);
2485 sbuf = option_as_string(option, l->options[option].data,
2486 l->options[option].len);
2489 case DHO_SUBNET_MASK:
2490 case DHO_TIME_SERVERS:
2491 case DHO_NAME_SERVERS:
2493 case DHO_DOMAIN_NAME_SERVERS:
2494 case DHO_LOG_SERVERS:
2495 case DHO_COOKIE_SERVERS:
2496 case DHO_LPR_SERVERS:
2497 case DHO_IMPRESS_SERVERS:
2498 case DHO_RESOURCE_LOCATION_SERVERS:
2499 case DHO_SWAP_SERVER:
2500 case DHO_BROADCAST_ADDRESS:
2501 case DHO_NIS_SERVERS:
2502 case DHO_NTP_SERVERS:
2503 case DHO_NETBIOS_NAME_SERVERS:
2504 case DHO_NETBIOS_DD_SERVER:
2505 case DHO_FONT_SERVERS:
2506 case DHO_DHCP_SERVER_IDENTIFIER:
2507 case DHO_NISPLUS_SERVERS:
2508 case DHO_MOBILE_IP_HOME_AGENT:
2509 case DHO_SMTP_SERVER:
2510 case DHO_POP_SERVER:
2511 case DHO_NNTP_SERVER:
2512 case DHO_WWW_SERVER:
2513 case DHO_FINGER_SERVER:
2514 case DHO_IRC_SERVER:
2515 case DHO_STREETTALK_SERVER:
2516 case DHO_STREETTALK_DA_SERVER:
2517 if (!ipv4addrs(opbuf)) {
2518 warning("Invalid IP address in option: %s", opbuf);
2523 case DHO_NIS_DOMAIN:
2524 case DHO_NISPLUS_DOMAIN:
2525 case DHO_TFTP_SERVER_NAME:
2526 if (!res_hnok(sbuf)) {
2527 warning("Bogus Host Name option %d: %s (%s)", option,
2529 l->options[option].len = 0;
2530 free(l->options[option].data);
2533 case DHO_DOMAIN_NAME:
2534 case DHO_DOMAIN_SEARCH:
2535 if (!res_hnok(sbuf)) {
2536 if (!check_search(sbuf)) {
2537 warning("Bogus domain search list %d: %s (%s)",
2538 option, sbuf, opbuf);
2539 l->options[option].len = 0;
2540 free(l->options[option].data);
2545 case DHO_TIME_OFFSET:
2547 case DHO_MERIT_DUMP:
2549 case DHO_EXTENSIONS_PATH:
2550 case DHO_IP_FORWARDING:
2551 case DHO_NON_LOCAL_SOURCE_ROUTING:
2552 case DHO_POLICY_FILTER:
2553 case DHO_MAX_DGRAM_REASSEMBLY:
2554 case DHO_DEFAULT_IP_TTL:
2555 case DHO_PATH_MTU_AGING_TIMEOUT:
2556 case DHO_PATH_MTU_PLATEAU_TABLE:
2557 case DHO_INTERFACE_MTU:
2558 case DHO_ALL_SUBNETS_LOCAL:
2559 case DHO_PERFORM_MASK_DISCOVERY:
2560 case DHO_MASK_SUPPLIER:
2561 case DHO_ROUTER_DISCOVERY:
2562 case DHO_ROUTER_SOLICITATION_ADDRESS:
2563 case DHO_STATIC_ROUTES:
2564 case DHO_TRAILER_ENCAPSULATION:
2565 case DHO_ARP_CACHE_TIMEOUT:
2566 case DHO_IEEE802_3_ENCAPSULATION:
2567 case DHO_DEFAULT_TCP_TTL:
2568 case DHO_TCP_KEEPALIVE_INTERVAL:
2569 case DHO_TCP_KEEPALIVE_GARBAGE:
2570 case DHO_VENDOR_ENCAPSULATED_OPTIONS:
2571 case DHO_NETBIOS_NODE_TYPE:
2572 case DHO_NETBIOS_SCOPE:
2573 case DHO_X_DISPLAY_MANAGER:
2574 case DHO_DHCP_REQUESTED_ADDRESS:
2575 case DHO_DHCP_LEASE_TIME:
2576 case DHO_DHCP_OPTION_OVERLOAD:
2577 case DHO_DHCP_MESSAGE_TYPE:
2578 case DHO_DHCP_PARAMETER_REQUEST_LIST:
2579 case DHO_DHCP_MESSAGE:
2580 case DHO_DHCP_MAX_MESSAGE_SIZE:
2581 case DHO_DHCP_RENEWAL_TIME:
2582 case DHO_DHCP_REBINDING_TIME:
2583 case DHO_DHCP_CLASS_IDENTIFIER:
2584 case DHO_DHCP_CLIENT_IDENTIFIER:
2585 case DHO_BOOTFILE_NAME:
2586 case DHO_DHCP_USER_CLASS_ID:
2589 case DHO_CLASSLESS_ROUTES:
2590 return (check_classless_option(l->options[option].data,
2591 l->options[option].len));
2593 warning("unknown dhcp option value 0x%x", option);
2594 return (unknown_ok);
2598 /* RFC 3442 The Classless Static Routes option checks */
2600 check_classless_option(unsigned char *data, int len)
2603 unsigned char width;
2604 in_addr_t addr, mask;
2607 warning("Too small length: %d", len);
2615 } else if (width < 9) {
2616 addr = (in_addr_t)(data[i] << 24);
2618 } else if (width < 17) {
2619 addr = (in_addr_t)(data[i] << 24) +
2620 (in_addr_t)(data[i + 1] << 16);
2622 } else if (width < 25) {
2623 addr = (in_addr_t)(data[i] << 24) +
2624 (in_addr_t)(data[i + 1] << 16) +
2625 (in_addr_t)(data[i + 2] << 8);
2627 } else if (width < 33) {
2628 addr = (in_addr_t)(data[i] << 24) +
2629 (in_addr_t)(data[i + 1] << 16) +
2630 (in_addr_t)(data[i + 2] << 8) +
2634 warning("Incorrect subnet width: %d", width);
2637 mask = (in_addr_t)(~0) << (32 - width);
2643 * ... After deriving a subnet number and subnet mask
2644 * from each destination descriptor, the DHCP client
2645 * MUST zero any bits in the subnet number where the
2646 * corresponding bit in the mask is zero...
2648 if ((addr & mask) != addr) {
2650 data[i - 1] = (unsigned char)(
2651 (addr >> (((32 - width)/8)*8)) & 0xFF);
2656 warning("Incorrect data length: %d (must be %d)", len, i);
2663 res_hnok(const char *dn)
2665 int pch = PERIOD, ch = *dn++;
2667 while (ch != '\0') {
2670 if (periodchar(ch)) {
2672 } else if (periodchar(pch)) {
2673 if (!borderchar(ch))
2675 } else if (periodchar(nch) || nch == '\0') {
2676 if (!borderchar(ch))
2679 if (!middlechar(ch))
2688 check_search(const char *srch)
2690 int pch = PERIOD, ch = *srch++;
2693 /* 256 char limit re resolv.conf(5) */
2694 if (strlen(srch) > 256)
2697 while (whitechar(ch))
2700 while (ch != '\0') {
2703 if (periodchar(ch) || whitechar(ch)) {
2705 } else if (periodchar(pch)) {
2706 if (!borderchar(ch))
2708 } else if (periodchar(nch) || nch == '\0') {
2709 if (!borderchar(ch))
2712 if (!middlechar(ch))
2715 if (!whitechar(ch)) {
2718 while (whitechar(nch)) {
2727 /* 6 domain limit re resolv.conf(5) */
2733 /* Does buf consist only of dotted decimal ipv4 addrs?
2734 * return how many if so,
2735 * otherwise, return 0
2738 ipv4addrs(const char * buf)
2743 while (inet_aton(buf, &jnk) == 1){
2745 while (periodchar(*buf) || digitchar(*buf))
2757 option_as_string(unsigned int code, unsigned char *data, int len)
2759 static char optbuf[32768]; /* XXX */
2761 int opleft = sizeof(optbuf);
2762 unsigned char *dp = data;
2765 error("option_as_string: bad code %d", code);
2767 for (; dp < data + len; dp++) {
2768 if (!isascii(*dp) || !isprint(*dp)) {
2769 if (dp + 1 != data + len || *dp != 0) {
2770 snprintf(op, opleft, "\\%03o", *dp);
2774 } else if (*dp == '"' || *dp == '\'' || *dp == '$' ||
2775 *dp == '`' || *dp == '\\') {
2789 warning("dhcp option too large");
2794 fork_privchld(int fd, int fd2)
2796 struct pollfd pfd[1];
2801 error("cannot fork");
2808 setproctitle("%s [priv]", ifi->name);
2811 dup2(nullfd, STDIN_FILENO);
2812 dup2(nullfd, STDOUT_FILENO);
2813 dup2(nullfd, STDERR_FILENO);
2821 pfd[0].events = POLLIN;
2822 if ((nfds = poll(pfd, 1, INFTIM)) == -1)
2824 error("poll error");
2826 if (nfds == 0 || !(pfd[0].revents & POLLIN))
2829 dispatch_imsg(ifi, fd);