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