1 /* SPDX-License-Identifier: BSD-2-Clause */
3 * dhcpcd - DHCP client daemon
4 * Copyright (c) 2006-2020 Roy Marples <roy@marples.name>
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 #include <sys/param.h>
30 #include <sys/socket.h>
32 #include <arpa/inet.h>
34 #include <net/route.h>
35 #include <netinet/if_ether.h>
36 #include <netinet/in_systm.h>
37 #include <netinet/in.h>
38 #include <netinet/ip.h>
39 #define __FAVOR_BSD /* Nasty glibc hack so we can use BSD semantics for UDP */
40 #include <netinet/udp.h>
44 # include <net/if_dl.h>
60 #define ELOOP_QUEUE ELOOP_DHCP
67 #include "dhcp-common.h"
78 #define DAD "Duplicate address detected"
79 #define DHCP_MIN_LEASE 20
81 #define IPV4A ADDRIPV4 | ARRAY
82 #define IPV4R ADDRIPV4 | REQUEST
84 /* We should define a maximum for the NAK exponential backoff */
87 /* Wait N nanoseconds between sending a RELEASE and dropping the address.
88 * This gives the kernel enough time to actually send it. */
89 #define RELEASE_DELAY_S 0
90 #define RELEASE_DELAY_NS 10000000
93 #define IPDEFTTL 64 /* RFC1340 */
96 /* Support older systems with different defines */
97 #if !defined(IP_RECVPKTINFO) && defined(IP_PKTINFO)
98 #define IP_RECVPKTINFO IP_PKTINFO
101 /* Assert the correct structure size for on wire */
102 __CTASSERT(sizeof(struct ip) == 20);
103 __CTASSERT(sizeof(struct udphdr) == 8);
104 __CTASSERT(sizeof(struct bootp) == 300);
111 static const struct dhcp_op dhcp_ops[] = {
112 { DHCP_DISCOVER, "DISCOVER" },
113 { DHCP_OFFER, "OFFER" },
114 { DHCP_REQUEST, "REQUEST" },
115 { DHCP_DECLINE, "DECLINE" },
118 { DHCP_RELEASE, "RELEASE" },
119 { DHCP_INFORM, "INFORM" },
120 { DHCP_FORCERENEW, "FORCERENEW"},
124 static const char * const dhcp_params[] = {
133 static int dhcp_openbpf(struct interface *);
134 static void dhcp_start1(void *);
135 #if defined(ARP) && (!defined(KERNEL_RFC5227) || defined(ARPING))
136 static void dhcp_arp_found(struct arp_state *, const struct arp_msg *);
138 static void dhcp_handledhcp(struct interface *, struct bootp *, size_t,
139 const struct in_addr *);
140 static void dhcp_handleifudp(void *);
141 static int dhcp_initstate(struct interface *);
144 dhcp_printoptions(const struct dhcpcd_ctx *ctx,
145 const struct dhcp_opt *opts, size_t opts_len)
147 const char * const *p;
149 const struct dhcp_opt *opt, *opt2;
152 for (p = dhcp_params; *p; p++)
155 for (i = 0, opt = ctx->dhcp_opts; i < ctx->dhcp_opts_len; i++, opt++) {
156 for (j = 0, opt2 = opts; j < opts_len; j++, opt2++)
157 if (opt->option == opt2->option)
160 cols = printf("%03d %s", opt->option, opt->var);
161 dhcp_print_option_encoding(opt, cols);
164 for (i = 0, opt = opts; i < opts_len; i++, opt++) {
165 cols = printf("%03d %s", opt->option, opt->var);
166 dhcp_print_option_encoding(opt, cols);
170 static const uint8_t *
171 get_option(struct dhcpcd_ctx *ctx,
172 const struct bootp *bootp, size_t bootp_len,
173 unsigned int opt, size_t *opt_len)
175 const uint8_t *p, *e;
176 uint8_t l, o, ol, overl, *bp;
180 if (bootp == NULL || bootp_len < DHCP_MIN_LEN) {
185 /* Check we have the magic cookie */
186 if (!IS_DHCP(bootp)) {
191 p = bootp->vend + 4; /* options after the 4 byte cookie */
192 e = (const uint8_t *)bootp + bootp_len;
201 /* No length to read */
205 /* bit 1 set means parse boot file */
206 overl = (uint8_t)(overl & ~1);
208 e = p + sizeof(bootp->file);
209 } else if (overl & 2) {
210 /* bit 2 set means parse server name */
211 overl = (uint8_t)(overl & ~2);
213 e = p + sizeof(bootp->sname);
216 /* No length to read */
220 /* Check we can read the length */
227 /* Check we can read the option data, if present */
233 if (o == DHO_OPTSOVERLOADED) {
234 /* Ensure we only get this option once by setting
235 * the last bit as well as the value.
236 * This is valid because only the first two bits
237 * actually mean anything in RFC2132 Section 9.3 */
238 if (l == 1 && !overl)
244 /* We must concatonate the options. */
245 if (bl + l > ctx->opt_buffer_len) {
251 (bp - ctx->opt_buffer);
254 nb = realloc(ctx->opt_buffer, bl + l);
257 ctx->opt_buffer = nb;
258 ctx->opt_buffer_len = bl + l;
259 bp = ctx->opt_buffer + pos;
262 bp = ctx->opt_buffer;
278 return (const uint8_t *)ctx->opt_buffer;
287 get_option_addr(struct dhcpcd_ctx *ctx,
288 struct in_addr *a, const struct bootp *bootp, size_t bootp_len,
294 p = get_option(ctx, bootp, bootp_len, option, &len);
295 if (!p || len < (ssize_t)sizeof(a->s_addr))
297 memcpy(&a->s_addr, p, sizeof(a->s_addr));
302 get_option_uint32(struct dhcpcd_ctx *ctx,
303 uint32_t *i, const struct bootp *bootp, size_t bootp_len, uint8_t option)
309 p = get_option(ctx, bootp, bootp_len, option, &len);
310 if (!p || len < (ssize_t)sizeof(d))
312 memcpy(&d, p, sizeof(d));
319 get_option_uint16(struct dhcpcd_ctx *ctx,
320 uint16_t *i, const struct bootp *bootp, size_t bootp_len, uint8_t option)
326 p = get_option(ctx, bootp, bootp_len, option, &len);
327 if (!p || len < (ssize_t)sizeof(d))
329 memcpy(&d, p, sizeof(d));
336 get_option_uint8(struct dhcpcd_ctx *ctx,
337 uint8_t *i, const struct bootp *bootp, size_t bootp_len, uint8_t option)
342 p = get_option(ctx, bootp, bootp_len, option, &len);
343 if (!p || len < (ssize_t)sizeof(*p))
351 print_rfc3442(FILE *fp, const uint8_t *data, size_t data_len)
353 const uint8_t *p = data, *e;
358 /* Minimum is 5 -first is CIDR and a router length of 4 */
367 if (fputc(' ', fp) == EOF)
375 ocets = (size_t)(cidr + 7) / NBBY;
376 if (p + 4 + ocets > e) {
380 /* If we have ocets then we have a destination and netmask */
383 memcpy(&addr.s_addr, p, ocets);
386 if (fprintf(fp, "%s/%d", inet_ntoa(addr), cidr) == -1)
389 /* Finally, snag the router */
390 memcpy(&addr.s_addr, p, 4);
392 if (fprintf(fp, " %s", inet_ntoa(addr)) == -1)
396 if (fputc('\0', fp) == EOF)
402 decode_rfc3442_rt(rb_tree_t *routes, struct interface *ifp,
403 const uint8_t *data, size_t dl, const struct bootp *bootp)
405 const uint8_t *p = data;
409 struct rt *rt = NULL;
410 struct in_addr dest, netmask, gateway;
413 /* Minimum is 5 -first is CIDR and a router length of 4 */
428 ocets = (size_t)(cidr + 7) / NBBY;
429 if (p + 4 + ocets > e) {
434 if ((rt = rt_new(ifp)) == NULL)
437 /* If we have ocets then we have a destination and netmask */
440 memcpy(&dest.s_addr, p, ocets);
442 netmask.s_addr = htonl(~0U << (32 - cidr));
446 /* Finally, snag the router */
447 memcpy(&gateway.s_addr, p, 4);
450 /* An on-link host route is normally set by having the
451 * gateway match the destination or assigned address */
452 if (gateway.s_addr == dest.s_addr ||
453 (gateway.s_addr == bootp->yiaddr ||
454 gateway.s_addr == bootp->ciaddr))
456 gateway.s_addr = INADDR_ANY;
457 netmask.s_addr = INADDR_BROADCAST;
459 if (netmask.s_addr == INADDR_BROADCAST)
460 rt->rt_flags = RTF_HOST;
462 sa_in_init(&rt->rt_dest, &dest);
463 sa_in_init(&rt->rt_netmask, &netmask);
464 sa_in_init(&rt->rt_gateway, &gateway);
465 if (rt_proto_add(routes, rt))
472 print_rfc3361(FILE *fp, const uint8_t *data, size_t dl)
475 char sip[NS_MAXDNAME];
487 if (decode_rfc1035(sip, sizeof(sip), data, dl) == -1)
489 if (efprintf(fp, "%s", sip) == -1)
497 addr.s_addr = INADDR_BROADCAST;
500 data += sizeof(addr.s_addr), dl -= sizeof(addr.s_addr))
502 memcpy(&addr.s_addr, data, sizeof(addr.s_addr));
503 if (fprintf(fp, "%s", inet_ntoa(addr)) == -1)
505 if (dl != sizeof(addr.s_addr)) {
506 if (fputc(' ', fp) == EOF)
510 if (fputc('\0', fp) == EOF)
522 get_option_string(struct dhcpcd_ctx *ctx,
523 const struct bootp *bootp, size_t bootp_len, uint8_t option)
529 p = get_option(ctx, bootp, bootp_len, option, &len);
530 if (!p || len == 0 || *p == '\0')
533 s = malloc(sizeof(char) * (len + 1));
541 /* This calculates the netmask that we should use for static routes.
542 * This IS different from the calculation used to calculate the netmask
543 * for an interface address. */
545 route_netmask(uint32_t ip_in)
547 /* used to be unsigned long - check if error */
548 uint32_t p = ntohl(ip_in);
570 /* We need to obey routing options.
571 * If we have a CSR then we only use that.
572 * Otherwise we add static routes and then routers. */
574 get_option_routes(rb_tree_t *routes, struct interface *ifp,
575 const struct bootp *bootp, size_t bootp_len)
577 struct if_options *ifo = ifp->options;
580 struct rt *rt = NULL;
581 struct in_addr dest, netmask, gateway;
583 const char *csr = "";
586 /* If we have CSR's then we MUST use these only */
587 if (!has_option_mask(ifo->nomask, DHO_CSR))
588 p = get_option(ifp->ctx, bootp, bootp_len, DHO_CSR, &len);
591 /* Check for crappy MS option */
592 if (!p && !has_option_mask(ifo->nomask, DHO_MSCSR)) {
593 p = get_option(ifp->ctx, bootp, bootp_len, DHO_MSCSR, &len);
597 if (p && (n = decode_rfc3442_rt(routes, ifp, p, len, bootp)) != -1) {
598 const struct dhcp_state *state;
600 state = D_CSTATE(ifp);
601 if (!(ifo->options & DHCPCD_CSR_WARNED) &&
602 !(state->added & STATE_FAKE))
604 logdebugx("%s: using %sClassless Static Routes",
606 ifo->options |= DHCPCD_CSR_WARNED;
612 /* OK, get our static routes first. */
613 if (!has_option_mask(ifo->nomask, DHO_STATICROUTE))
614 p = get_option(ifp->ctx, bootp, bootp_len,
615 DHO_STATICROUTE, &len);
618 /* RFC 2131 Section 5.8 states length MUST be in multiples of 8 */
619 if (p && len % 8 == 0) {
622 memcpy(&dest.s_addr, p, sizeof(dest.s_addr));
624 memcpy(&gateway.s_addr, p, sizeof(gateway.s_addr));
626 /* RFC 2131 Section 5.8 states default route is
628 if (gateway.s_addr == INADDR_ANY)
630 if ((rt = rt_new(ifp)) == NULL)
633 /* A on-link host route is normally set by having the
634 * gateway match the destination or assigned address */
635 if (gateway.s_addr == dest.s_addr ||
636 (gateway.s_addr == bootp->yiaddr ||
637 gateway.s_addr == bootp->ciaddr))
639 gateway.s_addr = INADDR_ANY;
640 netmask.s_addr = INADDR_BROADCAST;
642 netmask.s_addr = route_netmask(dest.s_addr);
643 if (netmask.s_addr == INADDR_BROADCAST)
644 rt->rt_flags = RTF_HOST;
646 sa_in_init(&rt->rt_dest, &dest);
647 sa_in_init(&rt->rt_netmask, &netmask);
648 sa_in_init(&rt->rt_gateway, &gateway);
649 if (rt_proto_add(routes, rt))
654 /* Now grab our routers */
655 if (!has_option_mask(ifo->nomask, DHO_ROUTER))
656 p = get_option(ifp->ctx, bootp, bootp_len, DHO_ROUTER, &len);
659 if (p && len % 4 == 0) {
661 dest.s_addr = INADDR_ANY;
662 netmask.s_addr = INADDR_ANY;
664 if ((rt = rt_new(ifp)) == NULL)
666 memcpy(&gateway.s_addr, p, sizeof(gateway.s_addr));
668 sa_in_init(&rt->rt_dest, &dest);
669 sa_in_init(&rt->rt_netmask, &netmask);
670 sa_in_init(&rt->rt_gateway, &gateway);
671 if (rt_proto_add(routes, rt))
680 dhcp_get_mtu(const struct interface *ifp)
682 const struct dhcp_state *state;
685 if (ifp->options->mtu)
686 return (uint16_t)ifp->options->mtu;
687 mtu = 0; /* bogus gcc warning */
688 if ((state = D_CSTATE(ifp)) == NULL ||
689 has_option_mask(ifp->options->nomask, DHO_MTU) ||
690 get_option_uint16(ifp->ctx, &mtu,
691 state->new, state->new_len, DHO_MTU) == -1)
696 /* Grab our routers from the DHCP message and apply any MTU value
697 * the message contains */
699 dhcp_get_routes(rb_tree_t *routes, struct interface *ifp)
701 const struct dhcp_state *state;
703 if ((state = D_CSTATE(ifp)) == NULL || !(state->added & STATE_ADDED))
705 return get_option_routes(routes, ifp, state->new, state->new_len);
708 /* Assumes DHCP options */
710 dhcp_message_add_addr(struct bootp *bootp,
711 uint8_t type, struct in_addr addr)
717 while (*p != DHO_END) {
722 len = (size_t)(p - bootp->vend);
723 if (len + 6 > sizeof(bootp->vend)) {
730 memcpy(p, &addr.s_addr, 4);
737 make_message(struct bootp **bootpm, const struct interface *ifp, uint8_t type)
741 uint8_t *n_params = NULL;
745 const struct dhcp_opt *opt;
746 struct if_options *ifo = ifp->options;
747 const struct dhcp_state *state = D_CSTATE(ifp);
748 const struct dhcp_lease *lease = &state->lease;
749 char hbuf[HOSTNAME_MAX_LEN + 1];
750 const char *hostname;
751 const struct vivco *vivco;
754 uint8_t *auth, auth_len;
757 if ((mtu = if_getmtu(ifp)) == -1)
758 logerr("%s: if_getmtu", ifp->name);
759 else if (mtu < MTU_MIN) {
760 if (if_setmtu(ifp, MTU_MIN) == -1)
761 logerr("%s: if_setmtu", ifp->name);
765 if (ifo->options & DHCPCD_BOOTP)
766 bootp = calloc(1, sizeof (*bootp));
768 /* Make the maximal message we could send */
769 bootp = calloc(1, (size_t)(mtu - IP_UDP_SIZE));
775 if (state->addr != NULL &&
776 (type == DHCP_INFORM || type == DHCP_RELEASE ||
777 (type == DHCP_REQUEST &&
778 state->addr->mask.s_addr == lease->mask.s_addr &&
779 (state->new == NULL || IS_DHCP(state->new)) &&
780 !(state->added & (STATE_FAKE | STATE_EXPIRED)))))
781 bootp->ciaddr = state->addr->addr.s_addr;
783 bootp->op = BOOTREQUEST;
784 bootp->htype = (uint8_t)ifp->hwtype;
785 if (ifp->hwlen != 0 && ifp->hwlen < sizeof(bootp->chaddr)) {
786 bootp->hlen = (uint8_t)ifp->hwlen;
787 memcpy(&bootp->chaddr, &ifp->hwaddr, ifp->hwlen);
790 if (ifo->options & DHCPCD_BROADCAST &&
791 bootp->ciaddr == 0 &&
792 type != DHCP_DECLINE &&
793 type != DHCP_RELEASE)
794 bootp->flags = htons(BROADCAST_FLAG);
796 if (type != DHCP_DECLINE && type != DHCP_RELEASE) {
798 unsigned long long secs;
800 clock_gettime(CLOCK_MONOTONIC, &tv);
801 secs = eloop_timespec_diff(&tv, &state->started, NULL);
802 if (secs > UINT16_MAX)
803 bootp->secs = htons((uint16_t)UINT16_MAX);
805 bootp->secs = htons((uint16_t)secs);
808 bootp->xid = htonl(state->xid);
810 if (ifo->options & DHCPCD_BOOTP)
811 return sizeof(*bootp);
814 e = (uint8_t *)bootp + (mtu - IP_UDP_SIZE) - 1; /* -1 for DHO_END */
816 ul = htonl(MAGIC_COOKIE);
817 memcpy(p, &ul, sizeof(ul));
820 #define AREA_LEFT (size_t)(e - p)
821 #define AREA_FIT(s) if ((s) > AREA_LEFT) goto toobig
822 #define AREA_CHECK(s) if ((s) + 2UL > AREA_LEFT) goto toobig
823 #define PUT_ADDR(o, a) do { \
827 memcpy(p, &(a)->s_addr, 4); \
829 } while (0 /* CONSTCOND */)
831 /* Options are listed in numerical order as per RFC 7844 Section 3.1
832 * XXX: They should be randomised. */
835 if (lease->addr.s_addr && lease->cookie == htonl(MAGIC_COOKIE)) {
836 if (type == DHCP_DECLINE ||
837 (type == DHCP_REQUEST &&
838 (state->addr == NULL ||
839 state->added & (STATE_FAKE | STATE_EXPIRED) ||
840 lease->addr.s_addr != state->addr->addr.s_addr)))
843 PUT_ADDR(DHO_IPADDRESS, &lease->addr);
848 *p++ = DHO_MESSAGETYPE;
852 if (lease->addr.s_addr && lease->cookie == htonl(MAGIC_COOKIE)) {
853 if (type == DHCP_RELEASE || putip) {
854 if (lease->server.s_addr)
855 PUT_ADDR(DHO_SERVERID, &lease->server);
859 if (type == DHCP_DECLINE) {
861 if (len > AREA_LEFT) {
869 #define DHCP_DIR(type) ((type) == DHCP_DISCOVER || (type) == DHCP_INFORM || \
870 (type) == DHCP_REQUEST)
872 if (DHCP_DIR(type)) {
873 /* vendor is already encoded correctly, so just add it */
874 if (ifo->vendor[0]) {
875 AREA_CHECK(ifo->vendor[0]);
877 memcpy(p, ifo->vendor, (size_t)ifo->vendor[0] + 1);
878 p += ifo->vendor[0] + 1;
882 if (type == DHCP_DISCOVER && ifo->options & DHCPCD_REQUEST)
883 PUT_ADDR(DHO_IPADDRESS, &ifo->req_addr);
885 if (DHCP_DIR(type)) {
886 if (type != DHCP_INFORM) {
887 if (ifo->leasetime != 0) {
889 *p++ = DHO_LEASETIME;
891 ul = htonl(ifo->leasetime);
898 *p++ = DHO_PARAMETERREQUESTLIST;
901 for (i = 0, opt = ifp->ctx->dhcp_opts;
902 i < ifp->ctx->dhcp_opts_len;
905 if (!DHC_REQOPT(opt, ifo->requestmask, ifo->nomask))
907 if (type == DHCP_INFORM &&
908 (opt->option == DHO_RENEWALTIME ||
909 opt->option == DHO_REBINDTIME))
912 *p++ = (uint8_t)opt->option;
914 for (i = 0, opt = ifo->dhcp_override;
915 i < ifo->dhcp_override_len;
918 /* Check if added above */
919 for (lp = n_params + 1; lp < p; lp++)
920 if (*lp == (uint8_t)opt->option)
924 if (!DHC_REQOPT(opt, ifo->requestmask, ifo->nomask))
926 if (type == DHCP_INFORM &&
927 (opt->option == DHO_RENEWALTIME ||
928 opt->option == DHO_REBINDTIME))
931 *p++ = (uint8_t)opt->option;
933 *n_params = (uint8_t)(p - n_params - 1);
936 !(has_option_mask(ifo->nomask, DHO_MAXMESSAGESIZE)))
939 *p++ = DHO_MAXMESSAGESIZE;
941 sz = htons((uint16_t)(mtu - IP_UDP_SIZE));
946 if (ifo->userclass[0] &&
947 !has_option_mask(ifo->nomask, DHO_USERCLASS))
949 AREA_CHECK(ifo->userclass[0]);
950 *p++ = DHO_USERCLASS;
951 memcpy(p, ifo->userclass,
952 (size_t)ifo->userclass[0] + 1);
953 p += ifo->userclass[0] + 1;
957 if (state->clientid) {
958 AREA_CHECK(state->clientid[0]);
960 memcpy(p, state->clientid, (size_t)state->clientid[0] + 1);
961 p += state->clientid[0] + 1;
964 if (DHCP_DIR(type) &&
965 !has_option_mask(ifo->nomask, DHO_VENDORCLASSID) &&
966 ifo->vendorclassid[0])
968 AREA_CHECK(ifo->vendorclassid[0]);
969 *p++ = DHO_VENDORCLASSID;
970 memcpy(p, ifo->vendorclassid, (size_t)ifo->vendorclassid[0]+1);
971 p += ifo->vendorclassid[0] + 1;
974 if (type == DHCP_DISCOVER &&
975 !(ifp->ctx->options & DHCPCD_TEST) &&
976 DHC_REQ(ifo->requestmask, ifo->nomask, DHO_RAPIDCOMMIT))
978 /* RFC 4039 Section 3 */
980 *p++ = DHO_RAPIDCOMMIT;
984 if (DHCP_DIR(type)) {
985 hostname = dhcp_get_hostname(hbuf, sizeof(hbuf), ifo);
988 * RFC4702 3.1 States that if we send the Client FQDN option
989 * then we MUST NOT also send the Host Name option.
990 * Technically we could, but that is not RFC conformant and
991 * also seems to break some DHCP server implemetations such as
992 * Windows. On the other hand, ISC dhcpd is just as non RFC
993 * conformant by not accepting a partially qualified FQDN.
995 if (ifo->fqdn != FQDN_DISABLE) {
996 /* IETF DHC-FQDN option (81), RFC4702 */
999 i += encode_rfc1035(hostname, NULL);
1005 * S: 1 => Client requests Server to update
1006 * a RR in DNS as well as PTR
1007 * O: 1 => Server indicates to client that
1008 * DNS has been updated
1009 * E: 1 => Name data is DNS format
1010 * N: 1 => Client requests Server to not
1014 *p++ = (uint8_t)((ifo->fqdn & 0x09) | 0x04);
1016 *p++ = (FQDN_NONE & 0x09) | 0x04;
1017 *p++ = 0; /* from server for PTR RR */
1018 *p++ = 0; /* from server for A RR if S=1 */
1020 i = encode_rfc1035(hostname, p);
1023 } else if (ifo->options & DHCPCD_HOSTNAME && hostname) {
1024 len = strlen(hostname);
1026 *p++ = DHO_HOSTNAME;
1027 *p++ = (uint8_t)len;
1028 memcpy(p, hostname, len);
1034 auth = NULL; /* appease GCC */
1036 if (ifo->auth.options & DHCPCD_AUTH_SEND) {
1037 ssize_t alen = dhcp_auth_encode(ifp->ctx, &ifo->auth,
1039 NULL, 0, 4, type, NULL, 0);
1040 if (alen != -1 && alen > UINT8_MAX) {
1045 logerr("%s: dhcp_auth_encode", ifp->name);
1046 else if (alen != 0) {
1047 auth_len = (uint8_t)alen;
1048 AREA_CHECK(auth_len);
1049 *p++ = DHO_AUTHENTICATION;
1057 /* RFC 2563 Auto Configure */
1058 if (type == DHCP_DISCOVER && ifo->options & DHCPCD_IPV4LL &&
1059 !(has_option_mask(ifo->nomask, DHO_AUTOCONFIGURE)))
1062 *p++ = DHO_AUTOCONFIGURE;
1067 if (DHCP_DIR(type)) {
1068 if (ifo->mudurl[0]) {
1069 AREA_CHECK(ifo->mudurl[0]);
1071 memcpy(p, ifo->mudurl, (size_t)ifo->mudurl[0] + 1);
1072 p += ifo->mudurl[0] + 1;
1075 if (ifo->vivco_len &&
1076 !has_option_mask(ifo->nomask, DHO_VIVCO))
1078 AREA_CHECK(sizeof(ul));
1082 ul = htonl(ifo->vivco_en);
1083 memcpy(p, &ul, sizeof(ul));
1085 for (i = 0, vivco = ifo->vivco;
1089 AREA_FIT(vivco->len);
1090 if (vivco->len + 2 + *lp > 255) {
1091 logerrx("%s: VIVCO option too big",
1096 *p++ = (uint8_t)vivco->len;
1097 memcpy(p, vivco->data, vivco->len);
1099 *lp = (uint8_t)(*lp + vivco->len + 1);
1104 if ((ifo->auth.options & DHCPCD_AUTH_SENDREQUIRE) !=
1105 DHCPCD_AUTH_SENDREQUIRE &&
1106 !has_option_mask(ifo->nomask, DHO_FORCERENEW_NONCE))
1108 /* We support HMAC-MD5 */
1110 *p++ = DHO_FORCERENEW_NONCE;
1112 *p++ = AUTH_ALG_HMAC_MD5;
1118 len = (size_t)(p - (uint8_t *)bootp);
1120 /* Pad out to the BOOTP message length.
1121 * Even if we send a DHCP packet with a variable length vendor area,
1122 * some servers / relay agents don't like packets smaller than
1123 * a BOOTP message which is fine because that's stipulated
1124 * in RFC1542 section 2.1. */
1125 while (len < sizeof(*bootp)) {
1131 if (ifo->auth.options & DHCPCD_AUTH_SEND && auth_len != 0)
1132 dhcp_auth_encode(ifp->ctx, &ifo->auth, state->auth.token,
1133 (uint8_t *)bootp, len, 4, type, auth, auth_len);
1136 return (ssize_t)len;
1139 logerrx("%s: DHCP message too big", ifp->name);
1145 read_lease(struct interface *ifp, struct bootp **bootp)
1149 uint8_t buf[FRAMELEN_MAX];
1151 struct dhcp_state *state = D_STATE(ifp);
1156 const uint8_t *auth;
1163 if (state->leasefile[0] == '\0') {
1164 logdebugx("reading standard input");
1165 sbytes = read(fileno(stdin), buf.buf, sizeof(buf.buf));
1167 logdebugx("%s: reading lease: %s",
1168 ifp->name, state->leasefile);
1169 sbytes = dhcp_readfile(ifp->ctx, state->leasefile,
1170 buf.buf, sizeof(buf.buf));
1173 if (errno != ENOENT)
1174 logerr("%s: %s", ifp->name, state->leasefile);
1177 bytes = (size_t)sbytes;
1179 /* Ensure the packet is at lease BOOTP sized
1180 * with a vendor area of 4 octets
1181 * (it should be more, and our read packet enforces this so this
1182 * code should not be needed, but of course people could
1183 * scribble whatever in the stored lease file. */
1184 if (bytes < DHCP_MIN_LEN) {
1185 logerrx("%s: %s: truncated lease", ifp->name, __func__);
1189 if (ifp->ctx->options & DHCPCD_DUMPLEASE)
1192 /* We may have found a BOOTP server */
1193 if (get_option_uint8(ifp->ctx, &type, &buf.bootp, bytes,
1194 DHO_MESSAGETYPE) == -1)
1198 /* Authenticate the message */
1199 auth = get_option(ifp->ctx, &buf.bootp, bytes,
1200 DHO_AUTHENTICATION, &auth_len);
1202 if (dhcp_auth_validate(&state->auth, &ifp->options->auth,
1203 &buf.bootp, bytes, 4, type, auth, auth_len) == NULL)
1205 logerr("%s: authentication failed", ifp->name);
1208 if (state->auth.token)
1209 logdebugx("%s: validated using 0x%08" PRIu32,
1210 ifp->name, state->auth.token->secretid);
1212 logdebugx("%s: accepted reconfigure key", ifp->name);
1213 } else if ((ifp->options->auth.options & DHCPCD_AUTH_SENDREQUIRE) ==
1214 DHCPCD_AUTH_SENDREQUIRE)
1216 logerrx("%s: authentication now required", ifp->name);
1222 *bootp = malloc(bytes);
1223 if (*bootp == NULL) {
1227 memcpy(*bootp, buf.buf, bytes);
1231 static const struct dhcp_opt *
1232 dhcp_getoverride(const struct if_options *ifo, unsigned int o)
1235 const struct dhcp_opt *opt;
1237 for (i = 0, opt = ifo->dhcp_override;
1238 i < ifo->dhcp_override_len;
1241 if (opt->option == o)
1247 static const uint8_t *
1248 dhcp_getoption(struct dhcpcd_ctx *ctx,
1249 size_t *os, unsigned int *code, size_t *len,
1250 const uint8_t *od, size_t ol, struct dhcp_opt **oopt)
1253 struct dhcp_opt *opt;
1260 *os = 2; /* code + len */
1261 *code = (unsigned int)*od++;
1262 *len = (size_t)*od++;
1263 if (*len > ol - *os) {
1270 for (i = 0, opt = ctx->dhcp_opts; i < ctx->dhcp_opts_len; i++, opt++) {
1271 if (opt->option == *code) {
1281 dhcp_env(FILE *fenv, const char *prefix, const struct interface *ifp,
1282 const struct bootp *bootp, size_t bootp_len)
1284 const struct if_options *ifo;
1286 struct in_addr addr;
1289 struct dhcp_opt *opt, *vo;
1291 char safe[(BOOTP_FILE_LEN * 4) + 1];
1296 if (get_option_uint8(ifp->ctx, &overl, bootp, bootp_len,
1297 DHO_OPTSOVERLOADED) == -1)
1300 if (bootp->yiaddr || bootp->ciaddr) {
1301 /* Set some useful variables that we derive from the DHCP
1302 * message but are not necessarily in the options */
1303 addr.s_addr = bootp->yiaddr ? bootp->yiaddr : bootp->ciaddr;
1304 if (efprintf(fenv, "%s_ip_address=%s",
1305 prefix, inet_ntoa(addr)) == -1)
1307 if (get_option_addr(ifp->ctx, &net,
1308 bootp, bootp_len, DHO_SUBNETMASK) == -1) {
1309 net.s_addr = ipv4_getnetmask(addr.s_addr);
1310 if (efprintf(fenv, "%s_subnet_mask=%s",
1311 prefix, inet_ntoa(net)) == -1)
1314 if (efprintf(fenv, "%s_subnet_cidr=%d",
1315 prefix, inet_ntocidr(net))== -1)
1317 if (get_option_addr(ifp->ctx, &brd,
1318 bootp, bootp_len, DHO_BROADCAST) == -1)
1320 brd.s_addr = addr.s_addr | ~net.s_addr;
1321 if (efprintf(fenv, "%s_broadcast_address=%s",
1322 prefix, inet_ntoa(brd)) == -1)
1325 addr.s_addr = bootp->yiaddr & net.s_addr;
1326 if (efprintf(fenv, "%s_network_number=%s",
1327 prefix, inet_ntoa(addr)) == -1)
1331 if (*bootp->file && !(overl & 1)) {
1332 print_string(safe, sizeof(safe), OT_STRING,
1333 bootp->file, sizeof(bootp->file));
1334 if (efprintf(fenv, "%s_filename=%s", prefix, safe) == -1)
1337 if (*bootp->sname && !(overl & 2)) {
1338 print_string(safe, sizeof(safe), OT_STRING | OT_DOMAIN,
1339 bootp->sname, sizeof(bootp->sname));
1340 if (efprintf(fenv, "%s_server_name=%s", prefix, safe) == -1)
1344 /* Zero our indexes */
1345 for (i = 0, opt = ifp->ctx->dhcp_opts;
1346 i < ifp->ctx->dhcp_opts_len;
1348 dhcp_zero_index(opt);
1349 for (i = 0, opt = ifp->options->dhcp_override;
1350 i < ifp->options->dhcp_override_len;
1352 dhcp_zero_index(opt);
1353 for (i = 0, opt = ifp->ctx->vivso;
1354 i < ifp->ctx->vivso_len;
1356 dhcp_zero_index(opt);
1358 for (i = 0, opt = ifp->ctx->dhcp_opts;
1359 i < ifp->ctx->dhcp_opts_len;
1362 if (has_option_mask(ifo->nomask, opt->option))
1364 if (dhcp_getoverride(ifo, opt->option))
1366 p = get_option(ifp->ctx, bootp, bootp_len, opt->option, &pl);
1369 dhcp_envoption(ifp->ctx, fenv, prefix, ifp->name,
1370 opt, dhcp_getoption, p, pl);
1372 if (opt->option != DHO_VIVSO || pl <= (int)sizeof(uint32_t))
1374 memcpy(&en, p, sizeof(en));
1376 vo = vivso_find(en, ifp);
1379 /* Skip over en + total size */
1380 p += sizeof(en) + 1;
1381 pl -= sizeof(en) + 1;
1382 dhcp_envoption(ifp->ctx, fenv, prefix, ifp->name,
1383 vo, dhcp_getoption, p, pl);
1386 for (i = 0, opt = ifo->dhcp_override;
1387 i < ifo->dhcp_override_len;
1390 if (has_option_mask(ifo->nomask, opt->option))
1392 p = get_option(ifp->ctx, bootp, bootp_len, opt->option, &pl);
1395 dhcp_envoption(ifp->ctx, fenv, prefix, ifp->name,
1396 opt, dhcp_getoption, p, pl);
1403 get_lease(struct interface *ifp,
1404 struct dhcp_lease *lease, const struct bootp *bootp, size_t len)
1406 struct dhcpcd_ctx *ctx;
1408 assert(bootp != NULL);
1410 memcpy(&lease->cookie, bootp->vend, sizeof(lease->cookie));
1411 /* BOOTP does not set yiaddr for replies when ciaddr is set. */
1412 lease->addr.s_addr = bootp->yiaddr ? bootp->yiaddr : bootp->ciaddr;
1414 if (ifp->options->options & (DHCPCD_STATIC | DHCPCD_INFORM)) {
1415 if (ifp->options->req_addr.s_addr != INADDR_ANY) {
1416 lease->mask = ifp->options->req_mask;
1417 if (ifp->options->req_brd.s_addr != INADDR_ANY)
1418 lease->brd = ifp->options->req_brd;
1421 lease->addr.s_addr | ~lease->mask.s_addr;
1423 const struct ipv4_addr *ia;
1425 ia = ipv4_iffindaddr(ifp, &lease->addr, NULL);
1427 lease->mask = ia->mask;
1428 lease->brd = ia->brd;
1431 if (get_option_addr(ctx, &lease->mask, bootp, len,
1432 DHO_SUBNETMASK) == -1)
1433 lease->mask.s_addr =
1434 ipv4_getnetmask(lease->addr.s_addr);
1435 if (get_option_addr(ctx, &lease->brd, bootp, len,
1436 DHO_BROADCAST) == -1)
1438 lease->addr.s_addr | ~lease->mask.s_addr;
1440 if (get_option_uint32(ctx, &lease->leasetime,
1441 bootp, len, DHO_LEASETIME) != 0)
1442 lease->leasetime = DHCP_INFINITE_LIFETIME;
1443 if (get_option_uint32(ctx, &lease->renewaltime,
1444 bootp, len, DHO_RENEWALTIME) != 0)
1445 lease->renewaltime = 0;
1446 if (get_option_uint32(ctx, &lease->rebindtime,
1447 bootp, len, DHO_REBINDTIME) != 0)
1448 lease->rebindtime = 0;
1449 if (get_option_addr(ctx, &lease->server, bootp, len, DHO_SERVERID) != 0)
1450 lease->server.s_addr = INADDR_ANY;
1454 get_dhcp_op(uint8_t type)
1456 const struct dhcp_op *d;
1458 for (d = dhcp_ops; d->name; d++)
1459 if (d->value == type)
1465 dhcp_fallback(void *arg)
1467 struct interface *iface;
1469 iface = (struct interface *)arg;
1470 dhcpcd_selectprofile(iface, iface->options->fallback);
1471 dhcpcd_startinterface(iface);
1475 dhcp_new_xid(struct interface *ifp)
1477 struct dhcp_state *state;
1478 const struct interface *ifp1;
1479 const struct dhcp_state *state1;
1481 state = D_STATE(ifp);
1482 if (ifp->options->options & DHCPCD_XID_HWADDR &&
1483 ifp->hwlen >= sizeof(state->xid))
1484 /* The lower bits are probably more unique on the network */
1486 (ifp->hwaddr + ifp->hwlen) - sizeof(state->xid),
1487 sizeof(state->xid));
1490 state->xid = arc4random();
1493 /* Ensure it's unique */
1494 TAILQ_FOREACH(ifp1, ifp->ctx->ifaces, next) {
1497 if ((state1 = D_CSTATE(ifp1)) == NULL)
1499 if (state1->xid == state->xid)
1503 if (ifp->options->options & DHCPCD_XID_HWADDR &&
1504 ifp->hwlen >= sizeof(state->xid))
1506 logerrx("%s: duplicate xid on %s",
1507 ifp->name, ifp1->name);
1513 /* We can't do this when sharing leases across interfaes */
1515 /* As the XID changes, re-apply the filter. */
1516 if (state->bpf_fd != -1) {
1517 if (bpf_bootp(ifp, state->bpf_fd) == -1)
1518 logerr(__func__); /* try to continue */
1524 dhcp_closebpf(struct interface *ifp)
1526 struct dhcpcd_ctx *ctx = ifp->ctx;
1527 struct dhcp_state *state = D_STATE(ifp);
1530 if (IN_PRIVSEP_SE(ctx))
1531 ps_bpf_closebootp(ifp);
1534 if (state->bpf != NULL) {
1535 eloop_event_delete(ctx->eloop, state->bpf->bpf_fd);
1536 bpf_close(state->bpf);
1542 dhcp_closeinet(struct interface *ifp)
1544 struct dhcpcd_ctx *ctx = ifp->ctx;
1545 struct dhcp_state *state = D_STATE(ifp);
1548 if (IN_PRIVSEP_SE(ctx)) {
1549 if (state->addr != NULL)
1550 ps_inet_closebootp(state->addr);
1554 if (state->udp_rfd != -1) {
1555 eloop_event_delete(ctx->eloop, state->udp_rfd);
1556 close(state->udp_rfd);
1557 state->udp_rfd = -1;
1562 dhcp_close(struct interface *ifp)
1564 struct dhcp_state *state = D_STATE(ifp);
1570 dhcp_closeinet(ifp);
1572 state->interval = 0;
1576 dhcp_openudp(struct in_addr *ia)
1579 struct sockaddr_in sin;
1582 if ((s = xsocket(PF_INET, SOCK_DGRAM | SOCK_CXNB, IPPROTO_UDP)) == -1)
1586 if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n)) == -1)
1589 if (setsockopt(s, IPPROTO_IP, IP_RECVIF, &n, sizeof(n)) == -1)
1592 if (setsockopt(s, IPPROTO_IP, IP_RECVPKTINFO, &n, sizeof(n)) == -1)
1596 if (setsockopt(s, SOL_SOCKET, SO_RERROR, &n, sizeof(n)) == -1)
1600 memset(&sin, 0, sizeof(sin));
1601 sin.sin_family = AF_INET;
1602 sin.sin_port = htons(BOOTPC);
1605 if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) == -1)
1616 in_cksum(const void *data, size_t len, uint32_t *isum)
1618 const uint16_t *word = data;
1619 uint32_t sum = isum != NULL ? *isum : 0;
1621 for (; len > 1; len -= sizeof(*word))
1625 sum += htons((uint16_t)(*(const uint8_t *)word << 8));
1630 sum = (sum >> 16) + (sum & 0xffff);
1633 return (uint16_t)~sum;
1636 static struct bootp_pkt *
1637 dhcp_makeudppacket(size_t *sz, const uint8_t *data, size_t length,
1638 struct in_addr source, struct in_addr dest)
1640 struct bootp_pkt *udpp;
1644 if ((udpp = calloc(1, sizeof(*ip) + sizeof(*udp) + length)) == NULL)
1649 /* OK, this is important :)
1650 * We copy the data to our packet and then create a small part of the
1651 * ip structure and an invalid ip_len (basically udp length).
1652 * We then fill the udp structure and put the checksum
1653 * of the whole packet into the udp checksum.
1654 * Finally we complete the ip structure and ip checksum.
1655 * If we don't do the ordering like so then the udp checksum will be
1656 * broken, so find another way of doing it! */
1658 memcpy(&udpp->bootp, data, length);
1660 ip->ip_p = IPPROTO_UDP;
1661 ip->ip_src.s_addr = source.s_addr;
1662 if (dest.s_addr == 0)
1663 ip->ip_dst.s_addr = INADDR_BROADCAST;
1665 ip->ip_dst.s_addr = dest.s_addr;
1667 udp->uh_sport = htons(BOOTPC);
1668 udp->uh_dport = htons(BOOTPS);
1669 udp->uh_ulen = htons((uint16_t)(sizeof(*udp) + length));
1670 ip->ip_len = udp->uh_ulen;
1671 udp->uh_sum = in_cksum(udpp, sizeof(*ip) + sizeof(*udp) + length, NULL);
1673 ip->ip_v = IPVERSION;
1674 ip->ip_hl = sizeof(*ip) >> 2;
1675 ip->ip_id = (uint16_t)arc4random_uniform(UINT16_MAX);
1676 ip->ip_ttl = IPDEFTTL;
1677 ip->ip_len = htons((uint16_t)(sizeof(*ip) + sizeof(*udp) + length));
1678 ip->ip_sum = in_cksum(ip, sizeof(*ip), NULL);
1679 if (ip->ip_sum == 0)
1680 ip->ip_sum = 0xffff; /* RFC 768 */
1682 *sz = sizeof(*ip) + sizeof(*udp) + length;
1687 dhcp_sendudp(struct interface *ifp, struct in_addr *to, void *data, size_t len)
1689 struct sockaddr_in sin = {
1690 .sin_family = AF_INET,
1692 .sin_port = htons(BOOTPS),
1694 .sin_len = sizeof(sin),
1697 struct udphdr udp = {
1698 .uh_sport = htons(BOOTPC),
1699 .uh_dport = htons(BOOTPS),
1700 .uh_ulen = htons((uint16_t)(sizeof(udp) + len)),
1702 struct iovec iov[] = {
1703 { .iov_base = &udp, .iov_len = sizeof(udp), },
1704 { .iov_base = data, .iov_len = len, },
1706 struct msghdr msg = {
1707 .msg_name = (void *)&sin,
1708 .msg_namelen = sizeof(sin),
1710 .msg_iovlen = __arraycount(iov),
1712 struct dhcpcd_ctx *ctx = ifp->ctx;
1715 if (ctx->options & DHCPCD_PRIVSEP)
1716 return ps_inet_sendbootp(ifp, &msg);
1718 return sendmsg(ctx->udp_wfd, &msg, 0);
1722 send_message(struct interface *ifp, uint8_t type,
1723 void (*callback)(void *))
1725 struct dhcp_state *state = D_STATE(ifp);
1726 struct if_options *ifo = ifp->options;
1727 struct bootp *bootp;
1728 struct bootp_pkt *udp;
1731 struct in_addr from, to;
1734 if (callback == NULL) {
1735 /* No carrier? Don't bother sending the packet. */
1736 if (!if_is_link_up(ifp))
1738 logdebugx("%s: sending %s with xid 0x%x",
1740 ifo->options & DHCPCD_BOOTP ? "BOOTP" : get_dhcp_op(type),
1742 RT = 0; /* bogus gcc warning */
1744 if (state->interval == 0)
1745 state->interval = 4;
1747 state->interval *= 2;
1748 if (state->interval > 64)
1749 state->interval = 64;
1751 RT = (state->interval * MSEC_PER_SEC) +
1752 (arc4random_uniform(MSEC_PER_SEC * 2) - MSEC_PER_SEC);
1753 /* No carrier? Don't bother sending the packet.
1754 * However, we do need to advance the timeout. */
1755 if (!if_is_link_up(ifp))
1757 logdebugx("%s: sending %s (xid 0x%x), next in %0.1f seconds",
1759 ifo->options & DHCPCD_BOOTP ? "BOOTP" : get_dhcp_op(type),
1761 (float)RT / MSEC_PER_SEC);
1764 r = make_message(&bootp, ifp, type);
1769 if (!(state->added & (STATE_FAKE | STATE_EXPIRED)) &&
1770 state->addr != NULL &&
1771 ipv4_iffindaddr(ifp, &state->lease.addr, NULL) != NULL)
1772 from.s_addr = state->lease.addr.s_addr;
1774 from.s_addr = INADDR_ANY;
1775 if (from.s_addr != INADDR_ANY &&
1776 state->lease.server.s_addr != INADDR_ANY)
1777 to.s_addr = state->lease.server.s_addr;
1779 to.s_addr = INADDR_BROADCAST;
1782 * If not listening on the unspecified address we can
1783 * only receive broadcast messages via BPF.
1784 * Sockets bound to an address cannot receive broadcast messages
1785 * even if they are setup to send them.
1786 * Broadcasting from UDP is only an optimisation for rebinding
1787 * and on BSD, at least, is reliant on the subnet route being
1788 * correctly configured to receive the unicast reply.
1789 * As such, we always broadcast and receive the reply to it via BPF.
1790 * This also guarantees we have a DHCP server attached to the
1791 * interface we want to configure because we can't dictate the
1792 * interface via IP_PKTINFO unlike for IPv6.
1794 if (to.s_addr != INADDR_BROADCAST) {
1795 if (dhcp_sendudp(ifp, &to, bootp, len) != -1)
1797 logerr("%s: dhcp_sendudp", ifp->name);
1800 if (dhcp_openbpf(ifp) == -1)
1803 udp = dhcp_makeudppacket(&ulen, (uint8_t *)bootp, len, from, to);
1805 logerr("%s: dhcp_makeudppacket", ifp->name);
1808 } else if (ifp->ctx->options & DHCPCD_PRIVSEP) {
1809 r = ps_bpf_sendbootp(ifp, udp, ulen);
1813 r = bpf_send(state->bpf, ETHERTYPE_IP, udp, ulen);
1816 /* If we failed to send a raw packet this normally means
1817 * we don't have the ability to work beneath the IP layer
1818 * for this interface.
1819 * As such we remove it from consideration without actually
1820 * stopping the interface. */
1822 logerr("%s: bpf_send", ifp->name);
1830 if (!(ifp->ctx->options & DHCPCD_TEST))
1831 dhcp_drop(ifp, "FAIL");
1832 eloop_timeout_delete(ifp->ctx->eloop,
1842 /* Even if we fail to send a packet we should continue as we are
1843 * as our failure timeouts will change out codepath when needed. */
1844 if (callback != NULL)
1845 eloop_timeout_add_msec(ifp->ctx->eloop, RT, callback, ifp);
1849 send_inform(void *arg)
1852 send_message((struct interface *)arg, DHCP_INFORM, send_inform);
1856 send_discover(void *arg)
1859 send_message((struct interface *)arg, DHCP_DISCOVER, send_discover);
1863 send_request(void *arg)
1866 send_message((struct interface *)arg, DHCP_REQUEST, send_request);
1870 send_renew(void *arg)
1873 send_message((struct interface *)arg, DHCP_REQUEST, send_renew);
1877 send_rebind(void *arg)
1880 send_message((struct interface *)arg, DHCP_REQUEST, send_rebind);
1884 dhcp_discover(void *arg)
1886 struct interface *ifp = arg;
1887 struct dhcp_state *state = D_STATE(ifp);
1888 struct if_options *ifo = ifp->options;
1890 state->state = DHS_DISCOVER;
1892 eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
1893 if (!(state->added & STATE_EXPIRED)) {
1895 eloop_timeout_add_sec(ifp->ctx->eloop,
1896 ifo->reboot, dhcp_fallback, ifp);
1898 else if (ifo->options & DHCPCD_IPV4LL)
1899 eloop_timeout_add_sec(ifp->ctx->eloop,
1900 ifo->reboot, ipv4ll_start, ifp);
1903 if (ifo->options & DHCPCD_REQUEST)
1904 loginfox("%s: soliciting a DHCP lease (requesting %s)",
1905 ifp->name, inet_ntoa(ifo->req_addr));
1907 loginfox("%s: soliciting a %s lease",
1908 ifp->name, ifo->options & DHCPCD_BOOTP ? "BOOTP" : "DHCP");
1913 dhcp_request(void *arg)
1915 struct interface *ifp = arg;
1916 struct dhcp_state *state = D_STATE(ifp);
1918 state->state = DHS_REQUEST;
1923 dhcp_expire(void *arg)
1925 struct interface *ifp = arg;
1926 struct dhcp_state *state = D_STATE(ifp);
1928 if (ifp->options->options & DHCPCD_LASTLEASE_EXTEND) {
1929 logwarnx("%s: DHCP lease expired, extending lease", ifp->name);
1930 state->added |= STATE_EXPIRED;
1932 logerrx("%s: DHCP lease expired", ifp->name);
1933 dhcp_drop(ifp, "EXPIRE");
1934 dhcp_unlink(ifp->ctx, state->leasefile);
1936 state->interval = 0;
1940 #if defined(ARP) || defined(IN_IFF_DUPLICATED)
1942 dhcp_decline(struct interface *ifp)
1945 send_message(ifp, DHCP_DECLINE, NULL);
1950 dhcp_startrenew(void *arg)
1952 struct interface *ifp = arg;
1953 struct dhcp_state *state;
1954 struct dhcp_lease *lease;
1956 if ((state = D_STATE(ifp)) == NULL)
1959 /* Only renew in the bound or renew states */
1960 if (state->state != DHS_BOUND &&
1961 state->state != DHS_RENEW)
1964 /* Remove the timeout as the renew may have been forced. */
1965 eloop_timeout_delete(ifp->ctx->eloop, dhcp_startrenew, ifp);
1967 lease = &state->lease;
1968 logdebugx("%s: renewing lease of %s", ifp->name,
1969 inet_ntoa(lease->addr));
1970 state->state = DHS_RENEW;
1972 state->interval = 0;
1977 dhcp_renew(struct interface *ifp)
1980 dhcp_startrenew(ifp);
1984 dhcp_rebind(void *arg)
1986 struct interface *ifp = arg;
1987 struct dhcp_state *state = D_STATE(ifp);
1988 struct dhcp_lease *lease = &state->lease;
1990 logwarnx("%s: failed to renew DHCP, rebinding", ifp->name);
1991 logdebugx("%s: expire in %"PRIu32" seconds",
1992 ifp->name, lease->leasetime - lease->rebindtime);
1993 state->state = DHS_REBIND;
1994 eloop_timeout_delete(ifp->ctx->eloop, send_renew, ifp);
1995 state->lease.server.s_addr = INADDR_ANY;
1996 state->interval = 0;
1997 ifp->options->options &= ~(DHCPCD_CSR_WARNED |
1998 DHCPCD_ROUTER_HOST_ROUTE_WARNED);
2002 #if defined(ARP) || defined(IN_IFF_DUPLICATED)
2004 dhcp_finish_dad(struct interface *ifp, struct in_addr *ia)
2006 struct dhcp_state *state = D_STATE(ifp);
2008 if (state->state != DHS_PROBE)
2010 if (state->offer == NULL || state->offer->yiaddr != ia->s_addr)
2013 logdebugx("%s: DAD completed for %s", ifp->name, inet_ntoa(*ia));
2014 if (!(ifp->options->options & DHCPCD_INFORM))
2016 #ifndef IN_IFF_DUPLICATED
2018 struct bootp *bootp;
2022 len = state->new_len;
2023 state->new = state->offer;
2024 state->new_len = state->offer_len;
2025 get_lease(ifp, &state->lease, state->new, state->new_len);
2026 ipv4_applyaddr(ifp);
2028 state->new_len = len;
2033 /* Stop IPv4LL now we have a working DHCP address */
2037 if (ifp->options->options & DHCPCD_INFORM)
2043 dhcp_addr_duplicated(struct interface *ifp, struct in_addr *ia)
2045 struct dhcp_state *state = D_STATE(ifp);
2046 unsigned long long opts = ifp->options->options;
2047 struct dhcpcd_ctx *ctx = ifp->ctx;
2048 bool deleted = false;
2049 #ifdef IN_IFF_DUPLICATED
2050 struct ipv4_addr *iap;
2053 if ((state->offer == NULL || state->offer->yiaddr != ia->s_addr) &&
2054 !IN_ARE_ADDR_EQUAL(ia, &state->lease.addr))
2057 /* RFC 2131 3.1.5, Client-server interaction */
2058 logerrx("%s: DAD detected %s", ifp->name, inet_ntoa(*ia));
2059 dhcp_unlink(ifp->ctx, state->leasefile);
2060 if (!(opts & DHCPCD_STATIC) && !state->lease.frominfo)
2062 #ifdef IN_IFF_DUPLICATED
2063 if ((iap = ipv4_iffindaddr(ifp, ia, NULL)) != NULL) {
2064 ipv4_deladdr(iap, 0);
2068 eloop_timeout_delete(ctx->eloop, NULL, ifp);
2069 if (opts & (DHCPCD_STATIC | DHCPCD_INFORM)) {
2070 state->reason = "EXPIRE";
2071 script_runreason(ifp, state->reason);
2072 #define NOT_ONLY_SELF (DHCPCD_MASTER | DHCPCD_IPV6RS | DHCPCD_DHCP6)
2073 if (!(ctx->options & NOT_ONLY_SELF))
2074 eloop_exit(ifp->ctx->eloop, EXIT_FAILURE);
2077 eloop_timeout_add_sec(ifp->ctx->eloop,
2078 DHCP_RAND_MAX, dhcp_discover, ifp);
2084 #ifdef KERNEL_RFC5227
2087 dhcp_arp_announced(struct arp_state *state)
2095 dhcp_arp_defend_failed(struct arp_state *astate)
2097 struct interface *ifp = astate->iface;
2099 dhcp_drop(ifp, "EXPIRED");
2104 #if !defined(KERNEL_RFC5227) || defined(ARPING)
2105 static void dhcp_arp_not_found(struct arp_state *);
2107 static struct arp_state *
2108 dhcp_arp_new(struct interface *ifp, struct in_addr *addr)
2110 struct arp_state *astate;
2112 astate = arp_new(ifp, addr);
2116 astate->found_cb = dhcp_arp_found;
2117 astate->not_found_cb = dhcp_arp_not_found;
2118 #ifdef KERNEL_RFC5227
2119 astate->announced_cb = dhcp_arp_announced;
2121 astate->announced_cb = NULL;
2122 astate->defend_failed_cb = dhcp_arp_defend_failed;
2130 dhcp_arping(struct interface *ifp)
2132 struct dhcp_state *state;
2133 struct if_options *ifo;
2134 struct arp_state *astate;
2135 struct in_addr addr;
2137 state = D_STATE(ifp);
2140 if (ifo->arping_len == 0 || state->arping_index > ifo->arping_len)
2143 if (state->arping_index + 1 == ifo->arping_len) {
2144 state->arping_index++;
2145 dhcpcd_startinterface(ifp);
2149 addr.s_addr = ifo->arping[++state->arping_index];
2150 astate = dhcp_arp_new(ifp, &addr);
2151 if (astate == NULL) {
2160 #if !defined(KERNEL_RFC5227) || defined(ARPING)
2162 dhcp_arp_not_found(struct arp_state *astate)
2164 struct interface *ifp;
2166 ifp = astate->iface;
2168 if (dhcp_arping(ifp) == 1) {
2174 dhcp_finish_dad(ifp, &astate->addr);
2178 dhcp_arp_found(struct arp_state *astate, const struct arp_msg *amsg)
2180 struct in_addr addr;
2181 struct interface *ifp = astate->iface;
2183 struct dhcp_state *state;
2184 struct if_options *ifo;
2186 state = D_STATE(ifp);
2189 if (state->arping_index != -1 &&
2190 state->arping_index < ifo->arping_len &&
2192 amsg->sip.s_addr == ifo->arping[state->arping_index])
2194 char buf[HWADDR_LEN * 3];
2196 hwaddr_ntoa(amsg->sha, ifp->hwlen, buf, sizeof(buf));
2197 if (dhcpcd_selectprofile(ifp, buf) == -1 &&
2198 dhcpcd_selectprofile(ifp, inet_ntoa(amsg->sip)) == -1)
2200 /* We didn't find a profile for this
2201 * address or hwaddr, so move to the next
2203 dhcp_arp_not_found(astate);
2207 eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
2208 dhcpcd_startinterface(ifp);
2215 addr = astate->addr;
2217 dhcp_addr_duplicated(ifp, &addr);
2224 dhcp_bind(struct interface *ifp)
2226 struct dhcpcd_ctx *ctx = ifp->ctx;
2227 struct dhcp_state *state = D_STATE(ifp);
2228 struct if_options *ifo = ifp->options;
2229 struct dhcp_lease *lease = &state->lease;
2232 state->reason = NULL;
2233 /* If we don't have an offer, we are re-binding a lease on preference,
2234 * normally when two interfaces have a lease matching IP addresses. */
2237 state->old = state->new;
2238 state->old_len = state->new_len;
2239 state->new = state->offer;
2240 state->new_len = state->offer_len;
2241 state->offer = NULL;
2242 state->offer_len = 0;
2244 get_lease(ifp, lease, state->new, state->new_len);
2245 if (ifo->options & DHCPCD_STATIC) {
2246 loginfox("%s: using static address %s/%d",
2247 ifp->name, inet_ntoa(lease->addr),
2248 inet_ntocidr(lease->mask));
2249 lease->leasetime = DHCP_INFINITE_LIFETIME;
2250 state->reason = "STATIC";
2251 } else if (ifo->options & DHCPCD_INFORM) {
2252 loginfox("%s: received approval for %s",
2253 ifp->name, inet_ntoa(lease->addr));
2254 lease->leasetime = DHCP_INFINITE_LIFETIME;
2255 state->reason = "INFORM";
2257 if (lease->frominfo)
2258 state->reason = "TIMEOUT";
2259 if (lease->leasetime == DHCP_INFINITE_LIFETIME) {
2260 lease->renewaltime =
2263 loginfox("%s: leased %s for infinity",
2264 ifp->name, inet_ntoa(lease->addr));
2266 if (lease->leasetime < DHCP_MIN_LEASE) {
2267 logwarnx("%s: minimum lease is %d seconds",
2268 ifp->name, DHCP_MIN_LEASE);
2269 lease->leasetime = DHCP_MIN_LEASE;
2271 if (lease->rebindtime == 0)
2273 (uint32_t)(lease->leasetime * T2);
2274 else if (lease->rebindtime >= lease->leasetime) {
2276 (uint32_t)(lease->leasetime * T2);
2277 logwarnx("%s: rebind time greater than lease "
2278 "time, forcing to %"PRIu32" seconds",
2279 ifp->name, lease->rebindtime);
2281 if (lease->renewaltime == 0)
2282 lease->renewaltime =
2283 (uint32_t)(lease->leasetime * T1);
2284 else if (lease->renewaltime > lease->rebindtime) {
2285 lease->renewaltime =
2286 (uint32_t)(lease->leasetime * T1);
2287 logwarnx("%s: renewal time greater than "
2288 "rebind time, forcing to %"PRIu32" seconds",
2289 ifp->name, lease->renewaltime);
2291 if (state->state == DHS_RENEW && state->addr &&
2292 lease->addr.s_addr == state->addr->addr.s_addr &&
2293 !(state->added & STATE_FAKE))
2294 logdebugx("%s: leased %s for %"PRIu32" seconds",
2295 ifp->name, inet_ntoa(lease->addr),
2298 loginfox("%s: leased %s for %"PRIu32" seconds",
2299 ifp->name, inet_ntoa(lease->addr),
2303 if (ctx->options & DHCPCD_TEST) {
2304 state->reason = "TEST";
2305 script_runreason(ifp, state->reason);
2306 eloop_exit(ctx->eloop, EXIT_SUCCESS);
2309 if (state->reason == NULL) {
2311 !(state->added & (STATE_FAKE | STATE_EXPIRED)))
2313 if (state->old->yiaddr == state->new->yiaddr &&
2314 lease->server.s_addr &&
2315 state->state != DHS_REBIND)
2316 state->reason = "RENEW";
2318 state->reason = "REBIND";
2319 } else if (state->state == DHS_REBOOT)
2320 state->reason = "REBOOT";
2322 state->reason = "BOUND";
2324 if (lease->leasetime == DHCP_INFINITE_LIFETIME)
2325 lease->renewaltime = lease->rebindtime = lease->leasetime;
2327 eloop_timeout_add_sec(ctx->eloop,
2328 lease->renewaltime, dhcp_startrenew, ifp);
2329 eloop_timeout_add_sec(ctx->eloop,
2330 lease->rebindtime, dhcp_rebind, ifp);
2331 eloop_timeout_add_sec(ctx->eloop,
2332 lease->leasetime, dhcp_expire, ifp);
2333 logdebugx("%s: renew in %"PRIu32" seconds, rebind in %"PRIu32
2335 ifp->name, lease->renewaltime, lease->rebindtime);
2337 state->state = DHS_BOUND;
2338 if (!state->lease.frominfo &&
2339 !(ifo->options & (DHCPCD_INFORM | DHCPCD_STATIC))) {
2340 logdebugx("%s: writing lease: %s",
2341 ifp->name, state->leasefile);
2342 if (dhcp_writefile(ifp->ctx, state->leasefile, 0640,
2343 state->new, state->new_len) == -1)
2344 logerr("dhcp_writefile: %s", state->leasefile);
2347 old_state = state->added;
2349 if (!(ifo->options & DHCPCD_CONFIGURE)) {
2350 struct ipv4_addr *ia;
2352 script_runreason(ifp, state->reason);
2353 dhcpcd_daemonise(ifp->ctx);
2355 /* We we are not configuring the address, we need to keep
2356 * the BPF socket open if the address does not exist. */
2357 ia = ipv4_iffindaddr(ifp, &state->lease.addr, NULL);
2360 state->added = STATE_ADDED;
2367 /* Add the address */
2368 if (ipv4_applyaddr(ifp) == NULL) {
2369 /* There was an error adding the address.
2370 * If we are in oneshot, exit with a failure. */
2371 if (ctx->options & DHCPCD_ONESHOT) {
2372 loginfox("exiting due to oneshot");
2373 eloop_exit(ctx->eloop, EXIT_FAILURE);
2378 /* Close the BPF filter as we can now receive DHCP messages
2379 * on a UDP socket. */
2383 /* If not in master mode, open an address specific socket. */
2384 if (ctx->options & DHCPCD_MASTER ||
2385 (state->old != NULL &&
2386 state->old->yiaddr == state->new->yiaddr &&
2387 old_state & STATE_ADDED && !(old_state & STATE_FAKE)))
2390 dhcp_closeinet(ifp);
2392 if (IN_PRIVSEP_SE(ctx)) {
2393 if (ps_inet_openbootp(state->addr) == -1)
2399 state->udp_rfd = dhcp_openudp(&state->addr->addr);
2400 if (state->udp_rfd == -1) {
2402 /* Address sharing without master mode is not supported.
2403 * It's also possible another DHCP client could be running,
2404 * which is even worse.
2405 * We still need to work, so re-open BPF. */
2409 eloop_event_add(ctx->eloop, state->udp_rfd, dhcp_handleifudp, ifp);
2413 dhcp_message_new(struct bootp **bootp,
2414 const struct in_addr *addr, const struct in_addr *mask)
2419 if ((*bootp = calloc(1, sizeof(**bootp))) == NULL)
2422 (*bootp)->yiaddr = addr->s_addr;
2425 cookie = htonl(MAGIC_COOKIE);
2426 memcpy(p, &cookie, sizeof(cookie));
2427 p += sizeof(cookie);
2429 if (mask->s_addr != INADDR_ANY) {
2430 *p++ = DHO_SUBNETMASK;
2431 *p++ = sizeof(mask->s_addr);
2432 memcpy(p, &mask->s_addr, sizeof(mask->s_addr));
2433 p+= sizeof(mask->s_addr);
2437 return sizeof(**bootp);
2440 #if defined(ARP) || defined(KERNEL_RFC5227)
2442 dhcp_arp_address(struct interface *ifp)
2444 struct dhcp_state *state;
2445 struct in_addr addr;
2446 struct ipv4_addr *ia;
2448 eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
2450 state = D_STATE(ifp);
2451 addr.s_addr = state->offer->yiaddr == INADDR_ANY ?
2452 state->offer->ciaddr : state->offer->yiaddr;
2453 /* If the interface already has the address configured
2454 * then we can't ARP for duplicate detection. */
2455 ia = ipv4_iffindaddr(ifp, &addr, NULL);
2456 #ifdef IN_IFF_NOTUSEABLE
2457 if (ia == NULL || ia->addr_flags & IN_IFF_NOTUSEABLE) {
2458 state->state = DHS_PROBE;
2460 struct dhcp_lease l;
2462 get_lease(ifp, &l, state->offer, state->offer_len);
2463 /* Add the address now, let the kernel handle DAD. */
2464 ipv4_addaddr(ifp, &l.addr, &l.mask, &l.brd,
2465 l.leasetime, l.rebindtime);
2466 } else if (ia->addr_flags & IN_IFF_DUPLICATED)
2467 dhcp_addr_duplicated(ifp, &ia->addr);
2469 loginfox("%s: waiting for DAD on %s",
2470 ifp->name, inet_ntoa(addr));
2474 if (!(ifp->flags & IFF_NOARP) &&
2475 ifp->options->options & DHCPCD_ARP)
2477 struct arp_state *astate;
2478 struct dhcp_lease l;
2480 /* Even if the address exists, we need to defend it. */
2481 astate = dhcp_arp_new(ifp, &addr);
2486 state->state = DHS_PROBE;
2487 get_lease(ifp, &l, state->offer, state->offer_len);
2488 loginfox("%s: probing address %s/%d",
2489 ifp->name, inet_ntoa(l.addr), inet_ntocidr(l.mask));
2490 /* We need to handle DAD. */
2501 dhcp_arp_bind(struct interface *ifp)
2504 if (ifp->ctx->options & DHCPCD_TEST ||
2505 dhcp_arp_address(ifp) == 1)
2511 dhcp_lastlease(void *arg)
2513 struct interface *ifp = arg;
2514 struct dhcp_state *state = D_STATE(ifp);
2516 loginfox("%s: timed out contacting a DHCP server, using last lease",
2518 #if defined(ARP) || defined(KERNEL_RFC5227)
2523 /* Set expired here because dhcp_bind() -> ipv4_addaddr() will reset
2525 state->added |= STATE_EXPIRED;
2526 state->interval = 0;
2531 dhcp_static(struct interface *ifp)
2533 struct if_options *ifo;
2534 struct dhcp_state *state;
2535 struct ipv4_addr *ia;
2537 state = D_STATE(ifp);
2541 if (ifo->req_addr.s_addr == INADDR_ANY &&
2542 (ia = ipv4_iffindaddr(ifp, NULL, NULL)) == NULL)
2544 loginfox("%s: waiting for 3rd party to "
2545 "configure IP address", ifp->name);
2546 state->reason = "3RDPARTY";
2547 script_runreason(ifp, state->reason);
2551 state->offer_len = dhcp_message_new(&state->offer,
2552 ia ? &ia->addr : &ifo->req_addr,
2553 ia ? &ia->mask : &ifo->req_mask);
2554 if (state->offer_len)
2555 #if defined(ARP) || defined(KERNEL_RFC5227)
2563 dhcp_inform(struct interface *ifp)
2565 struct dhcp_state *state;
2566 struct if_options *ifo;
2567 struct ipv4_addr *ia;
2569 state = D_STATE(ifp);
2572 state->state = DHS_INFORM;
2574 state->offer = NULL;
2575 state->offer_len = 0;
2577 if (ifo->req_addr.s_addr == INADDR_ANY) {
2578 ia = ipv4_iffindaddr(ifp, NULL, NULL);
2580 loginfox("%s: waiting for 3rd party to "
2581 "configure IP address",
2583 if (!(ifp->ctx->options & DHCPCD_TEST)) {
2584 state->reason = "3RDPARTY";
2585 script_runreason(ifp, state->reason);
2590 ia = ipv4_iffindaddr(ifp, &ifo->req_addr, &ifo->req_mask);
2592 if (ifp->ctx->options & DHCPCD_TEST) {
2593 logerrx("%s: cannot add IP address in test mode",
2597 ia = ipv4_iffindaddr(ifp, &ifo->req_addr, NULL);
2599 /* Netmask must be different, delete it. */
2600 ipv4_deladdr(ia, 1);
2601 state->offer_len = dhcp_message_new(&state->offer,
2602 &ifo->req_addr, &ifo->req_mask);
2604 if (dhcp_arp_address(ifp) != 1)
2607 ia = ipv4_iffindaddr(ifp,
2608 &ifo->req_addr, &ifo->req_mask);
2614 state->offer_len = dhcp_message_new(&state->offer,
2615 &ia->addr, &ia->mask);
2616 if (state->offer_len) {
2618 get_lease(ifp, &state->lease, state->offer, state->offer_len);
2624 dhcp_reboot_newopts(struct interface *ifp, unsigned long long oldopts)
2626 struct if_options *ifo;
2627 struct dhcp_state *state = D_STATE(ifp);
2629 if (state == NULL || state->state == DHS_NONE)
2632 if ((ifo->options & (DHCPCD_INFORM | DHCPCD_STATIC) &&
2633 (state->addr == NULL ||
2634 state->addr->addr.s_addr != ifo->req_addr.s_addr)) ||
2635 (oldopts & (DHCPCD_INFORM | DHCPCD_STATIC) &&
2636 !(ifo->options & (DHCPCD_INFORM | DHCPCD_STATIC))))
2638 dhcp_drop(ifp, "EXPIRE");
2644 dhcp_activeaddr(const struct interface *ifp, const struct in_addr *addr)
2646 const struct interface *ifp1;
2647 const struct dhcp_state *state;
2649 TAILQ_FOREACH(ifp1, ifp->ctx->ifaces, next) {
2652 if ((state = D_CSTATE(ifp1)) == NULL)
2654 switch(state->state) {
2664 if (state->lease.addr.s_addr == addr->s_addr)
2672 dhcp_reboot(struct interface *ifp)
2674 struct if_options *ifo;
2675 struct dhcp_state *state = D_STATE(ifp);
2677 struct ipv4_addr *ia;
2680 if (state == NULL || state->state == DHS_NONE)
2683 state->state = DHS_REBOOT;
2684 state->interval = 0;
2686 if (ifo->options & DHCPCD_LINK && !if_is_link_up(ifp)) {
2687 loginfox("%s: waiting for carrier", ifp->name);
2690 if (ifo->options & DHCPCD_STATIC) {
2694 if (ifo->options & DHCPCD_INFORM) {
2695 loginfox("%s: informing address of %s",
2696 ifp->name, inet_ntoa(state->lease.addr));
2700 if (ifo->reboot == 0 || state->offer == NULL) {
2704 if (!IS_DHCP(state->offer))
2707 loginfox("%s: rebinding lease of %s",
2708 ifp->name, inet_ntoa(state->lease.addr));
2711 #ifndef KERNEL_RFC5227
2712 /* Create the DHCP ARP state so we can defend it. */
2713 (void)dhcp_arp_new(ifp, &state->lease.addr);
2716 /* If the address exists on the interface and no other interface
2717 * is currently using it then announce it to ensure this
2718 * interface gets the reply. */
2719 ia = ipv4_iffindaddr(ifp, &state->lease.addr, NULL);
2721 !(ifp->ctx->options & DHCPCD_TEST) &&
2722 #ifdef IN_IFF_NOTUSEABLE
2723 !(ia->addr_flags & IN_IFF_NOTUSEABLE) &&
2725 dhcp_activeaddr(ifp, &state->lease.addr) == 0)
2726 arp_ifannounceaddr(ifp, &state->lease.addr);
2730 state->lease.server.s_addr = INADDR_ANY;
2731 eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
2734 /* Need to add this before dhcp_expire and friends. */
2735 if (!ifo->fallback && ifo->options & DHCPCD_IPV4LL)
2736 eloop_timeout_add_sec(ifp->ctx->eloop,
2737 ifo->reboot, ipv4ll_start, ifp);
2740 if (ifo->options & DHCPCD_LASTLEASE && state->lease.frominfo)
2741 eloop_timeout_add_sec(ifp->ctx->eloop,
2742 ifo->reboot, dhcp_lastlease, ifp);
2743 else if (!(ifo->options & DHCPCD_INFORM))
2744 eloop_timeout_add_sec(ifp->ctx->eloop,
2745 ifo->reboot, dhcp_expire, ifp);
2747 /* Don't bother ARP checking as the server could NAK us first.
2748 * Don't call dhcp_request as that would change the state */
2753 dhcp_drop(struct interface *ifp, const char *reason)
2755 struct dhcp_state *state;
2760 state = D_STATE(ifp);
2761 /* dhcp_start may just have been called and we don't yet have a state
2762 * but we do have a timeout, so punt it. */
2763 if (state == NULL || state->state == DHS_NONE) {
2764 eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
2769 if (state->addr != NULL)
2770 arp_freeaddr(ifp, &state->addr->addr);
2773 state->arping_index = -1;
2776 if (ifp->options->options & DHCPCD_RELEASE &&
2777 !(ifp->options->options & DHCPCD_INFORM))
2779 /* Failure to send the release may cause this function to
2780 * re-enter so guard by setting the state. */
2781 if (state->state == DHS_RELEASE)
2783 state->state = DHS_RELEASE;
2785 dhcp_unlink(ifp->ctx, state->leasefile);
2786 if (if_is_link_up(ifp) &&
2787 state->new != NULL &&
2788 state->lease.server.s_addr != INADDR_ANY)
2790 loginfox("%s: releasing lease of %s",
2791 ifp->name, inet_ntoa(state->lease.addr));
2793 send_message(ifp, DHCP_RELEASE, NULL);
2795 /* Give the packet a chance to go */
2796 ts.tv_sec = RELEASE_DELAY_S;
2797 ts.tv_nsec = RELEASE_DELAY_NS;
2798 nanosleep(&ts, NULL);
2803 else if (state->auth.reconf != NULL) {
2805 * Drop the lease as the token may only be present
2806 * in the initial reply message and not subsequent
2808 * If dhcpcd is restarted, the token is lost.
2809 * XXX persist this in another file?
2811 dhcp_unlink(ifp->ctx, state->leasefile);
2815 eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
2817 dhcp_auth_reset(&state->auth);
2820 /* Close DHCP ports so a changed interface family is picked
2821 * up by a new BPF state. */
2824 state->state = DHS_NONE;
2826 state->offer = NULL;
2827 state->offer_len = 0;
2829 state->old = state->new;
2830 state->old_len = state->new_len;
2833 state->reason = reason;
2834 if (ifp->options->options & DHCPCD_CONFIGURE)
2835 ipv4_applyaddr(ifp);
2839 script_runreason(ifp, state->reason);
2844 state->lease.addr.s_addr = 0;
2845 ifp->options->options &= ~(DHCPCD_CSR_WARNED |
2846 DHCPCD_ROUTER_HOST_ROUTE_WARNED);
2850 blacklisted_ip(const struct if_options *ifo, in_addr_t addr)
2854 for (i = 0; i < ifo->blacklist_len; i += 2)
2855 if (ifo->blacklist[i] == (addr & ifo->blacklist[i + 1]))
2860 #define WHTLST_NONE 0
2861 #define WHTLST_MATCH 1
2862 #define WHTLST_NOMATCH 2
2864 whitelisted_ip(const struct if_options *ifo, in_addr_t addr)
2868 if (ifo->whitelist_len == 0)
2870 for (i = 0; i < ifo->whitelist_len; i += 2)
2871 if (ifo->whitelist[i] == (addr & ifo->whitelist[i + 1]))
2872 return WHTLST_MATCH;
2873 return WHTLST_NOMATCH;
2877 log_dhcp(int loglevel, const char *msg,
2878 const struct interface *ifp, const struct bootp *bootp, size_t bootp_len,
2879 const struct in_addr *from, int ad)
2882 char *a, sname[sizeof(bootp->sname) * 4];
2883 struct in_addr addr;
2887 if (strcmp(msg, "NAK:") == 0) {
2888 a = get_option_string(ifp->ctx, bootp, bootp_len, DHO_MESSAGE);
2894 tmpl = (al * 4) + 1;
2901 print_string(tmp, tmpl, OT_STRING, (uint8_t *)a, al);
2905 } else if (ad && bootp->yiaddr != 0) {
2906 addr.s_addr = bootp->yiaddr;
2907 a = strdup(inet_ntoa(addr));
2916 r = get_option_addr(ifp->ctx, &addr, bootp, bootp_len, DHO_SERVERID);
2917 if (get_option_uint8(ifp->ctx, &overl, bootp, bootp_len,
2918 DHO_OPTSOVERLOADED) == -1)
2920 if (bootp->sname[0] && r == 0 && !(overl & 2)) {
2921 print_string(sname, sizeof(sname), OT_STRING | OT_DOMAIN,
2922 bootp->sname, sizeof(bootp->sname));
2924 logmessage(loglevel, "%s: %s %s %s %s",
2925 ifp->name, msg, tfrom, inet_ntoa(addr), sname);
2927 logmessage(loglevel, "%s: %s %s %s %s %s",
2928 ifp->name, msg, a, tfrom, inet_ntoa(addr), sname);
2935 logmessage(loglevel, "%s: %s %s %s",
2936 ifp->name, msg, tfrom, inet_ntoa(addr));
2938 logmessage(loglevel, "%s: %s %s %s %s",
2939 ifp->name, msg, a, tfrom, inet_ntoa(addr));
2944 /* If we're sharing the same IP address with another interface on the
2945 * same network, we may receive the DHCP reply on the wrong interface.
2946 * Try and re-direct it here. */
2948 dhcp_redirect_dhcp(struct interface *ifp, struct bootp *bootp, size_t bootp_len,
2949 const struct in_addr *from)
2951 struct interface *ifn;
2952 const struct dhcp_state *state;
2955 xid = ntohl(bootp->xid);
2956 TAILQ_FOREACH(ifn, ifp->ctx->ifaces, next) {
2959 state = D_CSTATE(ifn);
2960 if (state == NULL || state->state == DHS_NONE)
2962 if (state->xid != xid)
2964 if (ifn->hwlen <= sizeof(bootp->chaddr) &&
2965 memcmp(bootp->chaddr, ifn->hwaddr, ifn->hwlen))
2967 logdebugx("%s: redirecting DHCP message to %s",
2968 ifp->name, ifn->name);
2969 dhcp_handledhcp(ifn, bootp, bootp_len, from);
2974 dhcp_handledhcp(struct interface *ifp, struct bootp *bootp, size_t bootp_len,
2975 const struct in_addr *from)
2977 struct dhcp_state *state = D_STATE(ifp);
2978 struct if_options *ifo = ifp->options;
2979 struct dhcp_lease *lease = &state->lease;
2981 struct in_addr addr;
2985 uint32_t v6only_time = 0;
2986 bool use_v6only = false;
2988 const uint8_t *auth;
2991 #ifdef IN_IFF_DUPLICATED
2992 struct ipv4_addr *ia;
2995 #define LOGDHCP0(l, m) \
2996 log_dhcp((l), (m), ifp, bootp, bootp_len, from, 0)
2997 #define LOGDHCP(l, m) \
2998 log_dhcp((l), (m), ifp, bootp, bootp_len, from, 1)
3000 #define IS_STATE_ACTIVE(s) ((s)-state != DHS_NONE && \
3001 (s)->state != DHS_INIT && (s)->state != DHS_BOUND)
3003 if (bootp->op != BOOTREPLY) {
3004 if (IS_STATE_ACTIVE(state))
3005 logdebugx("%s: op (%d) is not BOOTREPLY",
3006 ifp->name, bootp->op);
3010 if (state->xid != ntohl(bootp->xid)) {
3011 if (IS_STATE_ACTIVE(state))
3012 logdebugx("%s: wrong xid 0x%x (expecting 0x%x) from %s",
3013 ifp->name, ntohl(bootp->xid), state->xid,
3015 dhcp_redirect_dhcp(ifp, bootp, bootp_len, from);
3019 if (ifp->hwlen <= sizeof(bootp->chaddr) &&
3020 memcmp(bootp->chaddr, ifp->hwaddr, ifp->hwlen))
3022 if (IS_STATE_ACTIVE(state)) {
3023 char buf[sizeof(bootp->chaddr) * 3];
3025 logdebugx("%s: xid 0x%x is for hwaddr %s",
3026 ifp->name, ntohl(bootp->xid),
3027 hwaddr_ntoa(bootp->chaddr, sizeof(bootp->chaddr),
3030 dhcp_redirect_dhcp(ifp, bootp, bootp_len, from);
3037 i = whitelisted_ip(ifp->options, from->s_addr);
3039 case WHTLST_NOMATCH:
3040 logwarnx("%s: non whitelisted DHCP packet from %s",
3041 ifp->name, inet_ntoa(*from));
3046 if (blacklisted_ip(ifp->options, from->s_addr) == 1) {
3047 logwarnx("%s: blacklisted DHCP packet from %s",
3048 ifp->name, inet_ntoa(*from));
3053 /* We may have found a BOOTP server */
3054 if (get_option_uint8(ifp->ctx, &type,
3055 bootp, bootp_len, DHO_MESSAGETYPE) == -1)
3057 else if (ifo->options & DHCPCD_BOOTP) {
3058 logdebugx("%s: ignoring DHCP reply (expecting BOOTP)",
3064 /* Authenticate the message */
3065 auth = get_option(ifp->ctx, bootp, bootp_len,
3066 DHO_AUTHENTICATION, &auth_len);
3068 if (dhcp_auth_validate(&state->auth, &ifo->auth,
3069 (uint8_t *)bootp, bootp_len, 4, type,
3070 auth, auth_len) == NULL)
3072 LOGDHCP0(LOG_ERR, "authentication failed");
3075 if (state->auth.token)
3076 logdebugx("%s: validated using 0x%08" PRIu32,
3077 ifp->name, state->auth.token->secretid);
3079 loginfox("%s: accepted reconfigure key", ifp->name);
3080 } else if (ifo->auth.options & DHCPCD_AUTH_SEND) {
3081 if (ifo->auth.options & DHCPCD_AUTH_REQUIRE) {
3082 LOGDHCP0(LOG_ERR, "no authentication");
3085 LOGDHCP0(LOG_WARNING, "no authentication");
3090 if (type == DHCP_FORCERENEW) {
3091 if (from->s_addr == INADDR_ANY ||
3092 from->s_addr == INADDR_BROADCAST)
3094 LOGDHCP(LOG_ERR, "discarding Force Renew");
3099 LOGDHCP(LOG_ERR, "unauthenticated Force Renew");
3100 if (ifo->auth.options & DHCPCD_AUTH_REQUIRE)
3103 if (state->state != DHS_BOUND && state->state != DHS_INFORM) {
3104 LOGDHCP(LOG_DEBUG, "not bound, ignoring Force Renew");
3107 LOGDHCP(LOG_INFO, "Force Renew from");
3108 /* The rebind and expire timings are still the same, we just
3109 * enter the renew state early */
3110 if (state->state == DHS_BOUND)
3113 eloop_timeout_delete(ifp->ctx->eloop,
3118 LOGDHCP(LOG_ERR, "unauthenticated Force Renew");
3123 if (state->state == DHS_BOUND) {
3124 LOGDHCP(LOG_DEBUG, "bound, ignoring");
3128 if (state->state == DHS_PROBE) {
3129 /* Ignore any DHCP messages whilst probing a lease to bind. */
3130 LOGDHCP(LOG_DEBUG, "probing, ignoring");
3134 /* reset the message counter */
3135 state->interval = 0;
3137 /* Ensure that no reject options are present */
3138 for (i = 1; i < 255; i++) {
3139 if (has_option_mask(ifo->rejectmask, i) &&
3140 get_option_uint8(ifp->ctx, &tmp,
3141 bootp, bootp_len, (uint8_t)i) == 0)
3143 LOGDHCP(LOG_WARNING, "reject DHCP");
3148 if (type == DHCP_NAK) {
3149 /* For NAK, only check if we require the ServerID */
3150 if (has_option_mask(ifo->requiremask, DHO_SERVERID) &&
3151 get_option_addr(ifp->ctx, &addr,
3152 bootp, bootp_len, DHO_SERVERID) == -1)
3154 LOGDHCP(LOG_WARNING, "reject NAK");
3158 /* We should restart on a NAK */
3159 LOGDHCP(LOG_WARNING, "NAK:");
3160 if ((msg = get_option_string(ifp->ctx,
3161 bootp, bootp_len, DHO_MESSAGE)))
3163 logwarnx("%s: message: %s", ifp->name, msg);
3166 if (state->state == DHS_INFORM) /* INFORM should not be NAKed */
3168 if (!(ifp->ctx->options & DHCPCD_TEST)) {
3169 dhcp_drop(ifp, "NAK");
3170 dhcp_unlink(ifp->ctx, state->leasefile);
3173 /* If we constantly get NAKS then we should slowly back off */
3174 eloop_timeout_add_sec(ifp->ctx->eloop,
3175 state->nakoff, dhcp_discover, ifp);
3176 if (state->nakoff == 0)
3180 if (state->nakoff > NAKOFF_MAX)
3181 state->nakoff = NAKOFF_MAX;
3186 /* Ensure that all required options are present */
3187 for (i = 1; i < 255; i++) {
3188 if (has_option_mask(ifo->requiremask, i) &&
3189 get_option_uint8(ifp->ctx, &tmp,
3190 bootp, bootp_len, (uint8_t)i) != 0)
3192 /* If we are BOOTP, then ignore the need for serverid.
3193 * To ignore BOOTP, require dhcp_message_type.
3194 * However, nothing really stops BOOTP from providing
3195 * DHCP style options as well so the above isn't
3197 if (type == 0 && i == DHO_SERVERID)
3199 LOGDHCP(LOG_WARNING, "reject DHCP");
3204 if (has_option_mask(ifo->requestmask, DHO_IPV6_PREFERRED_ONLY)) {
3205 if (get_option_uint32(ifp->ctx, &v6only_time, bootp, bootp_len,
3206 DHO_IPV6_PREFERRED_ONLY) == 0 &&
3207 (state->state == DHS_DISCOVER || state->state == DHS_REBOOT))
3212 if (v6only_time < MIN_V6ONLY_WAIT)
3213 v6only_time = MIN_V6ONLY_WAIT;
3214 snprintf(v6msg, sizeof(v6msg),
3215 "IPv6-Only Preferred received (%u seconds)",
3217 LOGDHCP(LOG_INFO, v6msg);
3221 /* DHCP Auto-Configure, RFC 2563 */
3222 if (type == DHCP_OFFER && bootp->yiaddr == 0) {
3223 LOGDHCP(LOG_WARNING, "no address given");
3224 if ((msg = get_option_string(ifp->ctx,
3225 bootp, bootp_len, DHO_MESSAGE)))
3227 logwarnx("%s: message: %s", ifp->name, msg);
3231 if (state->state == DHS_DISCOVER &&
3232 get_option_uint8(ifp->ctx, &tmp, bootp, bootp_len,
3233 DHO_AUTOCONFIGURE) == 0)
3237 LOGDHCP(LOG_WARNING, "IPv4LL disabled from");
3244 LOGDHCP(LOG_WARNING, "IPv4LL enabled from");
3248 logerrx("%s: unknown auto configuration "
3253 eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
3254 eloop_timeout_add_sec(ifp->ctx->eloop,
3255 use_v6only ? v6only_time : DHCP_MAX,
3256 dhcp_discover, ifp);
3263 dhcp_drop(ifp, "EXPIRE");
3264 dhcp_unlink(ifp->ctx, state->leasefile);
3265 eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
3266 eloop_timeout_add_sec(ifp->ctx->eloop, v6only_time,
3267 dhcp_discover, ifp);
3271 /* Ensure that the address offered is valid */
3272 if ((type == 0 || type == DHCP_OFFER || type == DHCP_ACK) &&
3273 (bootp->ciaddr == INADDR_ANY || bootp->ciaddr == INADDR_BROADCAST)
3275 (bootp->yiaddr == INADDR_ANY || bootp->yiaddr == INADDR_BROADCAST))
3277 LOGDHCP(LOG_WARNING, "reject invalid address");
3281 #ifdef IN_IFF_DUPLICATED
3282 ia = ipv4_iffindaddr(ifp, &lease->addr, NULL);
3283 if (ia && ia->addr_flags & IN_IFF_DUPLICATED) {
3284 LOGDHCP(LOG_WARNING, "declined duplicate address");
3287 ipv4_deladdr(ia, 0);
3288 eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
3289 eloop_timeout_add_sec(ifp->ctx->eloop,
3290 DHCP_RAND_MAX, dhcp_discover, ifp);
3295 bootp_copied = false;
3296 if ((type == 0 || type == DHCP_OFFER) && state->state == DHS_DISCOVER) {
3297 lease->frominfo = 0;
3298 lease->addr.s_addr = bootp->yiaddr;
3299 memcpy(&lease->cookie, bootp->vend, sizeof(lease->cookie));
3301 get_option_addr(ifp->ctx,
3302 &lease->server, bootp, bootp_len, DHO_SERVERID) != 0)
3303 lease->server.s_addr = INADDR_ANY;
3305 /* Test for rapid commit in the OFFER */
3306 if (!(ifp->ctx->options & DHCPCD_TEST) &&
3307 has_option_mask(ifo->requestmask, DHO_RAPIDCOMMIT) &&
3308 get_option(ifp->ctx, bootp, bootp_len,
3309 DHO_RAPIDCOMMIT, NULL))
3311 state->state = DHS_REQUEST;
3315 LOGDHCP(LOG_INFO, "offered");
3316 if (state->offer_len < bootp_len) {
3318 if ((state->offer = malloc(bootp_len)) == NULL) {
3320 state->offer_len = 0;
3324 state->offer_len = bootp_len;
3325 memcpy(state->offer, bootp, bootp_len);
3326 bootp_copied = true;
3327 if (ifp->ctx->options & DHCPCD_TEST) {
3329 state->old = state->new;
3330 state->old_len = state->new_len;
3331 state->new = state->offer;
3332 state->new_len = state->offer_len;
3333 state->offer = NULL;
3334 state->offer_len = 0;
3335 state->reason = "TEST";
3336 script_runreason(ifp, state->reason);
3337 eloop_exit(ifp->ctx->eloop, EXIT_SUCCESS);
3338 state->bpf->bpf_flags |= BPF_EOF;
3341 eloop_timeout_delete(ifp->ctx->eloop, send_discover, ifp);
3342 /* We don't request BOOTP addresses */
3344 /* We used to ARP check here, but that seems to be in
3345 * violation of RFC2131 where it only describes
3346 * DECLINE after REQUEST.
3347 * It also seems that some MS DHCP servers actually
3348 * ignore DECLINE if no REQUEST, ie we decline a
3356 if (type == DHCP_OFFER) {
3357 LOGDHCP(LOG_WARNING, "ignoring offer of");
3361 /* We should only be dealing with acks */
3362 if (type != DHCP_ACK) {
3363 LOGDHCP(LOG_ERR, "not ACK or OFFER");
3367 if (state->state == DHS_DISCOVER) {
3368 /* We only allow ACK of rapid commit DISCOVER. */
3369 if (has_option_mask(ifo->requestmask,
3371 get_option(ifp->ctx, bootp, bootp_len,
3372 DHO_RAPIDCOMMIT, NULL))
3373 state->state = DHS_REQUEST;
3375 LOGDHCP(LOG_DEBUG, "ignoring ack of");
3381 if (!(ifo->options & DHCPCD_INFORM))
3382 LOGDHCP(LOG_DEBUG, "acknowledged");
3384 ifo->options &= ~DHCPCD_STATIC;
3387 /* No NAK, so reset the backoff
3388 * We don't reset on an OFFER message because the server could
3389 * potentially NAK the REQUEST. */
3392 /* BOOTP could have already assigned this above. */
3393 if (!bootp_copied) {
3394 if (state->offer_len < bootp_len) {
3396 if ((state->offer = malloc(bootp_len)) == NULL) {
3398 state->offer_len = 0;
3402 state->offer_len = bootp_len;
3403 memcpy(state->offer, bootp, bootp_len);
3406 lease->frominfo = 0;
3407 eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
3409 #if defined(ARP) || defined(KERNEL_RFC5227)
3417 get_udp_data(void *packet, size_t *len)
3419 const struct ip *ip = packet;
3420 size_t ip_hl = (size_t)ip->ip_hl * 4;
3423 p += ip_hl + sizeof(struct udphdr);
3424 *len = (size_t)ntohs(ip->ip_len) - sizeof(struct udphdr) - ip_hl;
3429 is_packet_udp_bootp(void *packet, size_t plen)
3431 struct ip *ip = packet;
3435 if (plen < sizeof(*ip))
3438 if (ip->ip_v != IPVERSION || ip->ip_p != IPPROTO_UDP)
3442 if (ntohs(ip->ip_len) > plen)
3445 ip_hlen = (size_t)ip->ip_hl * 4;
3446 if (ip_hlen < sizeof(*ip))
3449 /* Check we have a UDP header and BOOTP. */
3450 if (ip_hlen + sizeof(udp) + offsetof(struct bootp, vend) > plen)
3454 memcpy(&udp, (char *)ip + ip_hlen, sizeof(udp));
3455 if (ntohs(udp.uh_ulen) < sizeof(udp))
3457 if (ip_hlen + ntohs(udp.uh_ulen) > plen)
3460 /* Check it's to and from the right ports. */
3461 if (udp.uh_dport != htons(BOOTPC) || udp.uh_sport != htons(BOOTPS))
3467 /* Lengths have already been checked. */
3469 checksums_valid(void *packet,
3470 struct in_addr *from, unsigned int flags)
3472 struct ip *ip = packet;
3475 uint16_t w[sizeof(struct ip) / 2];
3478 .ip_p = IPPROTO_UDP,
3479 .ip_src = ip->ip_src,
3480 .ip_dst = ip->ip_dst,
3485 char *udpp, *uh_sump;
3489 from->s_addr = ip->ip_src.s_addr;
3491 ip_hlen = (size_t)ip->ip_hl * 4;
3492 if (in_cksum(ip, ip_hlen, NULL) != 0)
3495 if (flags & BPF_PARTIALCSUM)
3498 udpp = (char *)ip + ip_hlen;
3499 memcpy(&udp, udpp, sizeof(udp));
3500 if (udp.uh_sum == 0)
3503 /* UDP checksum is based on a pseudo IP header alongside
3504 * the UDP header and payload. */
3505 pip.ip.ip_len = udp.uh_ulen;
3508 /* Need to zero the UDP sum in the packet for the checksum to work. */
3509 uh_sump = udpp + offsetof(struct udphdr, uh_sum);
3510 memset(uh_sump, 0, sizeof(udp.uh_sum));
3512 /* Checksum pseudo header and then UDP + payload. */
3513 in_cksum(pip.w, sizeof(pip.w), &csum);
3514 csum = in_cksum(udpp, ntohs(udp.uh_ulen), &csum);
3516 #if 0 /* Not needed, just here for completeness. */
3517 /* Put the checksum back. */
3518 memcpy(uh_sump, &udp.uh_sum, sizeof(udp.uh_sum));
3521 return csum == udp.uh_sum;
3525 dhcp_handlebootp(struct interface *ifp, struct bootp *bootp, size_t len,
3526 struct in_addr *from)
3530 if (len < offsetof(struct bootp, vend)) {
3531 logerrx("%s: truncated packet (%zu) from %s",
3532 ifp->name, len, inet_ntoa(*from));
3536 /* Unlikely, but appeases sanitizers. */
3537 if (len > FRAMELEN_MAX) {
3538 logerrx("%s: packet exceeded frame length (%zu) from %s",
3539 ifp->name, len, inet_ntoa(*from));
3543 /* To make our IS_DHCP macro easy, ensure the vendor
3544 * area has at least 4 octets. */
3545 v = len - offsetof(struct bootp, vend);
3547 bootp->vend[v++] = '\0';
3551 dhcp_handledhcp(ifp, bootp, len, from);
3555 dhcp_packet(struct interface *ifp, uint8_t *data, size_t len,
3556 unsigned int bpf_flags)
3558 struct bootp *bootp;
3559 struct in_addr from;
3561 size_t fl = bpf_frame_header_len(ifp);
3563 const struct dhcp_state *state = D_CSTATE(ifp);
3565 /* It's possible that an interface departs and arrives in short
3566 * order to receive a BPF frame out of order.
3567 * There is a similar check in ARP, but much lower down the stack.
3568 * It's not needed for other inet protocols because we send the
3569 * message as a whole and select the interface off that and then
3570 * check state. BPF on the other hand is very interface
3571 * specific and we do need this check. */
3575 /* Ignore double reads */
3576 if (IN_PRIVSEP(ifp->ctx)) {
3577 switch (state->state) {
3578 case DHS_BOUND: /* FALLTHROUGH */
3587 /* Trim frame header */
3590 logerrx("%s: %s: short frame header %zu",
3591 __func__, ifp->name, len);
3595 /* Move the data to avoid alignment errors. */
3596 memmove(data, data + fl, len);
3599 /* Validate filter. */
3600 if (!is_packet_udp_bootp(data, len)) {
3602 logerrx("%s: DHCP BPF validation failure", ifp->name);
3607 if (!checksums_valid(data, &from, bpf_flags)) {
3608 logerrx("%s: checksum failure from %s",
3609 ifp->name, inet_ntoa(from));
3614 * DHCP has a variable option area rather than a fixed vendor area.
3615 * Because DHCP uses the BOOTP protocol it should still send BOOTP
3616 * sized packets to be RFC compliant.
3617 * However some servers send a truncated vendor area.
3618 * dhcpcd can work fine without the vendor area being sent.
3620 bootp = get_udp_data(data, &udp_len);
3621 dhcp_handlebootp(ifp, bootp, udp_len, &from);
3625 dhcp_readbpf(void *arg)
3627 struct interface *ifp = arg;
3628 uint8_t buf[FRAMELEN_MAX];
3630 struct dhcp_state *state = D_STATE(ifp);
3631 struct bpf *bpf = state->bpf;
3633 bpf->bpf_flags &= ~BPF_EOF;
3634 while (!(bpf->bpf_flags & BPF_EOF)) {
3635 bytes = bpf_read(bpf, buf, sizeof(buf));
3637 if (state->state != DHS_NONE) {
3638 logerr("%s: %s", __func__, ifp->name);
3643 dhcp_packet(ifp, buf, (size_t)bytes, bpf->bpf_flags);
3644 /* Check we still have a state after processing. */
3645 if ((state = D_STATE(ifp)) == NULL)
3647 if ((bpf = state->bpf) == NULL)
3653 dhcp_recvmsg(struct dhcpcd_ctx *ctx, struct msghdr *msg)
3655 struct sockaddr_in *from = (struct sockaddr_in *)msg->msg_name;
3656 struct iovec *iov = &msg->msg_iov[0];
3657 struct interface *ifp;
3658 const struct dhcp_state *state;
3660 ifp = if_findifpfromcmsg(ctx, msg, NULL);
3665 state = D_CSTATE(ifp);
3666 if (state == NULL) {
3667 /* Try re-directing it to another interface. */
3668 dhcp_redirect_dhcp(ifp, (struct bootp *)iov->iov_base,
3669 iov->iov_len, &from->sin_addr);
3673 if (state->bpf != NULL) {
3674 /* Avoid a duplicate read if BPF is open for the interface. */
3678 if (IN_PRIVSEP(ctx)) {
3679 switch (state->state) {
3680 case DHS_BOUND: /* FALLTHROUGH */
3684 /* Any other state we ignore it or will receive
3691 dhcp_handlebootp(ifp, iov->iov_base, iov->iov_len,
3696 dhcp_readudp(struct dhcpcd_ctx *ctx, struct interface *ifp)
3698 const struct dhcp_state *state;
3699 struct sockaddr_in from;
3702 uint8_t buf[10 * 1024]; /* Maximum MTU */
3704 struct iovec iov = {
3705 .iov_base = iovbuf.buf,
3706 .iov_len = sizeof(iovbuf.buf),
3711 uint8_t buf[CMSG_SPACE(sizeof(struct sockaddr_dl))];
3713 uint8_t buf[CMSG_SPACE(sizeof(struct in_pktinfo))];
3715 } cmsgbuf = { .buf = { 0 } };
3716 struct msghdr msg = {
3717 .msg_name = &from, .msg_namelen = sizeof(from),
3718 .msg_iov = &iov, .msg_iovlen = 1,
3719 .msg_control = cmsgbuf.buf, .msg_controllen = sizeof(cmsgbuf.buf),
3725 state = D_CSTATE(ifp);
3730 bytes = recvmsg(s, &msg, 0);
3736 iov.iov_len = (size_t)bytes;
3737 dhcp_recvmsg(ctx, &msg);
3741 dhcp_handleudp(void *arg)
3743 struct dhcpcd_ctx *ctx = arg;
3745 dhcp_readudp(ctx, NULL);
3749 dhcp_handleifudp(void *arg)
3751 struct interface *ifp = arg;
3753 dhcp_readudp(ifp->ctx, ifp);
3757 dhcp_openbpf(struct interface *ifp)
3759 struct dhcp_state *state;
3761 state = D_STATE(ifp);
3764 if (IN_PRIVSEP_SE(ifp->ctx)) {
3765 if (ps_bpf_openbootp(ifp) == -1) {
3773 if (state->bpf != NULL)
3776 state->bpf = bpf_open(ifp, bpf_bootp, NULL);
3777 if (state->bpf == NULL) {
3778 if (errno == ENOENT) {
3779 logerrx("%s not found", bpf_name);
3780 /* May as well disable IPv4 entirely at
3781 * this point as we really need it. */
3782 ifp->options->options &= ~DHCPCD_IPV4;
3784 logerr("%s: %s", __func__, ifp->name);
3788 eloop_event_add(ifp->ctx->eloop,
3789 state->bpf->bpf_fd, dhcp_readbpf, ifp);
3794 dhcp_free(struct interface *ifp)
3796 struct dhcp_state *state = D_STATE(ifp);
3797 struct dhcpcd_ctx *ctx;
3804 state->state = DHS_NONE;
3808 free(state->clientid);
3813 /* If we don't have any more DHCP enabled interfaces,
3814 * close the global socket and release resources */
3816 TAILQ_FOREACH(ifp, ctx->ifaces, next) {
3817 state = D_STATE(ifp);
3818 if (state != NULL && state->state != DHS_NONE)
3823 if (ctx->udp_rfd != -1) {
3824 eloop_event_delete(ctx->eloop, ctx->udp_rfd);
3825 close(ctx->udp_rfd);
3828 if (ctx->udp_wfd != -1) {
3829 close(ctx->udp_wfd);
3833 free(ctx->opt_buffer);
3834 ctx->opt_buffer = NULL;
3839 dhcp_initstate(struct interface *ifp)
3841 struct dhcp_state *state;
3843 state = D_STATE(ifp);
3847 ifp->if_data[IF_DATA_DHCP] = calloc(1, sizeof(*state));
3848 state = D_STATE(ifp);
3852 state->state = DHS_NONE;
3853 /* 0 is a valid fd, so init to -1 */
3854 state->udp_rfd = -1;
3856 state->arping_index = -1;
3862 dhcp_init(struct interface *ifp)
3864 struct dhcp_state *state;
3865 struct if_options *ifo;
3867 char buf[(sizeof(ifo->clientid) - 1) * 3];
3869 if (dhcp_initstate(ifp) == -1)
3872 state = D_STATE(ifp);
3873 state->state = DHS_INIT;
3874 state->reason = "PREINIT";
3876 dhcp_set_leasefile(state->leasefile, sizeof(state->leasefile),
3880 /* We need to drop the leasefile so that dhcp_start
3881 * doesn't load it. */
3882 if (ifo->options & DHCPCD_REQUEST)
3883 dhcp_unlink(ifp->ctx, state->leasefile);
3885 free(state->clientid);
3886 state->clientid = NULL;
3888 if (ifo->options & DHCPCD_ANONYMOUS) {
3889 /* Removing the option could show that we want anonymous.
3890 * As such keep it as it's already in the hwaddr field. */
3892 } else if (*ifo->clientid) {
3893 state->clientid = malloc((size_t)(ifo->clientid[0] + 1));
3894 if (state->clientid == NULL)
3896 memcpy(state->clientid, ifo->clientid,
3897 (size_t)(ifo->clientid[0]) + 1);
3898 } else if (ifo->options & DHCPCD_CLIENTID) {
3899 if (ifo->options & DHCPCD_DUID) {
3900 state->clientid = malloc(ifp->ctx->duid_len + 6);
3901 if (state->clientid == NULL)
3903 state->clientid[0] =(uint8_t)(ifp->ctx->duid_len + 5);
3904 state->clientid[1] = 255; /* RFC 4361 */
3905 memcpy(state->clientid + 2, ifo->iaid, 4);
3906 memcpy(state->clientid + 6, ifp->ctx->duid,
3907 ifp->ctx->duid_len);
3910 len = (uint8_t)(ifp->hwlen + 1);
3911 state->clientid = malloc((size_t)len + 1);
3912 if (state->clientid == NULL)
3914 state->clientid[0] = len;
3915 state->clientid[1] = (uint8_t)ifp->hwtype;
3916 memcpy(state->clientid + 2, ifp->hwaddr,
3921 if (ifo->options & DHCPCD_DUID)
3922 /* Don't bother logging as DUID and IAID are reported
3923 * at device start. */
3926 if (ifo->options & DHCPCD_CLIENTID && state->clientid != NULL)
3927 logdebugx("%s: using ClientID %s", ifp->name,
3928 hwaddr_ntoa(state->clientid + 1, state->clientid[0],
3930 else if (ifp->hwlen)
3931 logdebugx("%s: using hwaddr %s", ifp->name,
3932 hwaddr_ntoa(ifp->hwaddr, ifp->hwlen, buf, sizeof(buf)));
3941 dhcp_start1(void *arg)
3943 struct interface *ifp = arg;
3944 struct dhcpcd_ctx *ctx = ifp->ctx;
3945 struct if_options *ifo = ifp->options;
3946 struct dhcp_state *state;
3950 if (!(ifo->options & DHCPCD_IPV4))
3953 /* Listen on *.*.*.*:bootpc so that the kernel never sends an
3954 * ICMP port unreachable message back to the DHCP server.
3955 * Only do this in master mode so we don't swallow messages
3956 * for dhcpcd running on another interface. */
3957 if ((ctx->options & (DHCPCD_MASTER|DHCPCD_PRIVSEP)) == DHCPCD_MASTER
3958 && ctx->udp_rfd == -1)
3960 ctx->udp_rfd = dhcp_openudp(NULL);
3961 if (ctx->udp_rfd == -1) {
3965 eloop_event_add(ctx->eloop, ctx->udp_rfd, dhcp_handleudp, ctx);
3967 if (!IN_PRIVSEP(ctx) && ctx->udp_wfd == -1) {
3968 ctx->udp_wfd = xsocket(PF_INET, SOCK_RAW|SOCK_CXNB,IPPROTO_UDP);
3969 if (ctx->udp_wfd == -1) {
3975 if (dhcp_init(ifp) == -1) {
3976 logerr("%s: dhcp_init", ifp->name);
3980 state = D_STATE(ifp);
3981 clock_gettime(CLOCK_MONOTONIC, &state->started);
3982 state->interval = 0;
3984 state->offer = NULL;
3985 state->offer_len = 0;
3988 if (ifo->arping_len && state->arping_index < ifo->arping_len) {
3994 if (ifo->options & DHCPCD_STATIC) {
3999 if (ifo->options & DHCPCD_INFORM) {
4004 /* We don't want to read the old lease if we NAK an old test */
4005 nolease = state->offer && ifp->ctx->options & DHCPCD_TEST;
4006 if (!nolease && ifo->options & DHCPCD_DHCP) {
4007 state->offer_len = read_lease(ifp, &state->offer);
4008 /* Check the saved lease matches the type we want */
4010 #ifdef IN_IFF_DUPLICATED
4011 struct in_addr addr;
4012 struct ipv4_addr *ia;
4014 addr.s_addr = state->offer->yiaddr;
4015 ia = ipv4_iffindaddr(ifp, &addr, NULL);
4018 if ((!IS_DHCP(state->offer) &&
4019 !(ifo->options & DHCPCD_BOOTP)) ||
4020 #ifdef IN_IFF_DUPLICATED
4021 (ia && ia->addr_flags & IN_IFF_DUPLICATED) ||
4023 (IS_DHCP(state->offer) &&
4024 ifo->options & DHCPCD_BOOTP))
4027 state->offer = NULL;
4028 state->offer_len = 0;
4033 struct ipv4_addr *ia;
4036 get_lease(ifp, &state->lease, state->offer, state->offer_len);
4037 state->lease.frominfo = 1;
4038 if (state->new == NULL &&
4039 (ia = ipv4_iffindaddr(ifp,
4040 &state->lease.addr, &state->lease.mask)) != NULL)
4042 /* We still have the IP address from the last lease.
4043 * Fake add the address and routes from it so the lease
4044 * can be cleaned up. */
4045 state->new = malloc(state->offer_len);
4048 state->offer, state->offer_len);
4049 state->new_len = state->offer_len;
4051 state->added |= STATE_ADDED | STATE_FAKE;
4052 rt_build(ifp->ctx, AF_INET);
4056 if (!IS_DHCP(state->offer)) {
4058 state->offer = NULL;
4059 state->offer_len = 0;
4060 } else if (!(ifo->options & DHCPCD_LASTLEASE_EXTEND) &&
4061 state->lease.leasetime != DHCP_INFINITE_LIFETIME &&
4062 dhcp_filemtime(ifp->ctx, state->leasefile, &mtime) == 0)
4066 /* Offset lease times and check expiry */
4069 (time_t)state->lease.leasetime < now - mtime)
4071 logdebugx("%s: discarding expired lease",
4074 state->offer = NULL;
4075 state->offer_len = 0;
4076 state->lease.addr.s_addr = 0;
4077 /* Technically we should discard the lease
4078 * as it's expired, just as DHCPv6 addresses
4079 * would be by the kernel.
4080 * However, this may violate POLA so
4081 * we currently leave it be.
4082 * If we get a totally different lease from
4083 * the DHCP server we'll drop it anyway, as
4084 * we will on any other event which would
4085 * trigger a lease drop.
4086 * This should only happen if dhcpcd stops
4087 * running and the lease expires before
4088 * dhcpcd starts again. */
4091 dhcp_drop(ifp, "EXPIRE");
4094 l = (uint32_t)(now - mtime);
4095 state->lease.leasetime -= l;
4096 state->lease.renewaltime -= l;
4097 state->lease.rebindtime -= l;
4103 if (!(ifo->options & DHCPCD_DHCP)) {
4104 if (ifo->options & DHCPCD_IPV4LL)
4110 if (state->offer == NULL ||
4111 !IS_DHCP(state->offer) ||
4112 ifo->options & DHCPCD_ANONYMOUS)
4119 dhcp_start(struct interface *ifp)
4123 const struct dhcp_state *state;
4126 if (!(ifp->options->options & DHCPCD_IPV4))
4129 /* If we haven't been given a netmask for our requested address,
4131 if (ifp->options->req_addr.s_addr != INADDR_ANY &&
4132 ifp->options->req_mask.s_addr == INADDR_ANY)
4133 ifp->options->req_mask.s_addr =
4134 ipv4_getnetmask(ifp->options->req_addr.s_addr);
4136 /* If we haven't specified a ClientID and our hardware address
4137 * length is greater than BOOTP CHADDR then we enforce a ClientID
4138 * of the hardware address type and the hardware address.
4139 * If there is no hardware address and no ClientID set,
4140 * force a DUID based ClientID. */
4141 if (ifp->hwlen > 16)
4142 ifp->options->options |= DHCPCD_CLIENTID;
4143 else if (ifp->hwlen == 0 && !(ifp->options->options & DHCPCD_CLIENTID))
4144 ifp->options->options |= DHCPCD_CLIENTID | DHCPCD_DUID;
4146 /* Firewire and InfiniBand interfaces require ClientID and
4147 * the broadcast option being set. */
4148 switch (ifp->hwtype) {
4149 case ARPHRD_IEEE1394: /* FALLTHROUGH */
4150 case ARPHRD_INFINIBAND:
4151 ifp->options->options |= DHCPCD_CLIENTID | DHCPCD_BROADCAST;
4155 /* If we violate RFC2131 section 3.7 then require ARP
4156 * to detect if any other client wants our address. */
4157 if (ifp->options->options & DHCPCD_LASTLEASE_EXTEND)
4158 ifp->options->options |= DHCPCD_ARP;
4160 /* No point in delaying a static configuration */
4161 if (ifp->options->options & DHCPCD_STATIC ||
4162 !(ifp->options->options & DHCPCD_INITIAL_DELAY))
4169 /* If we have arpinged then we have already delayed. */
4170 state = D_CSTATE(ifp);
4171 if (state != NULL && state->arping_index != -1) {
4176 delay = MSEC_PER_SEC +
4177 (arc4random_uniform(MSEC_PER_SEC * 2) - MSEC_PER_SEC);
4178 logdebugx("%s: delaying IPv4 for %0.1f seconds",
4179 ifp->name, (float)delay / MSEC_PER_SEC);
4181 eloop_timeout_add_msec(ifp->ctx->eloop, delay, dhcp_start1, ifp);
4185 dhcp_abort(struct interface *ifp)
4187 struct dhcp_state *state;
4189 state = D_STATE(ifp);
4192 state->arping_index = -1;
4195 eloop_timeout_delete(ifp->ctx->eloop, dhcp_start1, ifp);
4197 if (state != NULL && state->added) {
4198 rt_build(ifp->ctx, AF_INET);
4200 if (ifp->options->options & DHCPCD_ARP)
4201 arp_announceaddr(ifp->ctx, &state->addr->addr);
4207 dhcp_handleifa(int cmd, struct ipv4_addr *ia, pid_t pid)
4209 struct interface *ifp;
4210 struct dhcp_state *state;
4211 struct if_options *ifo;
4215 state = D_STATE(ifp);
4216 if (state == NULL || state->state == DHS_NONE)
4219 if (cmd == RTM_DELADDR) {
4220 if (state->addr == ia) {
4221 loginfox("%s: pid %d deleted IP address %s",
4222 ifp->name, pid, ia->saddr);
4225 /* Don't clear the added state as we need
4226 * to drop the lease. */
4227 dhcp_drop(ifp, "EXPIRE");
4233 if (cmd != RTM_NEWADDR)
4236 #ifdef IN_IFF_NOTUSEABLE
4237 if (!(ia->addr_flags & IN_IFF_NOTUSEABLE))
4238 dhcp_finish_dad(ifp, &ia->addr);
4239 else if (ia->addr_flags & IN_IFF_DUPLICATED)
4240 return dhcp_addr_duplicated(ifp, &ia->addr) ? NULL : ia;
4246 if (IN_PRIVSEP_SE(ifp->ctx) &&
4247 !(ifp->ctx->options & (DHCPCD_MASTER | DHCPCD_CONFIGURE)) &&
4248 IN_ARE_ADDR_EQUAL(&state->lease.addr, &ia->addr))
4251 state->added = STATE_ADDED;
4253 if (ps_inet_openbootp(ia) == -1)
4258 if (ifo->options & DHCPCD_INFORM) {
4259 if (state->state != DHS_INFORM)
4264 if (!(ifo->options & DHCPCD_STATIC))
4266 if (ifo->req_addr.s_addr != INADDR_ANY)
4270 state->old = state->new;
4271 state->new_len = dhcp_message_new(&state->new, &ia->addr, &ia->mask);
4272 if (state->new == NULL)
4274 if (ifp->flags & IFF_POINTOPOINT) {
4275 for (i = 1; i < 255; i++)
4276 if (i != DHO_ROUTER && has_option_mask(ifo->dstmask,i))
4277 dhcp_message_add_addr(state->new, i, ia->brd);
4279 state->reason = "STATIC";
4280 rt_build(ifp->ctx, AF_INET);
4281 script_runreason(ifp, state->reason);
4282 if (ifo->options & DHCPCD_INFORM) {
4283 state->state = DHS_INFORM;
4285 state->lease.server.s_addr = INADDR_ANY;
4295 dhcp_dump(struct interface *ifp)
4297 struct dhcp_state *state;
4299 ifp->if_data[IF_DATA_DHCP] = state = calloc(1, sizeof(*state));
4300 if (state == NULL) {
4304 state->new_len = read_lease(ifp, &state->new);
4305 if (state->new == NULL) {
4306 logerr("read_lease");
4309 state->reason = "DUMP";
4310 return script_runreason(ifp, state->reason);