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