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