dhcp: Only print "entering" message if state actually changes.
[sliver-openvswitch.git] / lib / dhcp-client.c
1 /* Copyright (c) 2008 The Board of Trustees of The Leland Stanford
2  * Junior University
3  *
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:
16  *
17  * The above copyright notice and this permission notice shall be
18  * included in all copies or substantial portions of the Software.
19  *
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
27  * SOFTWARE.
28  *
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.
32  */
33
34 #include <config.h>
35 #include "dhcp-client.h"
36 #include <arpa/inet.h>
37 #include <assert.h>
38 #include <errno.h>
39 #include <inttypes.h>
40 #include <limits.h>
41 #include <stdlib.h>
42 #include <string.h>
43 #include <time.h>
44 #include "buffer.h"
45 #include "csum.h"
46 #include "dhcp.h"
47 #include "dynamic-string.h"
48 #include "flow.h"
49 #include "netdev.h"
50 #include "ofp-print.h"
51 #include "poll-loop.h"
52
53 #define THIS_MODULE VLM_dhcp_client
54 #include "vlog.h"
55
56 #define DHCLIENT_STATES                         \
57     DHCLIENT_STATE(INIT, 1 << 0)                \
58     DHCLIENT_STATE(INIT_REBOOT, 1 << 1)         \
59     DHCLIENT_STATE(REBOOTING, 1 << 2)           \
60     DHCLIENT_STATE(SELECTING, 1 << 3)           \
61     DHCLIENT_STATE(REQUESTING, 1 << 4)          \
62     DHCLIENT_STATE(BOUND, 1 << 5)               \
63     DHCLIENT_STATE(RENEWING, 1 << 6)            \
64     DHCLIENT_STATE(REBINDING, 1 << 7)           \
65     DHCLIENT_STATE(RELEASED, 1 << 8)
66 enum dhclient_state {
67 #define DHCLIENT_STATE(NAME, VALUE) S_##NAME = VALUE,
68     DHCLIENT_STATES
69 #undef DHCLIENT_STATE
70 };
71
72 static const char *
73 state_name(enum dhclient_state state)
74 {
75     switch (state) {
76 #define DHCLIENT_STATE(NAME, VALUE) case S_##NAME: return #NAME;
77         DHCLIENT_STATES
78 #undef DHCLIENT_STATE
79     }
80     return "***ERROR***";
81 }
82
83 struct dhclient {
84     /* Configuration. */
85     struct netdev *netdev;
86
87     void (*modify_request)(struct dhcp_msg *, void *aux);
88     bool (*validate_offer)(const struct dhcp_msg *, void *aux);
89     void *aux;
90
91     /* DHCP state. */
92     enum dhclient_state state;
93     unsigned int state_entered; /* When we transitioned to this state. */
94     uint32_t xid;               /* In host byte order. */
95     uint32_t ipaddr, netmask, router;
96     uint32_t server_ip;
97     struct dhcp_msg *binding;
98     bool changed;
99
100     unsigned int retransmit, delay; /* Used by send_reliably(). */
101
102     unsigned int init_delay;    /* Used by S_INIT. */
103
104     time_t lease_expiration;
105     unsigned int bound_timeout;
106     unsigned int renewing_timeout;
107     unsigned int rebinding_timeout;
108
109     /* Used by dhclient_run() and dhclient_wait() */
110     unsigned int min_timeout;
111     int received;
112
113     /* Set when we send out a DHCPDISCOVER message. */
114     uint32_t secs;
115
116     struct ds s;
117 };
118
119 /* Minimum acceptable lease time, in seconds. */
120 #define MIN_ACCEPTABLE_LEASE 15
121
122 static void state_transition(struct dhclient *, enum dhclient_state);
123 static unsigned int elapsed_in_this_state(const struct dhclient *cli);
124 static bool timeout(struct dhclient *, unsigned int secs);
125
126 static void dhclient_msg_init(struct dhclient *, enum dhcp_msg_type,
127                               struct dhcp_msg *);
128 static void send_reliably(struct dhclient *cli,
129                           void (*make_packet)(struct dhclient *,
130                                               struct dhcp_msg *));
131 static bool do_receive_msg(struct dhclient *, struct dhcp_msg *);
132 static void do_send_msg(struct dhclient *, const struct dhcp_msg *);
133 static bool receive_ack(struct dhclient *);
134
135 static unsigned int fuzz(unsigned int x, int max_fuzz);
136 static unsigned int calc_t2(unsigned int lease);
137 static unsigned int calc_t1(unsigned int lease, unsigned int t2);
138
139 static unsigned int clamp(unsigned int x, unsigned int min, unsigned int max);
140 static unsigned int sat_add(unsigned int x, unsigned int y);
141 static unsigned int sat_sub(unsigned int x, unsigned int y);
142 static unsigned int sat_mul(unsigned int x, unsigned int y);
143
144 /* Creates a new DHCP client to configure the network device 'netdev_name'
145  * (e.g. "eth0").
146  *
147  * If 'modify_request' is non-null, then each DHCP message to discover or
148  * request an address will be passed to it (along with auxiliary data 'aux').
149  * It may then add any desired options to the message for transmission.
150  *
151  * If 'validate_offer' is non-null, then each DHCP message that offers an
152  * address will be passed to it (along with auxiliary data 'aux') for
153  * validation: if it returns true, the address will accepted; otherwise, it
154  * will be rejected.
155  *
156  * The DHCP client will not start advertising for an IP address until
157  * dhclient_init() is called.
158  *
159  * If successful, returns 0 and sets '*cli' to the new DHCP client.  Otherwise,
160  * returns a positive errno value and sets '*cli' to a null pointer. */
161 int
162 dhclient_create(const char *netdev_name,
163                 void (*modify_request)(struct dhcp_msg *, void *aux),
164                 bool (*validate_offer)(const struct dhcp_msg *, void *aux),
165                 void *aux, struct dhclient **cli_)
166 {
167     struct dhclient *cli;
168     struct netdev *netdev;
169     int error;
170
171     *cli_ = NULL;
172
173     error = netdev_open(netdev_name, ETH_TYPE_IP, &netdev);
174     /* XXX install socket filter to catch only DHCP packets. */
175     if (error) {
176         VLOG_ERR("could not open %s network device: %s",
177                  netdev_name, strerror(error));
178         return error;
179     }
180
181     error = netdev_turn_flags_on(netdev, NETDEV_UP, false);
182     if (error) {
183         VLOG_ERR("could not bring %s device up: %s",
184                  netdev_name, strerror(error));
185         netdev_close(netdev);
186         return error;
187     }
188
189     cli = xcalloc(1, sizeof *cli);
190     cli->modify_request = modify_request;
191     cli->validate_offer = validate_offer;
192     cli->aux = aux;
193     cli->netdev = netdev;
194     cli->state = S_RELEASED;
195     cli->state_entered = time(0);
196     cli->xid = random_uint32();
197     cli->ipaddr = 0;
198     cli->server_ip = 0;
199     cli->retransmit = cli->delay = 0;
200     cli->min_timeout = 1;
201     ds_init(&cli->s);
202     cli->changed = true;
203     *cli_ = cli;
204     return 0;
205 }
206
207 /* Forces 'cli' into a (re)initialization state, in which no address is bound
208  * but the client is advertising to obtain one.  If 'requested_ip' is nonzero,
209  * then the client will attempt to re-bind to that IP address; otherwise, it
210  * will not ask for any particular address. */
211 void
212 dhclient_init(struct dhclient *cli, uint32_t requested_ip)
213 {
214     state_transition(cli, requested_ip ? S_INIT_REBOOT : S_INIT);
215     cli->ipaddr = requested_ip;
216     cli->min_timeout = 0;
217     cli->init_delay = 0;
218 }
219
220 /* Forces 'cli' to release its bound IP address (if any).  The client will not
221  * advertise for a new address until dhclient_init() is called again. */
222 void
223 dhclient_release(struct dhclient *cli)
224 {
225     if (dhclient_is_bound(cli)) {
226         struct dhcp_msg msg;
227         dhclient_msg_init(cli, DHCPRELEASE, &msg);
228         msg.ciaddr = cli->ipaddr;
229         do_send_msg(cli, &msg);
230         dhcp_msg_uninit(&msg);
231     }
232     state_transition(cli, S_RELEASED);
233     cli->min_timeout = UINT_MAX;
234 }
235
236 static void
237 do_force_renew(struct dhclient *cli, int deadline)
238 {
239     time_t now = time(0);
240     unsigned int lease_left = sat_sub(cli->lease_expiration, now);
241     if (lease_left <= deadline) {
242         if (cli->state & (S_RENEWING | S_REBINDING)) {
243             return;
244         }
245         deadline = lease_left;
246     }
247     if (cli->state & (S_BOUND | S_RENEWING)) {
248         state_transition(cli, S_RENEWING);
249         cli->renewing_timeout = deadline * 3 / 4;
250         cli->rebinding_timeout = deadline * 1 / 4;
251     } else {
252         state_transition(cli, S_REBINDING);
253         cli->rebinding_timeout = deadline;
254     }
255     cli->min_timeout = 0;
256 }
257
258 /* Forces 'cli' to attempt to renew the lease its current IP address (if any)
259  * within 'deadline' seconds.  If the deadline is not met, then the client
260  * gives up its IP address binding and re-starts the DHCP process. */
261 void
262 dhclient_force_renew(struct dhclient *cli, int deadline)
263 {
264     /* Drain the receive queue so that we know that any DHCPACK we process is
265      * freshly received. */
266     netdev_drain(cli->netdev);
267
268     switch (cli->state) {
269     case S_INIT:
270     case S_INIT_REBOOT:
271     case S_REBOOTING:
272     case S_SELECTING:
273     case S_REQUESTING:
274         break;
275
276     case S_BOUND:
277     case S_RENEWING:
278     case S_REBINDING:
279         do_force_renew(cli, deadline);
280         break;
281
282     case S_RELEASED:
283         dhclient_init(cli, 0);
284         break;
285     }
286 }
287
288 /* Returns true if 'cli' is bound to an IP address, false otherwise. */
289 bool
290 dhclient_is_bound(const struct dhclient *cli)
291 {
292     return cli->state & (S_BOUND | S_RENEWING | S_REBINDING);
293 }
294
295 /* Returns true if 'cli' has changed from bound to unbound, or vice versa, at
296  * least once since the last time this function was called.  */
297 bool
298 dhclient_changed(struct dhclient *cli)
299 {
300     bool changed = cli->changed;
301     cli->changed = 0;
302     return changed;
303 }
304
305 /* If 'cli' is bound to an IP address, returns that IP address; otherwise,
306  * returns 0. */
307 uint32_t
308 dhclient_get_ip(const struct dhclient *cli)
309 {
310     return dhclient_is_bound(cli) ? cli->ipaddr : 0;
311 }
312
313 /* If 'cli' is bound to an IP address, returns the netmask for that IP address;
314  * otherwise, returns 0. */
315 uint32_t
316 dhclient_get_netmask(const struct dhclient *cli)
317 {
318     return dhclient_is_bound(cli) ? cli->netmask : 0;
319 }
320
321 /* If 'cli' is bound to an IP address and 'cli' has a default gateway, returns
322  * that default gateway; otherwise, returns 0. */
323 uint32_t
324 dhclient_get_router(const struct dhclient *cli)
325 {
326     return dhclient_is_bound(cli) ? cli->router : 0;
327 }
328
329 /* If 'cli' is bound to an IP address, returns the DHCP message that was
330  * received to obtain that IP address (so that the caller can obtain additional
331  * options from it).  Otherwise, returns a null pointer. */
332 const struct dhcp_msg *
333 dhclient_get_config(const struct dhclient *cli)
334 {
335     return dhclient_is_bound(cli) ? cli->binding : NULL;
336 }
337
338 /* Configures the network device backing 'cli' to the network address and other
339  * parameters obtained via DHCP.  If no address is bound on 'cli', removes any
340  * configured address from 'cli'.
341  *
342  * To use a dhclient as a regular DHCP client that binds and unbinds from IP
343  * addresses in the usual fashion, call this function after dhclient_run() if
344  * anything has changed, like so:
345  *
346  * dhclient_run(cli);
347  * if (dhclient_changed(cli)) {
348  *     dhclient_configure_netdev(cli);
349  * }
350  *
351  */
352 int
353 dhclient_configure_netdev(struct dhclient *cli)
354 {
355     struct in_addr addr = { dhclient_get_ip(cli) };
356     struct in_addr mask = { dhclient_get_netmask(cli) };
357     struct in_addr router = { dhclient_get_router(cli) };
358     int error;
359
360     error = netdev_set_in4(cli->netdev, addr, mask);
361     if (error) {
362         VLOG_ERR("could not set %s address "IP_FMT"/"IP_FMT": %s",
363                  netdev_get_name(cli->netdev),
364                  IP_ARGS(&addr.s_addr), IP_ARGS(&mask.s_addr),
365                  strerror(error));
366     }
367
368     if (!error && router.s_addr) {
369         error = netdev_add_router(cli->netdev, router);
370         if (error) {
371             VLOG_ERR("failed to add default route to "IP_FMT" on %s: %s",
372                      IP_ARGS(&router), netdev_get_name(cli->netdev),
373                      strerror(error));
374         }
375     }
376
377     return error;
378 }
379 \f
380 /* DHCP protocol. */
381
382 static void
383 make_dhcpdiscover(struct dhclient *cli, struct dhcp_msg *msg)
384 {
385     cli->secs = elapsed_in_this_state(cli);
386     dhclient_msg_init(cli, DHCPDISCOVER, msg);
387     if (cli->ipaddr) {
388         dhcp_msg_put_ip(msg, DHCP_CODE_REQUESTED_IP, cli->ipaddr);
389     }
390 }
391
392 static void
393 make_dhcprequest(struct dhclient *cli, struct dhcp_msg *msg)
394 {
395     dhclient_msg_init(cli, DHCPREQUEST, msg);
396     msg->ciaddr = dhclient_get_ip(cli);
397     if (cli->state == S_REQUESTING) {
398         dhcp_msg_put_ip(msg, DHCP_CODE_SERVER_IDENTIFIER, cli->server_ip);
399     }
400     dhcp_msg_put_ip(msg, DHCP_CODE_REQUESTED_IP, cli->ipaddr);
401 }
402
403 static void
404 do_init(struct dhclient *cli, enum dhclient_state next_state)
405 {
406     if (!cli->init_delay) {
407         cli->init_delay = clamp(fuzz(2, 8), 1, 10);
408     }
409     if (timeout(cli, cli->init_delay)) {
410         state_transition(cli, next_state);
411     }
412 }
413
414 static void
415 dhclient_run_INIT(struct dhclient *cli)
416 {
417     do_init(cli, S_SELECTING);
418 }
419
420 static void
421 dhclient_run_INIT_REBOOT(struct dhclient *cli)
422 {
423     do_init(cli, S_REBOOTING);
424 }
425
426 static void
427 dhclient_run_REBOOTING(struct dhclient *cli)
428 {
429     send_reliably(cli, make_dhcprequest);
430     if (!receive_ack(cli) && timeout(cli, 60)) {
431         state_transition(cli, S_INIT);
432     }
433 }
434
435 static bool
436 dhcp_receive(struct dhclient *cli, unsigned int msgs, struct dhcp_msg *msg)
437 {
438     while (do_receive_msg(cli, msg)) {
439         if (msg->type < 0 || msg->type > 31 || !((1u << msg->type) & msgs)) {
440             VLOG_DBG("received unexpected %s in %s state: %s",
441                      dhcp_type_name(msg->type), state_name(cli->state),
442                      dhcp_msg_to_string(msg, false, &cli->s));
443         } else if (msg->xid != cli->xid) {
444             VLOG_DBG("ignoring %s with xid != %08"PRIx32" in %s state: %s",
445                      dhcp_type_name(msg->type), msg->xid,
446                      state_name(cli->state),
447                      dhcp_msg_to_string(msg, false, &cli->s));
448         } else {
449             return true;
450         }
451         dhcp_msg_uninit(msg);
452     }
453     return false;
454 }
455
456 static bool
457 validate_offered_options(struct dhclient *cli, const struct dhcp_msg *msg)
458 {
459     uint32_t lease, netmask;
460     if (!dhcp_msg_get_secs(msg, DHCP_CODE_LEASE_TIME, 0, &lease)) {
461         VLOG_WARN("%s lacks lease time: %s", dhcp_type_name(msg->type),
462                   dhcp_msg_to_string(msg, false, &cli->s));
463     } else if (!dhcp_msg_get_ip(msg, DHCP_CODE_SUBNET_MASK, 0, &netmask)) {
464         VLOG_WARN("%s lacks netmask: %s", dhcp_type_name(msg->type),
465                   dhcp_msg_to_string(msg, false, &cli->s));
466     } else if (lease < MIN_ACCEPTABLE_LEASE) {
467         VLOG_WARN("Ignoring %s with %"PRIu32"-second lease time: %s",
468                   dhcp_type_name(msg->type), lease,
469                   dhcp_msg_to_string(msg, false, &cli->s));
470     } else if (cli->validate_offer && !cli->validate_offer(msg, cli->aux)) {
471         VLOG_DBG("client validation hook refused offer: %s",
472                  dhcp_msg_to_string(msg, false, &cli->s));
473     } else {
474         return true;
475     }
476     return false;
477 }
478
479 static void
480 dhclient_run_SELECTING(struct dhclient *cli)
481 {
482     struct dhcp_msg msg;
483
484     send_reliably(cli, make_dhcpdiscover);
485     if (cli->server_ip && timeout(cli, 60)) {
486         cli->server_ip = 0;
487         state_transition(cli, S_INIT);
488     }
489     for (; dhcp_receive(cli, 1u << DHCPOFFER, &msg); dhcp_msg_uninit(&msg)) {
490         if (!validate_offered_options(cli, &msg)) {
491             continue;
492         }
493         if (!dhcp_msg_get_ip(&msg, DHCP_CODE_SERVER_IDENTIFIER,
494                              0, &cli->server_ip)) {
495             VLOG_WARN("DHCPOFFER lacks server identifier: %s",
496                       dhcp_msg_to_string(&msg, false, &cli->s));
497             continue;
498         }
499
500         VLOG_DBG("accepting DHCPOFFER: %s",
501                  dhcp_msg_to_string(&msg, false, &cli->s));
502         cli->ipaddr = msg.yiaddr;
503         state_transition(cli, S_REQUESTING);
504         break;
505     }
506 }
507
508 static bool
509 receive_ack(struct dhclient *cli)
510 {
511     struct dhcp_msg msg;
512
513     if (!dhcp_receive(cli, (1u << DHCPACK) | (1u << DHCPNAK), &msg)) {
514         return false;
515     } else if (msg.type == DHCPNAK) {
516         dhcp_msg_uninit(&msg);
517         state_transition(cli, S_INIT);
518         return true;
519     } else if (!validate_offered_options(cli, &msg)) {
520         dhcp_msg_uninit(&msg);
521         return false;
522     } else {
523         uint32_t lease = 0, t1 = 0, t2 = 0;
524
525         if (cli->binding) {
526             dhcp_msg_uninit(cli->binding);
527         } else {
528             cli->binding = xmalloc(sizeof *cli->binding);
529         }
530         dhcp_msg_copy(cli->binding, &msg);
531
532         dhcp_msg_get_secs(&msg, DHCP_CODE_LEASE_TIME, 0, &lease);
533         dhcp_msg_get_secs(&msg, DHCP_CODE_T1, 0, &t1);
534         dhcp_msg_get_secs(&msg, DHCP_CODE_T2, 0, &t2);
535         assert(lease >= MIN_ACCEPTABLE_LEASE);
536
537         if (!t2 || t2 >= lease) {
538             t2 = calc_t2(lease);
539         }
540         if (!t1 || t1 >= t2) {
541             t1 = calc_t1(lease, t2);
542         }
543
544         cli->lease_expiration = sat_add(time(0), lease);
545         cli->bound_timeout = t1;
546         cli->renewing_timeout = t2 - t1;
547         cli->rebinding_timeout = lease - t2;
548
549         cli->ipaddr = msg.yiaddr;
550         dhcp_msg_get_ip(&msg, DHCP_CODE_SUBNET_MASK, 0, &cli->netmask);
551         if (!dhcp_msg_get_ip(&msg, DHCP_CODE_ROUTER, 0, &cli->router)) {
552             cli->router = INADDR_ANY;
553         }
554         state_transition(cli, S_BOUND);
555         VLOG_DBG("Bound: %s", dhcp_msg_to_string(&msg, false, &cli->s));
556         return true;
557     }
558 }
559
560 static void
561 dhclient_run_REQUESTING(struct dhclient *cli)
562 {
563     send_reliably(cli, make_dhcprequest);
564     if (!receive_ack(cli) && timeout(cli, 60)) {
565         state_transition(cli, S_INIT);
566     }
567 }
568
569 static void
570 dhclient_run_BOUND(struct dhclient *cli)
571 {
572     if (timeout(cli, cli->bound_timeout)) {
573         state_transition(cli, S_RENEWING);
574     }
575 }
576
577 static void
578 dhclient_run_RENEWING(struct dhclient *cli)
579 {
580     send_reliably(cli, make_dhcprequest);
581     if (!receive_ack(cli) && timeout(cli, cli->renewing_timeout)) {
582         state_transition(cli, S_REBINDING);
583     }
584 }
585
586 static void
587 dhclient_run_REBINDING(struct dhclient *cli)
588 {
589     send_reliably(cli, make_dhcprequest);
590     if (!receive_ack(cli) && timeout(cli, cli->rebinding_timeout)) {
591         state_transition(cli, S_INIT);
592     }
593 }
594
595 static void
596 dhclient_run_RELEASED(struct dhclient *cli UNUSED)
597 {
598     /* Nothing to do. */
599 }
600
601 /* Processes the DHCP protocol for 'cli'. */
602 void
603 dhclient_run(struct dhclient *cli)
604 {
605     int old_state;
606     do {
607         old_state = cli->state;
608         cli->min_timeout = UINT_MAX;
609         cli->received = 0;
610         switch (cli->state) {
611 #define DHCLIENT_STATE(NAME, VALUE) \
612             case S_##NAME: dhclient_run_##NAME(cli); break;
613             DHCLIENT_STATES
614 #undef DHCLIENT_STATE
615         default:
616             NOT_REACHED();
617         }
618     } while (cli->state != old_state);
619 }
620
621 /* Sets up poll timeouts to wake up the poll loop when 'cli' needs to do some
622  * work. */
623 void
624 dhclient_wait(struct dhclient *cli)
625 {
626     if (cli->min_timeout != UINT_MAX) {
627         poll_timer_wait(sat_mul(cli->min_timeout, 1000));
628     }
629     /* Reset timeout to 1 second.  This will have no effect ordinarily, because
630      * dhclient_run() will typically set it back to a higher value.  If,
631      * however, the caller fails to call dhclient_run() before its next call to
632      * dhclient_wait() we won't potentially block forever. */
633     cli->min_timeout = 1;
634
635     if (cli->state & (S_SELECTING | S_REQUESTING | S_RENEWING | S_REBINDING)) {
636         netdev_recv_wait(cli->netdev);
637     }
638 }
639
640 static void
641 state_transition(struct dhclient *cli, enum dhclient_state state)
642 {
643     bool was_bound = dhclient_is_bound(cli);
644     bool am_bound;
645     if (cli->state != state) {
646         VLOG_DBG("entering %s", state_name(state)); 
647         cli->state = state;
648     }
649     cli->state_entered = time(0);
650     cli->retransmit = cli->delay = 0;
651     am_bound = dhclient_is_bound(cli);
652     if (was_bound != am_bound) {
653         cli->changed = true;
654         if (am_bound) {
655             assert(cli->binding != NULL);
656             VLOG_WARN("%s: obtained address "IP_FMT", netmask "IP_FMT,
657                       netdev_get_name(cli->netdev),
658                       IP_ARGS(&cli->ipaddr), IP_ARGS(&cli->netmask));
659             if (cli->router) {
660                 VLOG_WARN("%s: obtained default gateway "IP_FMT,
661                           netdev_get_name(cli->netdev), IP_ARGS(&cli->router));
662             }
663         } else {
664             dhcp_msg_uninit(cli->binding);
665             free(cli->binding);
666             cli->binding = NULL;
667
668             VLOG_WARN("%s: network address unbound",
669                       netdev_get_name(cli->netdev));
670         }
671     }
672     if (cli->state & (S_SELECTING | S_REQUESTING | S_REBOOTING)) {
673         netdev_drain(cli->netdev);
674     }
675 }
676
677 static void
678 send_reliably(struct dhclient *cli,
679               void (*make_packet)(struct dhclient *, struct dhcp_msg *))
680 {
681     if (timeout(cli, cli->retransmit)) {
682         struct dhcp_msg msg;
683         make_packet(cli, &msg);
684         if (cli->modify_request) {
685             cli->modify_request(&msg, cli->aux);
686         }
687         do_send_msg(cli, &msg);
688         cli->delay = MIN(64, MAX(4, cli->delay * 2));
689         cli->retransmit += fuzz(cli->delay, 1);
690         timeout(cli, cli->retransmit);
691         dhcp_msg_uninit(&msg);
692      }
693 }
694
695 static void
696 dhclient_msg_init(struct dhclient *cli, enum dhcp_msg_type type,
697                   struct dhcp_msg *msg)
698 {
699     dhcp_msg_init(msg);
700     msg->op = DHCP_BOOTREQUEST;
701     msg->xid = cli->xid;
702     msg->secs = cli->secs;
703     msg->type = type;
704     memcpy(msg->chaddr, netdev_get_etheraddr(cli->netdev), ETH_ADDR_LEN);
705 }
706
707 static unsigned int
708 elapsed_in_this_state(const struct dhclient *cli)
709 {
710     return time(0) - cli->state_entered;
711 }
712
713 static bool
714 timeout(struct dhclient *cli, unsigned int secs)
715 {
716     cli->min_timeout = MIN(cli->min_timeout, secs);
717     return time(0) >= sat_add(cli->state_entered, secs);
718 }
719
720 static bool
721 do_receive_msg(struct dhclient *cli, struct dhcp_msg *msg)
722 {
723     struct buffer b;
724
725     buffer_init(&b, netdev_get_mtu(cli->netdev) + VLAN_ETH_HEADER_LEN);
726     for (; cli->received < 50; cli->received++) {
727         const struct ip_header *ip;
728         const struct dhcp_header *dhcp;
729         struct flow flow;
730         int error;
731
732         buffer_clear(&b);
733         error = netdev_recv(cli->netdev, &b);
734         if (error) {
735             goto drained;
736         }
737
738         flow_extract(&b, 0, &flow);
739         if (flow.dl_type != htons(ETH_TYPE_IP)
740             || flow.nw_proto != IP_TYPE_UDP
741             || flow.tp_dst != htons(68)
742             || !(eth_addr_is_broadcast(flow.dl_dst)
743                  || eth_addr_equals(flow.dl_dst,
744                                     netdev_get_etheraddr(cli->netdev)))) {
745             continue;
746         }
747
748         ip = b.l3;
749         if (IP_IS_FRAGMENT(ip->ip_frag_off)) {
750             /* We don't do reassembly. */
751             VLOG_WARN("ignoring fragmented DHCP datagram");
752             continue;
753         }
754
755         dhcp = b.l7;
756         if (!dhcp) {
757             VLOG_WARN("ignoring DHCP datagram with missing payload");
758             continue;
759         }
760
761         buffer_pull(&b, b.l7 - b.data);
762         error = dhcp_parse(msg, &b);
763         if (!error) {
764             VLOG_DBG("received %s", dhcp_msg_to_string(msg, false, &cli->s));
765             buffer_uninit(&b);
766             return true;
767         }
768     }
769     netdev_drain(cli->netdev);
770 drained:
771     buffer_uninit(&b);
772     return false;
773 }
774
775 static void
776 do_send_msg(struct dhclient *cli, const struct dhcp_msg *msg)
777 {
778     struct buffer b;
779     struct eth_header eh;
780     struct ip_header nh;
781     struct udp_header th;
782     uint32_t udp_csum;
783     int error;
784
785     buffer_init(&b, ETH_TOTAL_MAX);
786     buffer_reserve(&b, ETH_HEADER_LEN + IP_HEADER_LEN + UDP_HEADER_LEN);
787
788     dhcp_assemble(msg, &b);
789
790     memcpy(eh.eth_src, netdev_get_etheraddr(cli->netdev), ETH_ADDR_LEN);
791     memcpy(eh.eth_dst, eth_addr_broadcast, ETH_ADDR_LEN);
792     eh.eth_type = htons(ETH_TYPE_IP);
793
794     nh.ip_ihl_ver = IP_IHL_VER(5, IP_VERSION);
795     nh.ip_tos = 0;
796     nh.ip_tot_len = htons(IP_HEADER_LEN + UDP_HEADER_LEN + b.size);
797     /* We can't guarantee uniqueness of ip_id versus the host's, screwing up
798      * fragment reassembly, so prevent fragmentation and use an all-zeros
799      * ip_id.  RFC 791 doesn't say we can do this, but Linux does the same
800      * thing for DF packets, so it must not screw anything up.  */
801     nh.ip_id = 0;
802     nh.ip_frag_off = htons(IP_DONT_FRAGMENT);
803     nh.ip_ttl = 64;
804     nh.ip_proto = IP_TYPE_UDP;
805     nh.ip_csum = 0;
806     nh.ip_src = dhclient_get_ip(cli);
807     /* XXX need to use UDP socket for nonzero server IPs so that we can get
808      * routing table support.
809      *
810      * if (...have server IP and in appropriate state...) {
811      *    nh.ip_dst = cli->server_ip;
812      * } else {
813      *    nh.ip_dst = INADDR_BROADCAST;
814      * }
815      */
816     nh.ip_dst = INADDR_BROADCAST;
817     nh.ip_csum = csum(&nh, sizeof nh);
818
819     th.udp_src = htons(66);
820     th.udp_dst = htons(67);
821     th.udp_len = htons(UDP_HEADER_LEN + b.size);
822     th.udp_csum = 0;
823     udp_csum = csum_add32(0, nh.ip_src);
824     udp_csum = csum_add32(udp_csum, nh.ip_dst);
825     udp_csum = csum_add16(udp_csum, IP_TYPE_UDP << 8);
826     udp_csum = csum_add16(udp_csum, th.udp_len);
827     udp_csum = csum_continue(udp_csum, &th, sizeof th);
828     th.udp_csum = csum_finish(csum_continue(udp_csum, b.data, b.size));
829
830     buffer_push(&b, &th, sizeof th);
831     buffer_push(&b, &nh, sizeof nh);
832     buffer_push(&b, &eh, sizeof eh);
833
834     /* Don't try to send the frame if it's too long for an Ethernet frame.  We
835      * disregard the network device's actual MTU because we don't want the
836      * frame to have to be discarded or fragmented if it travels over a regular
837      * Ethernet at some point.  1500 bytes should be enough for anyone. */
838     if (b.size <= ETH_TOTAL_MAX) {
839         VLOG_DBG("sending %s", dhcp_msg_to_string(msg, false, &cli->s));
840         error = netdev_send(cli->netdev, &b);
841         if (error) {
842             VLOG_ERR("send failed on %s: %s",
843                      netdev_get_name(cli->netdev), strerror(error));
844         }
845     } else {
846         VLOG_ERR("cannot send %zu-byte Ethernet frame", b.size);
847     }
848
849     buffer_uninit(&b);
850 }
851
852 static unsigned int
853 fuzz(unsigned int x, int max_fuzz)
854 {
855     /* Generate number in range [-max_fuzz, +max_fuzz]. */
856     int fuzz = random_range(max_fuzz * 2 + 1) - max_fuzz;
857     unsigned int y = x + fuzz;
858     return fuzz >= 0 ? (y >= x ? y : UINT_MAX) : (y <= x ? y : 0);
859 }
860
861 static unsigned int
862 sat_add(unsigned int x, unsigned int y)
863 {
864     return x + y >= x ? x + y : UINT_MAX;
865 }
866
867 static unsigned int
868 sat_sub(unsigned int x, unsigned int y)
869 {
870     return x >= y ? x - y : 0;
871 }
872
873 static unsigned int
874 sat_mul(unsigned int x, unsigned int y)
875 {
876     assert(y);
877     return x <= UINT_MAX / y ? x * y : UINT_MAX;
878 }
879
880 static unsigned int
881 clamp(unsigned int x, unsigned int min, unsigned int max)
882 {
883     return x < min ? min : x > max ? max : x;
884 }
885
886 static unsigned int
887 calc_t2(unsigned int lease)
888 {
889     unsigned int base = lease * 0.875;
890     return lease >= 60 ? clamp(fuzz(base, 10), 0, lease - 1) : base;
891 }
892
893 static unsigned int
894 calc_t1(unsigned int lease, unsigned int t2)
895 {
896     unsigned int base = lease / 2;
897     return lease >= 60 ? clamp(fuzz(base, 10), 0, t2 - 1) : base;
898 }