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