etc/protocols - sync with NetBSD-8
[minix.git] / external / bsd / dhcpcd / dist / dhcp.c
blob721048ef4611560baf29b0686d3d1f243fc2e5d4
1 #include <sys/cdefs.h>
2 __RCSID("$NetBSD: dhcp.c,v 1.35 2015/09/04 12:25:01 roy Exp $");
4 /*
5 * dhcpcd - DHCP client daemon
6 * Copyright (c) 2006-2015 Roy Marples <roy@marples.name>
7 * All rights reserved
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
18 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
19 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
22 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28 * SUCH DAMAGE.
31 #include <sys/param.h>
32 #include <sys/socket.h>
33 #include <sys/stat.h>
35 #include <arpa/inet.h>
36 #include <net/if.h>
37 #include <net/route.h>
38 #include <netinet/if_ether.h>
39 #include <netinet/in_systm.h>
40 #include <netinet/in.h>
41 #include <netinet/ip.h>
42 #define __FAVOR_BSD /* Nasty glibc hack so we can use BSD semantics for UDP */
43 #include <netinet/udp.h>
44 #undef __FAVOR_BSD
46 #include <ctype.h>
47 #include <errno.h>
48 #include <fcntl.h>
49 #include <inttypes.h>
50 #include <stddef.h>
51 #include <stdlib.h>
52 #include <string.h>
53 #include <unistd.h>
55 #define ELOOP_QUEUE 2
56 #include "config.h"
57 #include "arp.h"
58 #include "common.h"
59 #include "dhcp.h"
60 #include "dhcpcd.h"
61 #include "dhcp-common.h"
62 #include "duid.h"
63 #include "eloop.h"
64 #include "if.h"
65 #include "ipv4.h"
66 #include "ipv4ll.h"
67 #include "script.h"
69 #define DAD "Duplicate address detected"
70 #define DHCP_MIN_LEASE 20
72 #define IPV4A ADDRIPV4 | ARRAY
73 #define IPV4R ADDRIPV4 | REQUEST
75 /* We should define a maximum for the NAK exponential backoff */
76 #define NAKOFF_MAX 60
78 /* Wait N nanoseconds between sending a RELEASE and dropping the address.
79 * This gives the kernel enough time to actually send it. */
80 #define RELEASE_DELAY_S 0
81 #define RELEASE_DELAY_NS 10000000
83 #ifndef IPDEFTTL
84 #define IPDEFTTL 64 /* RFC1340 */
85 #endif
87 struct dhcp_op {
88 uint8_t value;
89 const char *name;
92 static const struct dhcp_op dhcp_ops[] = {
93 { DHCP_DISCOVER, "DISCOVER" },
94 { DHCP_OFFER, "OFFER" },
95 { DHCP_REQUEST, "REQUEST" },
96 { DHCP_DECLINE, "DECLINE" },
97 { DHCP_ACK, "ACK" },
98 { DHCP_NAK, "NAK" },
99 { DHCP_RELEASE, "RELEASE" },
100 { DHCP_INFORM, "INFORM" },
101 { DHCP_FORCERENEW, "DHCP_FORCERENEW"},
102 { 0, NULL }
105 static const char * const dhcp_params[] = {
106 "ip_address",
107 "subnet_cidr",
108 "network_number",
109 "filename",
110 "server_name",
111 NULL
114 struct udp_dhcp_packet
116 struct ip ip;
117 struct udphdr udp;
118 struct dhcp_message dhcp;
121 static const size_t udp_dhcp_len = sizeof(struct udp_dhcp_packet);
123 static int dhcp_open(struct interface *ifp);
125 void
126 dhcp_printoptions(const struct dhcpcd_ctx *ctx,
127 const struct dhcp_opt *opts, size_t opts_len)
129 const char * const *p;
130 size_t i, j;
131 const struct dhcp_opt *opt, *opt2;
132 int cols;
134 for (p = dhcp_params; *p; p++)
135 printf(" %s\n", *p);
137 for (i = 0, opt = ctx->dhcp_opts; i < ctx->dhcp_opts_len; i++, opt++) {
138 for (j = 0, opt2 = opts; j < opts_len; j++, opt2++)
139 if (opt->option == opt2->option)
140 break;
141 if (j == opts_len) {
142 cols = printf("%03d %s", opt->option, opt->var);
143 dhcp_print_option_encoding(opt, cols);
146 for (i = 0, opt = opts; i < opts_len; i++, opt++) {
147 cols = printf("%03d %s", opt->option, opt->var);
148 dhcp_print_option_encoding(opt, cols);
152 #define get_option_raw(ctx, dhcp, opt) get_option(ctx, dhcp, opt, NULL)
153 static const uint8_t *
154 get_option(struct dhcpcd_ctx *ctx,
155 const struct dhcp_message *dhcp, unsigned int opt, size_t *len)
157 const uint8_t *p = dhcp->options;
158 const uint8_t *e = p + sizeof(dhcp->options);
159 uint8_t l, ol = 0;
160 uint8_t o = 0;
161 uint8_t overl = 0;
162 uint8_t *bp = NULL;
163 const uint8_t *op = NULL;
164 size_t bl = 0;
166 /* Check we have the magic cookie */
167 if (dhcp->cookie != htonl(MAGIC_COOKIE)) {
168 errno = ENOTSUP;
169 return NULL;
172 while (p < e) {
173 o = *p++;
174 switch (o) {
175 case DHO_PAD:
176 /* No length to read */
177 continue;
178 case DHO_END:
179 if (overl & 1) {
180 /* bit 1 set means parse boot file */
181 overl = (uint8_t)(overl & ~1);
182 p = dhcp->bootfile;
183 e = p + sizeof(dhcp->bootfile);
184 } else if (overl & 2) {
185 /* bit 2 set means parse server name */
186 overl = (uint8_t)(overl & ~2);
187 p = dhcp->servername;
188 e = p + sizeof(dhcp->servername);
189 } else
190 goto exit;
191 /* No length to read */
192 continue;
195 /* Check we can read the length */
196 if (p == e) {
197 errno = EINVAL;
198 return NULL;
200 l = *p++;
202 if (o == DHO_OPTIONSOVERLOADED) {
203 /* Ensure we only get this option once by setting
204 * the last bit as well as the value.
205 * This is valid because only the first two bits
206 * actually mean anything in RFC2132 Section 9.3 */
207 if (l == 1 && !overl)
208 overl = 0x80 | p[0];
211 if (o == opt) {
212 if (op) {
213 if (!ctx->opt_buffer) {
214 ctx->opt_buffer =
215 malloc(DHCP_OPTION_LEN +
216 BOOTFILE_LEN + SERVERNAME_LEN);
217 if (ctx->opt_buffer == NULL)
218 return NULL;
220 if (!bp)
221 bp = ctx->opt_buffer;
222 memcpy(bp, op, ol);
223 bp += ol;
225 ol = l;
226 if (p + ol >= e) {
227 errno = EINVAL;
228 return NULL;
230 op = p;
231 bl += ol;
233 p += l;
236 exit:
237 if (len)
238 *len = bl;
239 if (bp) {
240 memcpy(bp, op, ol);
241 return (const uint8_t *)ctx->opt_buffer;
243 if (op)
244 return op;
245 errno = ENOENT;
246 return NULL;
250 get_option_addr(struct dhcpcd_ctx *ctx,
251 struct in_addr *a, const struct dhcp_message *dhcp,
252 uint8_t option)
254 const uint8_t *p;
255 size_t len;
257 p = get_option(ctx, dhcp, option, &len);
258 if (!p || len < (ssize_t)sizeof(a->s_addr))
259 return -1;
260 memcpy(&a->s_addr, p, sizeof(a->s_addr));
261 return 0;
264 static int
265 get_option_uint32(struct dhcpcd_ctx *ctx,
266 uint32_t *i, const struct dhcp_message *dhcp, uint8_t option)
268 const uint8_t *p;
269 size_t len;
270 uint32_t d;
272 p = get_option(ctx, dhcp, option, &len);
273 if (!p || len < (ssize_t)sizeof(d))
274 return -1;
275 memcpy(&d, p, sizeof(d));
276 if (i)
277 *i = ntohl(d);
278 return 0;
281 static int
282 get_option_uint16(struct dhcpcd_ctx *ctx,
283 uint16_t *i, const struct dhcp_message *dhcp, uint8_t option)
285 const uint8_t *p;
286 size_t len;
287 uint16_t d;
289 p = get_option(ctx, dhcp, option, &len);
290 if (!p || len < (ssize_t)sizeof(d))
291 return -1;
292 memcpy(&d, p, sizeof(d));
293 if (i)
294 *i = ntohs(d);
295 return 0;
298 static int
299 get_option_uint8(struct dhcpcd_ctx *ctx,
300 uint8_t *i, const struct dhcp_message *dhcp, uint8_t option)
302 const uint8_t *p;
303 size_t len;
305 p = get_option(ctx, dhcp, option, &len);
306 if (!p || len < (ssize_t)sizeof(*p))
307 return -1;
308 if (i)
309 *i = *(p);
310 return 0;
313 ssize_t
314 decode_rfc3442(char *out, size_t len, const uint8_t *p, size_t pl)
316 const uint8_t *e;
317 size_t bytes = 0, ocets;
318 int b;
319 uint8_t cidr;
320 struct in_addr addr;
321 char *o = out;
323 /* Minimum is 5 -first is CIDR and a router length of 4 */
324 if (pl < 5) {
325 errno = EINVAL;
326 return -1;
329 e = p + pl;
330 while (p < e) {
331 cidr = *p++;
332 if (cidr > 32) {
333 errno = EINVAL;
334 return -1;
336 ocets = (size_t)(cidr + 7) / NBBY;
337 if (p + 4 + ocets > e) {
338 errno = ERANGE;
339 return -1;
341 if (!out) {
342 p += 4 + ocets;
343 bytes += ((4 * 4) * 2) + 4;
344 continue;
346 if ((((4 * 4) * 2) + 4) > len) {
347 errno = ENOBUFS;
348 return -1;
350 if (o != out) {
351 *o++ = ' ';
352 len--;
354 /* If we have ocets then we have a destination and netmask */
355 if (ocets > 0) {
356 addr.s_addr = 0;
357 memcpy(&addr.s_addr, p, ocets);
358 b = snprintf(o, len, "%s/%d", inet_ntoa(addr), cidr);
359 p += ocets;
360 } else
361 b = snprintf(o, len, "0.0.0.0/0");
362 o += b;
363 len -= (size_t)b;
365 /* Finally, snag the router */
366 memcpy(&addr.s_addr, p, 4);
367 p += 4;
368 b = snprintf(o, len, " %s", inet_ntoa(addr));
369 o += b;
370 len -= (size_t)b;
373 if (out)
374 return o - out;
375 return (ssize_t)bytes;
378 static struct rt_head *
379 decode_rfc3442_rt(struct dhcpcd_ctx *ctx, const uint8_t *data, size_t dl)
381 const uint8_t *p = data;
382 const uint8_t *e;
383 uint8_t cidr;
384 size_t ocets;
385 struct rt_head *routes;
386 struct rt *rt = NULL;
388 /* Minimum is 5 -first is CIDR and a router length of 4 */
389 if (dl < 5)
390 return NULL;
392 routes = malloc(sizeof(*routes));
393 TAILQ_INIT(routes);
394 e = p + dl;
395 while (p < e) {
396 cidr = *p++;
397 if (cidr > 32) {
398 ipv4_freeroutes(routes);
399 errno = EINVAL;
400 return NULL;
403 ocets = (size_t)(cidr + 7) / NBBY;
404 if (p + 4 + ocets > e) {
405 ipv4_freeroutes(routes);
406 errno = ERANGE;
407 return NULL;
410 rt = calloc(1, sizeof(*rt));
411 if (rt == NULL) {
412 logger(ctx, LOG_ERR, "%s: %m", __func__);
413 ipv4_freeroutes(routes);
414 return NULL;
416 TAILQ_INSERT_TAIL(routes, rt, next);
418 /* If we have ocets then we have a destination and netmask */
419 if (ocets > 0) {
420 memcpy(&rt->dest.s_addr, p, ocets);
421 p += ocets;
422 rt->net.s_addr = htonl(~0U << (32 - cidr));
425 /* Finally, snag the router */
426 memcpy(&rt->gate.s_addr, p, 4);
427 p += 4;
429 return routes;
432 char *
433 decode_rfc3361(const uint8_t *data, size_t dl)
435 uint8_t enc;
436 size_t l;
437 ssize_t r;
438 char *sip = NULL;
439 struct in_addr addr;
440 char *p;
442 if (dl < 2) {
443 errno = EINVAL;
444 return 0;
447 enc = *data++;
448 dl--;
449 switch (enc) {
450 case 0:
451 if ((r = decode_rfc1035(NULL, 0, data, dl)) > 0) {
452 l = (size_t)r;
453 sip = malloc(l);
454 if (sip == NULL)
455 return 0;
456 decode_rfc1035(sip, l, data, dl);
458 break;
459 case 1:
460 if (dl == 0 || dl % 4 != 0) {
461 errno = EINVAL;
462 break;
464 addr.s_addr = INADDR_BROADCAST;
465 l = ((dl / sizeof(addr.s_addr)) * ((4 * 4) + 1)) + 1;
466 sip = p = malloc(l);
467 if (sip == NULL)
468 return 0;
469 while (dl != 0) {
470 memcpy(&addr.s_addr, data, sizeof(addr.s_addr));
471 data += sizeof(addr.s_addr);
472 p += snprintf(p, l - (size_t)(p - sip),
473 "%s ", inet_ntoa(addr));
474 dl -= sizeof(addr.s_addr);
476 *--p = '\0';
477 break;
478 default:
479 errno = EINVAL;
480 return 0;
483 return sip;
486 /* Decode an RFC5969 6rd order option into a space
487 * separated string. Returns length of string (including
488 * terminating zero) or zero on error. */
489 ssize_t
490 decode_rfc5969(char *out, size_t len, const uint8_t *p, size_t pl)
492 uint8_t ipv4masklen, ipv6prefixlen;
493 uint8_t ipv6prefix[16];
494 uint8_t br[4];
495 int i;
496 ssize_t b, bytes = 0;
498 if (pl < 22) {
499 errno = EINVAL;
500 return 0;
503 ipv4masklen = *p++;
504 pl--;
505 ipv6prefixlen = *p++;
506 pl--;
508 for (i = 0; i < 16; i++) {
509 ipv6prefix[i] = *p++;
510 pl--;
512 if (out) {
513 b= snprintf(out, len,
514 "%d %d "
515 "%02x%02x:%02x%02x:"
516 "%02x%02x:%02x%02x:"
517 "%02x%02x:%02x%02x:"
518 "%02x%02x:%02x%02x",
519 ipv4masklen, ipv6prefixlen,
520 ipv6prefix[0], ipv6prefix[1], ipv6prefix[2], ipv6prefix[3],
521 ipv6prefix[4], ipv6prefix[5], ipv6prefix[6], ipv6prefix[7],
522 ipv6prefix[8], ipv6prefix[9], ipv6prefix[10],ipv6prefix[11],
523 ipv6prefix[12],ipv6prefix[13],ipv6prefix[14], ipv6prefix[15]
526 len -= (size_t)b;
527 out += b;
528 bytes += b;
529 } else {
530 bytes += 16 * 2 + 8 + 2 + 1 + 2;
533 while (pl >= 4) {
534 br[0] = *p++;
535 br[1] = *p++;
536 br[2] = *p++;
537 br[3] = *p++;
538 pl -= 4;
540 if (out) {
541 b= snprintf(out, len, " %d.%d.%d.%d",
542 br[0], br[1], br[2], br[3]);
543 len -= (size_t)b;
544 out += b;
545 bytes += b;
546 } else {
547 bytes += (4 * 4);
551 return bytes;
554 static char *
555 get_option_string(struct dhcpcd_ctx *ctx,
556 const struct dhcp_message *dhcp, uint8_t option)
558 size_t len;
559 const uint8_t *p;
560 char *s;
562 p = get_option(ctx, dhcp, option, &len);
563 if (!p || len == 0 || *p == '\0')
564 return NULL;
566 s = malloc(sizeof(char) * (len + 1));
567 if (s) {
568 memcpy(s, p, len);
569 s[len] = '\0';
571 return s;
574 /* This calculates the netmask that we should use for static routes.
575 * This IS different from the calculation used to calculate the netmask
576 * for an interface address. */
577 static uint32_t
578 route_netmask(uint32_t ip_in)
580 /* used to be unsigned long - check if error */
581 uint32_t p = ntohl(ip_in);
582 uint32_t t;
584 if (IN_CLASSA(p))
585 t = ~IN_CLASSA_NET;
586 else {
587 if (IN_CLASSB(p))
588 t = ~IN_CLASSB_NET;
589 else {
590 if (IN_CLASSC(p))
591 t = ~IN_CLASSC_NET;
592 else
593 t = 0;
597 while (t & p)
598 t >>= 1;
600 return (htonl(~t));
603 /* We need to obey routing options.
604 * If we have a CSR then we only use that.
605 * Otherwise we add static routes and then routers. */
606 static struct rt_head *
607 get_option_routes(struct interface *ifp, const struct dhcp_message *dhcp)
609 struct if_options *ifo = ifp->options;
610 const uint8_t *p;
611 const uint8_t *e;
612 struct rt_head *routes = NULL;
613 struct rt *route = NULL;
614 size_t len;
615 const char *csr = "";
617 /* If we have CSR's then we MUST use these only */
618 if (!has_option_mask(ifo->nomask, DHO_CSR))
619 p = get_option(ifp->ctx, dhcp, DHO_CSR, &len);
620 else
621 p = NULL;
622 /* Check for crappy MS option */
623 if (!p && !has_option_mask(ifo->nomask, DHO_MSCSR)) {
624 p = get_option(ifp->ctx, dhcp, DHO_MSCSR, &len);
625 if (p)
626 csr = "MS ";
628 if (p) {
629 routes = decode_rfc3442_rt(ifp->ctx, p, len);
630 if (routes) {
631 const struct dhcp_state *state;
633 state = D_CSTATE(ifp);
634 if (!(ifo->options & DHCPCD_CSR_WARNED) &&
635 !(state->added & STATE_FAKE))
637 logger(ifp->ctx, LOG_DEBUG,
638 "%s: using %sClassless Static Routes",
639 ifp->name, csr);
640 ifo->options |= DHCPCD_CSR_WARNED;
642 return routes;
646 /* OK, get our static routes first. */
647 routes = malloc(sizeof(*routes));
648 if (routes == NULL) {
649 logger(ifp->ctx, LOG_ERR, "%s: %m", __func__);
650 return NULL;
652 TAILQ_INIT(routes);
653 if (!has_option_mask(ifo->nomask, DHO_STATICROUTE))
654 p = get_option(ifp->ctx, dhcp, DHO_STATICROUTE, &len);
655 else
656 p = NULL;
657 /* RFC 2131 Section 5.8 states length MUST be in multiples of 8 */
658 if (p && len % 8 == 0) {
659 e = p + len;
660 while (p < e) {
661 if ((route = calloc(1, sizeof(*route))) == NULL) {
662 logger(ifp->ctx, LOG_ERR, "%s: %m", __func__);
663 ipv4_freeroutes(routes);
664 return NULL;
666 memcpy(&route->dest.s_addr, p, 4);
667 p += 4;
668 memcpy(&route->gate.s_addr, p, 4);
669 p += 4;
670 /* RFC 2131 Section 5.8 states default route is
671 * illegal */
672 if (route->dest.s_addr == htonl(INADDR_ANY)) {
673 errno = EINVAL;
674 free(route);
675 continue;
677 /* A host route is normally set by having the
678 * gateway match the destination or assigned address */
679 if (route->gate.s_addr == route->dest.s_addr ||
680 route->gate.s_addr == dhcp->yiaddr)
682 route->gate.s_addr = htonl(INADDR_ANY);
683 route->net.s_addr = htonl(INADDR_BROADCAST);
685 route->net.s_addr = route_netmask(route->dest.s_addr);
686 TAILQ_INSERT_TAIL(routes, route, next);
690 /* Now grab our routers */
691 if (!has_option_mask(ifo->nomask, DHO_ROUTER))
692 p = get_option(ifp->ctx, dhcp, DHO_ROUTER, &len);
693 else
694 p = NULL;
695 if (p) {
696 e = p + len;
697 while (p < e) {
698 if ((route = calloc(1, sizeof(*route))) == NULL) {
699 logger(ifp->ctx, LOG_ERR, "%s: %m", __func__);
700 ipv4_freeroutes(routes);
701 return NULL;
703 memcpy(&route->gate.s_addr, p, 4);
704 p += 4;
705 TAILQ_INSERT_TAIL(routes, route, next);
709 return routes;
712 uint16_t
713 dhcp_get_mtu(const struct interface *ifp)
715 const struct dhcp_message *dhcp;
716 uint16_t mtu;
718 if (ifp->options->mtu)
719 return (uint16_t)ifp->options->mtu;
720 mtu = 0; /* bogus gcc warning */
721 if ((dhcp = D_CSTATE(ifp)->new) == NULL ||
722 has_option_mask(ifp->options->nomask, DHO_MTU) ||
723 get_option_uint16(ifp->ctx, &mtu, dhcp, DHO_MTU) == -1)
724 return 0;
725 return mtu;
728 /* Grab our routers from the DHCP message and apply any MTU value
729 * the message contains */
730 struct rt_head *
731 dhcp_get_routes(struct interface *ifp)
733 struct rt_head *routes;
734 uint16_t mtu;
735 const struct dhcp_message *dhcp;
737 dhcp = D_CSTATE(ifp)->new;
738 routes = get_option_routes(ifp, dhcp);
739 if ((mtu = dhcp_get_mtu(ifp)) != 0) {
740 struct rt *rt;
742 TAILQ_FOREACH(rt, routes, next) {
743 rt->mtu = mtu;
746 return routes;
749 #define PUTADDR(_type, _val) \
751 *p++ = _type; \
752 *p++ = 4; \
753 memcpy(p, &_val.s_addr, 4); \
754 p += 4; \
758 dhcp_message_add_addr(struct dhcp_message *dhcp,
759 uint8_t type, struct in_addr addr)
761 uint8_t *p;
762 size_t len;
764 p = dhcp->options;
765 while (*p != DHO_END) {
766 p++;
767 p += *p + 1;
770 len = (size_t)(p - (uint8_t *)dhcp);
771 if (len + 6 > sizeof(*dhcp)) {
772 errno = ENOMEM;
773 return -1;
776 PUTADDR(type, addr);
777 *p = DHO_END;
778 return 0;
781 ssize_t
782 make_message(struct dhcp_message **message,
783 const struct interface *ifp,
784 uint8_t type)
786 struct dhcp_message *dhcp;
787 uint8_t *m, *lp, *p, *auth;
788 uint8_t *n_params = NULL, auth_len;
789 uint32_t ul;
790 uint16_t sz;
791 size_t len, i;
792 const struct dhcp_opt *opt;
793 struct if_options *ifo = ifp->options;
794 const struct dhcp_state *state = D_CSTATE(ifp);
795 const struct dhcp_lease *lease = &state->lease;
796 char hbuf[HOSTNAME_MAX_LEN + 1];
797 const char *hostname;
798 const struct vivco *vivco;
800 dhcp = calloc(1, sizeof (*dhcp));
801 if (dhcp == NULL)
802 return -1;
803 m = (uint8_t *)dhcp;
804 p = dhcp->options;
806 if ((type == DHCP_INFORM || type == DHCP_RELEASE ||
807 (type == DHCP_REQUEST &&
808 state->net.s_addr == lease->net.s_addr &&
809 (state->new == NULL ||
810 state->new->cookie == htonl(MAGIC_COOKIE)))))
812 dhcp->ciaddr = state->addr.s_addr;
813 /* In-case we haven't actually configured the address yet */
814 if (type == DHCP_INFORM && state->addr.s_addr == 0)
815 dhcp->ciaddr = lease->addr.s_addr;
818 dhcp->op = DHCP_BOOTREQUEST;
819 dhcp->hwtype = (uint8_t)ifp->family;
820 switch (ifp->family) {
821 case ARPHRD_ETHER:
822 case ARPHRD_IEEE802:
823 dhcp->hwlen = (uint8_t)ifp->hwlen;
824 memcpy(&dhcp->chaddr, &ifp->hwaddr, ifp->hwlen);
825 break;
828 if (ifo->options & DHCPCD_BROADCAST &&
829 dhcp->ciaddr == 0 &&
830 type != DHCP_DECLINE &&
831 type != DHCP_RELEASE)
832 dhcp->flags = htons(BROADCAST_FLAG);
834 if (type != DHCP_DECLINE && type != DHCP_RELEASE) {
835 struct timespec tv;
837 clock_gettime(CLOCK_MONOTONIC, &tv);
838 timespecsub(&tv, &state->started, &tv);
839 if (tv.tv_sec < 0 || tv.tv_sec > (time_t)UINT16_MAX)
840 dhcp->secs = htons((uint16_t)UINT16_MAX);
841 else
842 dhcp->secs = htons((uint16_t)tv.tv_sec);
844 dhcp->xid = htonl(state->xid);
845 dhcp->cookie = htonl(MAGIC_COOKIE);
847 if (!(ifo->options & DHCPCD_BOOTP)) {
848 *p++ = DHO_MESSAGETYPE;
849 *p++ = 1;
850 *p++ = type;
853 if (state->clientid) {
854 *p++ = DHO_CLIENTID;
855 memcpy(p, state->clientid, (size_t)state->clientid[0] + 1);
856 p += state->clientid[0] + 1;
859 if (lease->addr.s_addr && lease->cookie == htonl(MAGIC_COOKIE)) {
860 if (type == DHCP_DECLINE ||
861 (type == DHCP_REQUEST &&
862 lease->addr.s_addr != state->addr.s_addr))
864 PUTADDR(DHO_IPADDRESS, lease->addr);
865 if (lease->server.s_addr)
866 PUTADDR(DHO_SERVERID, lease->server);
869 if (type == DHCP_RELEASE) {
870 if (lease->server.s_addr)
871 PUTADDR(DHO_SERVERID, lease->server);
875 if (type == DHCP_DECLINE) {
876 *p++ = DHO_MESSAGE;
877 len = strlen(DAD);
878 *p++ = (uint8_t)len;
879 memcpy(p, DAD, len);
880 p += len;
883 if (type == DHCP_DISCOVER &&
884 !(ifp->ctx->options & DHCPCD_TEST) &&
885 has_option_mask(ifo->requestmask, DHO_RAPIDCOMMIT))
887 /* RFC 4039 Section 3 */
888 *p++ = DHO_RAPIDCOMMIT;
889 *p++ = 0;
892 if (type == DHCP_DISCOVER && ifo->options & DHCPCD_REQUEST)
893 PUTADDR(DHO_IPADDRESS, ifo->req_addr);
895 /* RFC 2563 Auto Configure */
896 if (type == DHCP_DISCOVER && ifo->options & DHCPCD_IPV4LL) {
897 *p++ = DHO_AUTOCONFIGURE;
898 *p++ = 1;
899 *p++ = 1;
902 if (type == DHCP_DISCOVER ||
903 type == DHCP_INFORM ||
904 type == DHCP_REQUEST)
906 if (!(ifo->options & DHCPCD_BOOTP)) {
907 int mtu;
909 if ((mtu = if_getmtu(ifp)) == -1)
910 logger(ifp->ctx, LOG_ERR,
911 "%s: if_getmtu: %m", ifp->name);
912 else if (mtu < MTU_MIN) {
913 if (if_setmtu(ifp, MTU_MIN) == -1)
914 logger(ifp->ctx, LOG_ERR,
915 "%s: if_setmtu: %m", ifp->name);
916 mtu = MTU_MIN;
917 } else if (mtu > MTU_MAX) {
918 /* Even though our MTU could be greater than
919 * MTU_MAX (1500) dhcpcd does not presently
920 * handle DHCP packets any bigger. */
921 mtu = MTU_MAX;
923 if (mtu != -1) {
924 *p++ = DHO_MAXMESSAGESIZE;
925 *p++ = 2;
926 sz = htons((uint16_t)mtu);
927 memcpy(p, &sz, 2);
928 p += 2;
932 if (ifo->userclass[0]) {
933 *p++ = DHO_USERCLASS;
934 memcpy(p, ifo->userclass,
935 (size_t)ifo->userclass[0] + 1);
936 p += ifo->userclass[0] + 1;
939 if (ifo->vendorclassid[0]) {
940 *p++ = DHO_VENDORCLASSID;
941 memcpy(p, ifo->vendorclassid,
942 (size_t)ifo->vendorclassid[0] + 1);
943 p += ifo->vendorclassid[0] + 1;
946 if (type != DHCP_INFORM) {
947 if (ifo->leasetime != 0) {
948 *p++ = DHO_LEASETIME;
949 *p++ = 4;
950 ul = htonl(ifo->leasetime);
951 memcpy(p, &ul, 4);
952 p += 4;
956 if (ifo->hostname[0] == '\0')
957 hostname = get_hostname(hbuf, sizeof(hbuf),
958 ifo->options & DHCPCD_HOSTNAME_SHORT ? 1 : 0);
959 else
960 hostname = ifo->hostname;
963 * RFC4702 3.1 States that if we send the Client FQDN option
964 * then we MUST NOT also send the Host Name option.
965 * Technically we could, but that is not RFC conformant and
966 * also seems to break some DHCP server implemetations such as
967 * Windows. On the other hand, ISC dhcpd is just as non RFC
968 * conformant by not accepting a partially qualified FQDN.
970 if (ifo->fqdn != FQDN_DISABLE) {
971 /* IETF DHC-FQDN option (81), RFC4702 */
972 *p++ = DHO_FQDN;
973 lp = p;
974 *p++ = 3;
976 * Flags: 0000NEOS
977 * S: 1 => Client requests Server to update
978 * a RR in DNS as well as PTR
979 * O: 1 => Server indicates to client that
980 * DNS has been updated
981 * E: 1 => Name data is DNS format
982 * N: 1 => Client requests Server to not
983 * update DNS
985 if (hostname)
986 *p++ = (uint8_t)((ifo->fqdn & 0x09) | 0x04);
987 else
988 *p++ = (FQDN_NONE & 0x09) | 0x04;
989 *p++ = 0; /* from server for PTR RR */
990 *p++ = 0; /* from server for A RR if S=1 */
991 if (hostname) {
992 i = encode_rfc1035(hostname, p);
993 *lp = (uint8_t)(*lp + i);
994 p += i;
996 } else if (ifo->options & DHCPCD_HOSTNAME && hostname) {
997 *p++ = DHO_HOSTNAME;
998 len = strlen(hostname);
999 *p++ = (uint8_t)len;
1000 memcpy(p, hostname, len);
1001 p += len;
1004 /* vendor is already encoded correctly, so just add it */
1005 if (ifo->vendor[0]) {
1006 *p++ = DHO_VENDOR;
1007 memcpy(p, ifo->vendor, (size_t)ifo->vendor[0] + 1);
1008 p += ifo->vendor[0] + 1;
1011 if ((ifo->auth.options & DHCPCD_AUTH_SENDREQUIRE) !=
1012 DHCPCD_AUTH_SENDREQUIRE)
1014 /* We support HMAC-MD5 */
1015 *p++ = DHO_FORCERENEW_NONCE;
1016 *p++ = 1;
1017 *p++ = AUTH_ALG_HMAC_MD5;
1020 if (ifo->vivco_len) {
1021 *p++ = DHO_VIVCO;
1022 lp = p++;
1023 *lp = sizeof(ul);
1024 ul = htonl(ifo->vivco_en);
1025 memcpy(p, &ul, sizeof(ul));
1026 p += sizeof(ul);
1027 for (i = 0, vivco = ifo->vivco;
1028 i < ifo->vivco_len;
1029 i++, vivco++)
1031 len = (size_t)(p - m) + vivco->len + 1;
1032 if (len > sizeof(*dhcp))
1033 goto toobig;
1034 if (vivco->len + 2 + *lp > 255) {
1035 logger(ifp->ctx, LOG_ERR,
1036 "%s: VIVCO option too big",
1037 ifp->name);
1038 free(dhcp);
1039 return -1;
1041 *p++ = (uint8_t)vivco->len;
1042 memcpy(p, vivco->data, vivco->len);
1043 p += vivco->len;
1044 *lp = (uint8_t)(*lp + vivco->len + 1);
1048 len = (size_t)((p - m) + 3);
1049 if (len > sizeof(*dhcp))
1050 goto toobig;
1051 *p++ = DHO_PARAMETERREQUESTLIST;
1052 n_params = p;
1053 *p++ = 0;
1054 for (i = 0, opt = ifp->ctx->dhcp_opts;
1055 i < ifp->ctx->dhcp_opts_len;
1056 i++, opt++)
1058 if (!(opt->type & REQUEST ||
1059 has_option_mask(ifo->requestmask, opt->option)))
1060 continue;
1061 if (opt->type & NOREQ)
1062 continue;
1063 if (type == DHCP_INFORM &&
1064 (opt->option == DHO_RENEWALTIME ||
1065 opt->option == DHO_REBINDTIME))
1066 continue;
1067 len = (size_t)((p - m) + 2);
1068 if (len > sizeof(*dhcp))
1069 goto toobig;
1070 *p++ = (uint8_t)opt->option;
1072 for (i = 0, opt = ifo->dhcp_override;
1073 i < ifo->dhcp_override_len;
1074 i++, opt++)
1076 /* Check if added above */
1077 for (lp = n_params + 1; lp < p; lp++)
1078 if (*lp == (uint8_t)opt->option)
1079 break;
1080 if (lp < p)
1081 continue;
1082 if (!(opt->type & REQUEST ||
1083 has_option_mask(ifo->requestmask, opt->option)))
1084 continue;
1085 if (opt->type & NOREQ)
1086 continue;
1087 if (type == DHCP_INFORM &&
1088 (opt->option == DHO_RENEWALTIME ||
1089 opt->option == DHO_REBINDTIME))
1090 continue;
1091 len = (size_t)((p - m) + 2);
1092 if (len > sizeof(*dhcp))
1093 goto toobig;
1094 *p++ = (uint8_t)opt->option;
1096 *n_params = (uint8_t)(p - n_params - 1);
1099 /* silence GCC */
1100 auth_len = 0;
1101 auth = NULL;
1103 if (ifo->auth.options & DHCPCD_AUTH_SEND) {
1104 ssize_t alen = dhcp_auth_encode(&ifo->auth,
1105 state->auth.token,
1106 NULL, 0, 4, type, NULL, 0);
1107 if (alen != -1 && alen > UINT8_MAX) {
1108 errno = ERANGE;
1109 alen = -1;
1111 if (alen == -1)
1112 logger(ifp->ctx, LOG_ERR,
1113 "%s: dhcp_auth_encode: %m", ifp->name);
1114 else if (alen != 0) {
1115 auth_len = (uint8_t)alen;
1116 len = (size_t)((p + alen) - m);
1117 if (len > sizeof(*dhcp))
1118 goto toobig;
1119 *p++ = DHO_AUTHENTICATION;
1120 *p++ = auth_len;
1121 auth = p;
1122 p += auth_len;
1126 *p++ = DHO_END;
1128 /* Pad out to the BOOTP minimum message length.
1129 * Some DHCP servers incorrectly require this. */
1130 while (p - m < BOOTP_MESSAGE_LENTH_MIN)
1131 *p++ = DHO_PAD;
1133 len = (size_t)(p - m);
1134 if (ifo->auth.options & DHCPCD_AUTH_SEND && auth_len != 0)
1135 dhcp_auth_encode(&ifo->auth, state->auth.token,
1136 m, len, 4, type, auth, auth_len);
1138 *message = dhcp;
1139 return (ssize_t)len;
1141 toobig:
1142 logger(ifp->ctx, LOG_ERR, "%s: DHCP messge too big", ifp->name);
1143 free(dhcp);
1144 return -1;
1147 static ssize_t
1148 write_lease(const struct interface *ifp, const struct dhcp_message *dhcp)
1150 int fd;
1151 size_t len;
1152 ssize_t bytes;
1153 const uint8_t *e, *p;
1154 uint8_t l;
1155 uint8_t o = 0;
1156 const struct dhcp_state *state = D_CSTATE(ifp);
1158 /* We don't write BOOTP leases */
1159 if (IS_BOOTP(ifp, dhcp)) {
1160 unlink(state->leasefile);
1161 return 0;
1164 logger(ifp->ctx, LOG_DEBUG, "%s: writing lease `%s'",
1165 ifp->name, state->leasefile);
1167 fd = open(state->leasefile, O_WRONLY | O_CREAT | O_TRUNC, 0644);
1168 if (fd == -1)
1169 return -1;
1171 /* Only write as much as we need */
1172 p = dhcp->options;
1173 e = p + sizeof(dhcp->options);
1174 len = sizeof(*dhcp);
1175 while (p < e) {
1176 o = *p;
1177 if (o == DHO_END) {
1178 len = (size_t)(p - (const uint8_t *)dhcp);
1179 break;
1181 p++;
1182 if (o != DHO_PAD) {
1183 l = *p++;
1184 p += l;
1187 bytes = write(fd, dhcp, len);
1188 close(fd);
1189 return bytes;
1192 static struct dhcp_message *
1193 read_lease(struct interface *ifp)
1195 int fd;
1196 struct dhcp_message *dhcp;
1197 struct dhcp_state *state = D_STATE(ifp);
1198 ssize_t bytes;
1199 const uint8_t *auth;
1200 uint8_t type;
1201 size_t auth_len;
1203 fd = open(state->leasefile, O_RDONLY);
1204 if (fd == -1) {
1205 if (errno != ENOENT)
1206 logger(ifp->ctx, LOG_ERR, "%s: open `%s': %m",
1207 ifp->name, state->leasefile);
1208 return NULL;
1210 logger(ifp->ctx, LOG_DEBUG, "%s: reading lease `%s'",
1211 ifp->name, state->leasefile);
1212 dhcp = calloc(1, sizeof(*dhcp));
1213 if (dhcp == NULL) {
1214 close(fd);
1215 return NULL;
1217 bytes = read(fd, dhcp, sizeof(*dhcp));
1218 close(fd);
1219 if (bytes < 0) {
1220 free(dhcp);
1221 return NULL;
1224 /* We may have found a BOOTP server */
1225 if (get_option_uint8(ifp->ctx, &type, dhcp, DHO_MESSAGETYPE) == -1)
1226 type = 0;
1228 /* Authenticate the message */
1229 auth = get_option(ifp->ctx, dhcp, DHO_AUTHENTICATION, &auth_len);
1230 if (auth) {
1231 if (dhcp_auth_validate(&state->auth, &ifp->options->auth,
1232 (uint8_t *)dhcp, sizeof(*dhcp), 4, type,
1233 auth, auth_len) == NULL)
1235 logger(ifp->ctx, LOG_DEBUG,
1236 "%s: dhcp_auth_validate: %m", ifp->name);
1237 free(dhcp);
1238 return NULL;
1240 if (state->auth.token)
1241 logger(ifp->ctx, LOG_DEBUG,
1242 "%s: validated using 0x%08" PRIu32,
1243 ifp->name, state->auth.token->secretid);
1244 else
1245 logger(ifp->ctx, LOG_DEBUG,
1246 "%s: accepted reconfigure key", ifp->name);
1247 } else if ((ifp->options->auth.options & DHCPCD_AUTH_SENDREQUIRE) ==
1248 DHCPCD_AUTH_SENDREQUIRE)
1250 logger(ifp->ctx, LOG_ERR,
1251 "%s: authentication now required", ifp->name);
1252 free(dhcp);
1253 return NULL;
1256 return dhcp;
1259 static const struct dhcp_opt *
1260 dhcp_getoverride(const struct if_options *ifo, unsigned int o)
1262 size_t i;
1263 const struct dhcp_opt *opt;
1265 for (i = 0, opt = ifo->dhcp_override;
1266 i < ifo->dhcp_override_len;
1267 i++, opt++)
1269 if (opt->option == o)
1270 return opt;
1272 return NULL;
1275 static const uint8_t *
1276 dhcp_getoption(struct dhcpcd_ctx *ctx,
1277 size_t *os, unsigned int *code, size_t *len,
1278 const uint8_t *od, size_t ol, struct dhcp_opt **oopt)
1280 size_t i;
1281 struct dhcp_opt *opt;
1283 if (od) {
1284 if (ol < 2) {
1285 errno = EINVAL;
1286 return NULL;
1288 *os = 2; /* code + len */
1289 *code = (unsigned int)*od++;
1290 *len = (size_t)*od++;
1291 if (*len > ol) {
1292 errno = EINVAL;
1293 return NULL;
1297 for (i = 0, opt = ctx->dhcp_opts; i < ctx->dhcp_opts_len; i++, opt++) {
1298 if (opt->option == *code) {
1299 *oopt = opt;
1300 break;
1304 return od;
1307 ssize_t
1308 dhcp_env(char **env, const char *prefix, const struct dhcp_message *dhcp,
1309 const struct interface *ifp)
1311 const struct if_options *ifo;
1312 const uint8_t *p;
1313 struct in_addr addr;
1314 struct in_addr net;
1315 struct in_addr brd;
1316 struct dhcp_opt *opt, *vo;
1317 size_t e, i, pl;
1318 char **ep;
1319 char cidr[4], safe[(BOOTFILE_LEN * 4) + 1];
1320 uint8_t overl = 0;
1321 uint32_t en;
1323 e = 0;
1324 ifo = ifp->options;
1325 get_option_uint8(ifp->ctx, &overl, dhcp, DHO_OPTIONSOVERLOADED);
1327 if (env == NULL) {
1328 if (dhcp->yiaddr || dhcp->ciaddr)
1329 e += 5;
1330 if (*dhcp->bootfile && !(overl & 1))
1331 e++;
1332 if (*dhcp->servername && !(overl & 2))
1333 e++;
1334 for (i = 0, opt = ifp->ctx->dhcp_opts;
1335 i < ifp->ctx->dhcp_opts_len;
1336 i++, opt++)
1338 if (has_option_mask(ifo->nomask, opt->option))
1339 continue;
1340 if (dhcp_getoverride(ifo, opt->option))
1341 continue;
1342 p = get_option(ifp->ctx, dhcp, opt->option, &pl);
1343 if (!p)
1344 continue;
1345 e += dhcp_envoption(ifp->ctx, NULL, NULL, ifp->name,
1346 opt, dhcp_getoption, p, pl);
1348 for (i = 0, opt = ifo->dhcp_override;
1349 i < ifo->dhcp_override_len;
1350 i++, opt++)
1352 if (has_option_mask(ifo->nomask, opt->option))
1353 continue;
1354 p = get_option(ifp->ctx, dhcp, opt->option, &pl);
1355 if (!p)
1356 continue;
1357 e += dhcp_envoption(ifp->ctx, NULL, NULL, ifp->name,
1358 opt, dhcp_getoption, p, pl);
1360 return (ssize_t)e;
1363 ep = env;
1364 if (dhcp->yiaddr || dhcp->ciaddr) {
1365 /* Set some useful variables that we derive from the DHCP
1366 * message but are not necessarily in the options */
1367 addr.s_addr = dhcp->yiaddr ? dhcp->yiaddr : dhcp->ciaddr;
1368 addvar(ifp->ctx, &ep, prefix, "ip_address", inet_ntoa(addr));
1369 if (get_option_addr(ifp->ctx, &net,
1370 dhcp, DHO_SUBNETMASK) == -1)
1372 net.s_addr = ipv4_getnetmask(addr.s_addr);
1373 addvar(ifp->ctx, &ep, prefix,
1374 "subnet_mask", inet_ntoa(net));
1376 snprintf(cidr, sizeof(cidr), "%d", inet_ntocidr(net));
1377 addvar(ifp->ctx, &ep, prefix, "subnet_cidr", cidr);
1378 if (get_option_addr(ifp->ctx, &brd,
1379 dhcp, DHO_BROADCAST) == -1)
1381 brd.s_addr = addr.s_addr | ~net.s_addr;
1382 addvar(ifp->ctx, &ep, prefix,
1383 "broadcast_address", inet_ntoa(brd));
1385 addr.s_addr = dhcp->yiaddr & net.s_addr;
1386 addvar(ifp->ctx, &ep, prefix,
1387 "network_number", inet_ntoa(addr));
1390 if (*dhcp->bootfile && !(overl & 1)) {
1391 print_string(safe, sizeof(safe), STRING,
1392 dhcp->bootfile, sizeof(dhcp->bootfile));
1393 addvar(ifp->ctx, &ep, prefix, "filename", safe);
1395 if (*dhcp->servername && !(overl & 2)) {
1396 print_string(safe, sizeof(safe), STRING | DOMAIN,
1397 dhcp->servername, sizeof(dhcp->servername));
1398 addvar(ifp->ctx, &ep, prefix, "server_name", safe);
1401 /* Zero our indexes */
1402 if (env) {
1403 for (i = 0, opt = ifp->ctx->dhcp_opts;
1404 i < ifp->ctx->dhcp_opts_len;
1405 i++, opt++)
1406 dhcp_zero_index(opt);
1407 for (i = 0, opt = ifp->options->dhcp_override;
1408 i < ifp->options->dhcp_override_len;
1409 i++, opt++)
1410 dhcp_zero_index(opt);
1411 for (i = 0, opt = ifp->ctx->vivso;
1412 i < ifp->ctx->vivso_len;
1413 i++, opt++)
1414 dhcp_zero_index(opt);
1417 for (i = 0, opt = ifp->ctx->dhcp_opts;
1418 i < ifp->ctx->dhcp_opts_len;
1419 i++, opt++)
1421 if (has_option_mask(ifo->nomask, opt->option))
1422 continue;
1423 if (dhcp_getoverride(ifo, opt->option))
1424 continue;
1425 if ((p = get_option(ifp->ctx, dhcp, opt->option, &pl))) {
1426 ep += dhcp_envoption(ifp->ctx, ep, prefix, ifp->name,
1427 opt, dhcp_getoption, p, pl);
1428 if (opt->option == DHO_VIVSO &&
1429 pl > (int)sizeof(uint32_t))
1431 memcpy(&en, p, sizeof(en));
1432 en = ntohl(en);
1433 vo = vivso_find(en, ifp);
1434 if (vo) {
1435 /* Skip over en + total size */
1436 p += sizeof(en) + 1;
1437 pl -= sizeof(en) + 1;
1438 ep += dhcp_envoption(ifp->ctx,
1439 ep, prefix, ifp->name,
1440 vo, dhcp_getoption, p, pl);
1446 for (i = 0, opt = ifo->dhcp_override;
1447 i < ifo->dhcp_override_len;
1448 i++, opt++)
1450 if (has_option_mask(ifo->nomask, opt->option))
1451 continue;
1452 if ((p = get_option(ifp->ctx, dhcp, opt->option, &pl)))
1453 ep += dhcp_envoption(ifp->ctx, ep, prefix, ifp->name,
1454 opt, dhcp_getoption, p, pl);
1457 return ep - env;
1460 static void
1461 get_lease(struct dhcpcd_ctx *ctx,
1462 struct dhcp_lease *lease, const struct dhcp_message *dhcp)
1465 lease->cookie = dhcp->cookie;
1466 /* BOOTP does not set yiaddr for replies when ciaddr is set. */
1467 if (dhcp->yiaddr)
1468 lease->addr.s_addr = dhcp->yiaddr;
1469 else
1470 lease->addr.s_addr = dhcp->ciaddr;
1471 if (get_option_addr(ctx, &lease->net, dhcp, DHO_SUBNETMASK) == -1)
1472 lease->net.s_addr = ipv4_getnetmask(lease->addr.s_addr);
1473 if (get_option_addr(ctx, &lease->brd, dhcp, DHO_BROADCAST) == -1)
1474 lease->brd.s_addr = lease->addr.s_addr | ~lease->net.s_addr;
1475 if (get_option_uint32(ctx, &lease->leasetime, dhcp, DHO_LEASETIME) != 0)
1476 lease->leasetime = ~0U; /* Default to infinite lease */
1477 if (get_option_uint32(ctx, &lease->renewaltime,
1478 dhcp, DHO_RENEWALTIME) != 0)
1479 lease->renewaltime = 0;
1480 if (get_option_uint32(ctx, &lease->rebindtime,
1481 dhcp, DHO_REBINDTIME) != 0)
1482 lease->rebindtime = 0;
1483 if (get_option_addr(ctx, &lease->server, dhcp, DHO_SERVERID) != 0)
1484 lease->server.s_addr = INADDR_ANY;
1487 static const char *
1488 get_dhcp_op(uint8_t type)
1490 const struct dhcp_op *d;
1492 for (d = dhcp_ops; d->name; d++)
1493 if (d->value == type)
1494 return d->name;
1495 return NULL;
1498 static void
1499 dhcp_fallback(void *arg)
1501 struct interface *iface;
1503 iface = (struct interface *)arg;
1504 dhcpcd_selectprofile(iface, iface->options->fallback);
1505 dhcpcd_startinterface(iface);
1508 uint32_t
1509 dhcp_xid(const struct interface *ifp)
1511 uint32_t xid;
1513 if (ifp->options->options & DHCPCD_XID_HWADDR &&
1514 ifp->hwlen >= sizeof(xid))
1515 /* The lower bits are probably more unique on the network */
1516 memcpy(&xid, (ifp->hwaddr + ifp->hwlen) - sizeof(xid),
1517 sizeof(xid));
1518 else
1519 xid = arc4random();
1521 return xid;
1524 void
1525 dhcp_close(struct interface *ifp)
1527 struct dhcp_state *state = D_STATE(ifp);
1529 if (state == NULL)
1530 return;
1532 if (state->raw_fd != -1) {
1533 eloop_event_delete(ifp->ctx->eloop, state->raw_fd);
1534 close(state->raw_fd);
1535 state->raw_fd = -1;
1538 state->interval = 0;
1541 static int
1542 dhcp_openudp(struct interface *ifp)
1544 int s;
1545 struct sockaddr_in sin;
1546 int n;
1547 struct dhcp_state *state;
1548 #ifdef SO_BINDTODEVICE
1549 struct ifreq ifr;
1550 char *p;
1551 #endif
1553 if ((s = xsocket(PF_INET, SOCK_DGRAM, IPPROTO_UDP, O_CLOEXEC)) == -1)
1554 return -1;
1556 n = 1;
1557 if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n)) == -1)
1558 goto eexit;
1559 #ifdef SO_BINDTODEVICE
1560 if (ifp) {
1561 memset(&ifr, 0, sizeof(ifr));
1562 strlcpy(ifr.ifr_name, ifp->name, sizeof(ifr.ifr_name));
1563 /* We can only bind to the real device */
1564 p = strchr(ifr.ifr_name, ':');
1565 if (p)
1566 *p = '\0';
1567 if (setsockopt(s, SOL_SOCKET, SO_BINDTODEVICE, &ifr,
1568 sizeof(ifr)) == -1)
1569 goto eexit;
1571 #endif
1572 memset(&sin, 0, sizeof(sin));
1573 sin.sin_family = AF_INET;
1574 sin.sin_port = htons(DHCP_CLIENT_PORT);
1575 if (ifp) {
1576 state = D_STATE(ifp);
1577 sin.sin_addr.s_addr = state->addr.s_addr;
1578 } else
1579 state = NULL; /* appease gcc */
1580 if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) == -1)
1581 goto eexit;
1583 return s;
1585 eexit:
1586 close(s);
1587 return -1;
1590 static uint16_t
1591 checksum(const void *data, unsigned int len)
1593 const uint8_t *addr = data;
1594 uint32_t sum = 0;
1596 while (len > 1) {
1597 sum += (uint32_t)(addr[0] * 256 + addr[1]);
1598 addr += 2;
1599 len -= 2;
1602 if (len == 1)
1603 sum += (uint32_t)(*addr * 256);
1605 sum = (sum >> 16) + (sum & 0xffff);
1606 sum += (sum >> 16);
1608 return (uint16_t)~htons((uint16_t)sum);
1611 static struct udp_dhcp_packet *
1612 dhcp_makeudppacket(size_t *sz, const uint8_t *data, size_t length,
1613 struct in_addr source, struct in_addr dest)
1615 struct udp_dhcp_packet *udpp;
1616 struct ip *ip;
1617 struct udphdr *udp;
1619 udpp = calloc(1, sizeof(*udpp));
1620 if (udpp == NULL)
1621 return NULL;
1622 ip = &udpp->ip;
1623 udp = &udpp->udp;
1625 /* OK, this is important :)
1626 * We copy the data to our packet and then create a small part of the
1627 * ip structure and an invalid ip_len (basically udp length).
1628 * We then fill the udp structure and put the checksum
1629 * of the whole packet into the udp checksum.
1630 * Finally we complete the ip structure and ip checksum.
1631 * If we don't do the ordering like so then the udp checksum will be
1632 * broken, so find another way of doing it! */
1634 memcpy(&udpp->dhcp, data, length);
1636 ip->ip_p = IPPROTO_UDP;
1637 ip->ip_src.s_addr = source.s_addr;
1638 if (dest.s_addr == 0)
1639 ip->ip_dst.s_addr = INADDR_BROADCAST;
1640 else
1641 ip->ip_dst.s_addr = dest.s_addr;
1643 udp->uh_sport = htons(DHCP_CLIENT_PORT);
1644 udp->uh_dport = htons(DHCP_SERVER_PORT);
1645 udp->uh_ulen = htons((uint16_t)(sizeof(*udp) + length));
1646 ip->ip_len = udp->uh_ulen;
1647 udp->uh_sum = checksum(udpp, sizeof(*udpp));
1649 ip->ip_v = IPVERSION;
1650 ip->ip_hl = sizeof(*ip) >> 2;
1651 ip->ip_id = (uint16_t)arc4random_uniform(UINT16_MAX);
1652 ip->ip_ttl = IPDEFTTL;
1653 ip->ip_len = htons((uint16_t)(sizeof(*ip) + sizeof(*udp) + length));
1654 ip->ip_sum = checksum(ip, sizeof(*ip));
1656 *sz = sizeof(*ip) + sizeof(*udp) + length;
1657 return udpp;
1660 static void
1661 send_message(struct interface *ifp, uint8_t type,
1662 void (*callback)(void *))
1664 struct dhcp_state *state = D_STATE(ifp);
1665 struct if_options *ifo = ifp->options;
1666 struct dhcp_message *dhcp;
1667 struct udp_dhcp_packet *udp;
1668 size_t len;
1669 ssize_t r;
1670 struct in_addr from, to;
1671 in_addr_t a = INADDR_ANY;
1672 struct timespec tv;
1673 int s;
1674 #ifdef IN_IFF_NOTUSEABLE
1675 struct ipv4_addr *ia;
1676 #endif
1678 s = -1;
1679 if (!callback) {
1680 /* No carrier? Don't bother sending the packet. */
1681 if (ifp->carrier == LINK_DOWN)
1682 return;
1683 logger(ifp->ctx, LOG_DEBUG, "%s: sending %s with xid 0x%x",
1684 ifp->name,
1685 ifo->options & DHCPCD_BOOTP ? "BOOTP" : get_dhcp_op(type),
1686 state->xid);
1687 } else {
1688 if (state->interval == 0)
1689 state->interval = 4;
1690 else {
1691 state->interval *= 2;
1692 if (state->interval > 64)
1693 state->interval = 64;
1695 tv.tv_sec = state->interval + DHCP_RAND_MIN;
1696 tv.tv_nsec = (suseconds_t)arc4random_uniform(
1697 (DHCP_RAND_MAX - DHCP_RAND_MIN) * NSEC_PER_SEC);
1698 timespecnorm(&tv);
1699 /* No carrier? Don't bother sending the packet.
1700 * However, we do need to advance the timeout. */
1701 if (ifp->carrier == LINK_DOWN)
1702 goto fail;
1703 logger(ifp->ctx, LOG_DEBUG,
1704 "%s: sending %s (xid 0x%x), next in %0.1f seconds",
1705 ifp->name,
1706 ifo->options & DHCPCD_BOOTP ? "BOOTP" : get_dhcp_op(type),
1707 state->xid,
1708 timespec_to_double(&tv));
1711 if (dhcp_open(ifp) == -1)
1712 return;
1714 if (state->added && !(state->added & STATE_FAKE) &&
1715 state->addr.s_addr != INADDR_ANY &&
1716 state->new != NULL &&
1717 #ifdef IN_IFF_NOTUSEABLE
1718 ((ia = ipv4_iffindaddr(ifp, &state->addr, NULL)) &&
1719 !(ia->addr_flags & IN_IFF_NOTUSEABLE)) &&
1720 #endif
1721 (state->lease.server.s_addr ||
1722 ifp->options->options & DHCPCD_INFORM) &&
1723 !IS_BOOTP(ifp, state->new))
1725 s = dhcp_openudp(ifp);
1726 if (s == -1) {
1727 if (errno != EADDRINUSE)
1728 logger(ifp->ctx, LOG_ERR,
1729 "%s: dhcp_openudp: %m", ifp->name);
1730 /* We cannot renew */
1731 a = state->addr.s_addr;
1732 state->addr.s_addr = INADDR_ANY;
1736 r = make_message(&dhcp, ifp, type);
1737 if (a != INADDR_ANY)
1738 state->addr.s_addr = a;
1739 if (r == -1)
1740 goto fail;
1741 len = (size_t)r;
1742 from.s_addr = dhcp->ciaddr;
1743 if (s != -1 && from.s_addr != INADDR_ANY)
1744 to.s_addr = state->lease.server.s_addr;
1745 else
1746 to.s_addr = INADDR_ANY;
1747 if (to.s_addr && to.s_addr != INADDR_BROADCAST) {
1748 struct sockaddr_in sin;
1750 memset(&sin, 0, sizeof(sin));
1751 sin.sin_family = AF_INET;
1752 sin.sin_addr.s_addr = to.s_addr;
1753 sin.sin_port = htons(DHCP_SERVER_PORT);
1754 r = sendto(s, (uint8_t *)dhcp, len, 0,
1755 (struct sockaddr *)&sin, sizeof(sin));
1756 if (r == -1)
1757 logger(ifp->ctx, LOG_ERR,
1758 "%s: dhcp_sendpacket: %m", ifp->name);
1759 } else {
1760 size_t ulen;
1762 r = 0;
1763 udp = dhcp_makeudppacket(&ulen, (uint8_t *)dhcp, len, from, to);
1764 if (udp == NULL) {
1765 logger(ifp->ctx, LOG_ERR, "dhcp_makeudppacket: %m");
1766 } else {
1767 r = if_sendrawpacket(ifp, ETHERTYPE_IP,
1768 (uint8_t *)udp, ulen);
1769 free(udp);
1771 /* If we failed to send a raw packet this normally means
1772 * we don't have the ability to work beneath the IP layer
1773 * for this interface.
1774 * As such we remove it from consideration without actually
1775 * stopping the interface. */
1776 if (r == -1) {
1777 logger(ifp->ctx, LOG_ERR,
1778 "%s: if_sendrawpacket: %m", ifp->name);
1779 switch(errno) {
1780 case ENETDOWN:
1781 case ENETRESET:
1782 case ENETUNREACH:
1783 break;
1784 default:
1785 if (!(ifp->ctx->options & DHCPCD_TEST))
1786 dhcp_drop(ifp, "FAIL");
1787 dhcp_free(ifp);
1788 eloop_timeout_delete(ifp->ctx->eloop,
1789 NULL, ifp);
1790 callback = NULL;
1794 free(dhcp);
1796 fail:
1797 if (s != -1)
1798 close(s);
1800 /* Even if we fail to send a packet we should continue as we are
1801 * as our failure timeouts will change out codepath when needed. */
1802 if (callback)
1803 eloop_timeout_add_tv(ifp->ctx->eloop, &tv, callback, ifp);
1806 static void
1807 send_inform(void *arg)
1810 send_message((struct interface *)arg, DHCP_INFORM, send_inform);
1813 static void
1814 send_discover(void *arg)
1817 send_message((struct interface *)arg, DHCP_DISCOVER, send_discover);
1820 static void
1821 send_request(void *arg)
1824 send_message((struct interface *)arg, DHCP_REQUEST, send_request);
1827 static void
1828 send_renew(void *arg)
1831 send_message((struct interface *)arg, DHCP_REQUEST, send_renew);
1834 static void
1835 send_rebind(void *arg)
1838 send_message((struct interface *)arg, DHCP_REQUEST, send_rebind);
1841 void
1842 dhcp_discover(void *arg)
1844 struct interface *ifp = arg;
1845 struct dhcp_state *state = D_STATE(ifp);
1846 struct if_options *ifo = ifp->options;
1848 state->state = DHS_DISCOVER;
1849 state->xid = dhcp_xid(ifp);
1850 eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
1851 if (ifo->fallback)
1852 eloop_timeout_add_sec(ifp->ctx->eloop,
1853 ifo->reboot, dhcp_fallback, ifp);
1854 else if (ifo->options & DHCPCD_IPV4LL)
1855 eloop_timeout_add_sec(ifp->ctx->eloop,
1856 ifo->reboot, ipv4ll_start, ifp);
1857 if (ifo->options & DHCPCD_REQUEST)
1858 logger(ifp->ctx, LOG_INFO,
1859 "%s: soliciting a DHCP lease (requesting %s)",
1860 ifp->name, inet_ntoa(ifo->req_addr));
1861 else
1862 logger(ifp->ctx, LOG_INFO,
1863 "%s: soliciting a %s lease",
1864 ifp->name, ifo->options & DHCPCD_BOOTP ? "BOOTP" : "DHCP");
1865 send_discover(ifp);
1868 static void
1869 dhcp_request(void *arg)
1871 struct interface *ifp = arg;
1872 struct dhcp_state *state = D_STATE(ifp);
1874 state->state = DHS_REQUEST;
1875 send_request(ifp);
1878 static void
1879 dhcp_expire(void *arg)
1881 struct interface *ifp = arg;
1882 struct dhcp_state *state = D_STATE(ifp);
1884 logger(ifp->ctx, LOG_ERR, "%s: DHCP lease expired", ifp->name);
1885 eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
1886 dhcp_drop(ifp, "EXPIRE");
1887 unlink(state->leasefile);
1888 state->interval = 0;
1889 dhcp_discover(ifp);
1892 static void
1893 dhcp_decline(struct interface *ifp)
1896 send_message(ifp, DHCP_DECLINE, NULL);
1899 static void
1900 dhcp_renew(void *arg)
1902 struct interface *ifp = arg;
1903 struct dhcp_state *state = D_STATE(ifp);
1904 struct dhcp_lease *lease = &state->lease;
1906 logger(ifp->ctx, LOG_DEBUG, "%s: renewing lease of %s",
1907 ifp->name, inet_ntoa(lease->addr));
1908 logger(ifp->ctx, LOG_DEBUG, "%s: rebind in %"PRIu32" seconds,"
1909 " expire in %"PRIu32" seconds",
1910 ifp->name, lease->rebindtime - lease->renewaltime,
1911 lease->leasetime - lease->renewaltime);
1912 state->state = DHS_RENEW;
1913 state->xid = dhcp_xid(ifp);
1914 send_renew(ifp);
1917 static void
1918 dhcp_arp_announced(struct arp_state *astate)
1921 arp_close(astate->iface);
1924 static void
1925 dhcp_rebind(void *arg)
1927 struct interface *ifp = arg;
1928 struct dhcp_state *state = D_STATE(ifp);
1929 struct dhcp_lease *lease = &state->lease;
1931 logger(ifp->ctx, LOG_WARNING,
1932 "%s: failed to renew DHCP, rebinding", ifp->name);
1933 logger(ifp->ctx, LOG_DEBUG, "%s: expire in %"PRIu32" seconds",
1934 ifp->name, lease->leasetime - lease->rebindtime);
1935 state->state = DHS_REBIND;
1936 eloop_timeout_delete(ifp->ctx->eloop, send_renew, ifp);
1937 state->lease.server.s_addr = 0;
1938 ifp->options->options &= ~(DHCPCD_CSR_WARNED |
1939 DHCPCD_ROUTER_HOST_ROUTE_WARNED);
1940 send_rebind(ifp);
1943 static void
1944 dhcp_arp_probed(struct arp_state *astate)
1946 struct dhcp_state *state;
1947 struct if_options *ifo;
1949 state = D_STATE(astate->iface);
1950 ifo = astate->iface->options;
1951 if (state->arping_index < ifo->arping_len) {
1952 /* We didn't find a profile for this
1953 * address or hwaddr, so move to the next
1954 * arping profile */
1955 if (++state->arping_index < ifo->arping_len) {
1956 astate->addr.s_addr =
1957 ifo->arping[state->arping_index - 1];
1958 arp_probe(astate);
1960 dhcpcd_startinterface(astate->iface);
1961 return;
1964 logger(astate->iface->ctx, LOG_DEBUG, "%s: DAD completed for %s",
1965 astate->iface->name, inet_ntoa(astate->addr));
1966 dhcp_bind(astate->iface);
1967 arp_announce(astate);
1969 /* Stop IPv4LL now we have a working DHCP address */
1970 ipv4ll_drop(astate->iface);
1973 static void
1974 dhcp_arp_conflicted(struct arp_state *astate, const struct arp_msg *amsg)
1976 struct interface *ifp;
1977 struct dhcp_state *state;
1978 struct if_options *ifo;
1980 ifp = astate->iface;
1981 ifo = ifp->options;
1982 state = D_STATE(ifp);
1983 if (state->arping_index &&
1984 state->arping_index <= ifo->arping_len &&
1985 amsg &&
1986 (amsg->sip.s_addr == ifo->arping[state->arping_index - 1] ||
1987 (amsg->sip.s_addr == 0 &&
1988 amsg->tip.s_addr == ifo->arping[state->arping_index - 1])))
1990 char buf[HWADDR_LEN * 3];
1992 astate->failed.s_addr = ifo->arping[state->arping_index - 1];
1993 arp_report_conflicted(astate, amsg);
1994 hwaddr_ntoa(amsg->sha, ifp->hwlen, buf, sizeof(buf));
1995 if (dhcpcd_selectprofile(ifp, buf) == -1 &&
1996 dhcpcd_selectprofile(ifp,
1997 inet_ntoa(astate->failed)) == -1)
1999 /* We didn't find a profile for this
2000 * address or hwaddr, so move to the next
2001 * arping profile */
2002 dhcp_arp_probed(astate);
2003 return;
2005 dhcp_close(ifp);
2006 arp_free(astate);
2007 eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
2008 dhcpcd_startinterface(ifp);
2011 /* RFC 2131 3.1.5, Client-server interaction
2012 * NULL amsg means IN_IFF_DUPLICATED */
2013 if (amsg == NULL || (state->offer &&
2014 (amsg->sip.s_addr == state->offer->yiaddr ||
2015 (amsg->sip.s_addr == 0 &&
2016 amsg->tip.s_addr == state->offer->yiaddr))))
2018 #ifdef IN_IFF_DUPLICATED
2019 struct ipv4_addr *ia;
2020 #endif
2022 if (amsg)
2023 astate->failed.s_addr = state->offer->yiaddr;
2024 else
2025 astate->failed = astate->addr;
2026 arp_report_conflicted(astate, amsg);
2027 unlink(state->leasefile);
2028 if (!(ifp->options->options & DHCPCD_STATIC) &&
2029 !state->lease.frominfo)
2030 dhcp_decline(ifp);
2031 #ifdef IN_IFF_DUPLICATED
2032 ia = ipv4_iffindaddr(ifp, &astate->addr, NULL);
2033 if (ia)
2034 ipv4_deladdr(ifp, &ia->addr, &ia->net, 1);
2035 #endif
2036 arp_free(astate);
2037 eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
2038 eloop_timeout_add_sec(ifp->ctx->eloop,
2039 DHCP_RAND_MAX, dhcp_discover, ifp);
2043 void
2044 dhcp_bind(struct interface *ifp)
2046 struct dhcp_state *state = D_STATE(ifp);
2047 struct if_options *ifo = ifp->options;
2048 struct dhcp_lease *lease = &state->lease;
2050 state->reason = NULL;
2051 free(state->old);
2052 state->old = state->new;
2053 state->new = state->offer;
2054 state->offer = NULL;
2055 get_lease(ifp->ctx, lease, state->new);
2056 if (ifo->options & DHCPCD_STATIC) {
2057 logger(ifp->ctx, LOG_INFO, "%s: using static address %s/%d",
2058 ifp->name, inet_ntoa(lease->addr),
2059 inet_ntocidr(lease->net));
2060 lease->leasetime = ~0U;
2061 state->reason = "STATIC";
2062 } else if (ifo->options & DHCPCD_INFORM) {
2063 if (ifo->req_addr.s_addr != 0)
2064 lease->addr.s_addr = ifo->req_addr.s_addr;
2065 else
2066 lease->addr.s_addr = state->addr.s_addr;
2067 logger(ifp->ctx, LOG_INFO, "%s: received approval for %s",
2068 ifp->name, inet_ntoa(lease->addr));
2069 lease->leasetime = ~0U;
2070 state->reason = "INFORM";
2071 } else {
2072 if (lease->frominfo)
2073 state->reason = "TIMEOUT";
2074 if (lease->leasetime == ~0U) {
2075 lease->renewaltime =
2076 lease->rebindtime =
2077 lease->leasetime;
2078 logger(ifp->ctx, LOG_INFO, "%s: leased %s for infinity",
2079 ifp->name, inet_ntoa(lease->addr));
2080 } else {
2081 if (lease->leasetime < DHCP_MIN_LEASE) {
2082 logger(ifp->ctx, LOG_WARNING,
2083 "%s: minimum lease is %d seconds",
2084 ifp->name, DHCP_MIN_LEASE);
2085 lease->leasetime = DHCP_MIN_LEASE;
2087 if (lease->rebindtime == 0)
2088 lease->rebindtime =
2089 (uint32_t)(lease->leasetime * T2);
2090 else if (lease->rebindtime >= lease->leasetime) {
2091 lease->rebindtime =
2092 (uint32_t)(lease->leasetime * T2);
2093 logger(ifp->ctx, LOG_WARNING,
2094 "%s: rebind time greater than lease "
2095 "time, forcing to %"PRIu32" seconds",
2096 ifp->name, lease->rebindtime);
2098 if (lease->renewaltime == 0)
2099 lease->renewaltime =
2100 (uint32_t)(lease->leasetime * T1);
2101 else if (lease->renewaltime > lease->rebindtime) {
2102 lease->renewaltime =
2103 (uint32_t)(lease->leasetime * T1);
2104 logger(ifp->ctx, LOG_WARNING,
2105 "%s: renewal time greater than rebind "
2106 "time, forcing to %"PRIu32" seconds",
2107 ifp->name, lease->renewaltime);
2109 logger(ifp->ctx,
2110 lease->addr.s_addr == state->addr.s_addr &&
2111 !(state->added & STATE_FAKE) ?
2112 LOG_DEBUG : LOG_INFO,
2113 "%s: leased %s for %"PRIu32" seconds", ifp->name,
2114 inet_ntoa(lease->addr), lease->leasetime);
2117 if (ifp->ctx->options & DHCPCD_TEST) {
2118 state->reason = "TEST";
2119 script_runreason(ifp, state->reason);
2120 eloop_exit(ifp->ctx->eloop, EXIT_SUCCESS);
2121 return;
2123 if (state->reason == NULL) {
2124 if (state->old && !(state->added & STATE_FAKE)) {
2125 if (state->old->yiaddr == state->new->yiaddr &&
2126 lease->server.s_addr)
2127 state->reason = "RENEW";
2128 else
2129 state->reason = "REBIND";
2130 } else if (state->state == DHS_REBOOT)
2131 state->reason = "REBOOT";
2132 else
2133 state->reason = "BOUND";
2135 if (lease->leasetime == ~0U)
2136 lease->renewaltime = lease->rebindtime = lease->leasetime;
2137 else {
2138 eloop_timeout_add_sec(ifp->ctx->eloop,
2139 (time_t)lease->renewaltime, dhcp_renew, ifp);
2140 eloop_timeout_add_sec(ifp->ctx->eloop,
2141 (time_t)lease->rebindtime, dhcp_rebind, ifp);
2142 eloop_timeout_add_sec(ifp->ctx->eloop,
2143 (time_t)lease->leasetime, dhcp_expire, ifp);
2144 logger(ifp->ctx, LOG_DEBUG,
2145 "%s: renew in %"PRIu32" seconds, rebind in %"PRIu32
2146 " seconds",
2147 ifp->name, lease->renewaltime, lease->rebindtime);
2149 state->state = DHS_BOUND;
2150 if (!state->lease.frominfo &&
2151 !(ifo->options & (DHCPCD_INFORM | DHCPCD_STATIC)))
2152 if (write_lease(ifp, state->new) == -1)
2153 logger(ifp->ctx, LOG_ERR,
2154 "%s: write_lease: %m", __func__);
2156 ipv4_applyaddr(ifp);
2159 static void
2160 dhcp_timeout(void *arg)
2162 struct interface *ifp = arg;
2163 struct dhcp_state *state = D_STATE(ifp);
2165 dhcp_bind(ifp);
2166 state->interval = 0;
2167 dhcp_discover(ifp);
2170 struct dhcp_message *
2171 dhcp_message_new(const struct in_addr *addr, const struct in_addr *mask)
2173 struct dhcp_message *dhcp;
2174 uint8_t *p;
2176 dhcp = calloc(1, sizeof(*dhcp));
2177 if (dhcp == NULL)
2178 return NULL;
2179 dhcp->yiaddr = addr->s_addr;
2180 dhcp->cookie = htonl(MAGIC_COOKIE);
2181 p = dhcp->options;
2182 if (mask && mask->s_addr != INADDR_ANY) {
2183 *p++ = DHO_SUBNETMASK;
2184 *p++ = sizeof(mask->s_addr);
2185 memcpy(p, &mask->s_addr, sizeof(mask->s_addr));
2186 p+= sizeof(mask->s_addr);
2188 *p++ = DHO_END;
2189 return dhcp;
2192 static void
2193 dhcp_arp_bind(struct interface *ifp)
2195 const struct dhcp_state *state;
2196 struct in_addr addr;
2197 struct ipv4_addr *ia;
2198 struct arp_state *astate;
2200 eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
2202 state = D_CSTATE(ifp);
2203 addr.s_addr = state->offer->yiaddr;
2204 /* If the interface already has the address configured
2205 * then we can't ARP for duplicate detection. */
2206 ia = ipv4_findaddr(ifp->ctx, &addr);
2208 #ifdef IN_IFF_TENTATIVE
2209 if (ia == NULL || ia->addr_flags & IN_IFF_NOTUSEABLE) {
2210 if ((astate = arp_new(ifp, &addr)) != NULL) {
2211 astate->probed_cb = dhcp_arp_probed;
2212 astate->conflicted_cb = dhcp_arp_conflicted;
2213 astate->announced_cb = dhcp_arp_announced;
2215 if (ia == NULL) {
2216 struct dhcp_lease l;
2218 get_lease(ifp->ctx, &l, state->offer);
2219 /* Add the address now, let the kernel handle DAD. */
2220 ipv4_addaddr(ifp, &l.addr, &l.net, &l.brd);
2221 } else
2222 logger(ifp->ctx, LOG_INFO, "%s: waiting for DAD on %s",
2223 ifp->name, inet_ntoa(addr));
2224 return;
2226 #else
2227 if (ifp->options->options & DHCPCD_ARP && ia == NULL) {
2228 struct dhcp_lease l;
2230 get_lease(ifp->ctx, &l, state->offer);
2231 logger(ifp->ctx, LOG_INFO, "%s: probing static address %s/%d",
2232 ifp->name, inet_ntoa(l.addr), inet_ntocidr(l.net));
2233 if ((astate = arp_new(ifp, &addr)) != NULL) {
2234 astate->probed_cb = dhcp_arp_probed;
2235 astate->conflicted_cb = dhcp_arp_conflicted;
2236 astate->announced_cb = dhcp_arp_announced;
2237 /* We need to handle DAD. */
2238 arp_probe(astate);
2240 return;
2242 #endif
2244 dhcp_bind(ifp);
2247 static void
2248 dhcp_static(struct interface *ifp)
2250 struct if_options *ifo;
2251 struct dhcp_state *state;
2252 struct ipv4_addr *ia;
2254 state = D_STATE(ifp);
2255 ifo = ifp->options;
2257 ia = NULL;
2258 if (ifo->req_addr.s_addr == INADDR_ANY &&
2259 (ia = ipv4_iffindaddr(ifp, NULL, NULL)) == NULL)
2261 logger(ifp->ctx, LOG_INFO,
2262 "%s: waiting for 3rd party to "
2263 "configure IP address",
2264 ifp->name);
2265 state->reason = "3RDPARTY";
2266 script_runreason(ifp, state->reason);
2267 return;
2270 state->offer = dhcp_message_new(ia ? &ia->addr : &ifo->req_addr,
2271 ia ? &ia->net : &ifo->req_mask);
2272 if (state->offer)
2273 dhcp_arp_bind(ifp);
2276 void
2277 dhcp_inform(struct interface *ifp)
2279 struct dhcp_state *state;
2280 struct if_options *ifo;
2281 struct ipv4_addr *ap;
2283 state = D_STATE(ifp);
2284 ifo = ifp->options;
2285 if (ifp->ctx->options & DHCPCD_TEST) {
2286 state->addr.s_addr = ifo->req_addr.s_addr;
2287 state->net.s_addr = ifo->req_mask.s_addr;
2288 } else {
2289 if (ifo->req_addr.s_addr == INADDR_ANY) {
2290 state = D_STATE(ifp);
2291 ap = ipv4_iffindaddr(ifp, NULL, NULL);
2292 if (ap == NULL) {
2293 logger(ifp->ctx, LOG_INFO,
2294 "%s: waiting for 3rd party to "
2295 "configure IP address",
2296 ifp->name);
2297 state->reason = "3RDPARTY";
2298 script_runreason(ifp, state->reason);
2299 return;
2301 state->offer =
2302 dhcp_message_new(&ap->addr, &ap->net);
2303 } else
2304 state->offer =
2305 dhcp_message_new(&ifo->req_addr, &ifo->req_mask);
2306 if (state->offer) {
2307 ifo->options |= DHCPCD_STATIC;
2308 dhcp_bind(ifp);
2309 ifo->options &= ~DHCPCD_STATIC;
2313 state->state = DHS_INFORM;
2314 state->xid = dhcp_xid(ifp);
2315 send_inform(ifp);
2318 void
2319 dhcp_reboot_newopts(struct interface *ifp, unsigned long long oldopts)
2321 struct if_options *ifo;
2322 struct dhcp_state *state = D_STATE(ifp);
2324 if (state == NULL)
2325 return;
2326 ifo = ifp->options;
2327 if ((ifo->options & (DHCPCD_INFORM | DHCPCD_STATIC) &&
2328 state->addr.s_addr != ifo->req_addr.s_addr) ||
2329 (oldopts & (DHCPCD_INFORM | DHCPCD_STATIC) &&
2330 !(ifo->options & (DHCPCD_INFORM | DHCPCD_STATIC))))
2332 dhcp_drop(ifp, "EXPIRE");
2336 static void
2337 dhcp_reboot(struct interface *ifp)
2339 struct if_options *ifo;
2340 struct dhcp_state *state = D_STATE(ifp);
2342 if (state == NULL)
2343 return;
2344 ifo = ifp->options;
2345 state->state = DHS_REBOOT;
2346 state->interval = 0;
2348 if (ifo->options & DHCPCD_LINK && ifp->carrier == LINK_DOWN) {
2349 logger(ifp->ctx, LOG_INFO,
2350 "%s: waiting for carrier", ifp->name);
2351 return;
2353 if (ifo->options & DHCPCD_STATIC) {
2354 dhcp_static(ifp);
2355 return;
2357 if (ifo->options & DHCPCD_INFORM) {
2358 logger(ifp->ctx, LOG_INFO, "%s: informing address of %s",
2359 ifp->name, inet_ntoa(state->lease.addr));
2360 dhcp_inform(ifp);
2361 return;
2363 if (ifo->reboot == 0 || state->offer == NULL) {
2364 dhcp_discover(ifp);
2365 return;
2367 if (state->offer->cookie == 0)
2368 return;
2370 logger(ifp->ctx, LOG_INFO, "%s: rebinding lease of %s",
2371 ifp->name, inet_ntoa(state->lease.addr));
2372 state->xid = dhcp_xid(ifp);
2373 state->lease.server.s_addr = 0;
2374 eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
2376 /* Need to add this before dhcp_expire and friends. */
2377 if (!ifo->fallback && ifo->options & DHCPCD_IPV4LL)
2378 eloop_timeout_add_sec(ifp->ctx->eloop,
2379 ifo->reboot, ipv4ll_start, ifp);
2381 if (ifo->options & DHCPCD_LASTLEASE && state->lease.frominfo)
2382 eloop_timeout_add_sec(ifp->ctx->eloop,
2383 ifo->reboot, dhcp_timeout, ifp);
2384 else if (!(ifo->options & DHCPCD_INFORM))
2385 eloop_timeout_add_sec(ifp->ctx->eloop,
2386 ifo->reboot, dhcp_expire, ifp);
2388 /* Don't bother ARP checking as the server could NAK us first.
2389 * Don't call dhcp_request as that would change the state */
2390 send_request(ifp);
2393 void
2394 dhcp_drop(struct interface *ifp, const char *reason)
2396 struct dhcp_state *state;
2397 #ifdef RELEASE_SLOW
2398 struct timespec ts;
2399 #endif
2401 state = D_STATE(ifp);
2402 /* dhcp_start may just have been called and we don't yet have a state
2403 * but we do have a timeout, so punt it. */
2404 if (state == NULL) {
2405 eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
2406 return;
2409 if (ifp->options->options & DHCPCD_RELEASE) {
2410 /* Failure to send the release may cause this function to
2411 * re-enter so guard by setting the state. */
2412 if (state->state == DHS_RELEASE)
2413 return;
2414 state->state = DHS_RELEASE;
2416 unlink(state->leasefile);
2417 if (ifp->carrier != LINK_DOWN &&
2418 state->new != NULL &&
2419 state->lease.server.s_addr != INADDR_ANY)
2421 logger(ifp->ctx, LOG_INFO, "%s: releasing lease of %s",
2422 ifp->name, inet_ntoa(state->lease.addr));
2423 state->xid = dhcp_xid(ifp);
2424 send_message(ifp, DHCP_RELEASE, NULL);
2425 #ifdef RELEASE_SLOW
2426 /* Give the packet a chance to go */
2427 ts.tv_sec = RELEASE_DELAY_S;
2428 ts.tv_nsec = RELEASE_DELAY_NS;
2429 nanosleep(&ts, NULL);
2430 #endif
2434 eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
2435 dhcp_auth_reset(&state->auth);
2436 dhcp_close(ifp);
2438 free(state->offer);
2439 state->offer = NULL;
2440 free(state->old);
2441 state->old = state->new;
2442 state->new = NULL;
2443 state->reason = reason;
2444 ipv4_applyaddr(ifp);
2445 free(state->old);
2446 state->old = NULL;
2447 state->lease.addr.s_addr = 0;
2448 ifp->options->options &= ~(DHCPCD_CSR_WARNED |
2449 DHCPCD_ROUTER_HOST_ROUTE_WARNED);
2452 static void
2453 log_dhcp1(int lvl, const char *msg,
2454 const struct interface *ifp, const struct dhcp_message *dhcp,
2455 const struct in_addr *from, int ad)
2457 const char *tfrom;
2458 char *a, sname[sizeof(dhcp->servername) * 4];
2459 struct in_addr addr;
2460 int r;
2462 if (strcmp(msg, "NAK:") == 0) {
2463 a = get_option_string(ifp->ctx, dhcp, DHO_MESSAGE);
2464 if (a) {
2465 char *tmp;
2466 size_t al, tmpl;
2468 al = strlen(a);
2469 tmpl = (al * 4) + 1;
2470 tmp = malloc(tmpl);
2471 if (tmp == NULL) {
2472 logger(ifp->ctx, LOG_ERR, "%s: %m", __func__);
2473 free(a);
2474 return;
2476 print_string(tmp, tmpl, STRING, (uint8_t *)a, al);
2477 free(a);
2478 a = tmp;
2480 } else if (ad && dhcp->yiaddr != 0) {
2481 addr.s_addr = dhcp->yiaddr;
2482 a = strdup(inet_ntoa(addr));
2483 if (a == NULL) {
2484 logger(ifp->ctx, LOG_ERR, "%s: %m", __func__);
2485 return;
2487 } else
2488 a = NULL;
2490 tfrom = "from";
2491 r = get_option_addr(ifp->ctx, &addr, dhcp, DHO_SERVERID);
2492 if (dhcp->servername[0] && r == 0) {
2493 print_string(sname, sizeof(sname), STRING,
2494 dhcp->servername, strlen((const char *)dhcp->servername));
2495 if (a == NULL)
2496 logger(ifp->ctx, lvl, "%s: %s %s %s `%s'",
2497 ifp->name, msg, tfrom, inet_ntoa(addr), sname);
2498 else
2499 logger(ifp->ctx, lvl, "%s: %s %s %s %s `%s'",
2500 ifp->name, msg, a, tfrom, inet_ntoa(addr), sname);
2501 } else {
2502 if (r != 0) {
2503 tfrom = "via";
2504 addr = *from;
2506 if (a == NULL)
2507 logger(ifp->ctx, lvl, "%s: %s %s %s",
2508 ifp->name, msg, tfrom, inet_ntoa(addr));
2509 else
2510 logger(ifp->ctx, lvl, "%s: %s %s %s %s",
2511 ifp->name, msg, a, tfrom, inet_ntoa(addr));
2513 free(a);
2516 static void
2517 log_dhcp(int lvl, const char *msg,
2518 const struct interface *ifp, const struct dhcp_message *dhcp,
2519 const struct in_addr *from)
2522 log_dhcp1(lvl, msg, ifp, dhcp, from, 1);
2525 static int
2526 blacklisted_ip(const struct if_options *ifo, in_addr_t addr)
2528 size_t i;
2530 for (i = 0; i < ifo->blacklist_len; i += 2)
2531 if (ifo->blacklist[i] == (addr & ifo->blacklist[i + 1]))
2532 return 1;
2533 return 0;
2536 static int
2537 whitelisted_ip(const struct if_options *ifo, in_addr_t addr)
2539 size_t i;
2541 if (ifo->whitelist_len == 0)
2542 return -1;
2543 for (i = 0; i < ifo->whitelist_len; i += 2)
2544 if (ifo->whitelist[i] == (addr & ifo->whitelist[i + 1]))
2545 return 1;
2546 return 0;
2549 static void
2550 dhcp_handledhcp(struct interface *ifp, struct dhcp_message **dhcpp,
2551 const struct in_addr *from)
2553 struct dhcp_state *state = D_STATE(ifp);
2554 struct if_options *ifo = ifp->options;
2555 struct dhcp_message *dhcp = *dhcpp;
2556 struct dhcp_lease *lease = &state->lease;
2557 uint8_t type, tmp;
2558 const uint8_t *auth;
2559 struct in_addr addr;
2560 unsigned int i;
2561 size_t auth_len;
2562 char *msg;
2563 #ifdef IN_IFF_DUPLICATED
2564 struct ipv4_addr *ia;
2565 #endif
2567 /* We may have found a BOOTP server */
2568 if (get_option_uint8(ifp->ctx, &type, dhcp, DHO_MESSAGETYPE) == -1)
2569 type = 0;
2570 else if (ifo->options & DHCPCD_BOOTP) {
2571 logger(ifp->ctx, LOG_DEBUG,
2572 "%s: ignoring DHCP reply (excpecting BOOTP)",
2573 ifp->name);
2574 return;
2577 /* Authenticate the message */
2578 auth = get_option(ifp->ctx, dhcp, DHO_AUTHENTICATION, &auth_len);
2579 if (auth) {
2580 if (dhcp_auth_validate(&state->auth, &ifo->auth,
2581 (uint8_t *)*dhcpp, sizeof(**dhcpp), 4, type,
2582 auth, auth_len) == NULL)
2584 logger(ifp->ctx, LOG_DEBUG,
2585 "%s: dhcp_auth_validate: %m", ifp->name);
2586 log_dhcp1(LOG_ERR, "authentication failed",
2587 ifp, dhcp, from, 0);
2588 return;
2590 if (state->auth.token)
2591 logger(ifp->ctx, LOG_DEBUG,
2592 "%s: validated using 0x%08" PRIu32,
2593 ifp->name, state->auth.token->secretid);
2594 else
2595 logger(ifp->ctx, LOG_DEBUG,
2596 "%s: accepted reconfigure key", ifp->name);
2597 } else if (ifo->auth.options & DHCPCD_AUTH_SEND) {
2598 if (ifo->auth.options & DHCPCD_AUTH_REQUIRE) {
2599 log_dhcp1(LOG_ERR, "no authentication",
2600 ifp, dhcp, from, 0);
2601 return;
2603 log_dhcp1(LOG_WARNING, "no authentication",
2604 ifp, dhcp, from, 0);
2607 /* RFC 3203 */
2608 if (type == DHCP_FORCERENEW) {
2609 if (from->s_addr == INADDR_ANY ||
2610 from->s_addr == INADDR_BROADCAST)
2612 log_dhcp(LOG_ERR, "discarding Force Renew",
2613 ifp, dhcp, from);
2614 return;
2616 if (auth == NULL) {
2617 log_dhcp(LOG_ERR, "unauthenticated Force Renew",
2618 ifp, dhcp, from);
2619 if (ifo->auth.options & DHCPCD_AUTH_REQUIRE)
2620 return;
2622 if (state->state != DHS_BOUND && state->state != DHS_INFORM) {
2623 log_dhcp(LOG_DEBUG, "not bound, ignoring Force Renew",
2624 ifp, dhcp, from);
2625 return;
2627 log_dhcp(LOG_ERR, "Force Renew from", ifp, dhcp, from);
2628 /* The rebind and expire timings are still the same, we just
2629 * enter the renew state early */
2630 if (state->state == DHS_BOUND) {
2631 eloop_timeout_delete(ifp->ctx->eloop,
2632 dhcp_renew, ifp);
2633 dhcp_renew(ifp);
2634 } else {
2635 eloop_timeout_delete(ifp->ctx->eloop,
2636 send_inform, ifp);
2637 dhcp_inform(ifp);
2639 return;
2642 if (state->state == DHS_BOUND) {
2643 /* Before we supported FORCERENEW we closed off the raw
2644 * port so we effectively ignored all messages.
2645 * As such we'll not log by default here. */
2646 //log_dhcp(LOG_DEBUG, "bound, ignoring", iface, dhcp, from);
2647 return;
2650 /* Ensure it's the right transaction */
2651 if (state->xid != ntohl(dhcp->xid)) {
2652 logger(ifp->ctx, LOG_DEBUG,
2653 "%s: wrong xid 0x%x (expecting 0x%x) from %s",
2654 ifp->name, ntohl(dhcp->xid), state->xid,
2655 inet_ntoa(*from));
2656 return;
2658 /* reset the message counter */
2659 state->interval = 0;
2661 /* Ensure that no reject options are present */
2662 for (i = 1; i < 255; i++) {
2663 if (has_option_mask(ifo->rejectmask, i) &&
2664 get_option_uint8(ifp->ctx, &tmp, dhcp, (uint8_t)i) == 0)
2666 log_dhcp(LOG_WARNING, "reject DHCP", ifp, dhcp, from);
2667 return;
2671 if (type == DHCP_NAK) {
2672 /* For NAK, only check if we require the ServerID */
2673 if (has_option_mask(ifo->requiremask, DHO_SERVERID) &&
2674 get_option_addr(ifp->ctx, &addr, dhcp, DHO_SERVERID) == -1)
2676 log_dhcp(LOG_WARNING, "reject NAK", ifp, dhcp, from);
2677 return;
2680 /* We should restart on a NAK */
2681 log_dhcp(LOG_WARNING, "NAK:", ifp, dhcp, from);
2682 if ((msg = get_option_string(ifp->ctx, dhcp, DHO_MESSAGE))) {
2683 logger(ifp->ctx, LOG_WARNING, "%s: message: %s",
2684 ifp->name, msg);
2685 free(msg);
2687 if (state->state == DHS_INFORM) /* INFORM should not be NAKed */
2688 return;
2689 if (!(ifp->ctx->options & DHCPCD_TEST)) {
2690 dhcp_drop(ifp, "NAK");
2691 unlink(state->leasefile);
2694 /* If we constantly get NAKS then we should slowly back off */
2695 eloop_timeout_add_sec(ifp->ctx->eloop,
2696 state->nakoff, dhcp_discover, ifp);
2697 if (state->nakoff == 0)
2698 state->nakoff = 1;
2699 else {
2700 state->nakoff *= 2;
2701 if (state->nakoff > NAKOFF_MAX)
2702 state->nakoff = NAKOFF_MAX;
2704 return;
2707 /* Ensure that all required options are present */
2708 for (i = 1; i < 255; i++) {
2709 if (has_option_mask(ifo->requiremask, i) &&
2710 get_option_uint8(ifp->ctx, &tmp, dhcp, (uint8_t)i) != 0)
2712 /* If we are BOOTP, then ignore the need for serverid.
2713 * To ignore BOOTP, require dhcp_message_type.
2714 * However, nothing really stops BOOTP from providing
2715 * DHCP style options as well so the above isn't
2716 * always true. */
2717 if (type == 0 && i == DHO_SERVERID)
2718 continue;
2719 log_dhcp(LOG_WARNING, "reject DHCP", ifp, dhcp, from);
2720 return;
2724 /* DHCP Auto-Configure, RFC 2563 */
2725 if (type == DHCP_OFFER && dhcp->yiaddr == 0) {
2726 log_dhcp(LOG_WARNING, "no address given", ifp, dhcp, from);
2727 if ((msg = get_option_string(ifp->ctx, dhcp, DHO_MESSAGE))) {
2728 logger(ifp->ctx, LOG_WARNING,
2729 "%s: message: %s", ifp->name, msg);
2730 free(msg);
2732 if (state->state == DHS_DISCOVER &&
2733 get_option_uint8(ifp->ctx, &tmp, dhcp,
2734 DHO_AUTOCONFIGURE) == 0)
2736 switch (tmp) {
2737 case 0:
2738 log_dhcp(LOG_WARNING, "IPv4LL disabled from",
2739 ifp, dhcp, from);
2740 ipv4ll_drop(ifp);
2741 arp_close(ifp);
2742 break;
2743 case 1:
2744 log_dhcp(LOG_WARNING, "IPv4LL enabled from",
2745 ifp, dhcp, from);
2746 ipv4ll_start(ifp);
2747 break;
2748 default:
2749 logger(ifp->ctx, LOG_ERR,
2750 "%s: unknown auto configuration option %d",
2751 ifp->name, tmp);
2752 break;
2754 eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
2755 eloop_timeout_add_sec(ifp->ctx->eloop,
2756 DHCP_MAX, dhcp_discover, ifp);
2758 return;
2761 /* Ensure that the address offered is valid */
2762 if ((type == 0 || type == DHCP_OFFER || type == DHCP_ACK) &&
2763 (dhcp->ciaddr == INADDR_ANY || dhcp->ciaddr == INADDR_BROADCAST) &&
2764 (dhcp->yiaddr == INADDR_ANY || dhcp->yiaddr == INADDR_BROADCAST))
2766 log_dhcp(LOG_WARNING, "reject invalid address",
2767 ifp, dhcp, from);
2768 return;
2771 #ifdef IN_IFF_DUPLICATED
2772 ia = ipv4_iffindaddr(ifp, &lease->addr, NULL);
2773 if (ia && ia->addr_flags & IN_IFF_DUPLICATED) {
2774 log_dhcp(LOG_WARNING, "declined duplicate address",
2775 ifp, dhcp, from);
2776 if (type)
2777 dhcp_decline(ifp);
2778 ipv4_deladdr(ifp, &ia->addr, &ia->net, 0);
2779 eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
2780 eloop_timeout_add_sec(ifp->ctx->eloop,
2781 DHCP_RAND_MAX, dhcp_discover, ifp);
2782 return;
2784 #endif
2786 if ((type == 0 || type == DHCP_OFFER) && state->state == DHS_DISCOVER) {
2787 lease->frominfo = 0;
2788 lease->addr.s_addr = dhcp->yiaddr;
2789 lease->cookie = dhcp->cookie;
2790 if (type == 0 ||
2791 get_option_addr(ifp->ctx,
2792 &lease->server, dhcp, DHO_SERVERID) != 0)
2793 lease->server.s_addr = INADDR_ANY;
2794 log_dhcp(LOG_INFO, "offered", ifp, dhcp, from);
2795 free(state->offer);
2796 state->offer = dhcp;
2797 *dhcpp = NULL;
2798 if (ifp->ctx->options & DHCPCD_TEST) {
2799 free(state->old);
2800 state->old = state->new;
2801 state->new = state->offer;
2802 state->offer = NULL;
2803 state->reason = "TEST";
2804 script_runreason(ifp, state->reason);
2805 eloop_exit(ifp->ctx->eloop, EXIT_SUCCESS);
2806 return;
2808 eloop_timeout_delete(ifp->ctx->eloop, send_discover, ifp);
2809 /* We don't request BOOTP addresses */
2810 if (type) {
2811 /* We used to ARP check here, but that seems to be in
2812 * violation of RFC2131 where it only describes
2813 * DECLINE after REQUEST.
2814 * It also seems that some MS DHCP servers actually
2815 * ignore DECLINE if no REQUEST, ie we decline a
2816 * DISCOVER. */
2817 dhcp_request(ifp);
2818 return;
2822 if (type) {
2823 if (type == DHCP_OFFER) {
2824 log_dhcp(LOG_WARNING, "ignoring offer of",
2825 ifp, dhcp, from);
2826 return;
2829 /* We should only be dealing with acks */
2830 if (type != DHCP_ACK) {
2831 log_dhcp(LOG_ERR, "not ACK or OFFER",
2832 ifp, dhcp, from);
2833 return;
2836 if (!(ifo->options & DHCPCD_INFORM))
2837 log_dhcp(LOG_DEBUG, "acknowledged", ifp, dhcp, from);
2838 else
2839 ifo->options &= ~DHCPCD_STATIC;
2842 /* No NAK, so reset the backoff
2843 * We don't reset on an OFFER message because the server could
2844 * potentially NAK the REQUEST. */
2845 state->nakoff = 0;
2847 /* BOOTP could have already assigned this above, so check we still
2848 * have a pointer. */
2849 if (*dhcpp) {
2850 free(state->offer);
2851 state->offer = dhcp;
2852 *dhcpp = NULL;
2855 lease->frominfo = 0;
2856 eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
2858 dhcp_arp_bind(ifp);
2861 static size_t
2862 get_udp_data(const uint8_t **data, const uint8_t *udp)
2864 struct udp_dhcp_packet p;
2866 memcpy(&p, udp, sizeof(p));
2867 *data = udp + offsetof(struct udp_dhcp_packet, dhcp);
2868 return ntohs(p.ip.ip_len) - sizeof(p.ip) - sizeof(p.udp);
2871 static int
2872 valid_udp_packet(const uint8_t *data, size_t data_len, struct in_addr *from,
2873 int noudpcsum)
2875 struct udp_dhcp_packet p;
2876 uint16_t bytes, udpsum;
2878 if (data_len < sizeof(p.ip)) {
2879 if (from)
2880 from->s_addr = INADDR_ANY;
2881 errno = EINVAL;
2882 return -1;
2884 memcpy(&p, data, MIN(data_len, sizeof(p)));
2885 if (from)
2886 from->s_addr = p.ip.ip_src.s_addr;
2887 if (data_len > sizeof(p)) {
2888 errno = EINVAL;
2889 return -1;
2891 if (checksum(&p.ip, sizeof(p.ip)) != 0) {
2892 errno = EINVAL;
2893 return -1;
2896 bytes = ntohs(p.ip.ip_len);
2897 if (data_len < bytes) {
2898 errno = EINVAL;
2899 return -1;
2902 if (noudpcsum == 0) {
2903 udpsum = p.udp.uh_sum;
2904 p.udp.uh_sum = 0;
2905 p.ip.ip_hl = 0;
2906 p.ip.ip_v = 0;
2907 p.ip.ip_tos = 0;
2908 p.ip.ip_len = p.udp.uh_ulen;
2909 p.ip.ip_id = 0;
2910 p.ip.ip_off = 0;
2911 p.ip.ip_ttl = 0;
2912 p.ip.ip_sum = 0;
2913 if (udpsum && checksum(&p, bytes) != udpsum) {
2914 errno = EINVAL;
2915 return -1;
2919 return 0;
2922 static void
2923 dhcp_handlepacket(void *arg)
2925 struct interface *ifp = arg;
2926 struct dhcp_message *dhcp = NULL;
2927 const uint8_t *pp;
2928 size_t bytes;
2929 struct in_addr from;
2930 int i, flags;
2931 const struct dhcp_state *state = D_CSTATE(ifp);
2933 /* Need this API due to BPF */
2934 flags = 0;
2935 while (!(flags & RAW_EOF)) {
2936 bytes = (size_t)if_readrawpacket(ifp, ETHERTYPE_IP,
2937 ifp->ctx->packet, udp_dhcp_len, &flags);
2938 if ((ssize_t)bytes == -1) {
2939 logger(ifp->ctx, LOG_ERR,
2940 "%s: dhcp if_readrawpacket: %m", ifp->name);
2941 dhcp_close(ifp);
2942 arp_close(ifp);
2943 break;
2945 if (valid_udp_packet(ifp->ctx->packet, bytes,
2946 &from, flags & RAW_PARTIALCSUM) == -1)
2948 logger(ifp->ctx, LOG_ERR,
2949 "%s: invalid UDP packet from %s",
2950 ifp->name, inet_ntoa(from));
2951 continue;
2953 i = whitelisted_ip(ifp->options, from.s_addr);
2954 if (i == 0) {
2955 logger(ifp->ctx, LOG_WARNING,
2956 "%s: non whitelisted DHCP packet from %s",
2957 ifp->name, inet_ntoa(from));
2958 continue;
2959 } else if (i != 1 &&
2960 blacklisted_ip(ifp->options, from.s_addr) == 1)
2962 logger(ifp->ctx, LOG_WARNING,
2963 "%s: blacklisted DHCP packet from %s",
2964 ifp->name, inet_ntoa(from));
2965 continue;
2967 if (ifp->flags & IFF_POINTOPOINT &&
2968 state->dst.s_addr != from.s_addr)
2970 logger(ifp->ctx, LOG_WARNING,
2971 "%s: server %s is not destination",
2972 ifp->name, inet_ntoa(from));
2974 bytes = get_udp_data(&pp, ifp->ctx->packet);
2975 if (bytes > sizeof(*dhcp)) {
2976 logger(ifp->ctx, LOG_ERR,
2977 "%s: packet greater than DHCP size from %s",
2978 ifp->name, inet_ntoa(from));
2979 continue;
2981 if (dhcp == NULL) {
2982 dhcp = calloc(1, sizeof(*dhcp));
2983 if (dhcp == NULL) {
2984 logger(ifp->ctx, LOG_ERR,
2985 "%s: calloc: %m", __func__);
2986 break;
2989 memcpy(dhcp, pp, bytes);
2990 if (dhcp->cookie != htonl(MAGIC_COOKIE)) {
2991 logger(ifp->ctx, LOG_DEBUG, "%s: bogus cookie from %s",
2992 ifp->name, inet_ntoa(from));
2993 continue;
2995 /* Ensure packet is for us */
2996 if (ifp->hwlen <= sizeof(dhcp->chaddr) &&
2997 memcmp(dhcp->chaddr, ifp->hwaddr, ifp->hwlen))
2999 char buf[sizeof(dhcp->chaddr) * 3];
3001 logger(ifp->ctx, LOG_DEBUG,
3002 "%s: xid 0x%x is for hwaddr %s",
3003 ifp->name, ntohl(dhcp->xid),
3004 hwaddr_ntoa(dhcp->chaddr, sizeof(dhcp->chaddr),
3005 buf, sizeof(buf)));
3006 continue;
3008 dhcp_handledhcp(ifp, &dhcp, &from);
3009 if (state->raw_fd == -1)
3010 break;
3012 free(dhcp);
3015 static void
3016 dhcp_handleudp(void *arg)
3018 struct dhcpcd_ctx *ctx;
3019 uint8_t buffer[sizeof(struct dhcp_message)];
3021 ctx = arg;
3023 /* Just read what's in the UDP fd and discard it as we always read
3024 * from the raw fd */
3025 if (read(ctx->udp_fd, buffer, sizeof(buffer)) == -1) {
3026 logger(ctx, LOG_ERR, "%s: %m", __func__);
3027 eloop_event_delete(ctx->eloop, ctx->udp_fd);
3028 close(ctx->udp_fd);
3029 ctx->udp_fd = -1;
3033 static int
3034 dhcp_open(struct interface *ifp)
3036 struct dhcp_state *state;
3038 if (ifp->ctx->packet == NULL) {
3039 ifp->ctx->packet = malloc(udp_dhcp_len);
3040 if (ifp->ctx->packet == NULL) {
3041 logger(ifp->ctx, LOG_ERR, "%s: %m", __func__);
3042 return -1;
3046 state = D_STATE(ifp);
3047 if (state->raw_fd == -1) {
3048 state->raw_fd = if_openrawsocket(ifp, ETHERTYPE_IP);
3049 if (state->raw_fd == -1) {
3050 if (errno == ENOENT) {
3051 logger(ifp->ctx, LOG_ERR,
3052 "%s not found", if_pfname);
3053 /* May as well disable IPv4 entirely at
3054 * this point as we really need it. */
3055 ifp->options->options &= ~DHCPCD_IPV4;
3056 } else
3057 logger(ifp->ctx, LOG_ERR, "%s: %s: %m",
3058 __func__, ifp->name);
3059 return -1;
3061 eloop_event_add(ifp->ctx->eloop,
3062 state->raw_fd, dhcp_handlepacket, ifp, NULL, NULL);
3064 return 0;
3068 dhcp_dump(struct interface *ifp)
3070 struct dhcp_state *state;
3072 ifp->if_data[IF_DATA_DHCP] = state = calloc(1, sizeof(*state));
3073 if (state == NULL)
3074 goto eexit;
3075 state->raw_fd = -1;
3076 dhcp_set_leasefile(state->leasefile, sizeof(state->leasefile),
3077 AF_INET, ifp);
3078 state->new = read_lease(ifp);
3079 if (state->new == NULL) {
3080 logger(ifp->ctx, LOG_ERR, "%s: %s: %m",
3081 *ifp->name ? ifp->name : state->leasefile, __func__);
3082 return -1;
3084 state->reason = "DUMP";
3085 return script_runreason(ifp, state->reason);
3087 eexit:
3088 logger(ifp->ctx, LOG_ERR, "%s: %m", __func__);
3089 return -1;
3092 void
3093 dhcp_free(struct interface *ifp)
3095 struct dhcp_state *state = D_STATE(ifp);
3096 struct dhcpcd_ctx *ctx;
3098 dhcp_close(ifp);
3099 arp_close(ifp);
3100 if (state) {
3101 free(state->old);
3102 free(state->new);
3103 free(state->offer);
3104 free(state->clientid);
3105 free(state);
3106 ifp->if_data[IF_DATA_DHCP] = NULL;
3109 ctx = ifp->ctx;
3110 /* If we don't have any more DHCP enabled interfaces,
3111 * close the global socket and release resources */
3112 if (ctx->ifaces) {
3113 TAILQ_FOREACH(ifp, ctx->ifaces, next) {
3114 if (D_STATE(ifp))
3115 break;
3118 if (ifp == NULL) {
3119 if (ctx->udp_fd != -1) {
3120 eloop_event_delete(ctx->eloop, ctx->udp_fd);
3121 close(ctx->udp_fd);
3122 ctx->udp_fd = -1;
3125 free(ctx->packet);
3126 free(ctx->opt_buffer);
3127 ctx->packet = NULL;
3128 ctx->opt_buffer = NULL;
3132 static int
3133 dhcp_init(struct interface *ifp)
3135 struct dhcp_state *state;
3136 const struct if_options *ifo;
3137 uint8_t len;
3138 char buf[(sizeof(ifo->clientid) - 1) * 3];
3140 state = D_STATE(ifp);
3141 if (state == NULL) {
3142 ifp->if_data[IF_DATA_DHCP] = calloc(1, sizeof(*state));
3143 state = D_STATE(ifp);
3144 if (state == NULL)
3145 return -1;
3146 /* 0 is a valid fd, so init to -1 */
3147 state->raw_fd = -1;
3149 /* Now is a good time to find IPv4 routes */
3150 if_initrt(ifp);
3153 state->state = DHS_INIT;
3154 state->reason = "PREINIT";
3155 state->nakoff = 0;
3156 dhcp_set_leasefile(state->leasefile, sizeof(state->leasefile),
3157 AF_INET, ifp);
3159 ifo = ifp->options;
3160 /* We need to drop the leasefile so that dhcp_start
3161 * doesn't load it. */
3162 if (ifo->options & DHCPCD_REQUEST)
3163 unlink(state->leasefile);
3165 free(state->clientid);
3166 state->clientid = NULL;
3168 if (*ifo->clientid) {
3169 state->clientid = malloc((size_t)(ifo->clientid[0] + 1));
3170 if (state->clientid == NULL)
3171 goto eexit;
3172 memcpy(state->clientid, ifo->clientid,
3173 (size_t)(ifo->clientid[0]) + 1);
3174 } else if (ifo->options & DHCPCD_CLIENTID) {
3175 if (ifo->options & DHCPCD_DUID) {
3176 state->clientid = malloc(ifp->ctx->duid_len + 6);
3177 if (state->clientid == NULL)
3178 goto eexit;
3179 state->clientid[0] =(uint8_t)(ifp->ctx->duid_len + 5);
3180 state->clientid[1] = 255; /* RFC 4361 */
3181 memcpy(state->clientid + 2, ifo->iaid, 4);
3182 memcpy(state->clientid + 6, ifp->ctx->duid,
3183 ifp->ctx->duid_len);
3184 } else {
3185 len = (uint8_t)(ifp->hwlen + 1);
3186 state->clientid = malloc((size_t)len + 1);
3187 if (state->clientid == NULL)
3188 goto eexit;
3189 state->clientid[0] = len;
3190 state->clientid[1] = (uint8_t)ifp->family;
3191 memcpy(state->clientid + 2, ifp->hwaddr,
3192 ifp->hwlen);
3196 if (ifo->options & DHCPCD_DUID)
3197 /* Don't bother logging as DUID and IAID are reported
3198 * at device start. */
3199 return 0;
3201 if (ifo->options & DHCPCD_CLIENTID)
3202 logger(ifp->ctx, LOG_DEBUG, "%s: using ClientID %s", ifp->name,
3203 hwaddr_ntoa(state->clientid + 1, state->clientid[0],
3204 buf, sizeof(buf)));
3205 else if (ifp->hwlen)
3206 logger(ifp->ctx, LOG_DEBUG, "%s: using hwaddr %s", ifp->name,
3207 hwaddr_ntoa(ifp->hwaddr, ifp->hwlen, buf, sizeof(buf)));
3208 return 0;
3210 eexit:
3211 logger(ifp->ctx, LOG_ERR, "%s: error making ClientID: %m", __func__);
3212 return -1;
3215 static void
3216 dhcp_start1(void *arg)
3218 struct interface *ifp = arg;
3219 struct if_options *ifo = ifp->options;
3220 struct dhcp_state *state;
3221 struct stat st;
3222 uint32_t l;
3223 int nolease;
3225 if (!(ifo->options & DHCPCD_IPV4))
3226 return;
3228 /* Listen on *.*.*.*:bootpc so that the kernel never sends an
3229 * ICMP port unreachable message back to the DHCP server */
3230 if (ifp->ctx->udp_fd == -1) {
3231 ifp->ctx->udp_fd = dhcp_openudp(NULL);
3232 if (ifp->ctx->udp_fd == -1) {
3233 /* Don't log an error if some other process
3234 * is handling this. */
3235 if (errno != EADDRINUSE)
3236 logger(ifp->ctx, LOG_ERR,
3237 "%s: dhcp_openudp: %m", __func__);
3238 } else
3239 eloop_event_add(ifp->ctx->eloop,
3240 ifp->ctx->udp_fd, dhcp_handleudp,
3241 ifp->ctx, NULL, NULL);
3244 if (dhcp_init(ifp) == -1) {
3245 logger(ifp->ctx, LOG_ERR, "%s: dhcp_init: %m", ifp->name);
3246 return;
3249 state = D_STATE(ifp);
3250 clock_gettime(CLOCK_MONOTONIC, &state->started);
3251 free(state->offer);
3252 state->offer = NULL;
3254 if (state->arping_index < ifo->arping_len) {
3255 struct arp_state *astate;
3257 astate = arp_new(ifp, NULL);
3258 if (astate) {
3259 astate->probed_cb = dhcp_arp_probed;
3260 astate->conflicted_cb = dhcp_arp_conflicted;
3261 dhcp_arp_probed(astate);
3263 return;
3266 if (ifo->options & DHCPCD_STATIC) {
3267 dhcp_static(ifp);
3268 return;
3271 if (ifo->options & DHCPCD_DHCP && dhcp_open(ifp) == -1)
3272 return;
3274 if (ifo->options & DHCPCD_INFORM) {
3275 dhcp_inform(ifp);
3276 return;
3278 if (ifp->hwlen == 0 && ifo->clientid[0] == '\0') {
3279 logger(ifp->ctx, LOG_WARNING,
3280 "%s: needs a clientid to configure", ifp->name);
3281 dhcp_drop(ifp, "FAIL");
3282 eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
3283 return;
3285 /* We don't want to read the old lease if we NAK an old test */
3286 nolease = state->offer && ifp->ctx->options & DHCPCD_TEST;
3287 if (!nolease && ifo->options & DHCPCD_DHCP) {
3288 state->offer = read_lease(ifp);
3289 /* Check the saved lease matches the type we want */
3290 if (state->offer) {
3291 #ifdef IN_IFF_DUPLICATED
3292 struct in_addr addr;
3293 struct ipv4_addr *ia;
3295 addr.s_addr = state->offer->yiaddr;
3296 ia = ipv4_iffindaddr(ifp, &addr, NULL);
3297 #endif
3299 if ((IS_BOOTP(ifp, state->offer) &&
3300 !(ifo->options & DHCPCD_BOOTP)) ||
3301 #ifdef IN_IFF_DUPLICATED
3302 (ia && ia->addr_flags & IN_IFF_DUPLICATED) ||
3303 #endif
3304 (!IS_BOOTP(ifp, state->offer) &&
3305 ifo->options & DHCPCD_BOOTP))
3307 free(state->offer);
3308 state->offer = NULL;
3312 if (state->offer) {
3313 get_lease(ifp->ctx, &state->lease, state->offer);
3314 state->lease.frominfo = 1;
3315 if (state->new == NULL &&
3316 ipv4_iffindaddr(ifp, &state->lease.addr, &state->lease.net))
3318 /* We still have the IP address from the last lease.
3319 * Fake add the address and routes from it so the lease
3320 * can be cleaned up. */
3321 state->new = malloc(sizeof(*state->new));
3322 if (state->new) {
3323 memcpy(state->new, state->offer,
3324 sizeof(*state->new));
3325 state->addr = state->lease.addr;
3326 state->net = state->lease.net;
3327 state->added |= STATE_ADDED | STATE_FAKE;
3328 ipv4_buildroutes(ifp->ctx);
3329 } else
3330 logger(ifp->ctx, LOG_ERR, "%s: %m", __func__);
3332 if (state->offer->cookie == 0) {
3333 if (state->offer->yiaddr == state->addr.s_addr) {
3334 free(state->offer);
3335 state->offer = NULL;
3337 } else if (state->lease.leasetime != ~0U &&
3338 stat(state->leasefile, &st) == 0)
3340 time_t now;
3342 /* Offset lease times and check expiry */
3343 now = time(NULL);
3344 if (now == -1 ||
3345 (time_t)state->lease.leasetime < now - st.st_mtime)
3347 logger(ifp->ctx, LOG_DEBUG,
3348 "%s: discarding expired lease", ifp->name);
3349 free(state->offer);
3350 state->offer = NULL;
3351 state->lease.addr.s_addr = 0;
3352 /* Technically we should discard the lease
3353 * as it's expired, just as DHCPv6 addresses
3354 * would be by the kernel.
3355 * However, this may violate POLA so
3356 * we currently leave it be.
3357 * If we get a totally different lease from
3358 * the DHCP server we'll drop it anyway, as
3359 * we will on any other event which would
3360 * trigger a lease drop.
3361 * This should only happen if dhcpcd stops
3362 * running and the lease expires before
3363 * dhcpcd starts again. */
3364 #if 0
3365 if (state->new)
3366 dhcp_drop(ifp, "EXPIRE");
3367 #endif
3368 } else {
3369 l = (uint32_t)(now - st.st_mtime);
3370 state->lease.leasetime -= l;
3371 state->lease.renewaltime -= l;
3372 state->lease.rebindtime -= l;
3377 if (!(ifo->options & DHCPCD_DHCP)) {
3378 if (ifo->options & DHCPCD_IPV4LL)
3379 ipv4ll_start(ifp);
3380 return;
3383 if (state->offer == NULL || state->offer->cookie == 0)
3384 dhcp_discover(ifp);
3385 else
3386 dhcp_reboot(ifp);
3389 void
3390 dhcp_start(struct interface *ifp)
3392 struct timespec tv;
3394 if (!(ifp->options->options & DHCPCD_IPV4))
3395 return;
3397 /* No point in delaying a static configuration */
3398 if (ifp->options->options & DHCPCD_STATIC ||
3399 !(ifp->options->options & DHCPCD_INITIAL_DELAY))
3401 dhcp_start1(ifp);
3402 return;
3405 tv.tv_sec = DHCP_MIN_DELAY;
3406 tv.tv_nsec = (suseconds_t)arc4random_uniform(
3407 (DHCP_MAX_DELAY - DHCP_MIN_DELAY) * NSEC_PER_SEC);
3408 timespecnorm(&tv);
3409 logger(ifp->ctx, LOG_DEBUG,
3410 "%s: delaying IPv4 for %0.1f seconds",
3411 ifp->name, timespec_to_double(&tv));
3413 eloop_timeout_add_tv(ifp->ctx->eloop, &tv, dhcp_start1, ifp);
3416 void
3417 dhcp_abort(struct interface *ifp)
3420 eloop_timeout_delete(ifp->ctx->eloop, dhcp_start1, ifp);
3423 void
3424 dhcp_handleifa(int cmd, struct interface *ifp,
3425 const struct in_addr *addr,
3426 const struct in_addr *net,
3427 const struct in_addr *dst,
3428 __unused int flags)
3430 struct dhcp_state *state;
3431 struct if_options *ifo;
3432 uint8_t i;
3434 state = D_STATE(ifp);
3435 if (state == NULL)
3436 return;
3438 if (cmd == RTM_DELADDR) {
3439 if (state->addr.s_addr == addr->s_addr &&
3440 state->net.s_addr == net->s_addr)
3442 logger(ifp->ctx, LOG_INFO,
3443 "%s: removing IP address %s/%d",
3444 ifp->name, inet_ntoa(state->addr),
3445 inet_ntocidr(state->net));
3446 dhcp_drop(ifp, "EXPIRE");
3448 return;
3451 if (cmd != RTM_NEWADDR)
3452 return;
3454 ifo = ifp->options;
3455 if (ifo->options & DHCPCD_INFORM) {
3456 if (state->state != DHS_INFORM)
3457 dhcp_inform(ifp);
3458 return;
3461 if (!(ifo->options & DHCPCD_STATIC))
3462 return;
3463 if (ifo->req_addr.s_addr != INADDR_ANY)
3464 return;
3466 free(state->old);
3467 state->old = state->new;
3468 state->new = dhcp_message_new(addr, net);
3469 if (state->new == NULL)
3470 return;
3471 state->dst.s_addr = dst ? dst->s_addr : INADDR_ANY;
3472 if (dst) {
3473 for (i = 1; i < 255; i++)
3474 if (i != DHO_ROUTER && has_option_mask(ifo->dstmask,i))
3475 dhcp_message_add_addr(state->new, i, *dst);
3477 state->reason = "STATIC";
3478 ipv4_buildroutes(ifp->ctx);
3479 script_runreason(ifp, state->reason);
3480 if (ifo->options & DHCPCD_INFORM) {
3481 state->state = DHS_INFORM;
3482 state->xid = dhcp_xid(ifp);
3483 state->lease.server.s_addr = dst ? dst->s_addr : INADDR_ANY;
3484 state->addr = *addr;
3485 state->net = *net;
3486 dhcp_inform(ifp);