xref: /dragonfly/contrib/dhcpcd/src/arp.c (revision eef623fc)
1 /* SPDX-License-Identifier: BSD-2-Clause */
2 /*
3  * dhcpcd - ARP handler
4  * Copyright (c) 2006-2019 Roy Marples <roy@marples.name>
5  * All rights reserved
6 
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
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.
15  *
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
26  * SUCH DAMAGE.
27  */
28 
29 #include <sys/socket.h>
30 #include <sys/types.h>
31 
32 #include <arpa/inet.h>
33 
34 #include <net/if.h>
35 #include <netinet/in.h>
36 #include <netinet/if_ether.h>
37 
38 #include <errno.h>
39 #include <stdlib.h>
40 #include <stdio.h>
41 #include <string.h>
42 #include <unistd.h>
43 
44 #define ELOOP_QUEUE 5
45 #include "config.h"
46 #include "arp.h"
47 #include "bpf.h"
48 #include "ipv4.h"
49 #include "common.h"
50 #include "dhcpcd.h"
51 #include "eloop.h"
52 #include "if.h"
53 #include "if-options.h"
54 #include "ipv4ll.h"
55 #include "logerr.h"
56 
57 #if defined(ARP)
58 #define ARP_LEN								      \
59 	(sizeof(struct arphdr) + (2 * sizeof(uint32_t)) + (2 * HWADDR_LEN))
60 
61 /* ARP debugging can be quite noisy. Enable this for more noise! */
62 //#define	ARP_DEBUG
63 
64 /* Assert the correct structure size for on wire */
65 __CTASSERT(sizeof(struct arphdr) == 8);
66 
67 static ssize_t
68 arp_request(const struct interface *ifp,
69     const struct in_addr *sip, const struct in_addr *tip)
70 {
71 	uint8_t arp_buffer[ARP_LEN];
72 	struct arphdr ar;
73 	size_t len;
74 	uint8_t *p;
75 	const struct iarp_state *state;
76 
77 	ar.ar_hrd = htons(ifp->family);
78 	ar.ar_pro = htons(ETHERTYPE_IP);
79 	ar.ar_hln = ifp->hwlen;
80 	ar.ar_pln = sizeof(tip->s_addr);
81 	ar.ar_op = htons(ARPOP_REQUEST);
82 
83 	p = arp_buffer;
84 	len = 0;
85 
86 #define CHECK(fun, b, l)						\
87 	do {								\
88 		if (len + (l) > sizeof(arp_buffer))			\
89 			goto eexit;					\
90 		fun(p, (b), (l));					\
91 		p += (l);						\
92 		len += (l);						\
93 	} while (/* CONSTCOND */ 0)
94 #define APPEND(b, l)	CHECK(memcpy, b, l)
95 #define ZERO(l)		CHECK(memset, 0, l)
96 
97 	APPEND(&ar, sizeof(ar));
98 	APPEND(ifp->hwaddr, ifp->hwlen);
99 	if (sip != NULL)
100 		APPEND(&sip->s_addr, sizeof(sip->s_addr));
101 	else
102 		ZERO(sizeof(tip->s_addr));
103 	ZERO(ifp->hwlen);
104 	APPEND(&tip->s_addr, sizeof(tip->s_addr));
105 
106 	state = ARP_CSTATE(ifp);
107 	return bpf_send(ifp, state->bpf_fd, ETHERTYPE_ARP, arp_buffer, len);
108 
109 eexit:
110 	errno = ENOBUFS;
111 	return -1;
112 }
113 
114 static void
115 arp_report_conflicted(const struct arp_state *astate,
116     const struct arp_msg *amsg)
117 {
118 	char buf[HWADDR_LEN * 3];
119 
120 	if (amsg == NULL) {
121 		logerrx("%s: DAD detected %s",
122 		    astate->iface->name, inet_ntoa(astate->addr));
123 		return;
124 	}
125 
126 	logerrx("%s: hardware address %s claims %s",
127 	    astate->iface->name,
128 	    hwaddr_ntoa(amsg->sha, astate->iface->hwlen, buf, sizeof(buf)),
129 	    inet_ntoa(astate->addr));
130 }
131 
132 
133 static void
134 arp_found(struct arp_state *astate, const struct arp_msg *amsg)
135 {
136 	struct interface *ifp;
137 	struct ivp4_addr *ia;
138 #ifndef KERNEL_RFC5227
139 	struct timespec now, defend;
140 #endif
141 
142 	arp_report_conflicted(astate, amsg);
143 	ifp = astate->iface;
144 
145 #pragma GCC diagnostic push /* GCC is clearly wrong about this warning. */
146 #pragma GCC diagnostic ignored "-Wincompatible-pointer-types"
147 	/* If we haven't added the address we're doing a probe. */
148 	ia = ipv4_iffindaddr(ifp, &astate->addr, NULL);
149 #pragma GCC diagnostic pop
150 	if (ia == NULL) {
151 		if (astate->found_cb != NULL)
152 			astate->found_cb(astate, amsg);
153 		return;
154 	}
155 
156 #ifndef KERNEL_RFC5227
157 	/* RFC 3927 Section 2.5 says a defence should
158 	 * broadcast an ARP announcement.
159 	 * Because the kernel will also unicast a reply to the
160 	 * hardware address which requested the IP address
161 	 * the other IPv4LL client will receieve two ARP
162 	 * messages.
163 	 * If another conflict happens within DEFEND_INTERVAL
164 	 * then we must drop our address and negotiate a new one. */
165 	defend.tv_sec = astate->defend.tv_sec + DEFEND_INTERVAL;
166 	defend.tv_nsec = astate->defend.tv_nsec;
167 	clock_gettime(CLOCK_MONOTONIC, &now);
168 	if (timespeccmp(&defend, &now, >))
169 		logwarnx("%s: %d second defence failed for %s",
170 		    ifp->name, DEFEND_INTERVAL, inet_ntoa(astate->addr));
171 	else if (arp_request(ifp, &astate->addr, &astate->addr) == -1)
172 		logerr(__func__);
173 	else {
174 		logdebugx("%s: defended address %s",
175 		    ifp->name, inet_ntoa(astate->addr));
176 		astate->defend = now;
177 		return;
178 	}
179 #endif
180 
181 	if (astate->defend_failed_cb != NULL)
182 		astate->defend_failed_cb(astate);
183 }
184 
185 static void
186 arp_packet(struct interface *ifp, uint8_t *data, size_t len)
187 {
188 	const struct interface *ifn;
189 	struct arphdr ar;
190 	struct arp_msg arm;
191 	const struct iarp_state *state;
192 	struct arp_state *astate, *astaten;
193 	uint8_t *hw_s, *hw_t;
194 
195 	/* We must have a full ARP header */
196 	if (len < sizeof(ar))
197 		return;
198 	memcpy(&ar, data, sizeof(ar));
199 
200 	/* These checks are enforced in the BPF filter. */
201 #if 0
202 	/* Families must match */
203 	if (ar.ar_hrd != htons(ifp->family))
204 		return;
205 	/* Protocol must be IP. */
206 	if (ar.ar_pro != htons(ETHERTYPE_IP))
207 		continue;
208 	/* lladdr length matches */
209 	if (ar.ar_hln != ifp->hwlen)
210 		continue;
211 	/* Protocol length must match in_addr_t */
212 	if (ar.ar_pln != sizeof(arm.sip.s_addr))
213 		return;
214 	/* Only these types are recognised */
215 	if (ar.ar_op != htons(ARPOP_REPLY) &&
216 	    ar.ar_op != htons(ARPOP_REQUEST))
217 		continue;
218 #endif
219 
220 	/* Get pointers to the hardware addresses */
221 	hw_s = data + sizeof(ar);
222 	hw_t = hw_s + ar.ar_hln + ar.ar_pln;
223 	/* Ensure we got all the data */
224 	if ((size_t)((hw_t + ar.ar_hln + ar.ar_pln) - data) > len)
225 		return;
226 	/* Ignore messages from ourself */
227 	TAILQ_FOREACH(ifn, ifp->ctx->ifaces, next) {
228 		if (ar.ar_hln == ifn->hwlen &&
229 		    memcmp(hw_s, ifn->hwaddr, ifn->hwlen) == 0)
230 			break;
231 	}
232 	if (ifn) {
233 #ifdef ARP_DEBUG
234 		logdebugx("%s: ignoring ARP from self", ifp->name);
235 #endif
236 		return;
237 	}
238 	/* Copy out the HW and IP addresses */
239 	memcpy(&arm.sha, hw_s, ar.ar_hln);
240 	memcpy(&arm.sip.s_addr, hw_s + ar.ar_hln, ar.ar_pln);
241 	memcpy(&arm.tha, hw_t, ar.ar_hln);
242 	memcpy(&arm.tip.s_addr, hw_t + ar.ar_hln, ar.ar_pln);
243 
244 	/* Match the ARP probe to our states.
245 	 * Ignore Unicast Poll, RFC1122. */
246 	state = ARP_CSTATE(ifp);
247 	TAILQ_FOREACH_SAFE(astate, &state->arp_states, next, astaten) {
248 		if (IN_ARE_ADDR_EQUAL(&arm.sip, &astate->addr) ||
249 		    (IN_IS_ADDR_UNSPECIFIED(&arm.sip) &&
250 		    IN_ARE_ADDR_EQUAL(&arm.tip, &astate->addr) &&
251 		    state->bpf_flags & BPF_BCAST))
252 			arp_found(astate, &arm);
253 	}
254 }
255 
256 static void
257 arp_close(struct interface *ifp)
258 {
259 	struct iarp_state *state;
260 
261 	if ((state = ARP_STATE(ifp)) == NULL || state->bpf_fd == -1)
262 		return;
263 
264 	eloop_event_delete(ifp->ctx->eloop, state->bpf_fd);
265 	bpf_close(ifp, state->bpf_fd);
266 	state->bpf_fd = -1;
267 	state->bpf_flags |= BPF_EOF;
268 }
269 
270 static void
271 arp_tryfree(struct interface *ifp)
272 {
273 	struct iarp_state *state = ARP_STATE(ifp);
274 
275 	/* If there are no more ARP states, close the socket. */
276 	if (TAILQ_FIRST(&state->arp_states) == NULL) {
277 		arp_close(ifp);
278 		if (state->bpf_flags & BPF_READING)
279 			state->bpf_flags |= BPF_EOF;
280 		else {
281 			free(state);
282 			ifp->if_data[IF_DATA_ARP] = NULL;
283 		}
284 	} else {
285 		if (bpf_arp(ifp, state->bpf_fd) == -1)
286 			logerr(__func__);
287 	}
288 }
289 
290 static void
291 arp_read(void *arg)
292 {
293 	struct interface *ifp = arg;
294 	struct iarp_state *state;
295 	uint8_t buf[ARP_LEN];
296 	ssize_t bytes;
297 
298 	/* Some RAW mechanisms are generic file descriptors, not sockets.
299 	 * This means we have no kernel call to just get one packet,
300 	 * so we have to process the entire buffer. */
301 	state = ARP_STATE(ifp);
302 	state->bpf_flags &= ~BPF_EOF;
303 	state->bpf_flags |= BPF_READING;
304 	while (!(state->bpf_flags & BPF_EOF)) {
305 		bytes = bpf_read(ifp, state->bpf_fd, buf, sizeof(buf),
306 				 &state->bpf_flags);
307 		if (bytes == -1) {
308 			logerr("%s: %s", __func__, ifp->name);
309 			arp_close(ifp);
310 			break;
311 		}
312 		arp_packet(ifp, buf, (size_t)bytes);
313 		/* Check we still have a state after processing. */
314 		if ((state = ARP_STATE(ifp)) == NULL)
315 			break;
316 	}
317 	if (state != NULL) {
318 		state->bpf_flags &= ~BPF_READING;
319 		/* Try and free the state if nothing left to do. */
320 		arp_tryfree(ifp);
321 	}
322 }
323 
324 static int
325 arp_open(struct interface *ifp)
326 {
327 	struct iarp_state *state;
328 
329 	state = ARP_STATE(ifp);
330 	if (state->bpf_fd == -1) {
331 		state->bpf_fd = bpf_open(ifp, bpf_arp);
332 		if (state->bpf_fd == -1) {
333 			logerr("%s: %s", __func__, ifp->name);
334 			return -1;
335 		}
336 		eloop_event_add(ifp->ctx->eloop, state->bpf_fd, arp_read, ifp);
337 	}
338 	return state->bpf_fd;
339 }
340 
341 static void
342 arp_probed(void *arg)
343 {
344 	struct arp_state *astate = arg;
345 
346 	timespecclear(&astate->defend);
347 	astate->not_found_cb(astate);
348 }
349 
350 static void
351 arp_probe1(void *arg)
352 {
353 	struct arp_state *astate = arg;
354 	struct interface *ifp = astate->iface;
355 	struct timespec tv;
356 
357 	if (++astate->probes < PROBE_NUM) {
358 		tv.tv_sec = PROBE_MIN;
359 		tv.tv_nsec = (suseconds_t)arc4random_uniform(
360 		    (PROBE_MAX - PROBE_MIN) * NSEC_PER_SEC);
361 		timespecnorm(&tv);
362 		eloop_timeout_add_tv(ifp->ctx->eloop, &tv, arp_probe1, astate);
363 	} else {
364 		tv.tv_sec = ANNOUNCE_WAIT;
365 		tv.tv_nsec = 0;
366 		eloop_timeout_add_tv(ifp->ctx->eloop, &tv, arp_probed, astate);
367 	}
368 	logdebugx("%s: ARP probing %s (%d of %d), next in %0.1f seconds",
369 	    ifp->name, inet_ntoa(astate->addr),
370 	    astate->probes ? astate->probes : PROBE_NUM, PROBE_NUM,
371 	    timespec_to_double(&tv));
372 	if (arp_request(ifp, NULL, &astate->addr) == -1)
373 		logerr(__func__);
374 }
375 
376 void
377 arp_probe(struct arp_state *astate)
378 {
379 
380 	if (arp_open(astate->iface) == -1) {
381 		logerr(__func__);
382 		return;
383 	} else {
384 		const struct iarp_state *state = ARP_CSTATE(astate->iface);
385 
386 		if (bpf_arp(astate->iface, state->bpf_fd) == -1)
387 			logerr(__func__);
388 	}
389 	astate->probes = 0;
390 	logdebugx("%s: probing for %s",
391 	    astate->iface->name, inet_ntoa(astate->addr));
392 	arp_probe1(astate);
393 }
394 #endif	/* ARP */
395 
396 static struct arp_state *
397 arp_find(struct interface *ifp, const struct in_addr *addr)
398 {
399 	struct iarp_state *state;
400 	struct arp_state *astate;
401 
402 	if ((state = ARP_STATE(ifp)) == NULL)
403 		goto out;
404 	TAILQ_FOREACH(astate, &state->arp_states, next) {
405 		if (astate->addr.s_addr == addr->s_addr && astate->iface == ifp)
406 			return astate;
407 	}
408 out:
409 	errno = ESRCH;
410 	return NULL;
411 }
412 
413 static void
414 arp_announced(void *arg)
415 {
416 	struct arp_state *astate = arg;
417 
418 	if (astate->announced_cb) {
419 		astate->announced_cb(astate);
420 		return;
421 	}
422 
423 	/* Keep the ARP state open to handle ongoing ACD. */
424 }
425 
426 static void
427 arp_announce1(void *arg)
428 {
429 	struct arp_state *astate = arg;
430 	struct interface *ifp = astate->iface;
431 
432 	if (++astate->claims < ANNOUNCE_NUM)
433 		logdebugx("%s: ARP announcing %s (%d of %d), "
434 		    "next in %d.0 seconds",
435 		    ifp->name, inet_ntoa(astate->addr),
436 		    astate->claims, ANNOUNCE_NUM, ANNOUNCE_WAIT);
437 	else
438 		logdebugx("%s: ARP announcing %s (%d of %d)",
439 		    ifp->name, inet_ntoa(astate->addr),
440 		    astate->claims, ANNOUNCE_NUM);
441 	if (arp_request(ifp, &astate->addr, &astate->addr) == -1)
442 		logerr(__func__);
443 	eloop_timeout_add_sec(ifp->ctx->eloop, ANNOUNCE_WAIT,
444 	    astate->claims < ANNOUNCE_NUM ? arp_announce1 : arp_announced,
445 	    astate);
446 }
447 
448 /*
449  * XXX FIXME
450  * Kernels supporting RFC5227 will announce the address when it's
451  * added.
452  * dhcpcd should not announce when this happens, nor need to open
453  * a BPF socket for it.
454  * Also, an address might be added to a non preferred inteface when
455  * the same address exists on a preferred one so we need to instruct
456  * the kernel not to announce the address somehow.
457  */
458 
459 void
460 arp_announce(struct arp_state *astate)
461 {
462 	struct iarp_state *state;
463 	struct interface *ifp;
464 	struct arp_state *a2;
465 	int r;
466 
467 	if (arp_open(astate->iface) == -1) {
468 		logerr(__func__);
469 		return;
470 	}
471 
472 	/* Cancel any other ARP announcements for this address. */
473 	TAILQ_FOREACH(ifp, astate->iface->ctx->ifaces, next) {
474 		state = ARP_STATE(ifp);
475 		if (state == NULL)
476 			continue;
477 		TAILQ_FOREACH(a2, &state->arp_states, next) {
478 			if (astate == a2 ||
479 			    a2->addr.s_addr != astate->addr.s_addr)
480 				continue;
481 			r = eloop_timeout_delete(a2->iface->ctx->eloop,
482 			    a2->claims < ANNOUNCE_NUM
483 			    ? arp_announce1 : arp_announced,
484 			    a2);
485 			if (r == -1)
486 				logerr(__func__);
487 			else if (r != 0)
488 				logdebugx("%s: ARP announcement "
489 				    "of %s cancelled",
490 				    a2->iface->name,
491 				    inet_ntoa(a2->addr));
492 		}
493 	}
494 
495 	astate->claims = 0;
496 	arp_announce1(astate);
497 }
498 
499 void
500 arp_ifannounceaddr(struct interface *ifp, const struct in_addr *ia)
501 {
502 	struct arp_state *astate;
503 
504 	astate = arp_find(ifp, ia);
505 	if (astate == NULL) {
506 		astate = arp_new(ifp, ia);
507 		if (astate == NULL)
508 			return;
509 		astate->announced_cb = arp_free;
510 	}
511 	arp_announce(astate);
512 }
513 
514 void
515 arp_announceaddr(struct dhcpcd_ctx *ctx, const struct in_addr *ia)
516 {
517 	struct interface *ifp, *iff = NULL;
518 	struct ipv4_addr *iap;
519 
520 	TAILQ_FOREACH(ifp, ctx->ifaces, next) {
521 		if (!ifp->active || ifp->carrier <= LINK_DOWN)
522 			continue;
523 		iap = ipv4_iffindaddr(ifp, ia, NULL);
524 		if (iap == NULL)
525 			continue;
526 #ifdef IN_IFF_NOTUSEABLE
527 		if (!(iap->addr_flags & IN_IFF_NOTUSEABLE))
528 			continue;
529 #endif
530 		if (iff != NULL && iff->metric < ifp->metric)
531 			continue;
532 		iff = ifp;
533 	}
534 	if (iff == NULL)
535 		return;
536 
537 	arp_ifannounceaddr(iff, ia);
538 }
539 
540 struct arp_state *
541 arp_new(struct interface *ifp, const struct in_addr *addr)
542 {
543 	struct iarp_state *state;
544 	struct arp_state *astate;
545 
546 	if ((state = ARP_STATE(ifp)) == NULL) {
547 	        ifp->if_data[IF_DATA_ARP] = malloc(sizeof(*state));
548 		state = ARP_STATE(ifp);
549 		if (state == NULL) {
550 			logerr(__func__);
551 			return NULL;
552 		}
553 		state->bpf_fd = -1;
554 		state->bpf_flags = 0;
555 		TAILQ_INIT(&state->arp_states);
556 	} else {
557 		if (addr && (astate = arp_find(ifp, addr)))
558 			return astate;
559 	}
560 
561 	if ((astate = calloc(1, sizeof(*astate))) == NULL) {
562 		logerr(__func__);
563 		return NULL;
564 	}
565 	astate->iface = ifp;
566 	if (addr)
567 		astate->addr = *addr;
568 	state = ARP_STATE(ifp);
569 	TAILQ_INSERT_TAIL(&state->arp_states, astate, next);
570 
571 	if (bpf_arp(ifp, state->bpf_fd) == -1)
572 		logerr(__func__); /* try and continue */
573 
574 	return astate;
575 }
576 
577 void
578 arp_cancel(struct arp_state *astate)
579 {
580 
581 	eloop_timeout_delete(astate->iface->ctx->eloop, NULL, astate);
582 }
583 
584 void
585 arp_free(struct arp_state *astate)
586 {
587 	struct interface *ifp;
588 	struct iarp_state *state;
589 
590 	if (astate == NULL)
591 		return;
592 
593 	ifp = astate->iface;
594 	eloop_timeout_delete(ifp->ctx->eloop, NULL, astate);
595 	state =	ARP_STATE(ifp);
596 	TAILQ_REMOVE(&state->arp_states, astate, next);
597 	if (astate->free_cb)
598 		astate->free_cb(astate);
599 	free(astate);
600 	arp_tryfree(ifp);
601 }
602 
603 void
604 arp_freeaddr(struct interface *ifp, const struct in_addr *ia)
605 {
606 	struct arp_state *astate;
607 
608 	astate = arp_find(ifp, ia);
609 	arp_free(astate);
610 }
611 
612 void
613 arp_drop(struct interface *ifp)
614 {
615 	struct iarp_state *state;
616 	struct arp_state *astate;
617 
618 	while ((state = ARP_STATE(ifp)) != NULL &&
619 	    (astate = TAILQ_FIRST(&state->arp_states)) != NULL)
620 		arp_free(astate);
621 
622 	/* No need to close because the last free will close */
623 }
624