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