1 /* SPDX-License-Identifier: BSD-2-Clause */
3 * dhcpcd - DHCP client daemon
4 * Copyright (c) 2006-2019 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>
33 #include <arpa/inet.h>
35 #include <net/route.h>
36 #include <netinet/if_ether.h>
37 #include <netinet/in_systm.h>
38 #include <netinet/in.h>
39 #include <netinet/ip.h>
40 #define __FAVOR_BSD /* Nasty glibc hack so we can use BSD semantics for UDP */
41 #include <netinet/udp.h>
63 #include "dhcp-common.h"
73 #define DAD "Duplicate address detected"
74 #define DHCP_MIN_LEASE 20
76 #define IPV4A ADDRIPV4 | ARRAY
77 #define IPV4R ADDRIPV4 | REQUEST
79 /* We should define a maximum for the NAK exponential backoff */
82 /* Wait N nanoseconds between sending a RELEASE and dropping the address.
83 * This gives the kernel enough time to actually send it. */
84 #define RELEASE_DELAY_S 0
85 #define RELEASE_DELAY_NS 10000000
88 #define IPDEFTTL 64 /* RFC1340 */
91 /* Support older systems with different defines */
92 #if !defined(IP_RECVPKTINFO) && defined(IP_PKTINFO)
93 #define IP_RECVPKTINFO IP_PKTINFO
96 /* Assert the correct structure size for on wire */
97 __CTASSERT(sizeof(struct ip) == 20);
98 __CTASSERT(sizeof(struct udphdr) == 8);
99 __CTASSERT(sizeof(struct bootp) == 300);
106 static const struct dhcp_op dhcp_ops[] = {
107 { DHCP_DISCOVER, "DISCOVER" },
108 { DHCP_OFFER, "OFFER" },
109 { DHCP_REQUEST, "REQUEST" },
110 { DHCP_DECLINE, "DECLINE" },
113 { DHCP_RELEASE, "RELEASE" },
114 { DHCP_INFORM, "INFORM" },
115 { DHCP_FORCERENEW, "FORCERENEW"},
119 static const char * const dhcp_params[] = {
128 static int dhcp_openbpf(struct interface *);
129 static void dhcp_start1(void *);
130 #if defined(ARP) && (!defined(KERNEL_RFC5227) || defined(ARPING))
131 static void dhcp_arp_found(struct arp_state *, const struct arp_msg *);
133 static void dhcp_handledhcp(struct interface *, struct bootp *, size_t,
134 const struct in_addr *);
136 static void dhcp_handleifudp(void *);
138 static int dhcp_initstate(struct interface *);
141 dhcp_printoptions(const struct dhcpcd_ctx *ctx,
142 const struct dhcp_opt *opts, size_t opts_len)
144 const char * const *p;
146 const struct dhcp_opt *opt, *opt2;
149 for (p = dhcp_params; *p; p++)
152 for (i = 0, opt = ctx->dhcp_opts; i < ctx->dhcp_opts_len; i++, opt++) {
153 for (j = 0, opt2 = opts; j < opts_len; j++, opt2++)
154 if (opt->option == opt2->option)
157 cols = printf("%03d %s", opt->option, opt->var);
158 dhcp_print_option_encoding(opt, cols);
161 for (i = 0, opt = opts; i < opts_len; i++, opt++) {
162 cols = printf("%03d %s", opt->option, opt->var);
163 dhcp_print_option_encoding(opt, cols);
167 #define get_option_raw(ctx, bootp, bootp_len, opt) \
168 get_option((ctx), (bootp), (bootp_len), NULL)
169 static const uint8_t *
170 get_option(struct dhcpcd_ctx *ctx,
171 const struct bootp *bootp, size_t bootp_len,
172 unsigned int opt, size_t *opt_len)
174 const uint8_t *p, *e;
175 uint8_t l, o, ol, overl, *bp;
179 /* Check we have the magic cookie */
180 if (!IS_DHCP(bootp)) {
185 p = bootp->vend + 4; /* options after the 4 byte cookie */
186 e = (const uint8_t *)bootp + bootp_len;
195 /* No length to read */
199 /* bit 1 set means parse boot file */
200 overl = (uint8_t)(overl & ~1);
202 e = p + sizeof(bootp->file);
203 } else if (overl & 2) {
204 /* bit 2 set means parse server name */
205 overl = (uint8_t)(overl & ~2);
207 e = p + sizeof(bootp->sname);
210 /* No length to read */
214 /* Check we can read the length */
221 /* Check we can read the option data, if present */
227 if (o == DHO_OPTSOVERLOADED) {
228 /* Ensure we only get this option once by setting
229 * the last bit as well as the value.
230 * This is valid because only the first two bits
231 * actually mean anything in RFC2132 Section 9.3 */
232 if (l == 1 && !overl)
238 /* We must concatonate the options. */
239 if (bl + l > ctx->opt_buffer_len) {
245 (bp - ctx->opt_buffer);
248 nb = realloc(ctx->opt_buffer, bl + l);
251 ctx->opt_buffer = nb;
252 ctx->opt_buffer_len = bl + l;
253 bp = ctx->opt_buffer + pos;
256 bp = ctx->opt_buffer;
272 return (const uint8_t *)ctx->opt_buffer;
281 get_option_addr(struct dhcpcd_ctx *ctx,
282 struct in_addr *a, const struct bootp *bootp, size_t bootp_len,
288 p = get_option(ctx, bootp, bootp_len, option, &len);
289 if (!p || len < (ssize_t)sizeof(a->s_addr))
291 memcpy(&a->s_addr, p, sizeof(a->s_addr));
296 get_option_uint32(struct dhcpcd_ctx *ctx,
297 uint32_t *i, const struct bootp *bootp, size_t bootp_len, uint8_t option)
303 p = get_option(ctx, bootp, bootp_len, option, &len);
304 if (!p || len < (ssize_t)sizeof(d))
306 memcpy(&d, p, sizeof(d));
313 get_option_uint16(struct dhcpcd_ctx *ctx,
314 uint16_t *i, const struct bootp *bootp, size_t bootp_len, uint8_t option)
320 p = get_option(ctx, bootp, bootp_len, option, &len);
321 if (!p || len < (ssize_t)sizeof(d))
323 memcpy(&d, p, sizeof(d));
330 get_option_uint8(struct dhcpcd_ctx *ctx,
331 uint8_t *i, const struct bootp *bootp, size_t bootp_len, uint8_t option)
336 p = get_option(ctx, bootp, bootp_len, option, &len);
337 if (!p || len < (ssize_t)sizeof(*p))
345 print_rfc3442(FILE *fp, const uint8_t *data, size_t data_len)
347 const uint8_t *p = data, *e;
352 /* Minimum is 5 -first is CIDR and a router length of 4 */
361 if (fputc(' ', fp) == EOF)
369 ocets = (size_t)(cidr + 7) / NBBY;
370 if (p + 4 + ocets > e) {
374 /* If we have ocets then we have a destination and netmask */
377 memcpy(&addr.s_addr, p, ocets);
380 if (fprintf(fp, "%s/%d", inet_ntoa(addr), cidr) == -1)
383 /* Finally, snag the router */
384 memcpy(&addr.s_addr, p, 4);
386 if (fprintf(fp, " %s", inet_ntoa(addr)) == -1)
390 if (fputc('\0', fp) == EOF)
396 decode_rfc3442_rt(rb_tree_t *routes, struct interface *ifp,
397 const uint8_t *data, size_t dl, const struct bootp *bootp)
399 const uint8_t *p = data;
403 struct rt *rt = NULL;
404 struct in_addr dest, netmask, gateway;
407 /* Minimum is 5 -first is CIDR and a router length of 4 */
422 ocets = (size_t)(cidr + 7) / NBBY;
423 if (p + 4 + ocets > e) {
428 if ((rt = rt_new(ifp)) == NULL)
431 /* If we have ocets then we have a destination and netmask */
434 memcpy(&dest.s_addr, p, ocets);
436 netmask.s_addr = htonl(~0U << (32 - cidr));
440 /* Finally, snag the router */
441 memcpy(&gateway.s_addr, p, 4);
444 /* An on-link host route is normally set by having the
445 * gateway match the destination or assigned address */
446 if (gateway.s_addr == dest.s_addr ||
447 (gateway.s_addr == bootp->yiaddr ||
448 gateway.s_addr == bootp->ciaddr))
450 gateway.s_addr = INADDR_ANY;
451 netmask.s_addr = INADDR_BROADCAST;
453 if (netmask.s_addr == INADDR_BROADCAST)
454 rt->rt_flags = RTF_HOST;
456 sa_in_init(&rt->rt_dest, &dest);
457 sa_in_init(&rt->rt_netmask, &netmask);
458 sa_in_init(&rt->rt_gateway, &gateway);
459 if (rt_proto_add(routes, rt))
466 print_rfc3361(FILE *fp, const uint8_t *data, size_t dl)
469 char sip[NS_MAXDNAME];
481 if (decode_rfc1035(sip, sizeof(sip), data, dl) == -1)
483 if (efprintf(fp, "%s", sip) == -1)
487 if (dl == 0 || dl % 4 != 0) {
491 addr.s_addr = INADDR_BROADCAST;
494 data += sizeof(addr.s_addr), dl -= sizeof(addr.s_addr))
496 memcpy(&addr.s_addr, data, sizeof(addr.s_addr));
497 if (fprintf(fp, "%s", inet_ntoa(addr)) == -1)
500 if (fputc(' ', fp) == EOF)
504 if (fputc('\0', fp) == EOF)
516 get_option_string(struct dhcpcd_ctx *ctx,
517 const struct bootp *bootp, size_t bootp_len, uint8_t option)
523 p = get_option(ctx, bootp, bootp_len, option, &len);
524 if (!p || len == 0 || *p == '\0')
527 s = malloc(sizeof(char) * (len + 1));
535 /* This calculates the netmask that we should use for static routes.
536 * This IS different from the calculation used to calculate the netmask
537 * for an interface address. */
539 route_netmask(uint32_t ip_in)
541 /* used to be unsigned long - check if error */
542 uint32_t p = ntohl(ip_in);
564 /* We need to obey routing options.
565 * If we have a CSR then we only use that.
566 * Otherwise we add static routes and then routers. */
568 get_option_routes(rb_tree_t *routes, struct interface *ifp,
569 const struct bootp *bootp, size_t bootp_len)
571 struct if_options *ifo = ifp->options;
574 struct rt *rt = NULL;
575 struct in_addr dest, netmask, gateway;
577 const char *csr = "";
580 /* If we have CSR's then we MUST use these only */
581 if (!has_option_mask(ifo->nomask, DHO_CSR))
582 p = get_option(ifp->ctx, bootp, bootp_len, DHO_CSR, &len);
585 /* Check for crappy MS option */
586 if (!p && !has_option_mask(ifo->nomask, DHO_MSCSR)) {
587 p = get_option(ifp->ctx, bootp, bootp_len, DHO_MSCSR, &len);
591 if (p && (n = decode_rfc3442_rt(routes, ifp, p, len, bootp)) != -1) {
592 const struct dhcp_state *state;
594 state = D_CSTATE(ifp);
595 if (!(ifo->options & DHCPCD_CSR_WARNED) &&
596 !(state->added & STATE_FAKE))
598 logdebugx("%s: using %sClassless Static Routes",
600 ifo->options |= DHCPCD_CSR_WARNED;
606 /* OK, get our static routes first. */
607 if (!has_option_mask(ifo->nomask, DHO_STATICROUTE))
608 p = get_option(ifp->ctx, bootp, bootp_len,
609 DHO_STATICROUTE, &len);
612 /* RFC 2131 Section 5.8 states length MUST be in multiples of 8 */
613 if (p && len % 8 == 0) {
616 memcpy(&dest.s_addr, p, sizeof(dest.s_addr));
618 memcpy(&gateway.s_addr, p, sizeof(gateway.s_addr));
620 /* RFC 2131 Section 5.8 states default route is
622 if (gateway.s_addr == INADDR_ANY)
624 if ((rt = rt_new(ifp)) == NULL)
627 /* A on-link host route is normally set by having the
628 * gateway match the destination or assigned address */
629 if (gateway.s_addr == dest.s_addr ||
630 (gateway.s_addr == bootp->yiaddr ||
631 gateway.s_addr == bootp->ciaddr))
633 gateway.s_addr = INADDR_ANY;
634 netmask.s_addr = INADDR_BROADCAST;
636 netmask.s_addr = route_netmask(dest.s_addr);
637 if (netmask.s_addr == INADDR_BROADCAST)
638 rt->rt_flags = RTF_HOST;
640 sa_in_init(&rt->rt_dest, &dest);
641 sa_in_init(&rt->rt_netmask, &netmask);
642 sa_in_init(&rt->rt_gateway, &gateway);
643 if (rt_proto_add(routes, rt))
648 /* Now grab our routers */
649 if (!has_option_mask(ifo->nomask, DHO_ROUTER))
650 p = get_option(ifp->ctx, bootp, bootp_len, DHO_ROUTER, &len);
653 if (p && len % 4 == 0) {
655 dest.s_addr = INADDR_ANY;
656 netmask.s_addr = INADDR_ANY;
658 if ((rt = rt_new(ifp)) == NULL)
660 memcpy(&gateway.s_addr, p, sizeof(gateway.s_addr));
662 sa_in_init(&rt->rt_dest, &dest);
663 sa_in_init(&rt->rt_netmask, &netmask);
664 sa_in_init(&rt->rt_gateway, &gateway);
665 if (rt_proto_add(routes, rt))
674 dhcp_get_mtu(const struct interface *ifp)
676 const struct dhcp_state *state;
679 if (ifp->options->mtu)
680 return (uint16_t)ifp->options->mtu;
681 mtu = 0; /* bogus gcc warning */
682 if ((state = D_CSTATE(ifp)) == NULL ||
683 has_option_mask(ifp->options->nomask, DHO_MTU) ||
684 get_option_uint16(ifp->ctx, &mtu,
685 state->new, state->new_len, DHO_MTU) == -1)
690 /* Grab our routers from the DHCP message and apply any MTU value
691 * the message contains */
693 dhcp_get_routes(rb_tree_t *routes, struct interface *ifp)
695 const struct dhcp_state *state;
697 if ((state = D_CSTATE(ifp)) == NULL || !(state->added & STATE_ADDED))
699 return get_option_routes(routes, ifp, state->new, state->new_len);
702 /* Assumes DHCP options */
704 dhcp_message_add_addr(struct bootp *bootp,
705 uint8_t type, struct in_addr addr)
711 while (*p != DHO_END) {
716 len = (size_t)(p - bootp->vend);
717 if (len + 6 > sizeof(bootp->vend)) {
724 memcpy(p, &addr.s_addr, 4);
731 make_message(struct bootp **bootpm, const struct interface *ifp, uint8_t type)
735 uint8_t *n_params = NULL;
739 const struct dhcp_opt *opt;
740 struct if_options *ifo = ifp->options;
741 const struct dhcp_state *state = D_CSTATE(ifp);
742 const struct dhcp_lease *lease = &state->lease;
743 char hbuf[HOSTNAME_MAX_LEN + 1];
744 const char *hostname;
745 const struct vivco *vivco;
748 uint8_t *auth, auth_len;
751 if ((mtu = if_getmtu(ifp)) == -1)
752 logerr("%s: if_getmtu", ifp->name);
753 else if (mtu < MTU_MIN) {
754 if (if_setmtu(ifp, MTU_MIN) == -1)
755 logerr("%s: if_setmtu", ifp->name);
759 if (ifo->options & DHCPCD_BOOTP)
760 bootp = calloc(1, sizeof (*bootp));
762 /* Make the maximal message we could send */
763 bootp = calloc(1, (size_t)(mtu - IP_UDP_SIZE));
769 if (state->addr != NULL &&
770 (type == DHCP_INFORM || type == DHCP_RELEASE ||
771 (type == DHCP_REQUEST &&
772 state->addr->mask.s_addr == lease->mask.s_addr &&
773 (state->new == NULL || IS_DHCP(state->new)) &&
774 !(state->added & STATE_FAKE))))
775 bootp->ciaddr = state->addr->addr.s_addr;
777 bootp->op = BOOTREQUEST;
778 bootp->htype = (uint8_t)ifp->family;
779 switch (ifp->family) {
782 bootp->hlen = (uint8_t)ifp->hwlen;
783 memcpy(&bootp->chaddr, &ifp->hwaddr, ifp->hwlen);
787 if (ifo->options & DHCPCD_BROADCAST &&
788 bootp->ciaddr == 0 &&
789 type != DHCP_DECLINE &&
790 type != DHCP_RELEASE)
791 bootp->flags = htons(BROADCAST_FLAG);
793 if (type != DHCP_DECLINE && type != DHCP_RELEASE) {
796 clock_gettime(CLOCK_MONOTONIC, &tv);
797 timespecsub(&tv, &state->started, &tv);
798 if (tv.tv_sec < 0 || tv.tv_sec > (time_t)UINT16_MAX)
799 bootp->secs = htons((uint16_t)UINT16_MAX);
801 bootp->secs = htons((uint16_t)tv.tv_sec);
804 bootp->xid = htonl(state->xid);
806 if (ifo->options & DHCPCD_BOOTP)
807 return sizeof(*bootp);
810 e = (uint8_t *)bootp + (mtu - IP_UDP_SIZE) - 1; /* -1 for DHO_END */
812 ul = htonl(MAGIC_COOKIE);
813 memcpy(p, &ul, sizeof(ul));
816 *p++ = DHO_MESSAGETYPE;
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 if (state->clientid) {
832 AREA_CHECK(state->clientid[0]);
834 memcpy(p, state->clientid, (size_t)state->clientid[0] + 1);
835 p += state->clientid[0] + 1;
838 if (lease->addr.s_addr && lease->cookie == htonl(MAGIC_COOKIE)) {
839 if (type == DHCP_DECLINE ||
840 (type == DHCP_REQUEST &&
841 (state->addr == NULL ||
842 state->added & STATE_FAKE ||
843 lease->addr.s_addr != state->addr->addr.s_addr)))
845 PUT_ADDR(DHO_IPADDRESS, &lease->addr);
846 if (lease->server.s_addr)
847 PUT_ADDR(DHO_SERVERID, &lease->server);
850 if (type == DHCP_RELEASE) {
851 if (lease->server.s_addr)
852 PUT_ADDR(DHO_SERVERID, &lease->server);
856 if (type == DHCP_DECLINE) {
858 if (len > AREA_LEFT) {
866 if (type == DHCP_DISCOVER &&
867 !(ifp->ctx->options & DHCPCD_TEST) &&
868 has_option_mask(ifo->requestmask, DHO_RAPIDCOMMIT))
870 /* RFC 4039 Section 3 */
872 *p++ = DHO_RAPIDCOMMIT;
876 if (type == DHCP_DISCOVER && ifo->options & DHCPCD_REQUEST)
877 PUT_ADDR(DHO_IPADDRESS, &ifo->req_addr);
879 /* RFC 2563 Auto Configure */
880 if (type == DHCP_DISCOVER && ifo->options & DHCPCD_IPV4LL) {
882 *p++ = DHO_AUTOCONFIGURE;
887 if (type == DHCP_DISCOVER ||
888 type == DHCP_INFORM ||
889 type == DHCP_REQUEST)
893 *p++ = DHO_MAXMESSAGESIZE;
895 sz = htons((uint16_t)(mtu - IP_UDP_SIZE));
900 if (ifo->userclass[0]) {
901 AREA_CHECK(ifo->userclass[0]);
902 *p++ = DHO_USERCLASS;
903 memcpy(p, ifo->userclass,
904 (size_t)ifo->userclass[0] + 1);
905 p += ifo->userclass[0] + 1;
908 if (ifo->vendorclassid[0]) {
909 AREA_CHECK(ifo->vendorclassid[0]);
910 *p++ = DHO_VENDORCLASSID;
911 memcpy(p, ifo->vendorclassid,
912 (size_t)ifo->vendorclassid[0] + 1);
913 p += ifo->vendorclassid[0] + 1;
916 if (ifo->mudurl[0]) {
917 AREA_CHECK(ifo->mudurl[0]);
919 memcpy(p, ifo->mudurl, (size_t)ifo->mudurl[0] + 1);
920 p += ifo->mudurl[0] + 1;
923 if (type != DHCP_INFORM) {
924 if (ifo->leasetime != 0) {
926 *p++ = DHO_LEASETIME;
928 ul = htonl(ifo->leasetime);
934 hostname = dhcp_get_hostname(hbuf, sizeof(hbuf), ifo);
937 * RFC4702 3.1 States that if we send the Client FQDN option
938 * then we MUST NOT also send the Host Name option.
939 * Technically we could, but that is not RFC conformant and
940 * also seems to break some DHCP server implemetations such as
941 * Windows. On the other hand, ISC dhcpd is just as non RFC
942 * conformant by not accepting a partially qualified FQDN.
944 if (ifo->fqdn != FQDN_DISABLE) {
945 /* IETF DHC-FQDN option (81), RFC4702 */
948 i += encode_rfc1035(hostname, NULL);
954 * S: 1 => Client requests Server to update
955 * a RR in DNS as well as PTR
956 * O: 1 => Server indicates to client that
957 * DNS has been updated
958 * E: 1 => Name data is DNS format
959 * N: 1 => Client requests Server to not
963 *p++ = (uint8_t)((ifo->fqdn & 0x09) | 0x04);
965 *p++ = (FQDN_NONE & 0x09) | 0x04;
966 *p++ = 0; /* from server for PTR RR */
967 *p++ = 0; /* from server for A RR if S=1 */
969 i = encode_rfc1035(hostname, p);
972 } else if (ifo->options & DHCPCD_HOSTNAME && hostname) {
973 len = strlen(hostname);
977 memcpy(p, hostname, len);
981 /* vendor is already encoded correctly, so just add it */
982 if (ifo->vendor[0]) {
983 AREA_CHECK(ifo->vendor[0]);
985 memcpy(p, ifo->vendor, (size_t)ifo->vendor[0] + 1);
986 p += ifo->vendor[0] + 1;
990 if ((ifo->auth.options & DHCPCD_AUTH_SENDREQUIRE) !=
991 DHCPCD_AUTH_SENDREQUIRE &&
992 !has_option_mask(ifo->nomask, DHO_FORCERENEW_NONCE))
994 /* We support HMAC-MD5 */
996 *p++ = DHO_FORCERENEW_NONCE;
998 *p++ = AUTH_ALG_HMAC_MD5;
1002 if (ifo->vivco_len) {
1003 AREA_CHECK(sizeof(ul));
1007 ul = htonl(ifo->vivco_en);
1008 memcpy(p, &ul, sizeof(ul));
1010 for (i = 0, vivco = ifo->vivco;
1014 AREA_FIT(vivco->len);
1015 if (vivco->len + 2 + *lp > 255) {
1016 logerrx("%s: VIVCO option too big",
1021 *p++ = (uint8_t)vivco->len;
1022 memcpy(p, vivco->data, vivco->len);
1024 *lp = (uint8_t)(*lp + vivco->len + 1);
1029 *p++ = DHO_PARAMETERREQUESTLIST;
1032 for (i = 0, opt = ifp->ctx->dhcp_opts;
1033 i < ifp->ctx->dhcp_opts_len;
1036 if (!DHC_REQOPT(opt, ifo->requestmask, ifo->nomask))
1038 if (type == DHCP_INFORM &&
1039 (opt->option == DHO_RENEWALTIME ||
1040 opt->option == DHO_REBINDTIME))
1043 *p++ = (uint8_t)opt->option;
1045 for (i = 0, opt = ifo->dhcp_override;
1046 i < ifo->dhcp_override_len;
1049 /* Check if added above */
1050 for (lp = n_params + 1; lp < p; lp++)
1051 if (*lp == (uint8_t)opt->option)
1055 if (!DHC_REQOPT(opt, ifo->requestmask, ifo->nomask))
1057 if (type == DHCP_INFORM &&
1058 (opt->option == DHO_RENEWALTIME ||
1059 opt->option == DHO_REBINDTIME))
1062 *p++ = (uint8_t)opt->option;
1064 *n_params = (uint8_t)(p - n_params - 1);
1068 auth = NULL; /* appease GCC */
1070 if (ifo->auth.options & DHCPCD_AUTH_SEND) {
1071 ssize_t alen = dhcp_auth_encode(&ifo->auth,
1073 NULL, 0, 4, type, NULL, 0);
1074 if (alen != -1 && alen > UINT8_MAX) {
1079 logerr("%s: dhcp_auth_encode", ifp->name);
1080 else if (alen != 0) {
1081 auth_len = (uint8_t)alen;
1082 AREA_CHECK(auth_len);
1083 *p++ = DHO_AUTHENTICATION;
1092 len = (size_t)(p - (uint8_t *)bootp);
1094 /* Pad out to the BOOTP message length.
1095 * Even if we send a DHCP packet with a variable length vendor area,
1096 * some servers / relay agents don't like packets smaller than
1097 * a BOOTP message which is fine because that's stipulated
1098 * in RFC1542 section 2.1. */
1099 while (len < sizeof(*bootp)) {
1105 if (ifo->auth.options & DHCPCD_AUTH_SEND && auth_len != 0)
1106 dhcp_auth_encode(&ifo->auth, state->auth.token,
1107 (uint8_t *)bootp, len, 4, type, auth, auth_len);
1110 return (ssize_t)len;
1113 logerrx("%s: DHCP message too big", ifp->name);
1119 write_lease(const struct interface *ifp, const struct bootp *bootp, size_t len)
1123 const struct dhcp_state *state = D_CSTATE(ifp);
1125 logdebugx("%s: writing lease `%s'", ifp->name, state->leasefile);
1127 fd = open(state->leasefile, O_WRONLY | O_CREAT | O_TRUNC, 0644);
1130 bytes = write(fd, bootp, len);
1136 read_lease(struct interface *ifp, struct bootp **bootp)
1140 struct dhcp_state *state = D_STATE(ifp);
1141 struct bootp *lease;
1145 const uint8_t *auth;
1152 if (state->leasefile[0] == '\0') {
1156 fd = open(state->leasefile, O_RDONLY);
1160 if (errno != ENOENT)
1161 logerr("%s: open `%s'",
1162 ifp->name, state->leasefile);
1165 if (state->leasefile[0] == '\0')
1166 logdebugx("reading standard input");
1168 logdebugx("%s: reading lease `%s'",
1169 ifp->name, state->leasefile);
1171 bytes = dhcp_read_lease_fd(fd, (void **)&lease);
1177 /* Ensure the packet is at lease BOOTP sized
1178 * with a vendor area of 4 octets
1179 * (it should be more, and our read packet enforces this so this
1180 * code should not be needed, but of course people could
1181 * scribble whatever in the stored lease file. */
1182 if (bytes < offsetof(struct bootp, vend) + 4) {
1184 logerrx("%s: %s: truncated lease", ifp->name, __func__);
1188 if (ifp->ctx->options & DHCPCD_DUMPLEASE)
1191 /* We may have found a BOOTP server */
1192 if (get_option_uint8(ifp->ctx, &type, (struct bootp *)lease, bytes,
1193 DHO_MESSAGETYPE) == -1)
1197 /* Authenticate the message */
1198 auth = get_option(ifp->ctx, (struct bootp *)lease, bytes,
1199 DHO_AUTHENTICATION, &auth_len);
1201 if (dhcp_auth_validate(&state->auth, &ifp->options->auth,
1202 lease, bytes, 4, type, auth, auth_len) == NULL)
1204 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);
1223 *bootp = (struct bootp *)lease;
1227 static const struct dhcp_opt *
1228 dhcp_getoverride(const struct if_options *ifo, unsigned int o)
1231 const struct dhcp_opt *opt;
1233 for (i = 0, opt = ifo->dhcp_override;
1234 i < ifo->dhcp_override_len;
1237 if (opt->option == o)
1243 static const uint8_t *
1244 dhcp_getoption(struct dhcpcd_ctx *ctx,
1245 size_t *os, unsigned int *code, size_t *len,
1246 const uint8_t *od, size_t ol, struct dhcp_opt **oopt)
1249 struct dhcp_opt *opt;
1256 *os = 2; /* code + len */
1257 *code = (unsigned int)*od++;
1258 *len = (size_t)*od++;
1259 if (*len > ol - *os) {
1266 for (i = 0, opt = ctx->dhcp_opts; i < ctx->dhcp_opts_len; i++, opt++) {
1267 if (opt->option == *code) {
1277 dhcp_env(FILE *fenv, const char *prefix, const struct interface *ifp,
1278 const struct bootp *bootp, size_t bootp_len)
1280 const struct if_options *ifo;
1282 struct in_addr addr;
1285 struct dhcp_opt *opt, *vo;
1287 char safe[(BOOTP_FILE_LEN * 4) + 1];
1292 if (get_option_uint8(ifp->ctx, &overl, bootp, bootp_len,
1293 DHO_OPTSOVERLOADED) == -1)
1296 if (bootp->yiaddr || bootp->ciaddr) {
1297 /* Set some useful variables that we derive from the DHCP
1298 * message but are not necessarily in the options */
1299 addr.s_addr = bootp->yiaddr ? bootp->yiaddr : bootp->ciaddr;
1300 if (efprintf(fenv, "%s_ip_address=%s",
1301 prefix, inet_ntoa(addr)) == -1)
1303 if (get_option_addr(ifp->ctx, &net,
1304 bootp, bootp_len, DHO_SUBNETMASK) == -1) {
1305 net.s_addr = ipv4_getnetmask(addr.s_addr);
1306 if (efprintf(fenv, "%s_subnet_mask=%s",
1307 prefix, inet_ntoa(net)) == -1)
1310 if (efprintf(fenv, "%s_subnet_cidr=%d",
1311 prefix, inet_ntocidr(net))== -1)
1313 if (get_option_addr(ifp->ctx, &brd,
1314 bootp, bootp_len, DHO_BROADCAST) == -1)
1316 brd.s_addr = addr.s_addr | ~net.s_addr;
1317 if (efprintf(fenv, "%s_broadcast_address=%s",
1318 prefix, inet_ntoa(brd)) == -1)
1321 addr.s_addr = bootp->yiaddr & net.s_addr;
1322 if (efprintf(fenv, "%s_network_number=%s",
1323 prefix, inet_ntoa(addr)) == -1)
1327 if (*bootp->file && !(overl & 1)) {
1328 print_string(safe, sizeof(safe), OT_STRING,
1329 bootp->file, sizeof(bootp->file));
1330 if (efprintf(fenv, "%s_filename=%s", prefix, safe) == -1)
1333 if (*bootp->sname && !(overl & 2)) {
1334 print_string(safe, sizeof(safe), OT_STRING | OT_DOMAIN,
1335 bootp->sname, sizeof(bootp->sname));
1336 if (efprintf(fenv, "%s_server_name=%s", prefix, safe) == -1)
1340 /* Zero our indexes */
1341 for (i = 0, opt = ifp->ctx->dhcp_opts;
1342 i < ifp->ctx->dhcp_opts_len;
1344 dhcp_zero_index(opt);
1345 for (i = 0, opt = ifp->options->dhcp_override;
1346 i < ifp->options->dhcp_override_len;
1348 dhcp_zero_index(opt);
1349 for (i = 0, opt = ifp->ctx->vivso;
1350 i < ifp->ctx->vivso_len;
1352 dhcp_zero_index(opt);
1354 for (i = 0, opt = ifp->ctx->dhcp_opts;
1355 i < ifp->ctx->dhcp_opts_len;
1358 if (has_option_mask(ifo->nomask, opt->option))
1360 if (dhcp_getoverride(ifo, opt->option))
1362 p = get_option(ifp->ctx, bootp, bootp_len, opt->option, &pl);
1365 dhcp_envoption(ifp->ctx, fenv, prefix, ifp->name,
1366 opt, dhcp_getoption, p, pl);
1368 if (opt->option != DHO_VIVSO || pl <= (int)sizeof(uint32_t))
1370 memcpy(&en, p, sizeof(en));
1372 vo = vivso_find(en, ifp);
1375 /* Skip over en + total size */
1376 p += sizeof(en) + 1;
1377 pl -= sizeof(en) + 1;
1378 dhcp_envoption(ifp->ctx, fenv, prefix, ifp->name,
1379 vo, dhcp_getoption, p, pl);
1382 for (i = 0, opt = ifo->dhcp_override;
1383 i < ifo->dhcp_override_len;
1386 if (has_option_mask(ifo->nomask, opt->option))
1388 p = get_option(ifp->ctx, bootp, bootp_len, opt->option, &pl);
1391 dhcp_envoption(ifp->ctx, fenv, prefix, ifp->name,
1392 opt, dhcp_getoption, p, pl);
1399 get_lease(struct interface *ifp,
1400 struct dhcp_lease *lease, const struct bootp *bootp, size_t len)
1402 struct dhcpcd_ctx *ctx;
1404 assert(bootp != NULL);
1406 memcpy(&lease->cookie, bootp->vend, sizeof(lease->cookie));
1407 /* BOOTP does not set yiaddr for replies when ciaddr is set. */
1408 lease->addr.s_addr = bootp->yiaddr ? bootp->yiaddr : bootp->ciaddr;
1410 if (ifp->options->options & (DHCPCD_STATIC | DHCPCD_INFORM)) {
1411 if (ifp->options->req_addr.s_addr != INADDR_ANY) {
1412 lease->mask = ifp->options->req_mask;
1413 if (ifp->options->req_brd.s_addr != INADDR_ANY)
1414 lease->brd = ifp->options->req_brd;
1417 lease->addr.s_addr | ~lease->mask.s_addr;
1419 const struct ipv4_addr *ia;
1421 ia = ipv4_iffindaddr(ifp, &lease->addr, NULL);
1423 lease->mask = ia->mask;
1424 lease->brd = ia->brd;
1427 if (get_option_addr(ctx, &lease->mask, bootp, len,
1428 DHO_SUBNETMASK) == -1)
1429 lease->mask.s_addr =
1430 ipv4_getnetmask(lease->addr.s_addr);
1431 if (get_option_addr(ctx, &lease->brd, bootp, len,
1432 DHO_BROADCAST) == -1)
1434 lease->addr.s_addr | ~lease->mask.s_addr;
1436 if (get_option_uint32(ctx, &lease->leasetime,
1437 bootp, len, DHO_LEASETIME) != 0)
1438 lease->leasetime = DHCP_INFINITE_LIFETIME;
1439 if (get_option_uint32(ctx, &lease->renewaltime,
1440 bootp, len, DHO_RENEWALTIME) != 0)
1441 lease->renewaltime = 0;
1442 if (get_option_uint32(ctx, &lease->rebindtime,
1443 bootp, len, DHO_REBINDTIME) != 0)
1444 lease->rebindtime = 0;
1445 if (get_option_addr(ctx, &lease->server, bootp, len, DHO_SERVERID) != 0)
1446 lease->server.s_addr = INADDR_ANY;
1450 get_dhcp_op(uint8_t type)
1452 const struct dhcp_op *d;
1454 for (d = dhcp_ops; d->name; d++)
1455 if (d->value == type)
1461 dhcp_fallback(void *arg)
1463 struct interface *iface;
1465 iface = (struct interface *)arg;
1466 dhcpcd_selectprofile(iface, iface->options->fallback);
1467 dhcpcd_startinterface(iface);
1471 dhcp_new_xid(struct interface *ifp)
1473 struct dhcp_state *state;
1474 const struct interface *ifp1;
1475 const struct dhcp_state *state1;
1477 state = D_STATE(ifp);
1478 if (ifp->options->options & DHCPCD_XID_HWADDR &&
1479 ifp->hwlen >= sizeof(state->xid))
1480 /* The lower bits are probably more unique on the network */
1482 (ifp->hwaddr + ifp->hwlen) - sizeof(state->xid),
1483 sizeof(state->xid));
1486 state->xid = arc4random();
1489 /* Ensure it's unique */
1490 TAILQ_FOREACH(ifp1, ifp->ctx->ifaces, next) {
1493 if ((state1 = D_CSTATE(ifp1)) == NULL)
1495 if (state1->xid == state->xid)
1499 if (ifp->options->options & DHCPCD_XID_HWADDR &&
1500 ifp->hwlen >= sizeof(state->xid))
1502 logerrx("%s: duplicate xid on %s",
1503 ifp->name, ifp1->name);
1509 /* We can't do this when sharing leases across interfaes */
1511 /* As the XID changes, re-apply the filter. */
1512 if (state->bpf_fd != -1) {
1513 if (bpf_bootp(ifp, state->bpf_fd) == -1)
1514 logerr(__func__); /* try to continue */
1520 dhcp_close(struct interface *ifp)
1522 struct dhcp_state *state = D_STATE(ifp);
1527 if (state->bpf_fd != -1) {
1528 eloop_event_delete(ifp->ctx->eloop, state->bpf_fd);
1529 bpf_close(ifp, state->bpf_fd);
1531 state->bpf_flags |= BPF_EOF;
1533 if (state->udp_fd != -1) {
1534 eloop_event_delete(ifp->ctx->eloop, state->udp_fd);
1535 close(state->udp_fd);
1539 state->interval = 0;
1543 dhcp_openudp(struct interface *ifp)
1546 struct sockaddr_in sin;
1549 if ((s = xsocket(PF_INET, SOCK_DGRAM|SOCK_CLOEXEC, IPPROTO_UDP)) == -1)
1553 if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n)) == -1)
1555 #ifdef IP_RECVPKTINFO
1556 if (setsockopt(s, IPPROTO_IP, IP_RECVPKTINFO, &n, sizeof(n)) == -1)
1559 memset(&sin, 0, sizeof(sin));
1560 sin.sin_family = AF_INET;
1561 sin.sin_port = htons(BOOTPC);
1563 const struct dhcp_state *state = D_CSTATE(ifp);
1566 sin.sin_addr.s_addr = state->addr->addr.s_addr;
1568 if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) == -1)
1579 in_cksum(const void *data, size_t len, uint32_t *isum)
1581 const uint16_t *word = data;
1582 uint32_t sum = isum != NULL ? *isum : 0;
1584 for (; len > 1; len -= sizeof(*word))
1588 sum += htons((uint16_t)(*(const uint8_t *)word << 8));
1593 sum = (sum >> 16) + (sum & 0xffff);
1596 return (uint16_t)~sum;
1599 static struct bootp_pkt *
1600 dhcp_makeudppacket(size_t *sz, const uint8_t *data, size_t length,
1601 struct in_addr source, struct in_addr dest)
1603 struct bootp_pkt *udpp;
1607 if ((udpp = calloc(1, sizeof(*ip) + sizeof(*udp) + length)) == NULL)
1612 /* OK, this is important :)
1613 * We copy the data to our packet and then create a small part of the
1614 * ip structure and an invalid ip_len (basically udp length).
1615 * We then fill the udp structure and put the checksum
1616 * of the whole packet into the udp checksum.
1617 * Finally we complete the ip structure and ip checksum.
1618 * If we don't do the ordering like so then the udp checksum will be
1619 * broken, so find another way of doing it! */
1621 memcpy(&udpp->bootp, data, length);
1623 ip->ip_p = IPPROTO_UDP;
1624 ip->ip_src.s_addr = source.s_addr;
1625 if (dest.s_addr == 0)
1626 ip->ip_dst.s_addr = INADDR_BROADCAST;
1628 ip->ip_dst.s_addr = dest.s_addr;
1630 udp->uh_sport = htons(BOOTPC);
1631 udp->uh_dport = htons(BOOTPS);
1632 udp->uh_ulen = htons((uint16_t)(sizeof(*udp) + length));
1633 ip->ip_len = udp->uh_ulen;
1634 udp->uh_sum = in_cksum(udpp, sizeof(*ip) + sizeof(*udp) + length, NULL);
1636 ip->ip_v = IPVERSION;
1637 ip->ip_hl = sizeof(*ip) >> 2;
1638 ip->ip_id = (uint16_t)arc4random_uniform(UINT16_MAX);
1639 ip->ip_ttl = IPDEFTTL;
1640 ip->ip_len = htons((uint16_t)(sizeof(*ip) + sizeof(*udp) + length));
1641 ip->ip_sum = in_cksum(ip, sizeof(*ip), NULL);
1642 if (ip->ip_sum == 0)
1643 ip->ip_sum = 0xffff; /* RFC 768 */
1645 *sz = sizeof(*ip) + sizeof(*udp) + length;
1650 dhcp_sendudp(struct interface *ifp, struct in_addr *to, void *data, size_t len)
1654 struct sockaddr_in sin;
1655 struct iovec iov[1];
1656 struct dhcp_state *state = D_STATE(ifp);
1659 iov[0].iov_base = data;
1660 iov[0].iov_len = len;
1662 memset(&sin, 0, sizeof(sin));
1663 sin.sin_family = AF_INET;
1665 sin.sin_port = htons(BOOTPS);
1667 sin.sin_len = sizeof(sin);
1670 memset(&msg, 0, sizeof(msg));
1671 msg.msg_name = (void *)&sin;
1672 msg.msg_namelen = sizeof(sin);
1678 s = dhcp_openudp(ifp);
1682 r = sendmsg(s, &msg, 0);
1683 if (state->udp_fd == -1)
1689 send_message(struct interface *ifp, uint8_t type,
1690 void (*callback)(void *))
1692 struct dhcp_state *state = D_STATE(ifp);
1693 struct if_options *ifo = ifp->options;
1694 struct bootp *bootp;
1695 struct bootp_pkt *udp;
1698 struct in_addr from, to;
1702 /* No carrier? Don't bother sending the packet. */
1703 if (ifp->carrier <= LINK_DOWN)
1705 logdebugx("%s: sending %s with xid 0x%x",
1707 ifo->options & DHCPCD_BOOTP ? "BOOTP" : get_dhcp_op(type),
1710 if (state->interval == 0)
1711 state->interval = 4;
1713 state->interval *= 2;
1714 if (state->interval > 64)
1715 state->interval = 64;
1717 tv.tv_sec = state->interval + DHCP_RAND_MIN;
1718 tv.tv_nsec = (suseconds_t)arc4random_uniform(
1719 (DHCP_RAND_MAX - DHCP_RAND_MIN) * NSEC_PER_SEC);
1721 /* No carrier? Don't bother sending the packet.
1722 * However, we do need to advance the timeout. */
1723 if (ifp->carrier <= LINK_DOWN)
1725 logdebugx("%s: sending %s (xid 0x%x), next in %0.1f seconds",
1727 ifo->options & DHCPCD_BOOTP ? "BOOTP" : get_dhcp_op(type),
1729 timespec_to_double(&tv));
1732 r = make_message(&bootp, ifp, type);
1737 if (ipv4_iffindaddr(ifp, &state->lease.addr, NULL) != NULL)
1738 from.s_addr = state->lease.addr.s_addr;
1740 from.s_addr = INADDR_ANY;
1741 if (from.s_addr != INADDR_ANY &&
1742 state->lease.server.s_addr != INADDR_ANY)
1743 to.s_addr = state->lease.server.s_addr;
1745 to.s_addr = INADDR_BROADCAST;
1748 * If not listening on the unspecified address we can
1749 * only receive broadcast messages via BPF.
1750 * Sockets bound to an address cannot receive broadcast messages
1751 * even if they are setup to send them.
1752 * Broadcasting from UDP is only an optimisation for rebinding
1753 * and on BSD, at least, is reliant on the subnet route being
1754 * correctly configured to recieve the unicast reply.
1755 * As such, we always broadcast and receive the reply to it via BPF.
1756 * This also guarantees we have a DHCP server attached to the
1757 * interface we want to configure because we can't dictate the
1758 * interface via IP_PKTINFO unlike for IPv6.
1760 if (to.s_addr != INADDR_BROADCAST)
1762 if (dhcp_sendudp(ifp, &to, bootp, len) != -1)
1764 logerr("%s: dhcp_sendudp", ifp->name);
1767 if (dhcp_openbpf(ifp) == -1)
1770 udp = dhcp_makeudppacket(&ulen, (uint8_t *)bootp, len, from, to);
1772 logerr("%s: dhcp_makeudppacket", ifp->name);
1775 r = bpf_send(ifp, state->bpf_fd,
1776 ETHERTYPE_IP, (uint8_t *)udp, ulen);
1779 /* If we failed to send a raw packet this normally means
1780 * we don't have the ability to work beneath the IP layer
1781 * for this interface.
1782 * As such we remove it from consideration without actually
1783 * stopping the interface. */
1785 logerr("%s: if_sendraw", ifp->name);
1793 if (!(ifp->ctx->options & DHCPCD_TEST))
1794 dhcp_drop(ifp, "FAIL");
1795 eloop_timeout_delete(ifp->ctx->eloop,
1805 /* Even if we fail to send a packet we should continue as we are
1806 * as our failure timeouts will change out codepath when needed. */
1808 eloop_timeout_add_tv(ifp->ctx->eloop, &tv, callback, ifp);
1812 send_inform(void *arg)
1815 send_message((struct interface *)arg, DHCP_INFORM, send_inform);
1819 send_discover(void *arg)
1822 send_message((struct interface *)arg, DHCP_DISCOVER, send_discover);
1826 send_request(void *arg)
1829 send_message((struct interface *)arg, DHCP_REQUEST, send_request);
1833 send_renew(void *arg)
1836 send_message((struct interface *)arg, DHCP_REQUEST, send_renew);
1840 send_rebind(void *arg)
1843 send_message((struct interface *)arg, DHCP_REQUEST, send_rebind);
1847 dhcp_discover(void *arg)
1849 struct interface *ifp = arg;
1850 struct dhcp_state *state = D_STATE(ifp);
1851 struct if_options *ifo = ifp->options;
1853 state->state = DHS_DISCOVER;
1855 eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
1857 eloop_timeout_add_sec(ifp->ctx->eloop,
1858 ifo->reboot, dhcp_fallback, ifp);
1860 else if (ifo->options & DHCPCD_IPV4LL)
1861 eloop_timeout_add_sec(ifp->ctx->eloop,
1862 ifo->reboot, ipv4ll_start, ifp);
1864 if (ifo->options & DHCPCD_REQUEST)
1865 loginfox("%s: soliciting a DHCP lease (requesting %s)",
1866 ifp->name, inet_ntoa(ifo->req_addr));
1868 loginfox("%s: soliciting a %s lease",
1869 ifp->name, ifo->options & DHCPCD_BOOTP ? "BOOTP" : "DHCP");
1874 dhcp_request(void *arg)
1876 struct interface *ifp = arg;
1877 struct dhcp_state *state = D_STATE(ifp);
1879 state->state = DHS_REQUEST;
1884 dhcp_expire1(struct interface *ifp)
1886 struct dhcp_state *state = D_STATE(ifp);
1888 eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
1889 dhcp_drop(ifp, "EXPIRE");
1890 unlink(state->leasefile);
1891 state->interval = 0;
1892 if (!(ifp->options->options & DHCPCD_LINK) || ifp->carrier > LINK_DOWN)
1897 dhcp_expire(void *arg)
1899 struct interface *ifp = arg;
1901 if (ifp->options->options & DHCPCD_LASTLEASE_EXTEND) {
1902 logwarnx("%s: DHCP lease expired, extending lease", ifp->name);
1906 logerrx("%s: DHCP lease expired", ifp->name);
1910 #if defined(ARP) || defined(IN_IFF_DUPLICATED)
1912 dhcp_decline(struct interface *ifp)
1915 send_message(ifp, DHCP_DECLINE, NULL);
1920 dhcp_startrenew(void *arg)
1922 struct interface *ifp = arg;
1923 struct dhcp_state *state;
1924 struct dhcp_lease *lease;
1926 if ((state = D_STATE(ifp)) == NULL)
1929 /* Only renew in the bound or renew states */
1930 if (state->state != DHS_BOUND &&
1931 state->state != DHS_RENEW)
1934 /* Remove the timeout as the renew may have been forced. */
1935 eloop_timeout_delete(ifp->ctx->eloop, dhcp_startrenew, ifp);
1937 lease = &state->lease;
1938 logdebugx("%s: renewing lease of %s", ifp->name,
1939 inet_ntoa(lease->addr));
1940 state->state = DHS_RENEW;
1942 state->interval = 0;
1947 dhcp_renew(struct interface *ifp)
1950 dhcp_startrenew(ifp);
1954 dhcp_rebind(void *arg)
1956 struct interface *ifp = arg;
1957 struct dhcp_state *state = D_STATE(ifp);
1958 struct dhcp_lease *lease = &state->lease;
1960 logwarnx("%s: failed to renew DHCP, rebinding", ifp->name);
1961 logdebugx("%s: expire in %"PRIu32" seconds",
1962 ifp->name, lease->leasetime - lease->rebindtime);
1963 state->state = DHS_REBIND;
1964 eloop_timeout_delete(ifp->ctx->eloop, send_renew, ifp);
1965 state->lease.server.s_addr = INADDR_ANY;
1966 state->interval = 0;
1967 ifp->options->options &= ~(DHCPCD_CSR_WARNED |
1968 DHCPCD_ROUTER_HOST_ROUTE_WARNED);
1972 #if defined(ARP) || defined(IN_IFF_DUPLICATED)
1974 dhcp_finish_dad(struct interface *ifp, struct in_addr *ia)
1976 struct dhcp_state *state = D_STATE(ifp);
1978 if (state->state != DHS_PROBE)
1980 if (state->offer == NULL || state->offer->yiaddr != ia->s_addr)
1983 logdebugx("%s: DAD completed for %s", ifp->name, inet_ntoa(*ia));
1984 if (!(ifp->options->options & DHCPCD_INFORM))
1986 #ifndef IN_IFF_DUPLICATED
1988 struct bootp *bootp;
1992 len = state->new_len;
1993 state->new = state->offer;
1994 state->new_len = state->offer_len;
1995 get_lease(ifp, &state->lease, state->new, state->new_len);
1996 ipv4_applyaddr(ifp);
1998 state->new_len = len;
2002 /* If we forked, stop here. */
2003 if (ifp->ctx->options & DHCPCD_FORKED)
2007 /* Stop IPv4LL now we have a working DHCP address */
2011 if (ifp->options->options & DHCPCD_INFORM)
2017 dhcp_addr_duplicated(struct interface *ifp, struct in_addr *ia)
2019 struct dhcp_state *state = D_STATE(ifp);
2020 unsigned long long opts = ifp->options->options;
2021 struct dhcpcd_ctx *ctx = ifp->ctx;
2022 bool deleted = false;
2023 #ifdef IN_IFF_DUPLICATED
2024 struct ipv4_addr *iap;
2027 if ((state->offer == NULL || state->offer->yiaddr != ia->s_addr) &&
2028 !IN_ARE_ADDR_EQUAL(ia, &state->lease.addr))
2031 /* RFC 2131 3.1.5, Client-server interaction */
2032 logerrx("%s: DAD detected %s", ifp->name, inet_ntoa(*ia));
2033 unlink(state->leasefile);
2034 if (!(opts & DHCPCD_STATIC) && !state->lease.frominfo)
2036 #ifdef IN_IFF_DUPLICATED
2037 if ((iap = ipv4_iffindaddr(ifp, ia, NULL)) != NULL) {
2038 ipv4_deladdr(iap, 0);
2042 eloop_timeout_delete(ctx->eloop, NULL, ifp);
2043 if (opts & (DHCPCD_STATIC | DHCPCD_INFORM)) {
2044 state->reason = "EXPIRE";
2045 script_runreason(ifp, state->reason);
2046 #define NOT_ONLY_SELF (DHCPCD_MASTER | DHCPCD_IPV6RS | DHCPCD_DHCP6)
2047 if (!(ctx->options & NOT_ONLY_SELF))
2048 eloop_exit(ifp->ctx->eloop, EXIT_FAILURE);
2051 eloop_timeout_add_sec(ifp->ctx->eloop,
2052 DHCP_RAND_MAX, dhcp_discover, ifp);
2057 #if defined(ARP) && (!defined(KERNEL_RFC5227) || defined(ARPING))
2059 dhcp_arp_not_found(struct arp_state *astate)
2061 struct interface *ifp;
2063 struct dhcp_state *state;
2064 struct if_options *ifo;
2067 ifp = astate->iface;
2069 state = D_STATE(ifp);
2071 if (ifo->arping_len && state->arping_index < ifo->arping_len) {
2072 /* We didn't find a profile for this
2073 * address or hwaddr, so move to the next
2075 if (++state->arping_index < ifo->arping_len) {
2076 astate->addr.s_addr =
2077 ifo->arping[state->arping_index];
2082 dhcpcd_startinterface(ifp);
2087 dhcp_finish_dad(ifp, &astate->addr);
2091 dhcp_arp_found(struct arp_state *astate, const struct arp_msg *amsg)
2093 struct in_addr addr;
2094 struct interface *ifp = astate->iface;
2096 struct dhcp_state *state;
2097 struct if_options *ifo;
2099 state = D_STATE(ifp);
2102 if (state->arping_index != -1 &&
2103 state->arping_index < ifo->arping_len &&
2105 amsg->sip.s_addr == ifo->arping[state->arping_index])
2107 char buf[HWADDR_LEN * 3];
2109 hwaddr_ntoa(amsg->sha, ifp->hwlen, buf, sizeof(buf));
2110 if (dhcpcd_selectprofile(ifp, buf) == -1 &&
2111 dhcpcd_selectprofile(ifp, inet_ntoa(amsg->sip)) == -1)
2113 /* We didn't find a profile for this
2114 * address or hwaddr, so move to the next
2116 dhcp_arp_not_found(astate);
2120 eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
2121 dhcpcd_startinterface(ifp);
2128 addr = astate->addr;
2130 dhcp_addr_duplicated(ifp, &addr);
2133 #ifdef KERNEL_RFC5227
2135 dhcp_arp_announced(struct arp_state *state)
2140 #endif /* KERNEL_RFC5227 */
2144 dhcp_bind(struct interface *ifp)
2146 struct dhcpcd_ctx *ctx = ifp->ctx;
2147 struct dhcp_state *state = D_STATE(ifp);
2148 struct if_options *ifo = ifp->options;
2149 struct dhcp_lease *lease = &state->lease;
2151 state->reason = NULL;
2152 /* If we don't have an offer, we are re-binding a lease on preference,
2153 * normally when two interfaces have a lease matching IP addresses. */
2156 state->old = state->new;
2157 state->old_len = state->new_len;
2158 state->new = state->offer;
2159 state->new_len = state->offer_len;
2160 state->offer = NULL;
2161 state->offer_len = 0;
2163 get_lease(ifp, lease, state->new, state->new_len);
2164 if (ifo->options & DHCPCD_STATIC) {
2165 loginfox("%s: using static address %s/%d",
2166 ifp->name, inet_ntoa(lease->addr),
2167 inet_ntocidr(lease->mask));
2168 lease->leasetime = DHCP_INFINITE_LIFETIME;
2169 state->reason = "STATIC";
2170 } else if (ifo->options & DHCPCD_INFORM) {
2171 loginfox("%s: received approval for %s",
2172 ifp->name, inet_ntoa(lease->addr));
2173 lease->leasetime = DHCP_INFINITE_LIFETIME;
2174 state->reason = "INFORM";
2176 if (lease->frominfo)
2177 state->reason = "TIMEOUT";
2178 if (lease->leasetime == DHCP_INFINITE_LIFETIME) {
2179 lease->renewaltime =
2182 loginfox("%s: leased %s for infinity",
2183 ifp->name, inet_ntoa(lease->addr));
2185 if (lease->leasetime < DHCP_MIN_LEASE) {
2186 logwarnx("%s: minimum lease is %d seconds",
2187 ifp->name, DHCP_MIN_LEASE);
2188 lease->leasetime = DHCP_MIN_LEASE;
2190 if (lease->rebindtime == 0)
2192 (uint32_t)(lease->leasetime * T2);
2193 else if (lease->rebindtime >= lease->leasetime) {
2195 (uint32_t)(lease->leasetime * T2);
2196 logwarnx("%s: rebind time greater than lease "
2197 "time, forcing to %"PRIu32" seconds",
2198 ifp->name, lease->rebindtime);
2200 if (lease->renewaltime == 0)
2201 lease->renewaltime =
2202 (uint32_t)(lease->leasetime * T1);
2203 else if (lease->renewaltime > lease->rebindtime) {
2204 lease->renewaltime =
2205 (uint32_t)(lease->leasetime * T1);
2206 logwarnx("%s: renewal time greater than "
2207 "rebind time, forcing to %"PRIu32" seconds",
2208 ifp->name, lease->renewaltime);
2211 lease->addr.s_addr == state->addr->addr.s_addr &&
2212 !(state->added & STATE_FAKE))
2213 logdebugx("%s: leased %s for %"PRIu32" seconds",
2214 ifp->name, inet_ntoa(lease->addr),
2217 loginfox("%s: leased %s for %"PRIu32" seconds",
2218 ifp->name, inet_ntoa(lease->addr),
2222 if (ctx->options & DHCPCD_TEST) {
2223 state->reason = "TEST";
2224 script_runreason(ifp, state->reason);
2225 eloop_exit(ctx->eloop, EXIT_SUCCESS);
2228 if (state->reason == NULL) {
2229 if (state->old && !(state->added & STATE_FAKE)) {
2230 if (state->old->yiaddr == state->new->yiaddr &&
2231 lease->server.s_addr &&
2232 state->state != DHS_REBIND)
2233 state->reason = "RENEW";
2235 state->reason = "REBIND";
2236 } else if (state->state == DHS_REBOOT)
2237 state->reason = "REBOOT";
2239 state->reason = "BOUND";
2241 if (lease->leasetime == DHCP_INFINITE_LIFETIME)
2242 lease->renewaltime = lease->rebindtime = lease->leasetime;
2244 eloop_timeout_add_sec(ctx->eloop,
2245 (time_t)lease->renewaltime, dhcp_startrenew, ifp);
2246 eloop_timeout_add_sec(ctx->eloop,
2247 (time_t)lease->rebindtime, dhcp_rebind, ifp);
2248 eloop_timeout_add_sec(ctx->eloop,
2249 (time_t)lease->leasetime, dhcp_expire, ifp);
2250 logdebugx("%s: renew in %"PRIu32" seconds, rebind in %"PRIu32
2252 ifp->name, lease->renewaltime, lease->rebindtime);
2254 state->state = DHS_BOUND;
2255 if (!state->lease.frominfo &&
2256 !(ifo->options & (DHCPCD_INFORM | DHCPCD_STATIC)))
2257 if (write_lease(ifp, state->new, state->new_len) == -1)
2260 ipv4_applyaddr(ifp);
2263 /* Close the BPF filter as we can now receive DHCP messages
2264 * on a UDP socket. */
2265 if (state->udp_fd == -1 ||
2266 (state->old != NULL && state->old->yiaddr != state->new->yiaddr))
2269 /* If not in master mode, open an address specific socket. */
2270 if (ctx->udp_fd == -1) {
2271 state->udp_fd = dhcp_openudp(ifp);
2272 if (state->udp_fd == -1) {
2274 /* Address sharing without master mode is
2275 * not supported. It's also possible another
2276 * DHCP client could be running which is
2278 * We still need to work, so re-open BPF. */
2281 eloop_event_add(ctx->eloop,
2282 state->udp_fd, dhcp_handleifudp, ifp);
2289 dhcp_lastlease(void *arg)
2291 struct interface *ifp = arg;
2292 struct dhcp_state *state = D_STATE(ifp);
2294 loginfox("%s: timed out contacting a DHCP server, using last lease",
2297 /* If we forked, stop here. */
2298 if (ifp->ctx->options & DHCPCD_FORKED)
2300 state->interval = 0;
2305 dhcp_message_new(struct bootp **bootp,
2306 const struct in_addr *addr, const struct in_addr *mask)
2311 if ((*bootp = calloc(1, sizeof(**bootp))) == NULL)
2314 (*bootp)->yiaddr = addr->s_addr;
2317 cookie = htonl(MAGIC_COOKIE);
2318 memcpy(p, &cookie, sizeof(cookie));
2319 p += sizeof(cookie);
2321 if (mask->s_addr != INADDR_ANY) {
2322 *p++ = DHO_SUBNETMASK;
2323 *p++ = sizeof(mask->s_addr);
2324 memcpy(p, &mask->s_addr, sizeof(mask->s_addr));
2325 p+= sizeof(mask->s_addr);
2329 return sizeof(**bootp);
2333 #ifndef KERNEL_RFC5227
2335 dhcp_arp_defend_failed(struct arp_state *astate)
2338 dhcp_drop(astate->iface, "EXPIRED");
2339 dhcp_start1(astate->iface);
2343 #if !defined(KERNEL_RFC5227) || defined(ARPING)
2344 static struct arp_state *
2345 dhcp_arp_new(struct interface *ifp, struct in_addr *addr)
2347 struct arp_state *astate;
2349 astate = arp_new(ifp, addr);
2353 astate->found_cb = dhcp_arp_found;
2354 astate->not_found_cb = dhcp_arp_not_found;
2355 #ifdef KERNEL_RFC5227
2356 astate->announced_cb = dhcp_arp_announced;
2358 astate->defend_failed_cb = dhcp_arp_defend_failed;
2365 #if defined(ARP) || defined(KERNEL_RFC5227)
2367 dhcp_arp_address(struct interface *ifp)
2369 struct dhcp_state *state;
2370 struct in_addr addr;
2371 struct ipv4_addr *ia;
2373 eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
2375 state = D_STATE(ifp);
2376 addr.s_addr = state->offer->yiaddr == INADDR_ANY ?
2377 state->offer->ciaddr : state->offer->yiaddr;
2378 /* If the interface already has the address configured
2379 * then we can't ARP for duplicate detection. */
2380 ia = ipv4_iffindaddr(ifp, &addr, NULL);
2381 #ifdef IN_IFF_NOTUSEABLE
2382 if (ia == NULL || ia->addr_flags & IN_IFF_NOTUSEABLE) {
2383 state->state = DHS_PROBE;
2385 struct dhcp_lease l;
2387 get_lease(ifp, &l, state->offer, state->offer_len);
2388 /* Add the address now, let the kernel handle DAD. */
2389 ipv4_addaddr(ifp, &l.addr, &l.mask, &l.brd,
2390 l.leasetime, l.rebindtime);
2391 } else if (ia->addr_flags & IN_IFF_DUPLICATED)
2392 dhcp_addr_duplicated(ifp, &ia->addr);
2394 loginfox("%s: waiting for DAD on %s",
2395 ifp->name, inet_ntoa(addr));
2399 if (!(ifp->flags & IFF_NOARP) &&
2400 ifp->options->options & DHCPCD_ARP &&
2403 struct arp_state *astate;
2404 struct dhcp_lease l;
2406 astate = dhcp_arp_new(ifp, &addr);
2410 state->state = DHS_PROBE;
2411 get_lease(ifp, &l, state->offer, state->offer_len);
2412 loginfox("%s: probing address %s/%d",
2413 ifp->name, inet_ntoa(l.addr), inet_ntocidr(l.mask));
2414 /* We need to handle DAD. */
2424 dhcp_arp_bind(struct interface *ifp)
2427 if (ifp->ctx->options & DHCPCD_TEST ||
2428 dhcp_arp_address(ifp) == 1)
2434 dhcp_static(struct interface *ifp)
2436 struct if_options *ifo;
2437 struct dhcp_state *state;
2438 struct ipv4_addr *ia;
2440 state = D_STATE(ifp);
2444 if (ifo->req_addr.s_addr == INADDR_ANY &&
2445 (ia = ipv4_iffindaddr(ifp, NULL, NULL)) == NULL)
2447 loginfox("%s: waiting for 3rd party to "
2448 "configure IP address", ifp->name);
2449 state->reason = "3RDPARTY";
2450 script_runreason(ifp, state->reason);
2454 state->offer_len = dhcp_message_new(&state->offer,
2455 ia ? &ia->addr : &ifo->req_addr,
2456 ia ? &ia->mask : &ifo->req_mask);
2457 if (state->offer_len)
2458 #if defined(ARP) || defined(KERNEL_RFC5227)
2466 dhcp_inform(struct interface *ifp)
2468 struct dhcp_state *state;
2469 struct if_options *ifo;
2470 struct ipv4_addr *ia;
2472 state = D_STATE(ifp);
2475 state->state = DHS_INFORM;
2477 state->offer = NULL;
2478 state->offer_len = 0;
2480 if (ifo->req_addr.s_addr == INADDR_ANY) {
2481 ia = ipv4_iffindaddr(ifp, NULL, NULL);
2483 loginfox("%s: waiting for 3rd party to "
2484 "configure IP address",
2486 if (!(ifp->ctx->options & DHCPCD_TEST)) {
2487 state->reason = "3RDPARTY";
2488 script_runreason(ifp, state->reason);
2493 ia = ipv4_iffindaddr(ifp, &ifo->req_addr, &ifo->req_mask);
2495 if (ifp->ctx->options & DHCPCD_TEST) {
2496 logerrx("%s: cannot add IP address in test mode",
2500 ia = ipv4_iffindaddr(ifp, &ifo->req_addr, NULL);
2502 /* Netmask must be different, delete it. */
2503 ipv4_deladdr(ia, 1);
2504 state->offer_len = dhcp_message_new(&state->offer,
2505 &ifo->req_addr, &ifo->req_mask);
2507 if (dhcp_arp_address(ifp) == 0)
2510 ia = ipv4_iffindaddr(ifp,
2511 &ifo->req_addr, &ifo->req_mask);
2517 state->offer_len = dhcp_message_new(&state->offer,
2518 &ia->addr, &ia->mask);
2519 if (state->offer_len) {
2521 get_lease(ifp, &state->lease, state->offer, state->offer_len);
2527 dhcp_reboot_newopts(struct interface *ifp, unsigned long long oldopts)
2529 struct if_options *ifo;
2530 struct dhcp_state *state = D_STATE(ifp);
2532 if (state == NULL || state->state == DHS_NONE)
2535 if ((ifo->options & (DHCPCD_INFORM | DHCPCD_STATIC) &&
2536 (state->addr == NULL ||
2537 state->addr->addr.s_addr != ifo->req_addr.s_addr)) ||
2538 (oldopts & (DHCPCD_INFORM | DHCPCD_STATIC) &&
2539 !(ifo->options & (DHCPCD_INFORM | DHCPCD_STATIC))))
2541 dhcp_drop(ifp, "EXPIRE");
2547 dhcp_activeaddr(const struct interface *ifp, const struct in_addr *addr)
2549 const struct interface *ifp1;
2550 const struct dhcp_state *state;
2552 TAILQ_FOREACH(ifp1, ifp->ctx->ifaces, next) {
2555 if ((state = D_CSTATE(ifp1)) == NULL)
2557 switch(state->state) {
2567 if (state->lease.addr.s_addr == addr->s_addr)
2575 dhcp_reboot(struct interface *ifp)
2577 struct if_options *ifo;
2578 struct dhcp_state *state = D_STATE(ifp);
2580 struct ipv4_addr *ia;
2583 if (state == NULL || state->state == DHS_NONE)
2586 state->state = DHS_REBOOT;
2587 state->interval = 0;
2589 if (ifo->options & DHCPCD_LINK && ifp->carrier <= LINK_DOWN) {
2590 loginfox("%s: waiting for carrier", ifp->name);
2593 if (ifo->options & DHCPCD_STATIC) {
2597 if (ifo->options & DHCPCD_INFORM) {
2598 loginfox("%s: informing address of %s",
2599 ifp->name, inet_ntoa(state->lease.addr));
2603 if (ifo->reboot == 0 || state->offer == NULL) {
2607 if (!IS_DHCP(state->offer))
2610 loginfox("%s: rebinding lease of %s",
2611 ifp->name, inet_ntoa(state->lease.addr));
2614 /* If the address exists on the interface and no other interface
2615 * is currently using it then announce it to ensure this
2616 * interface gets the reply. */
2617 ia = ipv4_iffindaddr(ifp, &state->lease.addr, NULL);
2619 !(ifp->ctx->options & DHCPCD_TEST) &&
2620 #ifdef IN_IFF_NOTUSEABLE
2621 !(ia->addr_flags & IN_IFF_NOTUSEABLE) &&
2623 dhcp_activeaddr(ifp, &state->lease.addr) == 0)
2624 arp_ifannounceaddr(ifp, &state->lease.addr);
2628 state->lease.server.s_addr = INADDR_ANY;
2629 eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
2632 /* Need to add this before dhcp_expire and friends. */
2633 if (!ifo->fallback && ifo->options & DHCPCD_IPV4LL)
2634 eloop_timeout_add_sec(ifp->ctx->eloop,
2635 ifo->reboot, ipv4ll_start, ifp);
2638 if (ifo->options & DHCPCD_LASTLEASE && state->lease.frominfo)
2639 eloop_timeout_add_sec(ifp->ctx->eloop,
2640 ifo->reboot, dhcp_lastlease, ifp);
2641 else if (!(ifo->options & DHCPCD_INFORM))
2642 eloop_timeout_add_sec(ifp->ctx->eloop,
2643 ifo->reboot, dhcp_expire, ifp);
2645 /* Don't bother ARP checking as the server could NAK us first.
2646 * Don't call dhcp_request as that would change the state */
2651 dhcp_drop(struct interface *ifp, const char *reason)
2653 struct dhcp_state *state;
2658 state = D_STATE(ifp);
2659 /* dhcp_start may just have been called and we don't yet have a state
2660 * but we do have a timeout, so punt it. */
2661 if (state == NULL || state->state == DHS_NONE) {
2662 eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
2667 if (state->addr != NULL)
2668 arp_freeaddr(ifp, &state->addr->addr);
2671 state->arping_index = -1;
2674 if (ifp->options->options & DHCPCD_RELEASE &&
2675 !(ifp->options->options & DHCPCD_INFORM))
2677 /* Failure to send the release may cause this function to
2678 * re-enter so guard by setting the state. */
2679 if (state->state == DHS_RELEASE)
2681 state->state = DHS_RELEASE;
2683 unlink(state->leasefile);
2684 if (ifp->carrier > LINK_DOWN &&
2685 state->new != NULL &&
2686 state->lease.server.s_addr != INADDR_ANY)
2688 loginfox("%s: releasing lease of %s",
2689 ifp->name, inet_ntoa(state->lease.addr));
2691 send_message(ifp, DHCP_RELEASE, NULL);
2693 /* Give the packet a chance to go */
2694 ts.tv_sec = RELEASE_DELAY_S;
2695 ts.tv_nsec = RELEASE_DELAY_NS;
2696 nanosleep(&ts, NULL);
2701 eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
2703 dhcp_auth_reset(&state->auth);
2706 state->state = DHS_NONE;
2708 state->offer = NULL;
2709 state->offer_len = 0;
2711 state->old = state->new;
2712 state->old_len = state->new_len;
2715 state->reason = reason;
2716 ipv4_applyaddr(ifp);
2720 state->lease.addr.s_addr = 0;
2721 ifp->options->options &= ~(DHCPCD_CSR_WARNED |
2722 DHCPCD_ROUTER_HOST_ROUTE_WARNED);
2726 blacklisted_ip(const struct if_options *ifo, in_addr_t addr)
2730 for (i = 0; i < ifo->blacklist_len; i += 2)
2731 if (ifo->blacklist[i] == (addr & ifo->blacklist[i + 1]))
2736 #define WHTLST_NONE 0
2737 #define WHTLST_MATCH 1
2738 #define WHTLST_NOMATCH 2
2740 whitelisted_ip(const struct if_options *ifo, in_addr_t addr)
2744 if (ifo->whitelist_len == 0)
2746 for (i = 0; i < ifo->whitelist_len; i += 2)
2747 if (ifo->whitelist[i] == (addr & ifo->whitelist[i + 1]))
2748 return WHTLST_MATCH;
2749 return WHTLST_NOMATCH;
2753 log_dhcp(logfunc_t *logfunc, const char *msg,
2754 const struct interface *ifp, const struct bootp *bootp, size_t bootp_len,
2755 const struct in_addr *from, int ad)
2758 char *a, sname[sizeof(bootp->sname) * 4];
2759 struct in_addr addr;
2763 if (strcmp(msg, "NAK:") == 0) {
2764 a = get_option_string(ifp->ctx, bootp, bootp_len, DHO_MESSAGE);
2770 tmpl = (al * 4) + 1;
2777 print_string(tmp, tmpl, OT_STRING, (uint8_t *)a, al);
2781 } else if (ad && bootp->yiaddr != 0) {
2782 addr.s_addr = bootp->yiaddr;
2783 a = strdup(inet_ntoa(addr));
2792 r = get_option_addr(ifp->ctx, &addr, bootp, bootp_len, DHO_SERVERID);
2793 if (get_option_uint8(ifp->ctx, &overl, bootp, bootp_len,
2794 DHO_OPTSOVERLOADED) == -1)
2796 if (bootp->sname[0] && r == 0 && !(overl & 2)) {
2797 print_string(sname, sizeof(sname), OT_STRING | OT_DOMAIN,
2798 bootp->sname, sizeof(bootp->sname));
2800 logfunc("%s: %s %s %s `%s'",
2801 ifp->name, msg, tfrom, inet_ntoa(addr), sname);
2803 logfunc("%s: %s %s %s %s `%s'",
2804 ifp->name, msg, a, tfrom, inet_ntoa(addr), sname);
2811 logfunc("%s: %s %s %s",
2812 ifp->name, msg, tfrom, inet_ntoa(addr));
2814 logfunc("%s: %s %s %s %s",
2815 ifp->name, msg, a, tfrom, inet_ntoa(addr));
2820 /* If we're sharing the same IP address with another interface on the
2821 * same network, we may receive the DHCP reply on the wrong interface.
2822 * Try and re-direct it here. */
2824 dhcp_redirect_dhcp(struct interface *ifp, struct bootp *bootp, size_t bootp_len,
2825 const struct in_addr *from)
2827 struct interface *ifn;
2828 const struct dhcp_state *state;
2831 xid = ntohl(bootp->xid);
2832 TAILQ_FOREACH(ifn, ifp->ctx->ifaces, next) {
2833 state = D_CSTATE(ifn);
2834 if (state == NULL || state->state == DHS_NONE)
2836 if (state->xid != xid)
2838 if (ifn->hwlen <= sizeof(bootp->chaddr) &&
2839 memcmp(bootp->chaddr, ifn->hwaddr, ifn->hwlen))
2841 logdebugx("%s: redirecting DHCP message to %s",
2842 ifp->name, ifn->name);
2843 dhcp_handledhcp(ifn, bootp, bootp_len, from);
2848 dhcp_handledhcp(struct interface *ifp, struct bootp *bootp, size_t bootp_len,
2849 const struct in_addr *from)
2851 struct dhcp_state *state = D_STATE(ifp);
2852 struct if_options *ifo = ifp->options;
2853 struct dhcp_lease *lease = &state->lease;
2855 struct in_addr addr;
2860 const uint8_t *auth;
2863 #ifdef IN_IFF_DUPLICATED
2864 struct ipv4_addr *ia;
2867 #define LOGDHCP0(l, m) \
2868 log_dhcp((l), (m), ifp, bootp, bootp_len, from, 0)
2869 #define LOGDHCP(l, m) \
2870 log_dhcp((l), (m), ifp, bootp, bootp_len, from, 1)
2872 #define IS_STATE_ACTIVE(s) ((s)-state != DHS_NONE && \
2873 (s)->state != DHS_INIT && (s)->state != DHS_BOUND)
2875 if (bootp->op != BOOTREPLY) {
2876 if (IS_STATE_ACTIVE(state))
2877 logdebugx("%s: op (%d) is not BOOTREPLY",
2878 ifp->name, bootp->op);
2882 if (state->xid != ntohl(bootp->xid)) {
2883 if (IS_STATE_ACTIVE(state))
2884 logdebugx("%s: wrong xid 0x%x (expecting 0x%x) from %s",
2885 ifp->name, ntohl(bootp->xid), state->xid,
2887 dhcp_redirect_dhcp(ifp, bootp, bootp_len, from);
2891 if (ifp->hwlen <= sizeof(bootp->chaddr) &&
2892 memcmp(bootp->chaddr, ifp->hwaddr, ifp->hwlen))
2894 if (IS_STATE_ACTIVE(state)) {
2895 char buf[sizeof(bootp->chaddr) * 3];
2897 logdebugx("%s: xid 0x%x is for hwaddr %s",
2898 ifp->name, ntohl(bootp->xid),
2899 hwaddr_ntoa(bootp->chaddr, sizeof(bootp->chaddr),
2902 dhcp_redirect_dhcp(ifp, bootp, bootp_len, from);
2909 i = whitelisted_ip(ifp->options, from->s_addr);
2911 case WHTLST_NOMATCH:
2912 logwarnx("%s: non whitelisted DHCP packet from %s",
2913 ifp->name, inet_ntoa(*from));
2918 if (blacklisted_ip(ifp->options, from->s_addr) == 1) {
2919 logwarnx("%s: blacklisted DHCP packet from %s",
2920 ifp->name, inet_ntoa(*from));
2925 /* We may have found a BOOTP server */
2926 if (get_option_uint8(ifp->ctx, &type,
2927 bootp, bootp_len, DHO_MESSAGETYPE) == -1)
2929 else if (ifo->options & DHCPCD_BOOTP) {
2930 logdebugx("%s: ignoring DHCP reply (expecting BOOTP)",
2936 /* Authenticate the message */
2937 auth = get_option(ifp->ctx, bootp, bootp_len,
2938 DHO_AUTHENTICATION, &auth_len);
2940 if (dhcp_auth_validate(&state->auth, &ifo->auth,
2941 (uint8_t *)bootp, bootp_len, 4, type,
2942 auth, auth_len) == NULL)
2944 LOGDHCP0(logerrx, "authentication failed");
2947 if (state->auth.token)
2948 logdebugx("%s: validated using 0x%08" PRIu32,
2949 ifp->name, state->auth.token->secretid);
2951 loginfox("%s: accepted reconfigure key", ifp->name);
2952 } else if (ifo->auth.options & DHCPCD_AUTH_SEND) {
2953 if (ifo->auth.options & DHCPCD_AUTH_REQUIRE) {
2954 LOGDHCP0(logerrx, "no authentication");
2957 LOGDHCP0(logwarnx, "no authentication");
2962 if (type == DHCP_FORCERENEW) {
2963 if (from->s_addr == INADDR_ANY ||
2964 from->s_addr == INADDR_BROADCAST)
2966 LOGDHCP(logerrx, "discarding Force Renew");
2971 LOGDHCP(logerrx, "unauthenticated Force Renew");
2972 if (ifo->auth.options & DHCPCD_AUTH_REQUIRE)
2975 if (state->state != DHS_BOUND && state->state != DHS_INFORM) {
2976 LOGDHCP(logdebugx, "not bound, ignoring Force Renew");
2979 LOGDHCP(loginfox, "Force Renew from");
2980 /* The rebind and expire timings are still the same, we just
2981 * enter the renew state early */
2982 if (state->state == DHS_BOUND)
2985 eloop_timeout_delete(ifp->ctx->eloop,
2990 LOGDHCP(logerrx, "unauthenticated Force Renew");
2995 if (state->state == DHS_BOUND) {
2996 LOGDHCP(logdebugx, "bound, ignoring");
3000 if (state->state == DHS_PROBE) {
3001 /* Ignore any DHCP messages whilst probing a lease to bind. */
3002 LOGDHCP(logdebugx, "probing, ignoring");
3006 /* reset the message counter */
3007 state->interval = 0;
3009 /* Ensure that no reject options are present */
3010 for (i = 1; i < 255; i++) {
3011 if (has_option_mask(ifo->rejectmask, i) &&
3012 get_option_uint8(ifp->ctx, &tmp,
3013 bootp, bootp_len, (uint8_t)i) == 0)
3015 LOGDHCP(logwarnx, "reject DHCP");
3020 if (type == DHCP_NAK) {
3021 /* For NAK, only check if we require the ServerID */
3022 if (has_option_mask(ifo->requiremask, DHO_SERVERID) &&
3023 get_option_addr(ifp->ctx, &addr,
3024 bootp, bootp_len, DHO_SERVERID) == -1)
3026 LOGDHCP(logwarnx, "reject NAK");
3030 /* We should restart on a NAK */
3031 LOGDHCP(logwarnx, "NAK:");
3032 if ((msg = get_option_string(ifp->ctx,
3033 bootp, bootp_len, DHO_MESSAGE)))
3035 logwarnx("%s: message: %s", ifp->name, msg);
3038 if (state->state == DHS_INFORM) /* INFORM should not be NAKed */
3040 if (!(ifp->ctx->options & DHCPCD_TEST)) {
3041 dhcp_drop(ifp, "NAK");
3042 unlink(state->leasefile);
3045 /* If we constantly get NAKS then we should slowly back off */
3046 eloop_timeout_add_sec(ifp->ctx->eloop,
3047 state->nakoff, dhcp_discover, ifp);
3048 if (state->nakoff == 0)
3052 if (state->nakoff > NAKOFF_MAX)
3053 state->nakoff = NAKOFF_MAX;
3058 /* Ensure that all required options are present */
3059 for (i = 1; i < 255; i++) {
3060 if (has_option_mask(ifo->requiremask, i) &&
3061 get_option_uint8(ifp->ctx, &tmp,
3062 bootp, bootp_len, (uint8_t)i) != 0)
3064 /* If we are BOOTP, then ignore the need for serverid.
3065 * To ignore BOOTP, require dhcp_message_type.
3066 * However, nothing really stops BOOTP from providing
3067 * DHCP style options as well so the above isn't
3069 if (type == 0 && i == DHO_SERVERID)
3071 LOGDHCP(logwarnx, "reject DHCP");
3076 /* DHCP Auto-Configure, RFC 2563 */
3077 if (type == DHCP_OFFER && bootp->yiaddr == 0) {
3078 LOGDHCP(logwarnx, "no address given");
3079 if ((msg = get_option_string(ifp->ctx,
3080 bootp, bootp_len, DHO_MESSAGE)))
3082 logwarnx("%s: message: %s", ifp->name, msg);
3086 if (state->state == DHS_DISCOVER &&
3087 get_option_uint8(ifp->ctx, &tmp, bootp, bootp_len,
3088 DHO_AUTOCONFIGURE) == 0)
3092 LOGDHCP(logwarnx, "IPv4LL disabled from");
3099 LOGDHCP(logwarnx, "IPv4LL enabled from");
3103 logerrx("%s: unknown auto configuration "
3108 eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
3109 eloop_timeout_add_sec(ifp->ctx->eloop,
3110 DHCP_MAX, dhcp_discover, ifp);
3116 /* Ensure that the address offered is valid */
3117 if ((type == 0 || type == DHCP_OFFER || type == DHCP_ACK) &&
3118 (bootp->ciaddr == INADDR_ANY || bootp->ciaddr == INADDR_BROADCAST)
3120 (bootp->yiaddr == INADDR_ANY || bootp->yiaddr == INADDR_BROADCAST))
3122 LOGDHCP(logwarnx, "reject invalid address");
3126 #ifdef IN_IFF_DUPLICATED
3127 ia = ipv4_iffindaddr(ifp, &lease->addr, NULL);
3128 if (ia && ia->addr_flags & IN_IFF_DUPLICATED) {
3129 LOGDHCP(logwarnx, "declined duplicate address");
3132 ipv4_deladdr(ia, 0);
3133 eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
3134 eloop_timeout_add_sec(ifp->ctx->eloop,
3135 DHCP_RAND_MAX, dhcp_discover, ifp);
3140 bootp_copied = false;
3141 if ((type == 0 || type == DHCP_OFFER) && state->state == DHS_DISCOVER) {
3142 lease->frominfo = 0;
3143 lease->addr.s_addr = bootp->yiaddr;
3144 memcpy(&lease->cookie, bootp->vend, sizeof(lease->cookie));
3146 get_option_addr(ifp->ctx,
3147 &lease->server, bootp, bootp_len, DHO_SERVERID) != 0)
3148 lease->server.s_addr = INADDR_ANY;
3150 /* Test for rapid commit in the OFFER */
3151 if (!(ifp->ctx->options & DHCPCD_TEST) &&
3152 has_option_mask(ifo->requestmask, DHO_RAPIDCOMMIT) &&
3153 get_option(ifp->ctx, bootp, bootp_len,
3154 DHO_RAPIDCOMMIT, NULL))
3156 state->state = DHS_REQUEST;
3160 LOGDHCP(loginfox, "offered");
3161 if (state->offer_len < bootp_len) {
3163 if ((state->offer = malloc(bootp_len)) == NULL) {
3165 state->offer_len = 0;
3169 state->offer_len = bootp_len;
3170 memcpy(state->offer, bootp, bootp_len);
3171 bootp_copied = true;
3172 if (ifp->ctx->options & DHCPCD_TEST) {
3174 state->old = state->new;
3175 state->old_len = state->new_len;
3176 state->new = state->offer;
3177 state->new_len = state->offer_len;
3178 state->offer = NULL;
3179 state->offer_len = 0;
3180 state->reason = "TEST";
3181 script_runreason(ifp, state->reason);
3182 eloop_exit(ifp->ctx->eloop, EXIT_SUCCESS);
3183 state->bpf_flags |= BPF_EOF;
3186 eloop_timeout_delete(ifp->ctx->eloop, send_discover, ifp);
3187 /* We don't request BOOTP addresses */
3189 /* We used to ARP check here, but that seems to be in
3190 * violation of RFC2131 where it only describes
3191 * DECLINE after REQUEST.
3192 * It also seems that some MS DHCP servers actually
3193 * ignore DECLINE if no REQUEST, ie we decline a
3201 if (type == DHCP_OFFER) {
3202 LOGDHCP(logwarnx, "ignoring offer of");
3206 /* We should only be dealing with acks */
3207 if (type != DHCP_ACK) {
3208 LOGDHCP(logerr, "not ACK or OFFER");
3212 if (state->state == DHS_DISCOVER) {
3213 /* We only allow ACK of rapid commit DISCOVER. */
3214 if (has_option_mask(ifo->requestmask,
3216 get_option(ifp->ctx, bootp, bootp_len,
3217 DHO_RAPIDCOMMIT, NULL))
3218 state->state = DHS_REQUEST;
3220 LOGDHCP(logdebugx, "ignoring ack of");
3226 if (!(ifo->options & DHCPCD_INFORM))
3227 LOGDHCP(logdebugx, "acknowledged");
3229 ifo->options &= ~DHCPCD_STATIC;
3232 /* No NAK, so reset the backoff
3233 * We don't reset on an OFFER message because the server could
3234 * potentially NAK the REQUEST. */
3237 /* BOOTP could have already assigned this above. */
3238 if (!bootp_copied) {
3239 if (state->offer_len < bootp_len) {
3241 if ((state->offer = malloc(bootp_len)) == NULL) {
3243 state->offer_len = 0;
3247 state->offer_len = bootp_len;
3248 memcpy(state->offer, bootp, bootp_len);
3251 lease->frominfo = 0;
3252 eloop_timeout_delete(ifp->ctx->eloop, NULL, ifp);
3254 #if defined(ARP) || defined(KERNEL_RFC5227)
3262 get_udp_data(void *packet, size_t *len)
3264 const struct ip *ip = packet;
3265 size_t ip_hl = (size_t)ip->ip_hl * 4;
3268 p += ip_hl + sizeof(struct udphdr);
3269 *len = (size_t)ntohs(ip->ip_len) - sizeof(struct udphdr) - ip_hl;
3274 is_packet_udp_bootp(void *packet, size_t plen)
3276 struct ip *ip = packet;
3280 if (sizeof(*ip) > plen)
3283 if (ip->ip_v != IPVERSION || ip->ip_p != IPPROTO_UDP)
3287 if (ntohs(ip->ip_len) != plen)
3290 ip_hlen = (size_t)ip->ip_hl * 4;
3291 /* Check we have a UDP header and BOOTP. */
3292 if (ip_hlen + sizeof(*udp) + offsetof(struct bootp, vend) > plen)
3295 /* Check it's to and from the right ports. */
3296 udp = (struct udphdr *)(void *)((char *)ip + ip_hlen);
3297 if (udp->uh_dport != htons(BOOTPC) || udp->uh_sport != htons(BOOTPS))
3303 /* Lengths have already been checked. */
3305 checksums_valid(void *packet,
3306 struct in_addr *from, unsigned int flags)
3308 struct ip *ip = packet;
3309 struct ip pseudo_ip = {
3310 .ip_p = IPPROTO_UDP,
3311 .ip_src = ip->ip_src,
3312 .ip_dst = ip->ip_dst
3315 uint16_t udp_len, uh_sum;
3320 from->s_addr = ip->ip_src.s_addr;
3322 ip_hlen = (size_t)ip->ip_hl * 4;
3323 if (in_cksum(ip, ip_hlen, NULL) != 0)
3326 if (flags & BPF_PARTIALCSUM)
3329 udp = (struct udphdr *)(void *)((char *)ip + ip_hlen);
3330 if (udp->uh_sum == 0)
3333 /* UDP checksum is based on a pseudo IP header alongside
3334 * the UDP header and payload. */
3335 udp_len = ntohs(udp->uh_ulen);
3336 uh_sum = udp->uh_sum;
3338 pseudo_ip.ip_len = udp->uh_ulen;
3340 in_cksum(&pseudo_ip, sizeof(pseudo_ip), &csum);
3341 csum = in_cksum(udp, udp_len, &csum);
3342 return csum == uh_sum;
3346 dhcp_handlebootp(struct interface *ifp, struct bootp *bootp, size_t len,
3347 struct in_addr *from)
3351 if (len < offsetof(struct bootp, vend)) {
3352 logerrx("%s: truncated packet (%zu) from %s",
3353 ifp->name, len, inet_ntoa(*from));
3357 /* To make our IS_DHCP macro easy, ensure the vendor
3358 * area has at least 4 octets. */
3359 v = len - offsetof(struct bootp, vend);
3361 bootp->vend[v++] = '\0';
3365 dhcp_handledhcp(ifp, bootp, len, from);
3369 dhcp_handlebpf(struct interface *ifp, uint8_t *data, size_t len)
3371 struct bootp *bootp;
3372 struct in_addr from;
3374 const struct dhcp_state *state = D_CSTATE(ifp);
3376 /* Validate filter. */
3377 if (!is_packet_udp_bootp(data, len)) {
3379 logerrx("%s: DHCP BPF validation failure", ifp->name);
3384 if (!checksums_valid(data, &from, state->bpf_flags)) {
3385 logerrx("%s: checksum failure from %s",
3386 ifp->name, inet_ntoa(from));
3391 * DHCP has a variable option area rather than a fixed vendor area.
3392 * Because DHCP uses the BOOTP protocol it should still send BOOTP
3393 * sized packets to be RFC compliant.
3394 * However some servers send a truncated vendor area.
3395 * dhcpcd can work fine without the vendor area being sent.
3397 bootp = get_udp_data(data, &udp_len);
3398 dhcp_handlebootp(ifp, bootp, udp_len, &from);
3402 dhcp_readbpf(void *arg)
3404 struct interface *ifp = arg;
3405 uint8_t buf[MTU_MAX];
3407 struct dhcp_state *state = D_STATE(ifp);
3409 /* Some RAW mechanisms are generic file descriptors, not sockets.
3410 * This means we have no kernel call to just get one packet,
3411 * so we have to process the entire buffer. */
3412 state->bpf_flags &= ~BPF_EOF;
3413 state->bpf_flags |= BPF_READING;
3414 while (!(state->bpf_flags & BPF_EOF)) {
3415 bytes = bpf_read(ifp, state->bpf_fd, buf, sizeof(buf),
3418 if (state->state != DHS_NONE) {
3419 logerr("%s: %s", __func__, ifp->name);
3424 dhcp_handlebpf(ifp, buf, (size_t)bytes);
3425 /* Check we still have a state after processing. */
3426 if ((state = D_STATE(ifp)) == NULL)
3430 state->bpf_flags &= ~BPF_READING;
3434 dhcp_readudp(struct dhcpcd_ctx *ctx, struct interface *ifp)
3436 const struct dhcp_state *state;
3437 struct sockaddr_in from;
3438 unsigned char buf[10 * 1024]; /* Maximum MTU */
3439 struct iovec iov = {
3441 .iov_len = sizeof(buf),
3444 unsigned char ctl[CMSG_SPACE(sizeof(struct in_pktinfo))] = { 0 };
3445 char sfrom[INET_ADDRSTRLEN];
3447 struct msghdr msg = {
3448 .msg_name = &from, .msg_namelen = sizeof(from),
3449 .msg_iov = &iov, .msg_iovlen = 1,
3451 .msg_control = ctl, .msg_controllen = sizeof(ctl),
3458 state = D_CSTATE(ifp);
3463 bytes = recvmsg(s, &msg, 0);
3470 inet_ntop(AF_INET, &from.sin_addr, sfrom, sizeof(sfrom));
3473 ifp = if_findifpfromcmsg(ctx, &msg, NULL);
3478 state = D_CSTATE(ifp);
3479 if (state == NULL) {
3480 logdebugx("%s: received BOOTP for inactive interface",
3486 if (state->bpf_fd != -1) {
3487 /* Avoid a duplicate read if BPF is open for the interface. */
3491 dhcp_handlebootp(ifp, (struct bootp *)(void *)buf, (size_t)bytes,
3497 dhcp_handleudp(void *arg)
3499 struct dhcpcd_ctx *ctx = arg;
3501 dhcp_readudp(ctx, NULL);
3506 dhcp_handleifudp(void *arg)
3508 struct interface *ifp = arg;
3510 dhcp_readudp(ifp->ctx, ifp);
3516 dhcp_openbpf(struct interface *ifp)
3518 struct dhcp_state *state;
3520 state = D_STATE(ifp);
3521 if (state->bpf_fd != -1)
3524 state->bpf_fd = bpf_open(ifp, bpf_bootp);
3525 if (state->bpf_fd == -1) {
3526 if (errno == ENOENT) {
3527 logerrx("%s not found", bpf_name);
3528 /* May as well disable IPv4 entirely at
3529 * this point as we really need it. */
3530 ifp->options->options &= ~DHCPCD_IPV4;
3532 logerr("%s: %s", __func__, ifp->name);
3536 eloop_event_add(ifp->ctx->eloop,
3537 state->bpf_fd, dhcp_readbpf, ifp);
3542 dhcp_dump(struct interface *ifp)
3544 struct dhcp_state *state;
3546 ifp->if_data[IF_DATA_DHCP] = state = calloc(1, sizeof(*state));
3550 dhcp_set_leasefile(state->leasefile, sizeof(state->leasefile),
3552 state->new_len = read_lease(ifp, &state->new);
3553 if (state->new == NULL) {
3555 *ifp->name ? ifp->name : state->leasefile, __func__);
3558 state->reason = "DUMP";
3559 return script_runreason(ifp, state->reason);
3567 dhcp_free(struct interface *ifp)
3569 struct dhcp_state *state = D_STATE(ifp);
3570 struct dhcpcd_ctx *ctx;
3577 state->state = DHS_NONE;
3581 free(state->clientid);
3586 /* If we don't have any more DHCP enabled interfaces,
3587 * close the global socket and release resources */
3589 TAILQ_FOREACH(ifp, ctx->ifaces, next) {
3590 state = D_STATE(ifp);
3591 if (state != NULL && state->state != DHS_NONE)
3596 if (ctx->udp_fd != -1) {
3597 eloop_event_delete(ctx->eloop, ctx->udp_fd);
3602 free(ctx->opt_buffer);
3603 ctx->opt_buffer = NULL;
3608 dhcp_initstate(struct interface *ifp)
3610 struct dhcp_state *state;
3612 state = D_STATE(ifp);
3616 ifp->if_data[IF_DATA_DHCP] = calloc(1, sizeof(*state));
3617 state = D_STATE(ifp);
3621 state->state = DHS_NONE;
3622 /* 0 is a valid fd, so init to -1 */
3626 state->arping_index = -1;
3632 dhcp_init(struct interface *ifp)
3634 struct dhcp_state *state;
3635 const struct if_options *ifo;
3637 char buf[(sizeof(ifo->clientid) - 1) * 3];
3639 if (dhcp_initstate(ifp) == -1)
3642 state = D_STATE(ifp);
3643 state->state = DHS_INIT;
3644 state->reason = "PREINIT";
3646 dhcp_set_leasefile(state->leasefile, sizeof(state->leasefile),
3650 /* We need to drop the leasefile so that dhcp_start
3651 * doesn't load it. */
3652 if (ifo->options & DHCPCD_REQUEST)
3653 unlink(state->leasefile);
3655 free(state->clientid);
3656 state->clientid = NULL;
3658 if (*ifo->clientid) {
3659 state->clientid = malloc((size_t)(ifo->clientid[0] + 1));
3660 if (state->clientid == NULL)
3662 memcpy(state->clientid, ifo->clientid,
3663 (size_t)(ifo->clientid[0]) + 1);
3664 } else if (ifo->options & DHCPCD_CLIENTID) {
3665 if (ifo->options & DHCPCD_DUID) {
3666 state->clientid = malloc(ifp->ctx->duid_len + 6);
3667 if (state->clientid == NULL)
3669 state->clientid[0] =(uint8_t)(ifp->ctx->duid_len + 5);
3670 state->clientid[1] = 255; /* RFC 4361 */
3671 memcpy(state->clientid + 2, ifo->iaid, 4);
3672 memcpy(state->clientid + 6, ifp->ctx->duid,
3673 ifp->ctx->duid_len);
3675 len = (uint8_t)(ifp->hwlen + 1);
3676 state->clientid = malloc((size_t)len + 1);
3677 if (state->clientid == NULL)
3679 state->clientid[0] = len;
3680 state->clientid[1] = (uint8_t)ifp->family;
3681 memcpy(state->clientid + 2, ifp->hwaddr,
3686 if (ifo->options & DHCPCD_DUID)
3687 /* Don't bother logging as DUID and IAID are reported
3688 * at device start. */
3691 if (ifo->options & DHCPCD_CLIENTID)
3692 logdebugx("%s: using ClientID %s", ifp->name,
3693 hwaddr_ntoa(state->clientid + 1, state->clientid[0],
3695 else if (ifp->hwlen)
3696 logdebugx("%s: using hwaddr %s", ifp->name,
3697 hwaddr_ntoa(ifp->hwaddr, ifp->hwlen, buf, sizeof(buf)));
3706 dhcp_start1(void *arg)
3708 struct interface *ifp = arg;
3709 struct dhcpcd_ctx *ctx = ifp->ctx;
3710 struct if_options *ifo = ifp->options;
3711 struct dhcp_state *state;
3716 if (!(ifo->options & DHCPCD_IPV4))
3719 /* Listen on *.*.*.*:bootpc so that the kernel never sends an
3720 * ICMP port unreachable message back to the DHCP server.
3721 * Only do this in master mode so we don't swallow messages
3722 * for dhcpcd running on another interface. */
3723 if (ctx->udp_fd == -1 && ctx->options & DHCPCD_MASTER) {
3724 ctx->udp_fd = dhcp_openudp(NULL);
3725 if (ctx->udp_fd == -1) {
3726 /* Don't log an error if some other process
3727 * is handling this. */
3728 if (errno != EADDRINUSE)
3729 logerr("%s: dhcp_openudp", __func__);
3731 eloop_event_add(ctx->eloop,
3732 ctx->udp_fd, dhcp_handleudp, ctx);
3735 if (dhcp_init(ifp) == -1) {
3736 logerr("%s: dhcp_init", ifp->name);
3740 state = D_STATE(ifp);
3741 clock_gettime(CLOCK_MONOTONIC, &state->started);
3742 state->interval = 0;
3744 state->offer = NULL;
3745 state->offer_len = 0;
3748 if (ifo->arping_len && state->arping_index < ifo->arping_len) {
3749 struct arp_state *astate;
3751 astate = dhcp_arp_new(ifp, NULL);
3753 dhcp_arp_not_found(astate);
3758 if (ifo->options & DHCPCD_STATIC) {
3763 if (ifo->options & DHCPCD_INFORM) {
3768 /* We don't want to read the old lease if we NAK an old test */
3769 nolease = state->offer && ifp->ctx->options & DHCPCD_TEST;
3770 if (!nolease && ifo->options & DHCPCD_DHCP) {
3771 state->offer_len = read_lease(ifp, &state->offer);
3772 /* Check the saved lease matches the type we want */
3774 #ifdef IN_IFF_DUPLICATED
3775 struct in_addr addr;
3776 struct ipv4_addr *ia;
3778 addr.s_addr = state->offer->yiaddr;
3779 ia = ipv4_iffindaddr(ifp, &addr, NULL);
3782 if ((!IS_DHCP(state->offer) &&
3783 !(ifo->options & DHCPCD_BOOTP)) ||
3784 #ifdef IN_IFF_DUPLICATED
3785 (ia && ia->addr_flags & IN_IFF_DUPLICATED) ||
3787 (IS_DHCP(state->offer) &&
3788 ifo->options & DHCPCD_BOOTP))
3791 state->offer = NULL;
3792 state->offer_len = 0;
3797 struct ipv4_addr *ia;
3799 get_lease(ifp, &state->lease, state->offer, state->offer_len);
3800 state->lease.frominfo = 1;
3801 if (state->new == NULL &&
3802 (ia = ipv4_iffindaddr(ifp,
3803 &state->lease.addr, &state->lease.mask)) != NULL)
3805 /* We still have the IP address from the last lease.
3806 * Fake add the address and routes from it so the lease
3807 * can be cleaned up. */
3808 state->new = malloc(state->offer_len);
3811 state->offer, state->offer_len);
3812 state->new_len = state->offer_len;
3814 state->added |= STATE_ADDED | STATE_FAKE;
3815 rt_build(ifp->ctx, AF_INET);
3819 if (!IS_DHCP(state->offer)) {
3821 state->offer = NULL;
3822 state->offer_len = 0;
3823 } else if (!(ifo->options & DHCPCD_LASTLEASE_EXTEND) &&
3824 state->lease.leasetime != DHCP_INFINITE_LIFETIME &&
3825 stat(state->leasefile, &st) == 0)
3829 /* Offset lease times and check expiry */
3832 (time_t)state->lease.leasetime < now - st.st_mtime)
3834 logdebugx("%s: discarding expired lease",
3837 state->offer = NULL;
3838 state->offer_len = 0;
3839 state->lease.addr.s_addr = 0;
3840 /* Technically we should discard the lease
3841 * as it's expired, just as DHCPv6 addresses
3842 * would be by the kernel.
3843 * However, this may violate POLA so
3844 * we currently leave it be.
3845 * If we get a totally different lease from
3846 * the DHCP server we'll drop it anyway, as
3847 * we will on any other event which would
3848 * trigger a lease drop.
3849 * This should only happen if dhcpcd stops
3850 * running and the lease expires before
3851 * dhcpcd starts again. */
3854 dhcp_drop(ifp, "EXPIRE");
3857 l = (uint32_t)(now - st.st_mtime);
3858 state->lease.leasetime -= l;
3859 state->lease.renewaltime -= l;
3860 state->lease.rebindtime -= l;
3866 if (!(ifo->options & DHCPCD_DHCP)) {
3867 if (ifo->options & DHCPCD_IPV4LL)
3873 if (state->offer == NULL || !IS_DHCP(state->offer))
3880 dhcp_start(struct interface *ifp)
3884 const struct dhcp_state *state;
3887 if (!(ifp->options->options & DHCPCD_IPV4))
3890 /* If we haven't been given a netmask for our requested address,
3892 if (ifp->options->req_addr.s_addr != INADDR_ANY &&
3893 ifp->options->req_mask.s_addr == INADDR_ANY)
3894 ifp->options->req_mask.s_addr =
3895 ipv4_getnetmask(ifp->options->req_addr.s_addr);
3897 /* If we haven't specified a ClientID and our hardware address
3898 * length is greater than BOOTP CHADDR then we enforce a ClientID
3899 * of the hardware address family and the hardware address.
3900 * If there is no hardware address and no ClientID set,
3901 * force a DUID based ClientID. */
3902 if (ifp->hwlen > 16)
3903 ifp->options->options |= DHCPCD_CLIENTID;
3904 else if (ifp->hwlen == 0 && !(ifp->options->options & DHCPCD_CLIENTID))
3905 ifp->options->options |= DHCPCD_CLIENTID | DHCPCD_DUID;
3907 /* Firewire and InfiniBand interfaces require ClientID and
3908 * the broadcast option being set. */
3909 switch (ifp->family) {
3910 case ARPHRD_IEEE1394: /* FALLTHROUGH */
3911 case ARPHRD_INFINIBAND:
3912 ifp->options->options |= DHCPCD_CLIENTID | DHCPCD_BROADCAST;
3916 /* If we violate RFC2131 section 3.7 then require ARP
3917 * to detect if any other client wants our address. */
3918 if (ifp->options->options & DHCPCD_LASTLEASE_EXTEND)
3919 ifp->options->options |= DHCPCD_ARP;
3921 /* No point in delaying a static configuration */
3922 if (ifp->options->options & DHCPCD_STATIC ||
3923 !(ifp->options->options & DHCPCD_INITIAL_DELAY))
3930 /* If we have arpinged then we have already delayed. */
3931 state = D_CSTATE(ifp);
3932 if (state != NULL && state->arping_index != -1) {
3938 tv.tv_sec = DHCP_MIN_DELAY;
3939 tv.tv_nsec = (suseconds_t)arc4random_uniform(
3940 (DHCP_MAX_DELAY - DHCP_MIN_DELAY) * NSEC_PER_SEC);
3942 logdebugx("%s: delaying IPv4 for %0.1f seconds",
3943 ifp->name, timespec_to_double(&tv));
3945 eloop_timeout_add_tv(ifp->ctx->eloop, &tv, dhcp_start1, ifp);
3949 dhcp_abort(struct interface *ifp)
3951 struct dhcp_state *state;
3953 state = D_STATE(ifp);
3956 state->arping_index = -1;
3959 eloop_timeout_delete(ifp->ctx->eloop, dhcp_start1, ifp);
3961 if (state != NULL && state->added) {
3962 rt_build(ifp->ctx, AF_INET);
3964 arp_announceaddr(ifp->ctx, &state->addr->addr);
3970 dhcp_handleifa(int cmd, struct ipv4_addr *ia, pid_t pid)
3972 struct interface *ifp;
3973 struct dhcp_state *state;
3974 struct if_options *ifo;
3978 state = D_STATE(ifp);
3979 if (state == NULL || state->state == DHS_NONE)
3982 if (cmd == RTM_DELADDR) {
3983 if (state->addr == ia) {
3984 loginfox("%s: pid %d deleted IP address %s",
3985 ifp->name, pid, ia->saddr);
3987 /* Don't clear the added state as we need
3988 * to drop the lease. */
3989 dhcp_drop(ifp, "EXPIRE");
3995 if (cmd != RTM_NEWADDR)
3998 #ifdef IN_IFF_NOTUSEABLE
3999 if (!(ia->addr_flags & IN_IFF_NOTUSEABLE))
4000 dhcp_finish_dad(ifp, &ia->addr);
4001 else if (ia->addr_flags & IN_IFF_DUPLICATED)
4002 return dhcp_addr_duplicated(ifp, &ia->addr) ? NULL : ia;
4006 if (ifo->options & DHCPCD_INFORM) {
4007 if (state->state != DHS_INFORM)
4012 if (!(ifo->options & DHCPCD_STATIC))
4014 if (ifo->req_addr.s_addr != INADDR_ANY)
4018 state->old = state->new;
4019 state->new_len = dhcp_message_new(&state->new, &ia->addr, &ia->mask);
4020 if (state->new == NULL)
4022 if (ifp->flags & IFF_POINTOPOINT) {
4023 for (i = 1; i < 255; i++)
4024 if (i != DHO_ROUTER && has_option_mask(ifo->dstmask,i))
4025 dhcp_message_add_addr(state->new, i, ia->brd);
4027 state->reason = "STATIC";
4028 rt_build(ifp->ctx, AF_INET);
4029 script_runreason(ifp, state->reason);
4030 if (ifo->options & DHCPCD_INFORM) {
4031 state->state = DHS_INFORM;
4033 state->lease.server.s_addr = INADDR_ANY;