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