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