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