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(). */
107 unsigned int init_delay; /* Used by S_INIT. */
109 time_t lease_expiration;
110 unsigned int bound_timeout;
111 unsigned int renewing_timeout;
112 unsigned int rebinding_timeout;
114 /* Used by dhclient_run() and dhclient_wait() */
115 unsigned int min_timeout;
118 /* Set when we send out a DHCPDISCOVER message. */
124 /* Minimum acceptable lease time, in seconds. */
125 #define MIN_ACCEPTABLE_LEASE 15
127 static void state_transition(struct dhclient *, enum dhclient_state);
128 static unsigned int elapsed_in_this_state(const struct dhclient *cli);
129 static bool timeout(struct dhclient *, unsigned int secs);
131 static void dhclient_msg_init(struct dhclient *, enum dhcp_msg_type,
133 static void send_reliably(struct dhclient *cli,
134 void (*make_packet)(struct dhclient *,
136 static bool do_receive_msg(struct dhclient *, struct dhcp_msg *);
137 static void do_send_msg(struct dhclient *, const struct dhcp_msg *);
138 static bool receive_ack(struct dhclient *);
140 static unsigned int fuzz(unsigned int x, int max_fuzz);
141 static unsigned int calc_t2(unsigned int lease);
142 static unsigned int calc_t1(unsigned int lease, unsigned int t2);
144 static unsigned int clamp(unsigned int x, unsigned int min, unsigned int max);
146 /* Creates a new DHCP client to configure the network device 'netdev_name'
149 * If 'modify_request' is non-null, then each DHCP message to discover or
150 * request an address will be passed to it (along with auxiliary data 'aux').
151 * It may then add any desired options to the message for transmission.
153 * If 'validate_offer' is non-null, then each DHCP message that offers an
154 * address will be passed to it (along with auxiliary data 'aux') for
155 * validation: if it returns true, the address will accepted; otherwise, it
158 * The DHCP client will not start advertising for an IP address until
159 * dhclient_init() is called.
161 * If successful, returns 0 and sets '*cli' to the new DHCP client. Otherwise,
162 * returns a positive errno value and sets '*cli' to a null pointer. */
164 dhclient_create(const char *netdev_name,
165 void (*modify_request)(struct dhcp_msg *, void *aux),
166 bool (*validate_offer)(const struct dhcp_msg *, void *aux),
167 void *aux, struct dhclient **cli_)
169 struct dhclient *cli;
170 struct netdev *netdev;
175 error = netdev_open(netdev_name, ETH_TYPE_IP, &netdev);
176 /* XXX install socket filter to catch only DHCP packets. */
178 VLOG_ERR("could not open %s network device: %s",
179 netdev_name, strerror(error));
183 error = netdev_turn_flags_on(netdev, NETDEV_UP, false);
185 VLOG_ERR("could not bring %s device up: %s",
186 netdev_name, strerror(error));
187 netdev_close(netdev);
191 cli = xcalloc(1, sizeof *cli);
192 cli->modify_request = modify_request;
193 cli->validate_offer = validate_offer;
195 cli->netdev = netdev;
196 cli->state = S_RELEASED;
197 cli->state_entered = time_now();
198 cli->xid = random_uint32();
201 cli->retransmit = cli->delay = 0;
202 cli->min_timeout = 1;
209 /* Forces 'cli' into a (re)initialization state, in which no address is bound
210 * but the client is advertising to obtain one. If 'requested_ip' is nonzero,
211 * then the client will attempt to re-bind to that IP address; otherwise, it
212 * will not ask for any particular address. */
214 dhclient_init(struct dhclient *cli, uint32_t requested_ip)
216 state_transition(cli, requested_ip ? S_INIT_REBOOT : S_INIT);
217 cli->ipaddr = requested_ip;
218 cli->min_timeout = 0;
222 /* Forces 'cli' to release its bound IP address (if any). The client will not
223 * advertise for a new address until dhclient_init() is called again. */
225 dhclient_release(struct dhclient *cli)
227 if (dhclient_is_bound(cli)) {
229 dhclient_msg_init(cli, DHCPRELEASE, &msg);
230 msg.ciaddr = cli->ipaddr;
231 do_send_msg(cli, &msg);
232 dhcp_msg_uninit(&msg);
234 state_transition(cli, S_RELEASED);
235 cli->min_timeout = UINT_MAX;
239 do_force_renew(struct dhclient *cli, int deadline)
241 time_t now = time_now();
242 unsigned int lease_left = sat_sub(cli->lease_expiration, now);
243 if (lease_left <= deadline) {
244 if (cli->state & (S_RENEWING | S_REBINDING)) {
247 deadline = lease_left;
249 if (cli->state & (S_BOUND | S_RENEWING)) {
250 state_transition(cli, S_RENEWING);
251 cli->renewing_timeout = deadline * 3 / 4;
252 cli->rebinding_timeout = deadline * 1 / 4;
254 state_transition(cli, S_REBINDING);
255 cli->rebinding_timeout = deadline;
257 cli->min_timeout = 0;
260 /* Forces 'cli' to attempt to renew the lease its current IP address (if any)
261 * within 'deadline' seconds. If the deadline is not met, then the client
262 * gives up its IP address binding and re-starts the DHCP process. */
264 dhclient_force_renew(struct dhclient *cli, int deadline)
266 /* Drain the receive queue so that we know that any DHCPACK we process is
267 * freshly received. */
268 netdev_drain(cli->netdev);
270 switch (cli->state) {
281 do_force_renew(cli, deadline);
285 dhclient_init(cli, 0);
290 /* Returns true if 'cli' is bound to an IP address, false otherwise. */
292 dhclient_is_bound(const struct dhclient *cli)
294 return cli->state & (S_BOUND | S_RENEWING | S_REBINDING);
297 /* Returns true if 'cli' has changed from bound to unbound, or vice versa, at
298 * least once since the last time this function was called. */
300 dhclient_changed(struct dhclient *cli)
302 bool changed = cli->changed;
307 /* Returns 'cli''s current state, as a string. The caller must not modify or
308 * free the string. */
310 dhclient_get_state(const struct dhclient *cli)
312 return state_name(cli->state);
315 /* Returns the number of seconds spent so far in 'cli''s current state. */
317 dhclient_get_state_elapsed(const struct dhclient *cli)
319 return elapsed_in_this_state(cli);
322 /* If 'cli' is bound, returns the number of seconds remaining in its lease;
323 * otherwise, returns 0. */
325 dhclient_get_lease_remaining(const struct dhclient *cli)
327 return dhclient_is_bound(cli) ? cli->lease_expiration - time_now() : 0;
330 /* If 'cli' is bound to an IP address, returns that IP address; otherwise,
333 dhclient_get_ip(const struct dhclient *cli)
335 return dhclient_is_bound(cli) ? cli->ipaddr : 0;
338 /* If 'cli' is bound to an IP address, returns the netmask for that IP address;
339 * otherwise, returns 0. */
341 dhclient_get_netmask(const struct dhclient *cli)
343 return dhclient_is_bound(cli) ? cli->netmask : 0;
346 /* If 'cli' is bound to an IP address and 'cli' has a default gateway, returns
347 * that default gateway; otherwise, returns 0. */
349 dhclient_get_router(const struct dhclient *cli)
351 return dhclient_is_bound(cli) ? cli->router : 0;
354 /* If 'cli' is bound to an IP address, returns the DHCP message that was
355 * received to obtain that IP address (so that the caller can obtain additional
356 * options from it). Otherwise, returns a null pointer. */
357 const struct dhcp_msg *
358 dhclient_get_config(const struct dhclient *cli)
360 return dhclient_is_bound(cli) ? cli->binding : NULL;
363 /* Configures the network device backing 'cli' to the network address and other
364 * parameters obtained via DHCP. If no address is bound on 'cli', removes any
365 * configured address from 'cli'.
367 * To use a dhclient as a regular DHCP client that binds and unbinds from IP
368 * addresses in the usual fashion, call this function after dhclient_run() if
369 * anything has changed, like so:
372 * if (dhclient_changed(cli)) {
373 * dhclient_configure_netdev(cli);
378 dhclient_configure_netdev(struct dhclient *cli)
380 struct in_addr addr = { dhclient_get_ip(cli) };
381 struct in_addr mask = { dhclient_get_netmask(cli) };
382 struct in_addr router = { dhclient_get_router(cli) };
385 error = netdev_set_in4(cli->netdev, addr, mask);
387 VLOG_ERR("could not set %s address "IP_FMT"/"IP_FMT": %s",
388 netdev_get_name(cli->netdev),
389 IP_ARGS(&addr.s_addr), IP_ARGS(&mask.s_addr),
393 if (!error && router.s_addr) {
394 error = netdev_add_router(cli->netdev, router);
396 VLOG_ERR("failed to add default route to "IP_FMT" on %s: %s",
397 IP_ARGS(&router), netdev_get_name(cli->netdev),
405 /* If 'cli' is bound and the binding includes DNS domain parameters, updates
406 * /etc/resolv.conf will be updated to match the received parameters. Returns
407 * 0 if successful, otherwise a positive errno value. */
409 dhclient_update_resolv_conf(struct dhclient *cli)
413 bool has_domain_name;
418 if (!dhclient_is_bound(cli)) {
421 if (!dhcp_msg_get_ip(cli->binding, DHCP_CODE_DNS_SERVER, 0, &dns_server)) {
422 VLOG_DBG("binding does not include any DNS servers");
426 sprintf(new_name, "/etc/resolv.conf.tmp%ld", (long int) getpid());
427 new = fopen(new_name, "w");
429 VLOG_WARN("%s: create: %s", new_name, strerror(errno));
433 domain_name = dhcp_msg_get_string(cli->binding, DHCP_CODE_DOMAIN_NAME);
434 has_domain_name = domain_name != NULL;
436 if (strspn(domain_name, "-_.0123456789abcdefghijklmnopqrstuvwxyz"
437 "ABCDEFGHIJKLMNOPQRSTUVWXYZ") == strlen(domain_name)) {
438 fprintf(new, "domain %s\n", domain_name);
440 VLOG_WARN("ignoring invalid domain name %s", domain_name);
441 has_domain_name = false;
444 VLOG_DBG("binding does not include domain name");
448 for (i = 0; dhcp_msg_get_ip(cli->binding, DHCP_CODE_DNS_SERVER,
449 i, &dns_server); i++) {
450 fprintf(new, "nameserver "IP_FMT"\n", IP_ARGS(&dns_server));
453 old = fopen("/etc/resolv.conf", "r");
457 while (fgets(line, sizeof line, old)) {
458 char *kw = xmemdup0(line, strcspn(line, " \t\r\n"));
459 if (strcmp(kw, "nameserver")
461 || (strcmp(kw, "domain") && strcmp(kw, "search")))) {
468 VLOG_DBG("/etc/resolv.conf: open: %s", strerror(errno));
471 if (fclose(new) < 0) {
472 VLOG_WARN("%s: close: %s", new_name, strerror(errno));
476 if (rename(new_name, "/etc/resolv.conf") < 0) {
477 VLOG_WARN("failed to rename %s to /etc/resolv.conf: %s",
478 new_name, strerror(errno));
488 make_dhcpdiscover(struct dhclient *cli, struct dhcp_msg *msg)
490 cli->secs = elapsed_in_this_state(cli);
491 dhclient_msg_init(cli, DHCPDISCOVER, msg);
493 dhcp_msg_put_ip(msg, DHCP_CODE_REQUESTED_IP, cli->ipaddr);
498 make_dhcprequest(struct dhclient *cli, struct dhcp_msg *msg)
500 dhclient_msg_init(cli, DHCPREQUEST, msg);
501 msg->ciaddr = dhclient_get_ip(cli);
502 if (cli->state == S_REQUESTING) {
503 dhcp_msg_put_ip(msg, DHCP_CODE_SERVER_IDENTIFIER, cli->server_ip);
505 dhcp_msg_put_ip(msg, DHCP_CODE_REQUESTED_IP, cli->ipaddr);
509 do_init(struct dhclient *cli, enum dhclient_state next_state)
511 if (!cli->init_delay) {
512 cli->init_delay = fuzz(2, 1);
514 if (timeout(cli, cli->init_delay)) {
515 state_transition(cli, next_state);
520 dhclient_run_INIT(struct dhclient *cli)
522 do_init(cli, S_SELECTING);
526 dhclient_run_INIT_REBOOT(struct dhclient *cli)
528 do_init(cli, S_REBOOTING);
532 dhclient_run_REBOOTING(struct dhclient *cli)
534 send_reliably(cli, make_dhcprequest);
535 if (!receive_ack(cli) && timeout(cli, 60)) {
536 state_transition(cli, S_INIT);
541 dhcp_receive(struct dhclient *cli, unsigned int msgs, struct dhcp_msg *msg)
543 while (do_receive_msg(cli, msg)) {
544 if (msg->type < 0 || msg->type > 31 || !((1u << msg->type) & msgs)) {
545 VLOG_DBG_RL(&rl, "received unexpected %s in %s state: %s",
546 dhcp_type_name(msg->type), state_name(cli->state),
547 dhcp_msg_to_string(msg, false, &cli->s));
548 } else if (msg->xid != cli->xid) {
550 "ignoring %s with xid != %08"PRIx32" in %s state: %s",
551 dhcp_type_name(msg->type), msg->xid,
552 state_name(cli->state),
553 dhcp_msg_to_string(msg, false, &cli->s));
557 dhcp_msg_uninit(msg);
563 validate_offered_options(struct dhclient *cli, const struct dhcp_msg *msg)
565 uint32_t lease, netmask;
566 if (!dhcp_msg_get_secs(msg, DHCP_CODE_LEASE_TIME, 0, &lease)) {
567 VLOG_WARN_RL(&rl, "%s lacks lease time: %s", dhcp_type_name(msg->type),
568 dhcp_msg_to_string(msg, false, &cli->s));
569 } else if (!dhcp_msg_get_ip(msg, DHCP_CODE_SUBNET_MASK, 0, &netmask)) {
570 VLOG_WARN_RL(&rl, "%s lacks netmask: %s", dhcp_type_name(msg->type),
571 dhcp_msg_to_string(msg, false, &cli->s));
572 } else if (lease < MIN_ACCEPTABLE_LEASE) {
573 VLOG_WARN_RL(&rl, "Ignoring %s with %"PRIu32"-second lease time: %s",
574 dhcp_type_name(msg->type), lease,
575 dhcp_msg_to_string(msg, false, &cli->s));
576 } else if (cli->validate_offer && !cli->validate_offer(msg, cli->aux)) {
577 VLOG_DBG_RL(&rl, "client validation hook refused offer: %s",
578 dhcp_msg_to_string(msg, false, &cli->s));
586 dhclient_run_SELECTING(struct dhclient *cli)
590 send_reliably(cli, make_dhcpdiscover);
591 if (cli->server_ip && timeout(cli, 60)) {
593 state_transition(cli, S_INIT);
595 for (; dhcp_receive(cli, 1u << DHCPOFFER, &msg); dhcp_msg_uninit(&msg)) {
596 if (!validate_offered_options(cli, &msg)) {
599 if (!dhcp_msg_get_ip(&msg, DHCP_CODE_SERVER_IDENTIFIER,
600 0, &cli->server_ip)) {
601 VLOG_WARN_RL(&rl, "DHCPOFFER lacks server identifier: %s",
602 dhcp_msg_to_string(&msg, false, &cli->s));
606 VLOG_DBG_RL(&rl, "accepting DHCPOFFER: %s",
607 dhcp_msg_to_string(&msg, false, &cli->s));
608 cli->ipaddr = msg.yiaddr;
609 state_transition(cli, S_REQUESTING);
615 same_binding(const struct dhcp_msg *old, const struct dhcp_msg *new)
617 static const int codes[] = {
618 DHCP_CODE_SUBNET_MASK,
620 DHCP_CODE_DNS_SERVER,
622 DHCP_CODE_DOMAIN_NAME,
625 DHCP_CODE_BROADCAST_ADDRESS,
626 DHCP_CODE_STATIC_ROUTE,
627 DHCP_CODE_ARP_CACHE_TIMEOUT,
628 DHCP_CODE_ETHERNET_ENCAPSULATION,
630 DHCP_CODE_SERVER_IDENTIFIER,
631 DHCP_CODE_OFP_CONTROLLER_VCONN,
632 DHCP_CODE_OFP_PKI_URI,
637 if (old->yiaddr != new->yiaddr) {
638 VLOG_WARN("DHCP binding changed IP address from "IP_FMT" to "IP_FMT,
639 IP_ARGS(&old->yiaddr), IP_ARGS(&new->yiaddr));
642 for (i = 0; i < ARRAY_SIZE(codes); i++) {
644 const struct dhcp_option *old_opt = &old->options[code];
645 const struct dhcp_option *new_opt = &new->options[code];
646 if (!dhcp_option_equals(old_opt, new_opt)) {
647 struct ds old_string = DS_EMPTY_INITIALIZER;
648 struct ds new_string = DS_EMPTY_INITIALIZER;
649 VLOG_WARN("DHCP binding changed option from %s to %s",
650 dhcp_option_to_string(old_opt, code, &old_string),
651 dhcp_option_to_string(new_opt, code, &new_string));
652 ds_destroy(&old_string);
653 ds_destroy(&new_string);
661 receive_ack(struct dhclient *cli)
665 if (!dhcp_receive(cli, (1u << DHCPACK) | (1u << DHCPNAK), &msg)) {
667 } else if (msg.type == DHCPNAK) {
668 dhcp_msg_uninit(&msg);
669 state_transition(cli, S_INIT);
671 } else if (!validate_offered_options(cli, &msg)) {
672 dhcp_msg_uninit(&msg);
675 uint32_t lease = 0, t1 = 0, t2 = 0;
678 if (!same_binding(cli->binding, &msg)) {
681 dhcp_msg_uninit(cli->binding);
683 cli->binding = xmalloc(sizeof *cli->binding);
685 dhcp_msg_copy(cli->binding, &msg);
687 dhcp_msg_get_secs(&msg, DHCP_CODE_LEASE_TIME, 0, &lease);
688 dhcp_msg_get_secs(&msg, DHCP_CODE_T1, 0, &t1);
689 dhcp_msg_get_secs(&msg, DHCP_CODE_T2, 0, &t2);
690 assert(lease >= MIN_ACCEPTABLE_LEASE);
692 if (!t2 || t2 >= lease) {
695 if (!t1 || t1 >= t2) {
696 t1 = calc_t1(lease, t2);
699 cli->lease_expiration = sat_add(time_now(), lease);
700 cli->bound_timeout = t1;
701 cli->renewing_timeout = t2 - t1;
702 cli->rebinding_timeout = lease - t2;
704 cli->ipaddr = msg.yiaddr;
705 dhcp_msg_get_ip(&msg, DHCP_CODE_SUBNET_MASK, 0, &cli->netmask);
706 if (!dhcp_msg_get_ip(&msg, DHCP_CODE_ROUTER, 0, &cli->router)) {
707 cli->router = INADDR_ANY;
709 state_transition(cli, S_BOUND);
710 VLOG_DBG("Bound: %s", dhcp_msg_to_string(&msg, false, &cli->s));
716 dhclient_run_REQUESTING(struct dhclient *cli)
718 send_reliably(cli, make_dhcprequest);
719 if (!receive_ack(cli) && timeout(cli, 60)) {
720 state_transition(cli, S_INIT);
725 dhclient_run_BOUND(struct dhclient *cli)
727 if (timeout(cli, cli->bound_timeout)) {
728 state_transition(cli, S_RENEWING);
733 dhclient_run_RENEWING(struct dhclient *cli)
735 send_reliably(cli, make_dhcprequest);
736 if (!receive_ack(cli) && timeout(cli, cli->renewing_timeout)) {
737 state_transition(cli, S_REBINDING);
742 dhclient_run_REBINDING(struct dhclient *cli)
744 send_reliably(cli, make_dhcprequest);
745 if (!receive_ack(cli) && timeout(cli, cli->rebinding_timeout)) {
746 state_transition(cli, S_INIT);
751 dhclient_run_RELEASED(struct dhclient *cli UNUSED)
756 /* Processes the DHCP protocol for 'cli'. */
758 dhclient_run(struct dhclient *cli)
762 old_state = cli->state;
763 cli->min_timeout = UINT_MAX;
765 switch (cli->state) {
766 #define DHCLIENT_STATE(NAME, VALUE) \
767 case S_##NAME: dhclient_run_##NAME(cli); break;
769 #undef DHCLIENT_STATE
773 } while (cli->state != old_state);
776 /* Sets up poll timeouts to wake up the poll loop when 'cli' needs to do some
779 dhclient_wait(struct dhclient *cli)
781 if (cli->min_timeout != UINT_MAX) {
782 poll_timer_wait(sat_mul(cli->min_timeout, 1000));
784 /* Reset timeout to 1 second. This will have no effect ordinarily, because
785 * dhclient_run() will typically set it back to a higher value. If,
786 * however, the caller fails to call dhclient_run() before its next call to
787 * dhclient_wait() we won't potentially block forever. */
788 cli->min_timeout = 1;
790 if (cli->state & (S_SELECTING | S_REQUESTING | S_RENEWING | S_REBINDING)) {
791 netdev_recv_wait(cli->netdev);
796 state_transition(struct dhclient *cli, enum dhclient_state state)
798 bool was_bound = dhclient_is_bound(cli);
800 if (cli->state != state) {
801 VLOG_DBG("entering %s", state_name(state));
804 cli->state_entered = time_now();
805 cli->retransmit = cli->delay = 0;
806 am_bound = dhclient_is_bound(cli);
807 if (was_bound != am_bound) {
810 assert(cli->binding != NULL);
811 VLOG_WARN("%s: obtained address "IP_FMT", netmask "IP_FMT,
812 netdev_get_name(cli->netdev),
813 IP_ARGS(&cli->ipaddr), IP_ARGS(&cli->netmask));
815 VLOG_WARN("%s: obtained default gateway "IP_FMT,
816 netdev_get_name(cli->netdev), IP_ARGS(&cli->router));
819 dhcp_msg_uninit(cli->binding);
823 VLOG_WARN("%s: network address unbound",
824 netdev_get_name(cli->netdev));
827 if (cli->state & (S_SELECTING | S_REQUESTING | S_REBOOTING)) {
828 netdev_drain(cli->netdev);
833 send_reliably(struct dhclient *cli,
834 void (*make_packet)(struct dhclient *, struct dhcp_msg *))
836 if (timeout(cli, cli->retransmit)) {
838 make_packet(cli, &msg);
839 if (cli->modify_request) {
840 cli->modify_request(&msg, cli->aux);
842 do_send_msg(cli, &msg);
843 cli->delay = MIN(64, MAX(4, cli->delay * 2));
844 cli->retransmit += fuzz(cli->delay, 1);
845 timeout(cli, cli->retransmit);
846 dhcp_msg_uninit(&msg);
851 dhclient_msg_init(struct dhclient *cli, enum dhcp_msg_type type,
852 struct dhcp_msg *msg)
855 msg->op = DHCP_BOOTREQUEST;
857 msg->secs = cli->secs;
859 memcpy(msg->chaddr, netdev_get_etheraddr(cli->netdev), ETH_ADDR_LEN);
863 elapsed_in_this_state(const struct dhclient *cli)
865 return time_now() - cli->state_entered;
869 timeout(struct dhclient *cli, unsigned int secs)
871 cli->min_timeout = MIN(cli->min_timeout, secs);
872 return time_now() >= sat_add(cli->state_entered, secs);
876 do_receive_msg(struct dhclient *cli, struct dhcp_msg *msg)
880 ofpbuf_init(&b, netdev_get_mtu(cli->netdev) + VLAN_ETH_HEADER_LEN);
881 for (; cli->received < 50; cli->received++) {
882 const struct ip_header *ip;
883 const struct dhcp_header *dhcp;
888 error = netdev_recv(cli->netdev, &b);
893 flow_extract(&b, 0, &flow);
894 if (flow.dl_type != htons(ETH_TYPE_IP)
895 || flow.nw_proto != IP_TYPE_UDP
896 || flow.tp_dst != htons(68)
897 || !(eth_addr_is_broadcast(flow.dl_dst)
898 || eth_addr_equals(flow.dl_dst,
899 netdev_get_etheraddr(cli->netdev)))) {
904 if (IP_IS_FRAGMENT(ip->ip_frag_off)) {
905 /* We don't do reassembly. */
906 VLOG_WARN_RL(&rl, "ignoring fragmented DHCP datagram");
912 VLOG_WARN_RL(&rl, "ignoring DHCP datagram with missing payload");
916 ofpbuf_pull(&b, (char *)b.l7 - (char*)b.data);
917 error = dhcp_parse(msg, &b);
919 VLOG_DBG_RL(&rl, "received %s",
920 dhcp_msg_to_string(msg, false, &cli->s));
925 netdev_drain(cli->netdev);
932 do_send_msg(struct dhclient *cli, const struct dhcp_msg *msg)
935 struct eth_header eh;
937 struct udp_header th;
941 ofpbuf_init(&b, ETH_TOTAL_MAX);
942 ofpbuf_reserve(&b, ETH_HEADER_LEN + IP_HEADER_LEN + UDP_HEADER_LEN);
944 dhcp_assemble(msg, &b);
946 memcpy(eh.eth_src, netdev_get_etheraddr(cli->netdev), ETH_ADDR_LEN);
947 memcpy(eh.eth_dst, eth_addr_broadcast, ETH_ADDR_LEN);
948 eh.eth_type = htons(ETH_TYPE_IP);
950 nh.ip_ihl_ver = IP_IHL_VER(5, IP_VERSION);
952 nh.ip_tot_len = htons(IP_HEADER_LEN + UDP_HEADER_LEN + b.size);
953 /* We can't guarantee uniqueness of ip_id versus the host's, screwing up
954 * fragment reassembly, so prevent fragmentation and use an all-zeros
955 * ip_id. RFC 791 doesn't say we can do this, but Linux does the same
956 * thing for DF packets, so it must not screw anything up. */
958 nh.ip_frag_off = htons(IP_DONT_FRAGMENT);
960 nh.ip_proto = IP_TYPE_UDP;
962 nh.ip_src = dhclient_get_ip(cli);
963 /* XXX need to use UDP socket for nonzero server IPs so that we can get
964 * routing table support.
966 * if (...have server IP and in appropriate state...) {
967 * nh.ip_dst = cli->server_ip;
969 * nh.ip_dst = INADDR_BROADCAST;
972 nh.ip_dst = INADDR_BROADCAST;
973 nh.ip_csum = csum(&nh, sizeof nh);
975 th.udp_src = htons(66);
976 th.udp_dst = htons(67);
977 th.udp_len = htons(UDP_HEADER_LEN + b.size);
979 udp_csum = csum_add32(0, nh.ip_src);
980 udp_csum = csum_add32(udp_csum, nh.ip_dst);
981 udp_csum = csum_add16(udp_csum, IP_TYPE_UDP << 8);
982 udp_csum = csum_add16(udp_csum, th.udp_len);
983 udp_csum = csum_continue(udp_csum, &th, sizeof th);
984 th.udp_csum = csum_finish(csum_continue(udp_csum, b.data, b.size));
986 ofpbuf_push(&b, &th, sizeof th);
987 ofpbuf_push(&b, &nh, sizeof nh);
988 ofpbuf_push(&b, &eh, sizeof eh);
990 /* Don't try to send the frame if it's too long for an Ethernet frame. We
991 * disregard the network device's actual MTU because we don't want the
992 * frame to have to be discarded or fragmented if it travels over a regular
993 * Ethernet at some point. 1500 bytes should be enough for anyone. */
994 if (b.size <= ETH_TOTAL_MAX) {
995 VLOG_DBG("sending %s", dhcp_msg_to_string(msg, false, &cli->s));
996 error = netdev_send(cli->netdev, &b);
998 VLOG_ERR("send failed on %s: %s",
999 netdev_get_name(cli->netdev), strerror(error));
1002 VLOG_ERR("cannot send %zu-byte Ethernet frame", b.size);
1009 fuzz(unsigned int x, int max_fuzz)
1011 /* Generate number in range [-max_fuzz, +max_fuzz]. */
1012 int fuzz = random_range(max_fuzz * 2 + 1) - max_fuzz;
1013 unsigned int y = x + fuzz;
1014 return fuzz >= 0 ? (y >= x ? y : UINT_MAX) : (y <= x ? y : 0);
1018 clamp(unsigned int x, unsigned int min, unsigned int max)
1020 return x < min ? min : x > max ? max : x;
1024 calc_t2(unsigned int lease)
1026 unsigned int base = lease * 0.875;
1027 return lease >= 60 ? clamp(fuzz(base, 10), 0, lease - 1) : base;
1031 calc_t1(unsigned int lease, unsigned int t2)
1033 unsigned int base = lease / 2;
1034 return lease >= 60 ? clamp(fuzz(base, 10), 0, t2 - 1) : base;