2 * Copyright (c) 2008, 2009, 2010 Nicira Networks.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at:
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
18 #include "dhcp-client.h"
19 #include <arpa/inet.h>
26 #include <sys/types.h>
31 #include "dynamic-string.h"
35 #include "poll-loop.h"
39 #define THIS_MODULE VLM_dhcp_client
42 #define DHCLIENT_STATES \
43 DHCLIENT_STATE(INIT, 1 << 0) \
44 DHCLIENT_STATE(INIT_REBOOT, 1 << 1) \
45 DHCLIENT_STATE(REBOOTING, 1 << 2) \
46 DHCLIENT_STATE(SELECTING, 1 << 3) \
47 DHCLIENT_STATE(REQUESTING, 1 << 4) \
48 DHCLIENT_STATE(BOUND, 1 << 5) \
49 DHCLIENT_STATE(RENEWING, 1 << 6) \
50 DHCLIENT_STATE(REBINDING, 1 << 7) \
51 DHCLIENT_STATE(RELEASED, 1 << 8)
53 #define DHCLIENT_STATE(NAME, VALUE) S_##NAME = VALUE,
58 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(60, 60);
61 state_name(enum dhclient_state state)
64 #define DHCLIENT_STATE(NAME, VALUE) case S_##NAME: return #NAME;
73 struct netdev *netdev;
75 void (*modify_request)(struct dhcp_msg *, void *aux);
76 bool (*validate_offer)(const struct dhcp_msg *, void *aux);
80 enum dhclient_state state;
81 unsigned int state_entered; /* When we transitioned to this state. */
82 uint32_t xid; /* In host byte order. */
83 uint32_t ipaddr, netmask, router;
85 struct dhcp_msg *binding;
88 unsigned int retransmit, delay; /* Used by send_reliably(). */
89 unsigned int max_timeout;
91 unsigned int init_delay; /* Used by S_INIT. */
93 time_t lease_expiration;
94 unsigned int bound_timeout;
95 unsigned int renewing_timeout;
96 unsigned int rebinding_timeout;
98 /* Used by dhclient_run() and dhclient_wait() */
99 unsigned int min_timeout;
102 /* Set when we send out a DHCPDISCOVER message. */
108 /* Minimum acceptable lease time, in seconds. */
109 #define MIN_ACCEPTABLE_LEASE 15
111 static void state_transition(struct dhclient *, enum dhclient_state);
112 static unsigned int elapsed_in_this_state(const struct dhclient *cli);
113 static bool timeout(struct dhclient *, unsigned int secs);
115 static void dhclient_msg_init(struct dhclient *, enum dhcp_msg_type,
117 static void send_reliably(struct dhclient *cli,
118 void (*make_packet)(struct dhclient *,
120 static bool do_receive_msg(struct dhclient *, struct dhcp_msg *);
121 static void do_send_msg(struct dhclient *, const struct dhcp_msg *);
122 static bool receive_ack(struct dhclient *);
124 static unsigned int fuzz(unsigned int x, int max_fuzz);
125 static unsigned int calc_t2(unsigned int lease);
126 static unsigned int calc_t1(unsigned int lease, unsigned int t2);
128 static unsigned int clamp(unsigned int x, unsigned int min, unsigned int max);
130 /* Creates a new DHCP client to configure the network device 'netdev_name'
133 * If 'modify_request' is non-null, then each DHCP message to discover or
134 * request an address will be passed to it (along with auxiliary data 'aux').
135 * It may then add any desired options to the message for transmission.
137 * If 'validate_offer' is non-null, then each DHCP message that offers an
138 * address will be passed to it (along with auxiliary data 'aux') for
139 * validation: if it returns true, the address will accepted; otherwise, it
142 * The DHCP client will not start advertising for an IP address until
143 * dhclient_init() is called.
145 * If successful, returns 0 and sets '*cli' to the new DHCP client. Otherwise,
146 * returns a positive errno value and sets '*cli' to a null pointer. */
148 dhclient_create(const char *netdev_name,
149 void (*modify_request)(struct dhcp_msg *, void *aux),
150 bool (*validate_offer)(const struct dhcp_msg *, void *aux),
151 void *aux, struct dhclient **cli_)
153 struct dhclient *cli;
154 struct netdev *netdev;
159 error = netdev_open(netdev_name, ETH_TYPE_IP, &netdev);
160 /* XXX install socket filter to catch only DHCP packets. */
162 VLOG_ERR("could not open %s network device: %s",
163 netdev_name, strerror(error));
167 error = netdev_turn_flags_on(netdev, NETDEV_UP, false);
169 VLOG_ERR("could not bring %s device up: %s",
170 netdev_name, strerror(error));
171 netdev_close(netdev);
175 cli = xcalloc(1, sizeof *cli);
176 cli->modify_request = modify_request;
177 cli->validate_offer = validate_offer;
179 cli->netdev = netdev;
180 cli->state = S_RELEASED;
181 cli->state_entered = time_now();
182 cli->xid = random_uint32();
185 cli->retransmit = cli->delay = 0;
186 cli->max_timeout = 64;
187 cli->min_timeout = 1;
194 /* Sets the maximum amount of timeout that 'cli' will wait for a reply from
195 * the DHCP server before retransmitting, in seconds, to 'max_timeout'. The
196 * default is 64 seconds. */
198 dhclient_set_max_timeout(struct dhclient *cli, unsigned int max_timeout)
200 cli->max_timeout = MAX(2, max_timeout);
203 /* Destroys 'cli' and frees all related resources. */
205 dhclient_destroy(struct dhclient *cli)
208 dhcp_msg_uninit(cli->binding);
210 netdev_close(cli->netdev);
216 /* Returns the network device in use by 'cli'. The caller must not destroy
217 * the returned device. */
219 dhclient_get_netdev(struct dhclient *cli)
224 /* Forces 'cli' into a (re)initialization state, in which no address is bound
225 * but the client is advertising to obtain one. If 'requested_ip' is nonzero,
226 * then the client will attempt to re-bind to that IP address; otherwise, it
227 * will not ask for any particular address. */
229 dhclient_init(struct dhclient *cli, uint32_t requested_ip)
231 state_transition(cli, requested_ip ? S_INIT_REBOOT : S_INIT);
232 cli->ipaddr = requested_ip;
233 cli->min_timeout = 0;
237 /* Forces 'cli' to release its bound IP address (if any). The client will not
238 * advertise for a new address until dhclient_init() is called again. */
240 dhclient_release(struct dhclient *cli)
242 if (dhclient_is_bound(cli)) {
244 dhclient_msg_init(cli, DHCPRELEASE, &msg);
245 msg.ciaddr = cli->ipaddr;
246 do_send_msg(cli, &msg);
247 dhcp_msg_uninit(&msg);
249 state_transition(cli, S_RELEASED);
250 cli->min_timeout = UINT_MAX;
254 do_force_renew(struct dhclient *cli, int deadline)
256 time_t now = time_now();
257 unsigned int lease_left = sat_sub(cli->lease_expiration, now);
258 if (lease_left <= deadline) {
259 if (cli->state & (S_RENEWING | S_REBINDING)) {
262 deadline = lease_left;
264 if (cli->state & (S_BOUND | S_RENEWING)) {
265 state_transition(cli, S_RENEWING);
266 cli->renewing_timeout = deadline * 3 / 4;
267 cli->rebinding_timeout = deadline * 1 / 4;
269 state_transition(cli, S_REBINDING);
270 cli->rebinding_timeout = deadline;
272 cli->min_timeout = 0;
275 /* Forces 'cli' to attempt to renew the lease its current IP address (if any)
276 * within 'deadline' seconds. If the deadline is not met, then the client
277 * gives up its IP address binding and re-starts the DHCP process. */
279 dhclient_force_renew(struct dhclient *cli, int deadline)
281 /* Drain the receive queue so that we know that any DHCPACK we process is
282 * freshly received. */
283 netdev_drain(cli->netdev);
285 switch (cli->state) {
296 do_force_renew(cli, deadline);
300 dhclient_init(cli, 0);
305 /* Returns true if 'cli' is bound to an IP address, false otherwise. */
307 dhclient_is_bound(const struct dhclient *cli)
309 return cli->state & (S_BOUND | S_RENEWING | S_REBINDING);
312 /* Returns true if 'cli' has changed from bound to unbound, or vice versa, at
313 * least once since the last time this function was called. */
315 dhclient_changed(struct dhclient *cli)
317 bool changed = cli->changed;
322 /* Returns 'cli''s current state, as a string. The caller must not modify or
323 * free the string. */
325 dhclient_get_state(const struct dhclient *cli)
327 return state_name(cli->state);
330 /* Returns the number of seconds spent so far in 'cli''s current state. */
332 dhclient_get_state_elapsed(const struct dhclient *cli)
334 return elapsed_in_this_state(cli);
337 /* If 'cli' is bound, returns the number of seconds remaining in its lease;
338 * otherwise, returns 0. */
340 dhclient_get_lease_remaining(const struct dhclient *cli)
342 if (dhclient_is_bound(cli)) {
343 time_t now = time_now();
344 return cli->lease_expiration > now ? cli->lease_expiration - now : 0;
350 /* If 'cli' is bound to an IP address, returns that IP address; otherwise,
353 dhclient_get_ip(const struct dhclient *cli)
355 return dhclient_is_bound(cli) ? cli->ipaddr : 0;
358 /* If 'cli' is bound to an IP address, returns the netmask for that IP address;
359 * otherwise, returns 0. */
361 dhclient_get_netmask(const struct dhclient *cli)
363 return dhclient_is_bound(cli) ? cli->netmask : 0;
366 /* If 'cli' is bound to an IP address and 'cli' has a default gateway, returns
367 * that default gateway; otherwise, returns 0. */
369 dhclient_get_router(const struct dhclient *cli)
371 return dhclient_is_bound(cli) ? cli->router : 0;
374 /* If 'cli' is bound to an IP address, returns the DHCP message that was
375 * received to obtain that IP address (so that the caller can obtain additional
376 * options from it). Otherwise, returns a null pointer. */
377 const struct dhcp_msg *
378 dhclient_get_config(const struct dhclient *cli)
380 return dhclient_is_bound(cli) ? cli->binding : NULL;
383 /* Configures the network device backing 'cli' to the network address and other
384 * parameters obtained via DHCP. If no address is bound on 'cli', removes any
385 * configured address from 'cli'.
387 * To use a dhclient as a regular DHCP client that binds and unbinds from IP
388 * addresses in the usual fashion, call this function after dhclient_run() if
389 * anything has changed, like so:
392 * if (dhclient_changed(cli)) {
393 * dhclient_configure_netdev(cli);
398 dhclient_configure_netdev(struct dhclient *cli)
400 struct in_addr addr = { dhclient_get_ip(cli) };
401 struct in_addr mask = { dhclient_get_netmask(cli) };
402 struct in_addr router = { dhclient_get_router(cli) };
405 error = netdev_set_in4(cli->netdev, addr, mask);
407 VLOG_ERR("could not set %s address "IP_FMT"/"IP_FMT": %s",
408 netdev_get_name(cli->netdev),
409 IP_ARGS(&addr.s_addr), IP_ARGS(&mask.s_addr),
413 if (!error && router.s_addr) {
414 error = netdev_add_router(cli->netdev, router);
416 VLOG_ERR("failed to add default route to "IP_FMT" on %s: %s",
417 IP_ARGS(&router), netdev_get_name(cli->netdev),
425 /* If 'cli' is bound and the binding includes DNS domain parameters, updates
426 * /etc/resolv.conf will be updated to match the received parameters. Returns
427 * 0 if successful, otherwise a positive errno value. */
429 dhclient_update_resolv_conf(struct dhclient *cli)
433 bool has_domain_name;
438 if (!dhclient_is_bound(cli)) {
441 if (!dhcp_msg_get_ip(cli->binding, DHCP_CODE_DNS_SERVER, 0, &dns_server)) {
442 VLOG_DBG("binding does not include any DNS servers");
446 sprintf(new_name, "/etc/resolv.conf.tmp%ld", (long int) getpid());
447 new = fopen(new_name, "w");
449 VLOG_WARN("%s: create: %s", new_name, strerror(errno));
453 domain_name = dhcp_msg_get_string(cli->binding, DHCP_CODE_DOMAIN_NAME);
454 has_domain_name = domain_name != NULL;
456 if (strspn(domain_name, "-_.0123456789abcdefghijklmnopqrstuvwxyz"
457 "ABCDEFGHIJKLMNOPQRSTUVWXYZ") == strlen(domain_name)) {
458 fprintf(new, "domain %s\n", domain_name);
460 VLOG_WARN("ignoring invalid domain name %s", domain_name);
461 has_domain_name = false;
464 VLOG_DBG("binding does not include domain name");
468 for (i = 0; dhcp_msg_get_ip(cli->binding, DHCP_CODE_DNS_SERVER,
469 i, &dns_server); i++) {
470 fprintf(new, "nameserver "IP_FMT"\n", IP_ARGS(&dns_server));
473 old = fopen("/etc/resolv.conf", "r");
477 while (fgets(line, sizeof line, old)) {
478 char *kw = xmemdup0(line, strcspn(line, " \t\r\n"));
479 if (strcmp(kw, "nameserver")
481 || (strcmp(kw, "domain") && strcmp(kw, "search")))) {
488 VLOG_DBG("/etc/resolv.conf: open: %s", strerror(errno));
491 if (fclose(new) < 0) {
492 VLOG_WARN("%s: close: %s", new_name, strerror(errno));
496 if (rename(new_name, "/etc/resolv.conf") < 0) {
497 VLOG_WARN("failed to rename %s to /etc/resolv.conf: %s",
498 new_name, strerror(errno));
508 make_dhcpdiscover(struct dhclient *cli, struct dhcp_msg *msg)
510 cli->secs = elapsed_in_this_state(cli);
511 dhclient_msg_init(cli, DHCPDISCOVER, msg);
513 dhcp_msg_put_ip(msg, DHCP_CODE_REQUESTED_IP, cli->ipaddr);
518 make_dhcprequest(struct dhclient *cli, struct dhcp_msg *msg)
520 dhclient_msg_init(cli, DHCPREQUEST, msg);
521 msg->ciaddr = dhclient_get_ip(cli);
522 if (cli->state == S_REQUESTING) {
523 dhcp_msg_put_ip(msg, DHCP_CODE_SERVER_IDENTIFIER, cli->server_ip);
525 dhcp_msg_put_ip(msg, DHCP_CODE_REQUESTED_IP, cli->ipaddr);
529 do_init(struct dhclient *cli, enum dhclient_state next_state)
531 if (!cli->init_delay) {
532 cli->init_delay = fuzz(2, 1);
534 if (timeout(cli, cli->init_delay)) {
535 state_transition(cli, next_state);
540 dhclient_run_INIT(struct dhclient *cli)
542 do_init(cli, S_SELECTING);
546 dhclient_run_INIT_REBOOT(struct dhclient *cli)
548 do_init(cli, S_REBOOTING);
552 dhclient_run_REBOOTING(struct dhclient *cli)
554 send_reliably(cli, make_dhcprequest);
555 if (!receive_ack(cli) && timeout(cli, 60)) {
556 state_transition(cli, S_INIT);
561 dhcp_receive(struct dhclient *cli, unsigned int msgs, struct dhcp_msg *msg)
563 while (do_receive_msg(cli, msg)) {
564 if (msg->type > 31 || !((1u << msg->type) & msgs)) {
565 VLOG_DBG_RL(&rl, "received unexpected %s in %s state: %s",
566 dhcp_type_name(msg->type), state_name(cli->state),
567 dhcp_msg_to_string(msg, false, &cli->s));
568 } else if (msg->xid != cli->xid) {
570 "ignoring %s with xid != %08"PRIx32" in %s state: %s",
571 dhcp_type_name(msg->type), msg->xid,
572 state_name(cli->state),
573 dhcp_msg_to_string(msg, false, &cli->s));
577 dhcp_msg_uninit(msg);
583 validate_offered_options(struct dhclient *cli, const struct dhcp_msg *msg)
585 uint32_t lease, netmask;
586 if (!dhcp_msg_get_secs(msg, DHCP_CODE_LEASE_TIME, 0, &lease)) {
587 VLOG_WARN_RL(&rl, "%s lacks lease time: %s", dhcp_type_name(msg->type),
588 dhcp_msg_to_string(msg, false, &cli->s));
589 } else if (!dhcp_msg_get_ip(msg, DHCP_CODE_SUBNET_MASK, 0, &netmask)) {
590 VLOG_WARN_RL(&rl, "%s lacks netmask: %s", dhcp_type_name(msg->type),
591 dhcp_msg_to_string(msg, false, &cli->s));
592 } else if (lease < MIN_ACCEPTABLE_LEASE) {
593 VLOG_WARN_RL(&rl, "Ignoring %s with %"PRIu32"-second lease time: %s",
594 dhcp_type_name(msg->type), lease,
595 dhcp_msg_to_string(msg, false, &cli->s));
596 } else if (cli->validate_offer && !cli->validate_offer(msg, cli->aux)) {
597 VLOG_DBG_RL(&rl, "client validation hook refused offer: %s",
598 dhcp_msg_to_string(msg, false, &cli->s));
606 dhclient_run_SELECTING(struct dhclient *cli)
610 send_reliably(cli, make_dhcpdiscover);
611 if (cli->server_ip && timeout(cli, 60)) {
613 state_transition(cli, S_INIT);
615 for (; dhcp_receive(cli, 1u << DHCPOFFER, &msg); dhcp_msg_uninit(&msg)) {
616 if (!validate_offered_options(cli, &msg)) {
619 if (!dhcp_msg_get_ip(&msg, DHCP_CODE_SERVER_IDENTIFIER,
620 0, &cli->server_ip)) {
621 VLOG_WARN_RL(&rl, "DHCPOFFER lacks server identifier: %s",
622 dhcp_msg_to_string(&msg, false, &cli->s));
626 VLOG_DBG_RL(&rl, "accepting DHCPOFFER: %s",
627 dhcp_msg_to_string(&msg, false, &cli->s));
628 cli->ipaddr = msg.yiaddr;
629 state_transition(cli, S_REQUESTING);
635 same_binding(const struct dhcp_msg *old, const struct dhcp_msg *new)
637 static const int codes[] = {
638 DHCP_CODE_SUBNET_MASK,
640 DHCP_CODE_DNS_SERVER,
642 DHCP_CODE_DOMAIN_NAME,
645 DHCP_CODE_BROADCAST_ADDRESS,
646 DHCP_CODE_STATIC_ROUTE,
647 DHCP_CODE_ARP_CACHE_TIMEOUT,
648 DHCP_CODE_ETHERNET_ENCAPSULATION,
650 DHCP_CODE_SERVER_IDENTIFIER,
651 DHCP_CODE_OFP_CONTROLLER_VCONN,
652 DHCP_CODE_OFP_PKI_URI,
657 if (old->yiaddr != new->yiaddr) {
658 VLOG_WARN("DHCP binding changed IP address from "IP_FMT" to "IP_FMT,
659 IP_ARGS(&old->yiaddr), IP_ARGS(&new->yiaddr));
662 for (i = 0; i < ARRAY_SIZE(codes); i++) {
664 const struct dhcp_option *old_opt = &old->options[code];
665 const struct dhcp_option *new_opt = &new->options[code];
666 if (!dhcp_option_equals(old_opt, new_opt)) {
667 struct ds old_string = DS_EMPTY_INITIALIZER;
668 struct ds new_string = DS_EMPTY_INITIALIZER;
669 VLOG_WARN("DHCP binding changed option from %s to %s",
670 dhcp_option_to_string(old_opt, code, &old_string),
671 dhcp_option_to_string(new_opt, code, &new_string));
672 ds_destroy(&old_string);
673 ds_destroy(&new_string);
681 receive_ack(struct dhclient *cli)
685 if (!dhcp_receive(cli, (1u << DHCPACK) | (1u << DHCPNAK), &msg)) {
687 } else if (msg.type == DHCPNAK) {
688 dhcp_msg_uninit(&msg);
689 state_transition(cli, S_INIT);
691 } else if (!validate_offered_options(cli, &msg)) {
692 dhcp_msg_uninit(&msg);
695 uint32_t lease = 0, t1 = 0, t2 = 0;
698 if (!same_binding(cli->binding, &msg)) {
701 dhcp_msg_uninit(cli->binding);
703 cli->binding = xmalloc(sizeof *cli->binding);
705 dhcp_msg_copy(cli->binding, &msg);
707 dhcp_msg_get_secs(&msg, DHCP_CODE_LEASE_TIME, 0, &lease);
708 dhcp_msg_get_secs(&msg, DHCP_CODE_T1, 0, &t1);
709 dhcp_msg_get_secs(&msg, DHCP_CODE_T2, 0, &t2);
710 assert(lease >= MIN_ACCEPTABLE_LEASE);
712 if (!t2 || t2 >= lease) {
715 if (!t1 || t1 >= t2) {
716 t1 = calc_t1(lease, t2);
719 cli->lease_expiration = sat_add(time_now(), lease);
720 cli->bound_timeout = t1;
721 cli->renewing_timeout = t2 - t1;
722 cli->rebinding_timeout = lease - t2;
724 cli->ipaddr = msg.yiaddr;
725 dhcp_msg_get_ip(&msg, DHCP_CODE_SUBNET_MASK, 0, &cli->netmask);
726 if (!dhcp_msg_get_ip(&msg, DHCP_CODE_ROUTER, 0, &cli->router)) {
727 cli->router = INADDR_ANY;
729 state_transition(cli, S_BOUND);
730 VLOG_DBG("Bound: %s", dhcp_msg_to_string(&msg, false, &cli->s));
736 dhclient_run_REQUESTING(struct dhclient *cli)
738 send_reliably(cli, make_dhcprequest);
739 if (!receive_ack(cli) && timeout(cli, 60)) {
740 state_transition(cli, S_INIT);
745 dhclient_run_BOUND(struct dhclient *cli)
747 if (timeout(cli, cli->bound_timeout)) {
748 state_transition(cli, S_RENEWING);
753 dhclient_run_RENEWING(struct dhclient *cli)
755 send_reliably(cli, make_dhcprequest);
756 if (!receive_ack(cli) && timeout(cli, cli->renewing_timeout)) {
757 state_transition(cli, S_REBINDING);
762 dhclient_run_REBINDING(struct dhclient *cli)
764 send_reliably(cli, make_dhcprequest);
765 if (!receive_ack(cli) && timeout(cli, cli->rebinding_timeout)) {
766 state_transition(cli, S_INIT);
771 dhclient_run_RELEASED(struct dhclient *cli OVS_UNUSED)
776 /* Processes the DHCP protocol for 'cli'. */
778 dhclient_run(struct dhclient *cli)
782 old_state = cli->state;
783 cli->min_timeout = UINT_MAX;
785 switch (cli->state) {
786 #define DHCLIENT_STATE(NAME, VALUE) \
787 case S_##NAME: dhclient_run_##NAME(cli); break;
789 #undef DHCLIENT_STATE
793 } while (cli->state != old_state);
796 /* Sets up poll timeouts to wake up the poll loop when 'cli' needs to do some
799 dhclient_wait(struct dhclient *cli)
801 if (cli->min_timeout != UINT_MAX) {
802 time_t now = time_now();
803 unsigned int wake = sat_add(cli->state_entered, cli->min_timeout);
805 poll_immediate_wake();
807 poll_timer_wait(sat_mul(sat_sub(wake, now), 1000));
810 /* Reset timeout to 1 second. This will have no effect ordinarily, because
811 * dhclient_run() will typically set it back to a higher value. If,
812 * however, the caller fails to call dhclient_run() before its next call to
813 * dhclient_wait() we won't potentially block forever. */
814 cli->min_timeout = 1;
816 if (cli->state & (S_SELECTING | S_REQUESTING | S_RENEWING | S_REBINDING)) {
817 netdev_recv_wait(cli->netdev);
822 state_transition(struct dhclient *cli, enum dhclient_state state)
824 bool was_bound = dhclient_is_bound(cli);
826 if (cli->state != state) {
827 VLOG_DBG("entering %s", state_name(state));
830 cli->state_entered = time_now();
831 cli->retransmit = cli->delay = 0;
832 am_bound = dhclient_is_bound(cli);
833 if (was_bound != am_bound) {
836 assert(cli->binding != NULL);
837 VLOG_INFO("%s: obtained address "IP_FMT", netmask "IP_FMT,
838 netdev_get_name(cli->netdev),
839 IP_ARGS(&cli->ipaddr), IP_ARGS(&cli->netmask));
841 VLOG_INFO("%s: obtained default gateway "IP_FMT,
842 netdev_get_name(cli->netdev), IP_ARGS(&cli->router));
845 dhcp_msg_uninit(cli->binding);
849 VLOG_INFO("%s: network address unbound",
850 netdev_get_name(cli->netdev));
853 if (cli->state & (S_SELECTING | S_REQUESTING | S_REBOOTING)) {
854 netdev_drain(cli->netdev);
859 send_reliably(struct dhclient *cli,
860 void (*make_packet)(struct dhclient *, struct dhcp_msg *))
862 if (timeout(cli, cli->retransmit)) {
864 make_packet(cli, &msg);
865 if (cli->modify_request) {
866 cli->modify_request(&msg, cli->aux);
868 do_send_msg(cli, &msg);
869 cli->delay = MIN(cli->max_timeout, MAX(4, cli->delay * 2));
870 cli->retransmit += fuzz(cli->delay, 1);
871 timeout(cli, cli->retransmit);
872 dhcp_msg_uninit(&msg);
877 dhclient_msg_init(struct dhclient *cli, enum dhcp_msg_type type,
878 struct dhcp_msg *msg)
881 msg->op = DHCP_BOOTREQUEST;
883 msg->secs = cli->secs;
885 netdev_get_etheraddr(cli->netdev, msg->chaddr);
888 /* If time goes backward this returns a large number, which makes it look like
889 * we've been in the current state a very long time. That's probably
890 * fine for that corner case--we'll just expire our lease, etc., and try to
893 elapsed_in_this_state(const struct dhclient *cli)
895 return time_now() - cli->state_entered;
899 timeout(struct dhclient *cli, unsigned int secs)
901 cli->min_timeout = MIN(cli->min_timeout, secs);
902 return time_now() >= sat_add(cli->state_entered, secs);
906 do_receive_msg(struct dhclient *cli, struct dhcp_msg *msg)
908 uint8_t cli_mac[ETH_ADDR_LEN];
912 netdev_get_mtu(cli->netdev, &mtu);
913 ofpbuf_init(&b, mtu + VLAN_ETH_HEADER_LEN);
914 netdev_get_etheraddr(cli->netdev, cli_mac);
915 for (; cli->received < 50; cli->received++) {
916 const struct ip_header *ip;
917 const struct dhcp_header *dhcp;
922 error = netdev_recv(cli->netdev, &b);
927 flow_extract(&b, 0, &flow);
928 if (flow.dl_type != htons(ETH_TYPE_IP)
929 || flow.nw_proto != IP_TYPE_UDP
930 || flow.tp_dst != htons(DHCP_CLIENT_PORT)
931 || !(eth_addr_is_broadcast(flow.dl_dst)
932 || eth_addr_equals(flow.dl_dst, cli_mac))) {
937 if (IP_IS_FRAGMENT(ip->ip_frag_off)) {
938 /* We don't do reassembly. */
939 VLOG_WARN_RL(&rl, "ignoring fragmented DHCP datagram");
945 VLOG_WARN_RL(&rl, "ignoring DHCP datagram with missing payload");
949 ofpbuf_pull(&b, (char *)b.l7 - (char*)b.data);
950 error = dhcp_parse(msg, &b);
952 if (VLOG_IS_DBG_ENABLED()) {
953 VLOG_DBG_RL(&rl, "received %s",
954 dhcp_msg_to_string(msg, false, &cli->s));
956 VLOG_INFO_RL(&rl, "received %s", dhcp_type_name(msg->type));
962 netdev_drain(cli->netdev);
969 do_send_msg(struct dhclient *cli, const struct dhcp_msg *msg)
972 struct eth_header eh;
974 struct udp_header th;
978 ofpbuf_init(&b, ETH_TOTAL_MAX);
979 ofpbuf_reserve(&b, ETH_HEADER_LEN + IP_HEADER_LEN + UDP_HEADER_LEN);
981 dhcp_assemble(msg, &b);
983 netdev_get_etheraddr(cli->netdev, eh.eth_src);
984 memcpy(eh.eth_dst, eth_addr_broadcast, ETH_ADDR_LEN);
985 eh.eth_type = htons(ETH_TYPE_IP);
987 nh.ip_ihl_ver = IP_IHL_VER(5, IP_VERSION);
989 nh.ip_tot_len = htons(IP_HEADER_LEN + UDP_HEADER_LEN + b.size);
990 /* We can't guarantee uniqueness of ip_id versus the host's, screwing up
991 * fragment reassembly, so prevent fragmentation and use an all-zeros
992 * ip_id. RFC 791 doesn't say we can do this, but Linux does the same
993 * thing for DF packets, so it must not screw anything up. */
995 nh.ip_frag_off = htons(IP_DONT_FRAGMENT);
997 nh.ip_proto = IP_TYPE_UDP;
999 nh.ip_src = dhclient_get_ip(cli);
1000 /* XXX need to use UDP socket for nonzero server IPs so that we can get
1001 * routing table support.
1003 * if (...have server IP and in appropriate state...) {
1004 * nh.ip_dst = cli->server_ip;
1006 * nh.ip_dst = INADDR_BROADCAST;
1009 nh.ip_dst = INADDR_BROADCAST;
1010 nh.ip_csum = csum(&nh, sizeof nh);
1012 th.udp_src = htons(DHCP_CLIENT_PORT);
1013 th.udp_dst = htons(DHCP_SERVER_PORT);
1014 th.udp_len = htons(UDP_HEADER_LEN + b.size);
1016 udp_csum = csum_add32(0, nh.ip_src);
1017 udp_csum = csum_add32(udp_csum, nh.ip_dst);
1018 udp_csum = csum_add16(udp_csum, IP_TYPE_UDP << 8);
1019 udp_csum = csum_add16(udp_csum, th.udp_len);
1020 udp_csum = csum_continue(udp_csum, &th, sizeof th);
1021 th.udp_csum = csum_finish(csum_continue(udp_csum, b.data, b.size));
1023 ofpbuf_push(&b, &th, sizeof th);
1024 ofpbuf_push(&b, &nh, sizeof nh);
1025 ofpbuf_push(&b, &eh, sizeof eh);
1027 /* Don't try to send the frame if it's too long for an Ethernet frame. We
1028 * disregard the network device's actual MTU because we don't want the
1029 * frame to have to be discarded or fragmented if it travels over a regular
1030 * Ethernet at some point. 1500 bytes should be enough for anyone. */
1031 if (b.size <= ETH_TOTAL_MAX) {
1032 if (VLOG_IS_DBG_ENABLED()) {
1033 VLOG_DBG("sending %s", dhcp_msg_to_string(msg, false, &cli->s));
1035 VLOG_INFO("sending %s", dhcp_type_name(msg->type));
1037 error = netdev_send(cli->netdev, &b);
1039 VLOG_ERR("send failed on %s: %s",
1040 netdev_get_name(cli->netdev), strerror(error));
1043 VLOG_ERR("cannot send %zu-byte Ethernet frame", b.size);
1050 fuzz(unsigned int x, int max_fuzz)
1052 /* Generate number in range [-max_fuzz, +max_fuzz]. */
1053 int fuzz = random_range(max_fuzz * 2 + 1) - max_fuzz;
1054 unsigned int y = x + fuzz;
1055 return fuzz >= 0 ? (y >= x ? y : UINT_MAX) : (y <= x ? y : 0);
1059 clamp(unsigned int x, unsigned int min, unsigned int max)
1061 return x < min ? min : x > max ? max : x;
1065 calc_t2(unsigned int lease)
1067 unsigned int base = lease * 0.875;
1068 return lease >= 60 ? clamp(fuzz(base, 10), 0, lease - 1) : base;
1072 calc_t1(unsigned int lease, unsigned int t2)
1074 unsigned int base = lease / 2;
1075 return lease >= 60 ? clamp(fuzz(base, 10), 0, t2 - 1) : base;