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