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