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