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