1 /* Copyright (c) 2008 The Board of Trustees of The Leland Stanford
4 * We are making the OpenFlow specification and associated documentation
5 * (Software) available for public use and benefit with the expectation
6 * that others will use, modify and enhance the Software and contribute
7 * those enhancements back to the community. However, since we would
8 * like to make the Software available for broadest use, with as few
9 * restrictions as possible permission is hereby granted, free of
10 * charge, to any person obtaining a copy of this Software to deal in
11 * the Software under the copyrights without restriction, including
12 * without limitation the rights to use, copy, modify, merge, publish,
13 * distribute, sublicense, and/or sell copies of the Software, and to
14 * permit persons to whom the Software is furnished to do so, subject to
15 * the following conditions:
17 * The above copyright notice and this permission notice shall be
18 * included in all copies or substantial portions of the Software.
20 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
24 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
25 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
26 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29 * The name and trademarks of copyright holder(s) may NOT be used in
30 * advertising or publicity pertaining to the Software or any
31 * derivatives without specific, written prior permission.
35 #include "dhcp-client.h"
36 #include <arpa/inet.h>
43 #include <sys/types.h>
48 #include "dynamic-string.h"
52 #include "poll-loop.h"
56 #define THIS_MODULE VLM_dhcp_client
59 #define DHCLIENT_STATES \
60 DHCLIENT_STATE(INIT, 1 << 0) \
61 DHCLIENT_STATE(INIT_REBOOT, 1 << 1) \
62 DHCLIENT_STATE(REBOOTING, 1 << 2) \
63 DHCLIENT_STATE(SELECTING, 1 << 3) \
64 DHCLIENT_STATE(REQUESTING, 1 << 4) \
65 DHCLIENT_STATE(BOUND, 1 << 5) \
66 DHCLIENT_STATE(RENEWING, 1 << 6) \
67 DHCLIENT_STATE(REBINDING, 1 << 7) \
68 DHCLIENT_STATE(RELEASED, 1 << 8)
70 #define DHCLIENT_STATE(NAME, VALUE) S_##NAME = VALUE,
75 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(60, 60);
78 state_name(enum dhclient_state state)
81 #define DHCLIENT_STATE(NAME, VALUE) case S_##NAME: return #NAME;
90 struct netdev *netdev;
92 void (*modify_request)(struct dhcp_msg *, void *aux);
93 bool (*validate_offer)(const struct dhcp_msg *, void *aux);
97 enum dhclient_state state;
98 unsigned int state_entered; /* When we transitioned to this state. */
99 uint32_t xid; /* In host byte order. */
100 uint32_t ipaddr, netmask, router;
102 struct dhcp_msg *binding;
105 unsigned int retransmit, delay; /* Used by send_reliably(). */
106 unsigned int max_timeout;
108 unsigned int init_delay; /* Used by S_INIT. */
110 time_t lease_expiration;
111 unsigned int bound_timeout;
112 unsigned int renewing_timeout;
113 unsigned int rebinding_timeout;
115 /* Used by dhclient_run() and dhclient_wait() */
116 unsigned int min_timeout;
119 /* Set when we send out a DHCPDISCOVER message. */
125 /* Minimum acceptable lease time, in seconds. */
126 #define MIN_ACCEPTABLE_LEASE 15
128 static void state_transition(struct dhclient *, enum dhclient_state);
129 static unsigned int elapsed_in_this_state(const struct dhclient *cli);
130 static bool timeout(struct dhclient *, unsigned int secs);
132 static void dhclient_msg_init(struct dhclient *, enum dhcp_msg_type,
134 static void send_reliably(struct dhclient *cli,
135 void (*make_packet)(struct dhclient *,
137 static bool do_receive_msg(struct dhclient *, struct dhcp_msg *);
138 static void do_send_msg(struct dhclient *, const struct dhcp_msg *);
139 static bool receive_ack(struct dhclient *);
141 static unsigned int fuzz(unsigned int x, int max_fuzz);
142 static unsigned int calc_t2(unsigned int lease);
143 static unsigned int calc_t1(unsigned int lease, unsigned int t2);
145 static unsigned int clamp(unsigned int x, unsigned int min, unsigned int max);
147 /* Creates a new DHCP client to configure the network device 'netdev_name'
150 * If 'modify_request' is non-null, then each DHCP message to discover or
151 * request an address will be passed to it (along with auxiliary data 'aux').
152 * It may then add any desired options to the message for transmission.
154 * If 'validate_offer' is non-null, then each DHCP message that offers an
155 * address will be passed to it (along with auxiliary data 'aux') for
156 * validation: if it returns true, the address will accepted; otherwise, it
159 * The DHCP client will not start advertising for an IP address until
160 * dhclient_init() is called.
162 * If successful, returns 0 and sets '*cli' to the new DHCP client. Otherwise,
163 * returns a positive errno value and sets '*cli' to a null pointer. */
165 dhclient_create(const char *netdev_name,
166 void (*modify_request)(struct dhcp_msg *, void *aux),
167 bool (*validate_offer)(const struct dhcp_msg *, void *aux),
168 void *aux, struct dhclient **cli_)
170 struct dhclient *cli;
171 struct netdev *netdev;
176 error = netdev_open(netdev_name, ETH_TYPE_IP, &netdev);
177 /* XXX install socket filter to catch only DHCP packets. */
179 VLOG_ERR("could not open %s network device: %s",
180 netdev_name, strerror(error));
184 error = netdev_turn_flags_on(netdev, NETDEV_UP, false);
186 VLOG_ERR("could not bring %s device up: %s",
187 netdev_name, strerror(error));
188 netdev_close(netdev);
192 cli = xcalloc(1, sizeof *cli);
193 cli->modify_request = modify_request;
194 cli->validate_offer = validate_offer;
196 cli->netdev = netdev;
197 cli->state = S_RELEASED;
198 cli->state_entered = time_now();
199 cli->xid = random_uint32();
202 cli->retransmit = cli->delay = 0;
203 cli->max_timeout = 64;
204 cli->min_timeout = 1;
211 /* Sets the maximum amount of timeout that 'cli' will wait for a reply from
212 * the DHCP server before retransmitting, in seconds, to 'max_timeout'. The
213 * default is 64 seconds. */
215 dhclient_set_max_timeout(struct dhclient *cli, unsigned int max_timeout)
217 cli->max_timeout = MAX(2, max_timeout);
220 /* Destroys 'cli' and frees all related resources. */
222 dhclient_destroy(struct dhclient *cli)
225 dhcp_msg_uninit(cli->binding);
227 netdev_close(cli->netdev);
233 /* Returns the network device in use by 'cli'. The caller must not destroy
234 * the returned device. */
236 dhclient_get_netdev(struct dhclient *cli)
241 /* Forces 'cli' into a (re)initialization state, in which no address is bound
242 * but the client is advertising to obtain one. If 'requested_ip' is nonzero,
243 * then the client will attempt to re-bind to that IP address; otherwise, it
244 * will not ask for any particular address. */
246 dhclient_init(struct dhclient *cli, uint32_t requested_ip)
248 state_transition(cli, requested_ip ? S_INIT_REBOOT : S_INIT);
249 cli->ipaddr = requested_ip;
250 cli->min_timeout = 0;
254 /* Forces 'cli' to release its bound IP address (if any). The client will not
255 * advertise for a new address until dhclient_init() is called again. */
257 dhclient_release(struct dhclient *cli)
259 if (dhclient_is_bound(cli)) {
261 dhclient_msg_init(cli, DHCPRELEASE, &msg);
262 msg.ciaddr = cli->ipaddr;
263 do_send_msg(cli, &msg);
264 dhcp_msg_uninit(&msg);
266 state_transition(cli, S_RELEASED);
267 cli->min_timeout = UINT_MAX;
271 do_force_renew(struct dhclient *cli, int deadline)
273 time_t now = time_now();
274 unsigned int lease_left = sat_sub(cli->lease_expiration, now);
275 if (lease_left <= deadline) {
276 if (cli->state & (S_RENEWING | S_REBINDING)) {
279 deadline = lease_left;
281 if (cli->state & (S_BOUND | S_RENEWING)) {
282 state_transition(cli, S_RENEWING);
283 cli->renewing_timeout = deadline * 3 / 4;
284 cli->rebinding_timeout = deadline * 1 / 4;
286 state_transition(cli, S_REBINDING);
287 cli->rebinding_timeout = deadline;
289 cli->min_timeout = 0;
292 /* Forces 'cli' to attempt to renew the lease its current IP address (if any)
293 * within 'deadline' seconds. If the deadline is not met, then the client
294 * gives up its IP address binding and re-starts the DHCP process. */
296 dhclient_force_renew(struct dhclient *cli, int deadline)
298 /* Drain the receive queue so that we know that any DHCPACK we process is
299 * freshly received. */
300 netdev_drain(cli->netdev);
302 switch (cli->state) {
313 do_force_renew(cli, deadline);
317 dhclient_init(cli, 0);
322 /* Returns true if 'cli' is bound to an IP address, false otherwise. */
324 dhclient_is_bound(const struct dhclient *cli)
326 return cli->state & (S_BOUND | S_RENEWING | S_REBINDING);
329 /* Returns true if 'cli' has changed from bound to unbound, or vice versa, at
330 * least once since the last time this function was called. */
332 dhclient_changed(struct dhclient *cli)
334 bool changed = cli->changed;
339 /* Returns 'cli''s current state, as a string. The caller must not modify or
340 * free the string. */
342 dhclient_get_state(const struct dhclient *cli)
344 return state_name(cli->state);
347 /* Returns the number of seconds spent so far in 'cli''s current state. */
349 dhclient_get_state_elapsed(const struct dhclient *cli)
351 return elapsed_in_this_state(cli);
354 /* If 'cli' is bound, returns the number of seconds remaining in its lease;
355 * otherwise, returns 0. */
357 dhclient_get_lease_remaining(const struct dhclient *cli)
359 return dhclient_is_bound(cli) ? cli->lease_expiration - time_now() : 0;
362 /* If 'cli' is bound to an IP address, returns that IP address; otherwise,
365 dhclient_get_ip(const struct dhclient *cli)
367 return dhclient_is_bound(cli) ? cli->ipaddr : 0;
370 /* If 'cli' is bound to an IP address, returns the netmask for that IP address;
371 * otherwise, returns 0. */
373 dhclient_get_netmask(const struct dhclient *cli)
375 return dhclient_is_bound(cli) ? cli->netmask : 0;
378 /* If 'cli' is bound to an IP address and 'cli' has a default gateway, returns
379 * that default gateway; otherwise, returns 0. */
381 dhclient_get_router(const struct dhclient *cli)
383 return dhclient_is_bound(cli) ? cli->router : 0;
386 /* If 'cli' is bound to an IP address, returns the DHCP message that was
387 * received to obtain that IP address (so that the caller can obtain additional
388 * options from it). Otherwise, returns a null pointer. */
389 const struct dhcp_msg *
390 dhclient_get_config(const struct dhclient *cli)
392 return dhclient_is_bound(cli) ? cli->binding : NULL;
395 /* Configures the network device backing 'cli' to the network address and other
396 * parameters obtained via DHCP. If no address is bound on 'cli', removes any
397 * configured address from 'cli'.
399 * To use a dhclient as a regular DHCP client that binds and unbinds from IP
400 * addresses in the usual fashion, call this function after dhclient_run() if
401 * anything has changed, like so:
404 * if (dhclient_changed(cli)) {
405 * dhclient_configure_netdev(cli);
410 dhclient_configure_netdev(struct dhclient *cli)
412 struct in_addr addr = { dhclient_get_ip(cli) };
413 struct in_addr mask = { dhclient_get_netmask(cli) };
414 struct in_addr router = { dhclient_get_router(cli) };
417 error = netdev_set_in4(cli->netdev, addr, mask);
419 VLOG_ERR("could not set %s address "IP_FMT"/"IP_FMT": %s",
420 netdev_get_name(cli->netdev),
421 IP_ARGS(&addr.s_addr), IP_ARGS(&mask.s_addr),
425 if (!error && router.s_addr) {
426 error = netdev_add_router(cli->netdev, router);
428 VLOG_ERR("failed to add default route to "IP_FMT" on %s: %s",
429 IP_ARGS(&router), netdev_get_name(cli->netdev),
437 /* If 'cli' is bound and the binding includes DNS domain parameters, updates
438 * /etc/resolv.conf will be updated to match the received parameters. Returns
439 * 0 if successful, otherwise a positive errno value. */
441 dhclient_update_resolv_conf(struct dhclient *cli)
445 bool has_domain_name;
450 if (!dhclient_is_bound(cli)) {
453 if (!dhcp_msg_get_ip(cli->binding, DHCP_CODE_DNS_SERVER, 0, &dns_server)) {
454 VLOG_DBG("binding does not include any DNS servers");
458 sprintf(new_name, "/etc/resolv.conf.tmp%ld", (long int) getpid());
459 new = fopen(new_name, "w");
461 VLOG_WARN("%s: create: %s", new_name, strerror(errno));
465 domain_name = dhcp_msg_get_string(cli->binding, DHCP_CODE_DOMAIN_NAME);
466 has_domain_name = domain_name != NULL;
468 if (strspn(domain_name, "-_.0123456789abcdefghijklmnopqrstuvwxyz"
469 "ABCDEFGHIJKLMNOPQRSTUVWXYZ") == strlen(domain_name)) {
470 fprintf(new, "domain %s\n", domain_name);
472 VLOG_WARN("ignoring invalid domain name %s", domain_name);
473 has_domain_name = false;
476 VLOG_DBG("binding does not include domain name");
480 for (i = 0; dhcp_msg_get_ip(cli->binding, DHCP_CODE_DNS_SERVER,
481 i, &dns_server); i++) {
482 fprintf(new, "nameserver "IP_FMT"\n", IP_ARGS(&dns_server));
485 old = fopen("/etc/resolv.conf", "r");
489 while (fgets(line, sizeof line, old)) {
490 char *kw = xmemdup0(line, strcspn(line, " \t\r\n"));
491 if (strcmp(kw, "nameserver")
493 || (strcmp(kw, "domain") && strcmp(kw, "search")))) {
500 VLOG_DBG("/etc/resolv.conf: open: %s", strerror(errno));
503 if (fclose(new) < 0) {
504 VLOG_WARN("%s: close: %s", new_name, strerror(errno));
508 if (rename(new_name, "/etc/resolv.conf") < 0) {
509 VLOG_WARN("failed to rename %s to /etc/resolv.conf: %s",
510 new_name, strerror(errno));
520 make_dhcpdiscover(struct dhclient *cli, struct dhcp_msg *msg)
522 cli->secs = elapsed_in_this_state(cli);
523 dhclient_msg_init(cli, DHCPDISCOVER, msg);
525 dhcp_msg_put_ip(msg, DHCP_CODE_REQUESTED_IP, cli->ipaddr);
530 make_dhcprequest(struct dhclient *cli, struct dhcp_msg *msg)
532 dhclient_msg_init(cli, DHCPREQUEST, msg);
533 msg->ciaddr = dhclient_get_ip(cli);
534 if (cli->state == S_REQUESTING) {
535 dhcp_msg_put_ip(msg, DHCP_CODE_SERVER_IDENTIFIER, cli->server_ip);
537 dhcp_msg_put_ip(msg, DHCP_CODE_REQUESTED_IP, cli->ipaddr);
541 do_init(struct dhclient *cli, enum dhclient_state next_state)
543 if (!cli->init_delay) {
544 cli->init_delay = fuzz(2, 1);
546 if (timeout(cli, cli->init_delay)) {
547 state_transition(cli, next_state);
552 dhclient_run_INIT(struct dhclient *cli)
554 do_init(cli, S_SELECTING);
558 dhclient_run_INIT_REBOOT(struct dhclient *cli)
560 do_init(cli, S_REBOOTING);
564 dhclient_run_REBOOTING(struct dhclient *cli)
566 send_reliably(cli, make_dhcprequest);
567 if (!receive_ack(cli) && timeout(cli, 60)) {
568 state_transition(cli, S_INIT);
573 dhcp_receive(struct dhclient *cli, unsigned int msgs, struct dhcp_msg *msg)
575 while (do_receive_msg(cli, msg)) {
576 if (msg->type < 0 || msg->type > 31 || !((1u << msg->type) & msgs)) {
577 VLOG_DBG_RL(&rl, "received unexpected %s in %s state: %s",
578 dhcp_type_name(msg->type), state_name(cli->state),
579 dhcp_msg_to_string(msg, false, &cli->s));
580 } else if (msg->xid != cli->xid) {
582 "ignoring %s with xid != %08"PRIx32" in %s state: %s",
583 dhcp_type_name(msg->type), msg->xid,
584 state_name(cli->state),
585 dhcp_msg_to_string(msg, false, &cli->s));
589 dhcp_msg_uninit(msg);
595 validate_offered_options(struct dhclient *cli, const struct dhcp_msg *msg)
597 uint32_t lease, netmask;
598 if (!dhcp_msg_get_secs(msg, DHCP_CODE_LEASE_TIME, 0, &lease)) {
599 VLOG_WARN_RL(&rl, "%s lacks lease time: %s", dhcp_type_name(msg->type),
600 dhcp_msg_to_string(msg, false, &cli->s));
601 } else if (!dhcp_msg_get_ip(msg, DHCP_CODE_SUBNET_MASK, 0, &netmask)) {
602 VLOG_WARN_RL(&rl, "%s lacks netmask: %s", dhcp_type_name(msg->type),
603 dhcp_msg_to_string(msg, false, &cli->s));
604 } else if (lease < MIN_ACCEPTABLE_LEASE) {
605 VLOG_WARN_RL(&rl, "Ignoring %s with %"PRIu32"-second lease time: %s",
606 dhcp_type_name(msg->type), lease,
607 dhcp_msg_to_string(msg, false, &cli->s));
608 } else if (cli->validate_offer && !cli->validate_offer(msg, cli->aux)) {
609 VLOG_DBG_RL(&rl, "client validation hook refused offer: %s",
610 dhcp_msg_to_string(msg, false, &cli->s));
618 dhclient_run_SELECTING(struct dhclient *cli)
622 send_reliably(cli, make_dhcpdiscover);
623 if (cli->server_ip && timeout(cli, 60)) {
625 state_transition(cli, S_INIT);
627 for (; dhcp_receive(cli, 1u << DHCPOFFER, &msg); dhcp_msg_uninit(&msg)) {
628 if (!validate_offered_options(cli, &msg)) {
631 if (!dhcp_msg_get_ip(&msg, DHCP_CODE_SERVER_IDENTIFIER,
632 0, &cli->server_ip)) {
633 VLOG_WARN_RL(&rl, "DHCPOFFER lacks server identifier: %s",
634 dhcp_msg_to_string(&msg, false, &cli->s));
638 VLOG_DBG_RL(&rl, "accepting DHCPOFFER: %s",
639 dhcp_msg_to_string(&msg, false, &cli->s));
640 cli->ipaddr = msg.yiaddr;
641 state_transition(cli, S_REQUESTING);
647 same_binding(const struct dhcp_msg *old, const struct dhcp_msg *new)
649 static const int codes[] = {
650 DHCP_CODE_SUBNET_MASK,
652 DHCP_CODE_DNS_SERVER,
654 DHCP_CODE_DOMAIN_NAME,
657 DHCP_CODE_BROADCAST_ADDRESS,
658 DHCP_CODE_STATIC_ROUTE,
659 DHCP_CODE_ARP_CACHE_TIMEOUT,
660 DHCP_CODE_ETHERNET_ENCAPSULATION,
662 DHCP_CODE_SERVER_IDENTIFIER,
663 DHCP_CODE_OFP_CONTROLLER_VCONN,
664 DHCP_CODE_OFP_PKI_URI,
669 if (old->yiaddr != new->yiaddr) {
670 VLOG_WARN("DHCP binding changed IP address from "IP_FMT" to "IP_FMT,
671 IP_ARGS(&old->yiaddr), IP_ARGS(&new->yiaddr));
674 for (i = 0; i < ARRAY_SIZE(codes); i++) {
676 const struct dhcp_option *old_opt = &old->options[code];
677 const struct dhcp_option *new_opt = &new->options[code];
678 if (!dhcp_option_equals(old_opt, new_opt)) {
679 struct ds old_string = DS_EMPTY_INITIALIZER;
680 struct ds new_string = DS_EMPTY_INITIALIZER;
681 VLOG_WARN("DHCP binding changed option from %s to %s",
682 dhcp_option_to_string(old_opt, code, &old_string),
683 dhcp_option_to_string(new_opt, code, &new_string));
684 ds_destroy(&old_string);
685 ds_destroy(&new_string);
693 receive_ack(struct dhclient *cli)
697 if (!dhcp_receive(cli, (1u << DHCPACK) | (1u << DHCPNAK), &msg)) {
699 } else if (msg.type == DHCPNAK) {
700 dhcp_msg_uninit(&msg);
701 state_transition(cli, S_INIT);
703 } else if (!validate_offered_options(cli, &msg)) {
704 dhcp_msg_uninit(&msg);
707 uint32_t lease = 0, t1 = 0, t2 = 0;
710 if (!same_binding(cli->binding, &msg)) {
713 dhcp_msg_uninit(cli->binding);
715 cli->binding = xmalloc(sizeof *cli->binding);
717 dhcp_msg_copy(cli->binding, &msg);
719 dhcp_msg_get_secs(&msg, DHCP_CODE_LEASE_TIME, 0, &lease);
720 dhcp_msg_get_secs(&msg, DHCP_CODE_T1, 0, &t1);
721 dhcp_msg_get_secs(&msg, DHCP_CODE_T2, 0, &t2);
722 assert(lease >= MIN_ACCEPTABLE_LEASE);
724 if (!t2 || t2 >= lease) {
727 if (!t1 || t1 >= t2) {
728 t1 = calc_t1(lease, t2);
731 cli->lease_expiration = sat_add(time_now(), lease);
732 cli->bound_timeout = t1;
733 cli->renewing_timeout = t2 - t1;
734 cli->rebinding_timeout = lease - t2;
736 cli->ipaddr = msg.yiaddr;
737 dhcp_msg_get_ip(&msg, DHCP_CODE_SUBNET_MASK, 0, &cli->netmask);
738 if (!dhcp_msg_get_ip(&msg, DHCP_CODE_ROUTER, 0, &cli->router)) {
739 cli->router = INADDR_ANY;
741 state_transition(cli, S_BOUND);
742 VLOG_DBG("Bound: %s", dhcp_msg_to_string(&msg, false, &cli->s));
748 dhclient_run_REQUESTING(struct dhclient *cli)
750 send_reliably(cli, make_dhcprequest);
751 if (!receive_ack(cli) && timeout(cli, 60)) {
752 state_transition(cli, S_INIT);
757 dhclient_run_BOUND(struct dhclient *cli)
759 if (timeout(cli, cli->bound_timeout)) {
760 state_transition(cli, S_RENEWING);
765 dhclient_run_RENEWING(struct dhclient *cli)
767 send_reliably(cli, make_dhcprequest);
768 if (!receive_ack(cli) && timeout(cli, cli->renewing_timeout)) {
769 state_transition(cli, S_REBINDING);
774 dhclient_run_REBINDING(struct dhclient *cli)
776 send_reliably(cli, make_dhcprequest);
777 if (!receive_ack(cli) && timeout(cli, cli->rebinding_timeout)) {
778 state_transition(cli, S_INIT);
783 dhclient_run_RELEASED(struct dhclient *cli UNUSED)
788 /* Processes the DHCP protocol for 'cli'. */
790 dhclient_run(struct dhclient *cli)
794 old_state = cli->state;
795 cli->min_timeout = UINT_MAX;
797 switch (cli->state) {
798 #define DHCLIENT_STATE(NAME, VALUE) \
799 case S_##NAME: dhclient_run_##NAME(cli); break;
801 #undef DHCLIENT_STATE
805 } while (cli->state != old_state);
808 /* Sets up poll timeouts to wake up the poll loop when 'cli' needs to do some
811 dhclient_wait(struct dhclient *cli)
813 if (cli->min_timeout != UINT_MAX) {
814 time_t now = time_now();
815 unsigned int wake = sat_add(cli->state_entered, cli->min_timeout);
817 poll_immediate_wake();
819 poll_timer_wait(sat_mul(sat_sub(wake, now), 1000));
822 /* Reset timeout to 1 second. This will have no effect ordinarily, because
823 * dhclient_run() will typically set it back to a higher value. If,
824 * however, the caller fails to call dhclient_run() before its next call to
825 * dhclient_wait() we won't potentially block forever. */
826 cli->min_timeout = 1;
828 if (cli->state & (S_SELECTING | S_REQUESTING | S_RENEWING | S_REBINDING)) {
829 netdev_recv_wait(cli->netdev);
834 state_transition(struct dhclient *cli, enum dhclient_state state)
836 bool was_bound = dhclient_is_bound(cli);
838 if (cli->state != state) {
839 VLOG_DBG("entering %s", state_name(state));
842 cli->state_entered = time_now();
843 cli->retransmit = cli->delay = 0;
844 am_bound = dhclient_is_bound(cli);
845 if (was_bound != am_bound) {
848 assert(cli->binding != NULL);
849 VLOG_WARN("%s: obtained address "IP_FMT", netmask "IP_FMT,
850 netdev_get_name(cli->netdev),
851 IP_ARGS(&cli->ipaddr), IP_ARGS(&cli->netmask));
853 VLOG_WARN("%s: obtained default gateway "IP_FMT,
854 netdev_get_name(cli->netdev), IP_ARGS(&cli->router));
857 dhcp_msg_uninit(cli->binding);
861 VLOG_WARN("%s: network address unbound",
862 netdev_get_name(cli->netdev));
865 if (cli->state & (S_SELECTING | S_REQUESTING | S_REBOOTING)) {
866 netdev_drain(cli->netdev);
871 send_reliably(struct dhclient *cli,
872 void (*make_packet)(struct dhclient *, struct dhcp_msg *))
874 if (timeout(cli, cli->retransmit)) {
876 make_packet(cli, &msg);
877 if (cli->modify_request) {
878 cli->modify_request(&msg, cli->aux);
880 do_send_msg(cli, &msg);
881 cli->delay = MIN(cli->max_timeout, MAX(4, cli->delay * 2));
882 cli->retransmit += fuzz(cli->delay, 1);
883 timeout(cli, cli->retransmit);
884 dhcp_msg_uninit(&msg);
889 dhclient_msg_init(struct dhclient *cli, enum dhcp_msg_type type,
890 struct dhcp_msg *msg)
893 msg->op = DHCP_BOOTREQUEST;
895 msg->secs = cli->secs;
897 memcpy(msg->chaddr, netdev_get_etheraddr(cli->netdev), ETH_ADDR_LEN);
901 elapsed_in_this_state(const struct dhclient *cli)
903 return time_now() - cli->state_entered;
907 timeout(struct dhclient *cli, unsigned int secs)
909 cli->min_timeout = MIN(cli->min_timeout, secs);
910 return time_now() >= sat_add(cli->state_entered, secs);
914 do_receive_msg(struct dhclient *cli, struct dhcp_msg *msg)
918 ofpbuf_init(&b, netdev_get_mtu(cli->netdev) + VLAN_ETH_HEADER_LEN);
919 for (; cli->received < 50; cli->received++) {
920 const struct ip_header *ip;
921 const struct dhcp_header *dhcp;
926 error = netdev_recv(cli->netdev, &b);
931 flow_extract(&b, 0, &flow);
932 if (flow.dl_type != htons(ETH_TYPE_IP)
933 || flow.nw_proto != IP_TYPE_UDP
934 || flow.tp_dst != htons(68)
935 || !(eth_addr_is_broadcast(flow.dl_dst)
936 || eth_addr_equals(flow.dl_dst,
937 netdev_get_etheraddr(cli->netdev)))) {
942 if (IP_IS_FRAGMENT(ip->ip_frag_off)) {
943 /* We don't do reassembly. */
944 VLOG_WARN_RL(&rl, "ignoring fragmented DHCP datagram");
950 VLOG_WARN_RL(&rl, "ignoring DHCP datagram with missing payload");
954 ofpbuf_pull(&b, (char *)b.l7 - (char*)b.data);
955 error = dhcp_parse(msg, &b);
957 if (VLOG_IS_DBG_ENABLED()) {
958 VLOG_DBG_RL(&rl, "received %s",
959 dhcp_msg_to_string(msg, false, &cli->s));
961 VLOG_WARN_RL(&rl, "received %s", dhcp_type_name(msg->type));
967 netdev_drain(cli->netdev);
974 do_send_msg(struct dhclient *cli, const struct dhcp_msg *msg)
977 struct eth_header eh;
979 struct udp_header th;
983 ofpbuf_init(&b, ETH_TOTAL_MAX);
984 ofpbuf_reserve(&b, ETH_HEADER_LEN + IP_HEADER_LEN + UDP_HEADER_LEN);
986 dhcp_assemble(msg, &b);
988 memcpy(eh.eth_src, netdev_get_etheraddr(cli->netdev), ETH_ADDR_LEN);
989 memcpy(eh.eth_dst, eth_addr_broadcast, ETH_ADDR_LEN);
990 eh.eth_type = htons(ETH_TYPE_IP);
992 nh.ip_ihl_ver = IP_IHL_VER(5, IP_VERSION);
994 nh.ip_tot_len = htons(IP_HEADER_LEN + UDP_HEADER_LEN + b.size);
995 /* We can't guarantee uniqueness of ip_id versus the host's, screwing up
996 * fragment reassembly, so prevent fragmentation and use an all-zeros
997 * ip_id. RFC 791 doesn't say we can do this, but Linux does the same
998 * thing for DF packets, so it must not screw anything up. */
1000 nh.ip_frag_off = htons(IP_DONT_FRAGMENT);
1002 nh.ip_proto = IP_TYPE_UDP;
1004 nh.ip_src = dhclient_get_ip(cli);
1005 /* XXX need to use UDP socket for nonzero server IPs so that we can get
1006 * routing table support.
1008 * if (...have server IP and in appropriate state...) {
1009 * nh.ip_dst = cli->server_ip;
1011 * nh.ip_dst = INADDR_BROADCAST;
1014 nh.ip_dst = INADDR_BROADCAST;
1015 nh.ip_csum = csum(&nh, sizeof nh);
1017 th.udp_src = htons(66);
1018 th.udp_dst = htons(67);
1019 th.udp_len = htons(UDP_HEADER_LEN + b.size);
1021 udp_csum = csum_add32(0, nh.ip_src);
1022 udp_csum = csum_add32(udp_csum, nh.ip_dst);
1023 udp_csum = csum_add16(udp_csum, IP_TYPE_UDP << 8);
1024 udp_csum = csum_add16(udp_csum, th.udp_len);
1025 udp_csum = csum_continue(udp_csum, &th, sizeof th);
1026 th.udp_csum = csum_finish(csum_continue(udp_csum, b.data, b.size));
1028 ofpbuf_push(&b, &th, sizeof th);
1029 ofpbuf_push(&b, &nh, sizeof nh);
1030 ofpbuf_push(&b, &eh, sizeof eh);
1032 /* Don't try to send the frame if it's too long for an Ethernet frame. We
1033 * disregard the network device's actual MTU because we don't want the
1034 * frame to have to be discarded or fragmented if it travels over a regular
1035 * Ethernet at some point. 1500 bytes should be enough for anyone. */
1036 if (b.size <= ETH_TOTAL_MAX) {
1037 if (VLOG_IS_DBG_ENABLED()) {
1038 VLOG_DBG("sending %s", dhcp_msg_to_string(msg, false, &cli->s));
1040 VLOG_WARN("sending %s", dhcp_type_name(msg->type));
1042 error = netdev_send(cli->netdev, &b);
1044 VLOG_ERR("send failed on %s: %s",
1045 netdev_get_name(cli->netdev), strerror(error));
1048 VLOG_ERR("cannot send %zu-byte Ethernet frame", b.size);
1055 fuzz(unsigned int x, int max_fuzz)
1057 /* Generate number in range [-max_fuzz, +max_fuzz]. */
1058 int fuzz = random_range(max_fuzz * 2 + 1) - max_fuzz;
1059 unsigned int y = x + fuzz;
1060 return fuzz >= 0 ? (y >= x ? y : UINT_MAX) : (y <= x ? y : 0);
1064 clamp(unsigned int x, unsigned int min, unsigned int max)
1066 return x < min ? min : x > max ? max : x;
1070 calc_t2(unsigned int lease)
1072 unsigned int base = lease * 0.875;
1073 return lease >= 60 ? clamp(fuzz(base, 10), 0, lease - 1) : base;
1077 calc_t1(unsigned int lease, unsigned int t2)
1079 unsigned int base = lease / 2;
1080 return lease >= 60 ? clamp(fuzz(base, 10), 0, t2 - 1) : base;