xref: /freebsd/sys/netinet/in.c (revision 8881d206f4e68b564c2c5f50fc717086fc3e827a)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1982, 1986, 1991, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  * Copyright (C) 2001 WIDE Project.  All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  *	@(#)in.c	8.4 (Berkeley) 1/9/95
33  */
34 
35 #include <sys/cdefs.h>
36 __FBSDID("$FreeBSD$");
37 
38 #include "opt_inet.h"
39 
40 #define IN_HISTORICAL_NETS		/* include class masks */
41 
42 #include <sys/param.h>
43 #include <sys/eventhandler.h>
44 #include <sys/systm.h>
45 #include <sys/sockio.h>
46 #include <sys/malloc.h>
47 #include <sys/priv.h>
48 #include <sys/socket.h>
49 #include <sys/jail.h>
50 #include <sys/kernel.h>
51 #include <sys/lock.h>
52 #include <sys/proc.h>
53 #include <sys/sysctl.h>
54 #include <sys/syslog.h>
55 #include <sys/sx.h>
56 
57 #include <net/if.h>
58 #include <net/if_var.h>
59 #include <net/if_arp.h>
60 #include <net/if_dl.h>
61 #include <net/if_llatbl.h>
62 #include <net/if_types.h>
63 #include <net/route.h>
64 #include <net/route/nhop.h>
65 #include <net/route/route_ctl.h>
66 #include <net/vnet.h>
67 
68 #include <netinet/if_ether.h>
69 #include <netinet/in.h>
70 #include <netinet/in_fib.h>
71 #include <netinet/in_var.h>
72 #include <netinet/in_pcb.h>
73 #include <netinet/ip_var.h>
74 #include <netinet/ip_carp.h>
75 #include <netinet/igmp_var.h>
76 #include <netinet/udp.h>
77 #include <netinet/udp_var.h>
78 
79 static int in_aifaddr_ioctl(u_long, caddr_t, struct ifnet *, struct thread *);
80 static int in_difaddr_ioctl(u_long, caddr_t, struct ifnet *, struct thread *);
81 static int in_gifaddr_ioctl(u_long, caddr_t, struct ifnet *, struct thread *);
82 
83 static void	in_socktrim(struct sockaddr_in *);
84 static void	in_purgemaddrs(struct ifnet *);
85 
86 static bool	ia_need_loopback_route(const struct in_ifaddr *);
87 
88 VNET_DEFINE_STATIC(int, nosameprefix);
89 #define	V_nosameprefix			VNET(nosameprefix)
90 SYSCTL_INT(_net_inet_ip, OID_AUTO, no_same_prefix, CTLFLAG_VNET | CTLFLAG_RW,
91 	&VNET_NAME(nosameprefix), 0,
92 	"Refuse to create same prefixes on different interfaces");
93 
94 VNET_DEFINE_STATIC(bool, broadcast_lowest);
95 #define	V_broadcast_lowest		VNET(broadcast_lowest)
96 SYSCTL_BOOL(_net_inet_ip, OID_AUTO, broadcast_lowest, CTLFLAG_VNET | CTLFLAG_RW,
97 	&VNET_NAME(broadcast_lowest), 0,
98 	"Treat lowest address on a subnet (host 0) as broadcast");
99 
100 VNET_DECLARE(struct inpcbinfo, ripcbinfo);
101 #define	V_ripcbinfo			VNET(ripcbinfo)
102 
103 static struct sx in_control_sx;
104 SX_SYSINIT(in_control_sx, &in_control_sx, "in_control");
105 
106 /*
107  * Return 1 if an internet address is for a ``local'' host
108  * (one to which we have a connection).
109  */
110 int
111 in_localaddr(struct in_addr in)
112 {
113 	u_long i = ntohl(in.s_addr);
114 	struct in_ifaddr *ia;
115 
116 	NET_EPOCH_ASSERT();
117 
118 	CK_STAILQ_FOREACH(ia, &V_in_ifaddrhead, ia_link) {
119 		if ((i & ia->ia_subnetmask) == ia->ia_subnet)
120 			return (1);
121 	}
122 
123 	return (0);
124 }
125 
126 /*
127  * Return 1 if an internet address is for the local host and configured
128  * on one of its interfaces.
129  */
130 bool
131 in_localip(struct in_addr in)
132 {
133 	struct in_ifaddr *ia;
134 
135 	NET_EPOCH_ASSERT();
136 
137 	CK_LIST_FOREACH(ia, INADDR_HASH(in.s_addr), ia_hash)
138 		if (IA_SIN(ia)->sin_addr.s_addr == in.s_addr)
139 			return (true);
140 
141 	return (false);
142 }
143 
144 /*
145  * Like in_localip(), but FIB-aware.
146  */
147 bool
148 in_localip_fib(struct in_addr in, uint16_t fib)
149 {
150 	struct in_ifaddr *ia;
151 
152 	NET_EPOCH_ASSERT();
153 
154 	CK_LIST_FOREACH(ia, INADDR_HASH(in.s_addr), ia_hash)
155 		if (IA_SIN(ia)->sin_addr.s_addr == in.s_addr &&
156 		    ia->ia_ifa.ifa_ifp->if_fib == fib)
157 			return (true);
158 
159 	return (false);
160 }
161 
162 /*
163  * Return 1 if an internet address is configured on an interface.
164  */
165 int
166 in_ifhasaddr(struct ifnet *ifp, struct in_addr in)
167 {
168 	struct ifaddr *ifa;
169 	struct in_ifaddr *ia;
170 
171 	NET_EPOCH_ASSERT();
172 
173 	CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
174 		if (ifa->ifa_addr->sa_family != AF_INET)
175 			continue;
176 		ia = (struct in_ifaddr *)ifa;
177 		if (ia->ia_addr.sin_addr.s_addr == in.s_addr)
178 			return (1);
179 	}
180 
181 	return (0);
182 }
183 
184 /*
185  * Return a reference to the interface address which is different to
186  * the supplied one but with same IP address value.
187  */
188 static struct in_ifaddr *
189 in_localip_more(struct in_ifaddr *original_ia)
190 {
191 	struct epoch_tracker et;
192 	in_addr_t original_addr = IA_SIN(original_ia)->sin_addr.s_addr;
193 	uint32_t original_fib = original_ia->ia_ifa.ifa_ifp->if_fib;
194 	struct in_ifaddr *ia;
195 
196 	NET_EPOCH_ENTER(et);
197 	CK_LIST_FOREACH(ia, INADDR_HASH(original_addr), ia_hash) {
198 		in_addr_t addr = IA_SIN(ia)->sin_addr.s_addr;
199 		uint32_t fib = ia->ia_ifa.ifa_ifp->if_fib;
200 		if (!V_rt_add_addr_allfibs && (original_fib != fib))
201 			continue;
202 		if ((original_ia != ia) && (original_addr == addr)) {
203 			ifa_ref(&ia->ia_ifa);
204 			NET_EPOCH_EXIT(et);
205 			return (ia);
206 		}
207 	}
208 	NET_EPOCH_EXIT(et);
209 
210 	return (NULL);
211 }
212 
213 /*
214  * Tries to find first IPv4 address in the provided fib.
215  * Prefers non-loopback addresses and return loopback IFF
216  * @loopback_ok is set.
217  *
218  * Returns ifa or NULL.
219  */
220 struct in_ifaddr *
221 in_findlocal(uint32_t fibnum, bool loopback_ok)
222 {
223 	struct in_ifaddr *ia = NULL, *ia_lo = NULL;
224 
225 	NET_EPOCH_ASSERT();
226 
227 	CK_STAILQ_FOREACH(ia, &V_in_ifaddrhead, ia_link) {
228 		uint32_t ia_fib = ia->ia_ifa.ifa_ifp->if_fib;
229 		if (!V_rt_add_addr_allfibs && (fibnum != ia_fib))
230 			continue;
231 
232 		if (!IN_LOOPBACK(ntohl(IA_SIN(ia)->sin_addr.s_addr)))
233 			break;
234 		if (loopback_ok)
235 			ia_lo = ia;
236 	}
237 
238 	if (ia == NULL)
239 		ia = ia_lo;
240 
241 	return (ia);
242 }
243 
244 /*
245  * Determine whether an IP address is in a reserved set of addresses
246  * that may not be forwarded, or whether datagrams to that destination
247  * may be forwarded.
248  */
249 int
250 in_canforward(struct in_addr in)
251 {
252 	u_long i = ntohl(in.s_addr);
253 
254 	if (IN_EXPERIMENTAL(i) || IN_MULTICAST(i) || IN_LINKLOCAL(i) ||
255 	    IN_ZERONET(i) || IN_LOOPBACK(i))
256 		return (0);
257 	return (1);
258 }
259 
260 /*
261  * Trim a mask in a sockaddr
262  */
263 static void
264 in_socktrim(struct sockaddr_in *ap)
265 {
266     char *cplim = (char *) &ap->sin_addr;
267     char *cp = (char *) (&ap->sin_addr + 1);
268 
269     ap->sin_len = 0;
270     while (--cp >= cplim)
271 	if (*cp) {
272 	    (ap)->sin_len = cp - (char *) (ap) + 1;
273 	    break;
274 	}
275 }
276 
277 /*
278  * Generic internet control operations (ioctl's).
279  */
280 int
281 in_control(struct socket *so, u_long cmd, caddr_t data, struct ifnet *ifp,
282     struct thread *td)
283 {
284 	struct ifreq *ifr = (struct ifreq *)data;
285 	struct sockaddr_in *addr = (struct sockaddr_in *)&ifr->ifr_addr;
286 	struct epoch_tracker et;
287 	struct ifaddr *ifa;
288 	struct in_ifaddr *ia;
289 	int error;
290 
291 	if (ifp == NULL)
292 		return (EADDRNOTAVAIL);
293 
294 	/*
295 	 * Filter out 4 ioctls we implement directly.  Forward the rest
296 	 * to specific functions and ifp->if_ioctl().
297 	 */
298 	switch (cmd) {
299 	case SIOCGIFADDR:
300 	case SIOCGIFBRDADDR:
301 	case SIOCGIFDSTADDR:
302 	case SIOCGIFNETMASK:
303 		break;
304 	case SIOCGIFALIAS:
305 		sx_xlock(&in_control_sx);
306 		error = in_gifaddr_ioctl(cmd, data, ifp, td);
307 		sx_xunlock(&in_control_sx);
308 		return (error);
309 	case SIOCDIFADDR:
310 		sx_xlock(&in_control_sx);
311 		error = in_difaddr_ioctl(cmd, data, ifp, td);
312 		sx_xunlock(&in_control_sx);
313 		return (error);
314 	case OSIOCAIFADDR:	/* 9.x compat */
315 	case SIOCAIFADDR:
316 		sx_xlock(&in_control_sx);
317 		error = in_aifaddr_ioctl(cmd, data, ifp, td);
318 		sx_xunlock(&in_control_sx);
319 		return (error);
320 	case SIOCSIFADDR:
321 	case SIOCSIFBRDADDR:
322 	case SIOCSIFDSTADDR:
323 	case SIOCSIFNETMASK:
324 		/* We no longer support that old commands. */
325 		return (EINVAL);
326 	default:
327 		if (ifp->if_ioctl == NULL)
328 			return (EOPNOTSUPP);
329 		return ((*ifp->if_ioctl)(ifp, cmd, data));
330 	}
331 
332 	if (addr->sin_addr.s_addr != INADDR_ANY &&
333 	    prison_check_ip4(td->td_ucred, &addr->sin_addr) != 0)
334 		return (EADDRNOTAVAIL);
335 
336 	/*
337 	 * Find address for this interface, if it exists.  If an
338 	 * address was specified, find that one instead of the
339 	 * first one on the interface, if possible.
340 	 */
341 	NET_EPOCH_ENTER(et);
342 	CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
343 		if (ifa->ifa_addr->sa_family != AF_INET)
344 			continue;
345 		ia = (struct in_ifaddr *)ifa;
346 		if (ia->ia_addr.sin_addr.s_addr == addr->sin_addr.s_addr)
347 			break;
348 	}
349 	if (ifa == NULL)
350 		CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link)
351 			if (ifa->ifa_addr->sa_family == AF_INET) {
352 				ia = (struct in_ifaddr *)ifa;
353 				if (prison_check_ip4(td->td_ucred,
354 				    &ia->ia_addr.sin_addr) == 0)
355 					break;
356 			}
357 
358 	if (ifa == NULL) {
359 		NET_EPOCH_EXIT(et);
360 		return (EADDRNOTAVAIL);
361 	}
362 
363 	error = 0;
364 	switch (cmd) {
365 	case SIOCGIFADDR:
366 		*addr = ia->ia_addr;
367 		break;
368 
369 	case SIOCGIFBRDADDR:
370 		if ((ifp->if_flags & IFF_BROADCAST) == 0) {
371 			error = EINVAL;
372 			break;
373 		}
374 		*addr = ia->ia_broadaddr;
375 		break;
376 
377 	case SIOCGIFDSTADDR:
378 		if ((ifp->if_flags & IFF_POINTOPOINT) == 0) {
379 			error = EINVAL;
380 			break;
381 		}
382 		*addr = ia->ia_dstaddr;
383 		break;
384 
385 	case SIOCGIFNETMASK:
386 		*addr = ia->ia_sockmask;
387 		break;
388 	}
389 
390 	NET_EPOCH_EXIT(et);
391 
392 	return (error);
393 }
394 
395 static int
396 in_aifaddr_ioctl(u_long cmd, caddr_t data, struct ifnet *ifp, struct thread *td)
397 {
398 	const struct in_aliasreq *ifra = (struct in_aliasreq *)data;
399 	const struct sockaddr_in *addr = &ifra->ifra_addr;
400 	const struct sockaddr_in *broadaddr = &ifra->ifra_broadaddr;
401 	const struct sockaddr_in *mask = &ifra->ifra_mask;
402 	const struct sockaddr_in *dstaddr = &ifra->ifra_dstaddr;
403 	const int vhid = (cmd == SIOCAIFADDR) ? ifra->ifra_vhid : 0;
404 	struct epoch_tracker et;
405 	struct ifaddr *ifa;
406 	struct in_ifaddr *ia;
407 	bool iaIsFirst;
408 	int error = 0;
409 
410 	error = priv_check(td, PRIV_NET_ADDIFADDR);
411 	if (error)
412 		return (error);
413 
414 	/*
415 	 * ifra_addr must be present and be of INET family.
416 	 * ifra_broadaddr/ifra_dstaddr and ifra_mask are optional.
417 	 */
418 	if (addr->sin_len != sizeof(struct sockaddr_in) ||
419 	    addr->sin_family != AF_INET)
420 		return (EINVAL);
421 	if (broadaddr->sin_len != 0 &&
422 	    (broadaddr->sin_len != sizeof(struct sockaddr_in) ||
423 	    broadaddr->sin_family != AF_INET))
424 		return (EINVAL);
425 	if (mask->sin_len != 0 &&
426 	    (mask->sin_len != sizeof(struct sockaddr_in) ||
427 	    mask->sin_family != AF_INET))
428 		return (EINVAL);
429 	if ((ifp->if_flags & IFF_POINTOPOINT) &&
430 	    (dstaddr->sin_len != sizeof(struct sockaddr_in) ||
431 	     dstaddr->sin_addr.s_addr == INADDR_ANY))
432 		return (EDESTADDRREQ);
433 	if (vhid != 0 && carp_attach_p == NULL)
434 		return (EPROTONOSUPPORT);
435 
436 	/*
437 	 * See whether address already exist.
438 	 */
439 	iaIsFirst = true;
440 	ia = NULL;
441 	NET_EPOCH_ENTER(et);
442 	CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
443 		struct in_ifaddr *it;
444 
445 		if (ifa->ifa_addr->sa_family != AF_INET)
446 			continue;
447 
448 		it = (struct in_ifaddr *)ifa;
449 		if (it->ia_addr.sin_addr.s_addr == addr->sin_addr.s_addr &&
450 		    prison_check_ip4(td->td_ucred, &addr->sin_addr) == 0)
451 			ia = it;
452 		else
453 			iaIsFirst = false;
454 	}
455 	NET_EPOCH_EXIT(et);
456 
457 	if (ia != NULL)
458 		(void )in_difaddr_ioctl(cmd, data, ifp, td);
459 
460 	ifa = ifa_alloc(sizeof(struct in_ifaddr), M_WAITOK);
461 	ia = (struct in_ifaddr *)ifa;
462 	ifa->ifa_addr = (struct sockaddr *)&ia->ia_addr;
463 	ifa->ifa_dstaddr = (struct sockaddr *)&ia->ia_dstaddr;
464 	ifa->ifa_netmask = (struct sockaddr *)&ia->ia_sockmask;
465 	callout_init_rw(&ia->ia_garp_timer, &ifp->if_addr_lock,
466 	    CALLOUT_RETURNUNLOCKED);
467 
468 	ia->ia_ifp = ifp;
469 	ia->ia_addr = *addr;
470 	if (mask->sin_len != 0) {
471 		ia->ia_sockmask = *mask;
472 		ia->ia_subnetmask = ntohl(ia->ia_sockmask.sin_addr.s_addr);
473 	} else {
474 		in_addr_t i = ntohl(addr->sin_addr.s_addr);
475 
476 		/*
477 	 	 * If netmask isn't supplied, use historical default.
478 		 * This is deprecated for interfaces other than loopback
479 		 * or point-to-point; warn in other cases.  In the future
480 		 * we should return an error rather than warning.
481 	 	 */
482 		if ((ifp->if_flags & (IFF_POINTOPOINT | IFF_LOOPBACK)) == 0)
483 			printf("%s: set address: WARNING: network mask "
484 			     "should be specified; using historical default\n",
485 			     ifp->if_xname);
486 		if (IN_CLASSA(i))
487 			ia->ia_subnetmask = IN_CLASSA_NET;
488 		else if (IN_CLASSB(i))
489 			ia->ia_subnetmask = IN_CLASSB_NET;
490 		else
491 			ia->ia_subnetmask = IN_CLASSC_NET;
492 		ia->ia_sockmask.sin_addr.s_addr = htonl(ia->ia_subnetmask);
493 	}
494 	ia->ia_subnet = ntohl(addr->sin_addr.s_addr) & ia->ia_subnetmask;
495 	in_socktrim(&ia->ia_sockmask);
496 
497 	if (ifp->if_flags & IFF_BROADCAST) {
498 		if (broadaddr->sin_len != 0) {
499 			ia->ia_broadaddr = *broadaddr;
500 		} else if (ia->ia_subnetmask == IN_RFC3021_MASK) {
501 			ia->ia_broadaddr.sin_addr.s_addr = INADDR_BROADCAST;
502 			ia->ia_broadaddr.sin_len = sizeof(struct sockaddr_in);
503 			ia->ia_broadaddr.sin_family = AF_INET;
504 		} else {
505 			ia->ia_broadaddr.sin_addr.s_addr =
506 			    htonl(ia->ia_subnet | ~ia->ia_subnetmask);
507 			ia->ia_broadaddr.sin_len = sizeof(struct sockaddr_in);
508 			ia->ia_broadaddr.sin_family = AF_INET;
509 		}
510 	}
511 
512 	if (ifp->if_flags & IFF_POINTOPOINT)
513 		ia->ia_dstaddr = *dstaddr;
514 
515 	if (vhid != 0) {
516 		error = (*carp_attach_p)(&ia->ia_ifa, vhid);
517 		if (error)
518 			return (error);
519 	}
520 
521 	/* if_addrhead is already referenced by ifa_alloc() */
522 	IF_ADDR_WLOCK(ifp);
523 	CK_STAILQ_INSERT_TAIL(&ifp->if_addrhead, ifa, ifa_link);
524 	IF_ADDR_WUNLOCK(ifp);
525 
526 	ifa_ref(ifa);			/* in_ifaddrhead */
527 	sx_assert(&in_control_sx, SA_XLOCKED);
528 	CK_STAILQ_INSERT_TAIL(&V_in_ifaddrhead, ia, ia_link);
529 	CK_LIST_INSERT_HEAD(INADDR_HASH(ia->ia_addr.sin_addr.s_addr), ia,
530 	    ia_hash);
531 
532 	/*
533 	 * Give the interface a chance to initialize
534 	 * if this is its first address,
535 	 * and to validate the address if necessary.
536 	 */
537 	if (ifp->if_ioctl != NULL) {
538 		error = (*ifp->if_ioctl)(ifp, SIOCSIFADDR, (caddr_t)ia);
539 		if (error)
540 			goto fail1;
541 	}
542 
543 	/*
544 	 * Add route for the network.
545 	 */
546 	if (vhid == 0) {
547 		error = in_addprefix(ia);
548 		if (error)
549 			goto fail1;
550 	}
551 
552 	/*
553 	 * Add a loopback route to self.
554 	 */
555 	if (vhid == 0 && ia_need_loopback_route(ia)) {
556 		struct in_ifaddr *eia;
557 
558 		eia = in_localip_more(ia);
559 
560 		if (eia == NULL) {
561 			error = ifa_add_loopback_route((struct ifaddr *)ia,
562 			    (struct sockaddr *)&ia->ia_addr);
563 			if (error)
564 				goto fail2;
565 		} else
566 			ifa_free(&eia->ia_ifa);
567 	}
568 
569 	if (iaIsFirst && (ifp->if_flags & IFF_MULTICAST)) {
570 		struct in_addr allhosts_addr;
571 		struct in_ifinfo *ii;
572 
573 		ii = ((struct in_ifinfo *)ifp->if_afdata[AF_INET]);
574 		allhosts_addr.s_addr = htonl(INADDR_ALLHOSTS_GROUP);
575 
576 		error = in_joingroup(ifp, &allhosts_addr, NULL,
577 			&ii->ii_allhosts);
578 	}
579 
580 	/*
581 	 * Note: we don't need extra reference for ifa, since we called
582 	 * with sx lock held, and ifaddr can not be deleted in concurrent
583 	 * thread.
584 	 */
585 	EVENTHANDLER_INVOKE(ifaddr_event_ext, ifp, ifa, IFADDR_EVENT_ADD);
586 
587 	return (error);
588 
589 fail2:
590 	if (vhid == 0)
591 		(void )in_scrubprefix(ia, LLE_STATIC);
592 
593 fail1:
594 	if (ia->ia_ifa.ifa_carp)
595 		(*carp_detach_p)(&ia->ia_ifa, false);
596 
597 	IF_ADDR_WLOCK(ifp);
598 	CK_STAILQ_REMOVE(&ifp->if_addrhead, &ia->ia_ifa, ifaddr, ifa_link);
599 	IF_ADDR_WUNLOCK(ifp);
600 	ifa_free(&ia->ia_ifa);		/* if_addrhead */
601 
602 	sx_assert(&in_control_sx, SA_XLOCKED);
603 	CK_STAILQ_REMOVE(&V_in_ifaddrhead, ia, in_ifaddr, ia_link);
604 	CK_LIST_REMOVE(ia, ia_hash);
605 	ifa_free(&ia->ia_ifa);		/* in_ifaddrhead */
606 
607 	return (error);
608 }
609 
610 static int
611 in_difaddr_ioctl(u_long cmd, caddr_t data, struct ifnet *ifp, struct thread *td)
612 {
613 	const struct ifreq *ifr = (struct ifreq *)data;
614 	const struct sockaddr_in *addr = (const struct sockaddr_in *)
615 	    &ifr->ifr_addr;
616 	struct ifaddr *ifa;
617 	struct in_ifaddr *ia;
618 	bool deleteAny, iaIsLast;
619 	int error;
620 
621 	if (td != NULL) {
622 		error = priv_check(td, PRIV_NET_DELIFADDR);
623 		if (error)
624 			return (error);
625 	}
626 
627 	if (addr->sin_len != sizeof(struct sockaddr_in) ||
628 	    addr->sin_family != AF_INET)
629 		deleteAny = true;
630 	else
631 		deleteAny = false;
632 
633 	iaIsLast = true;
634 	ia = NULL;
635 	IF_ADDR_WLOCK(ifp);
636 	CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
637 		struct in_ifaddr *it;
638 
639 		if (ifa->ifa_addr->sa_family != AF_INET)
640 			continue;
641 
642 		it = (struct in_ifaddr *)ifa;
643 		if (deleteAny && ia == NULL && (td == NULL ||
644 		    prison_check_ip4(td->td_ucred, &it->ia_addr.sin_addr) == 0))
645 			ia = it;
646 
647 		if (it->ia_addr.sin_addr.s_addr == addr->sin_addr.s_addr &&
648 		    (td == NULL || prison_check_ip4(td->td_ucred,
649 		    &addr->sin_addr) == 0))
650 			ia = it;
651 
652 		if (it != ia)
653 			iaIsLast = false;
654 	}
655 
656 	if (ia == NULL) {
657 		IF_ADDR_WUNLOCK(ifp);
658 		return (EADDRNOTAVAIL);
659 	}
660 
661 	CK_STAILQ_REMOVE(&ifp->if_addrhead, &ia->ia_ifa, ifaddr, ifa_link);
662 	IF_ADDR_WUNLOCK(ifp);
663 	ifa_free(&ia->ia_ifa);		/* if_addrhead */
664 
665 	sx_assert(&in_control_sx, SA_XLOCKED);
666 	CK_STAILQ_REMOVE(&V_in_ifaddrhead, ia, in_ifaddr, ia_link);
667 	CK_LIST_REMOVE(ia, ia_hash);
668 
669 	/*
670 	 * in_scrubprefix() kills the interface route.
671 	 */
672 	in_scrubprefix(ia, LLE_STATIC);
673 
674 	/*
675 	 * in_ifadown gets rid of all the rest of
676 	 * the routes.  This is not quite the right
677 	 * thing to do, but at least if we are running
678 	 * a routing process they will come back.
679 	 */
680 	in_ifadown(&ia->ia_ifa, 1);
681 
682 	if (ia->ia_ifa.ifa_carp)
683 		(*carp_detach_p)(&ia->ia_ifa, cmd == SIOCAIFADDR);
684 
685 	/*
686 	 * If this is the last IPv4 address configured on this
687 	 * interface, leave the all-hosts group.
688 	 * No state-change report need be transmitted.
689 	 */
690 	if (iaIsLast && (ifp->if_flags & IFF_MULTICAST)) {
691 		struct in_ifinfo *ii;
692 
693 		ii = ((struct in_ifinfo *)ifp->if_afdata[AF_INET]);
694 		if (ii->ii_allhosts) {
695 			(void)in_leavegroup(ii->ii_allhosts, NULL);
696 			ii->ii_allhosts = NULL;
697 		}
698 	}
699 
700 	IF_ADDR_WLOCK(ifp);
701 	if (callout_stop(&ia->ia_garp_timer) == 1) {
702 		ifa_free(&ia->ia_ifa);
703 	}
704 	IF_ADDR_WUNLOCK(ifp);
705 
706 	EVENTHANDLER_INVOKE(ifaddr_event_ext, ifp, &ia->ia_ifa,
707 	    IFADDR_EVENT_DEL);
708 	ifa_free(&ia->ia_ifa);		/* in_ifaddrhead */
709 
710 	return (0);
711 }
712 
713 static int
714 in_gifaddr_ioctl(u_long cmd, caddr_t data, struct ifnet *ifp, struct thread *td)
715 {
716 	struct in_aliasreq *ifra = (struct in_aliasreq *)data;
717 	const struct sockaddr_in *addr = &ifra->ifra_addr;
718 	struct epoch_tracker et;
719 	struct ifaddr *ifa;
720 	struct in_ifaddr *ia;
721 
722 	/*
723 	 * ifra_addr must be present and be of INET family.
724 	 */
725 	if (addr->sin_len != sizeof(struct sockaddr_in) ||
726 	    addr->sin_family != AF_INET)
727 		return (EINVAL);
728 
729 	/*
730 	 * See whether address exist.
731 	 */
732 	ia = NULL;
733 	NET_EPOCH_ENTER(et);
734 	CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
735 		struct in_ifaddr *it;
736 
737 		if (ifa->ifa_addr->sa_family != AF_INET)
738 			continue;
739 
740 		it = (struct in_ifaddr *)ifa;
741 		if (it->ia_addr.sin_addr.s_addr == addr->sin_addr.s_addr &&
742 		    prison_check_ip4(td->td_ucred, &addr->sin_addr) == 0) {
743 			ia = it;
744 			break;
745 		}
746 	}
747 	if (ia == NULL) {
748 		NET_EPOCH_EXIT(et);
749 		return (EADDRNOTAVAIL);
750 	}
751 
752 	ifra->ifra_mask = ia->ia_sockmask;
753 	if ((ifp->if_flags & IFF_POINTOPOINT) &&
754 	    ia->ia_dstaddr.sin_family == AF_INET)
755 		ifra->ifra_dstaddr = ia->ia_dstaddr;
756 	else if ((ifp->if_flags & IFF_BROADCAST) &&
757 	    ia->ia_broadaddr.sin_family == AF_INET)
758 		ifra->ifra_broadaddr = ia->ia_broadaddr;
759 	else
760 		memset(&ifra->ifra_broadaddr, 0,
761 		    sizeof(ifra->ifra_broadaddr));
762 
763 	NET_EPOCH_EXIT(et);
764 	return (0);
765 }
766 
767 static int
768 in_match_ifaddr(const struct rtentry *rt, const struct nhop_object *nh, void *arg)
769 {
770 
771 	if (nh->nh_ifa == (struct ifaddr *)arg)
772 		return (1);
773 
774 	return (0);
775 }
776 
777 static int
778 in_handle_prefix_route(uint32_t fibnum, int cmd,
779     struct sockaddr_in *dst, struct sockaddr_in *netmask, struct ifaddr *ifa,
780     struct ifnet *ifp)
781 {
782 
783 	NET_EPOCH_ASSERT();
784 
785 	/* Prepare gateway */
786 	struct sockaddr_dl_short sdl = {
787 		.sdl_family = AF_LINK,
788 		.sdl_len = sizeof(struct sockaddr_dl_short),
789 		.sdl_type = ifa->ifa_ifp->if_type,
790 		.sdl_index = ifa->ifa_ifp->if_index,
791 	};
792 
793 	struct rt_addrinfo info = {
794 		.rti_ifa = ifa,
795 		.rti_ifp = ifp,
796 		.rti_flags = RTF_PINNED | ((netmask != NULL) ? 0 : RTF_HOST),
797 		.rti_info = {
798 			[RTAX_DST] = (struct sockaddr *)dst,
799 			[RTAX_NETMASK] = (struct sockaddr *)netmask,
800 			[RTAX_GATEWAY] = (struct sockaddr *)&sdl,
801 		},
802 		/* Ensure we delete the prefix IFF prefix ifa matches */
803 		.rti_filter = in_match_ifaddr,
804 		.rti_filterdata = ifa,
805 	};
806 
807 	return (rib_handle_ifaddr_info(fibnum, cmd, &info));
808 }
809 
810 /*
811  * Routing table interaction with interface addresses.
812  *
813  * In general, two types of routes needs to be installed:
814  * a) "interface" or "prefix" route, telling user that the addresses
815  *   behind the ifa prefix are reached directly.
816  * b) "loopback" route installed for the ifa address, telling user that
817  *   the address belongs to local system.
818  *
819  * Handling for (a) and (b) differs in multi-fib aspects, hence they
820  *  are implemented in different functions below.
821  *
822  * The cases above may intersect - /32 interface aliases results in
823  *  the same prefix produced by (a) and (b). This blurs the definition
824  *  of the "loopback" route and complicate interactions. The interaction
825  *  table is defined below. The case numbers are used in the multiple
826  *  functions below to refer to the particular test case.
827  *
828  * There can be multiple options:
829  * 1) Adding address with prefix on non-p2p/non-loopback interface.
830  *  Example: 192.0.2.1/24. Action:
831  *  * add "prefix" route towards 192.0.2.0/24 via @ia interface,
832  *    using @ia as an address source.
833  *  * add "loopback" route towards 192.0.2.1 via V_loif, saving
834  *   @ia ifp in the gateway and using @ia as an address source.
835  *
836  * 2) Adding address with /32 mask to non-p2p/non-loopback interface.
837  *  Example: 192.0.2.2/32. Action:
838  *  * add "prefix" host route via V_loif, using @ia as an address source.
839  *
840  * 3) Adding address with or without prefix to p2p interface.
841  *  Example: 10.0.0.1/24->10.0.0.2. Action:
842  *  * add "prefix" host route towards 10.0.0.2 via this interface, using @ia
843  *    as an address source. Note: no sense in installing full /24 as the interface
844  *    is point-to-point.
845  *  * add "loopback" route towards 10.0.9.1 via V_loif, saving
846  *   @ia ifp in the gateway and using @ia as an address source.
847  *
848  * 4) Adding address with or without prefix to loopback interface.
849  *  Example: 192.0.2.1/24. Action:
850  *  * add "prefix" host route via @ia interface, using @ia as an address source.
851  *    Note: Skip installing /24 prefix as it would introduce TTL loop
852  *    for the traffic destined to these addresses.
853  */
854 
855 /*
856  * Checks if @ia needs to install loopback route to @ia address via
857  *  ifa_maintain_loopback_route().
858  *
859  * Return true on success.
860  */
861 static bool
862 ia_need_loopback_route(const struct in_ifaddr *ia)
863 {
864 	struct ifnet *ifp = ia->ia_ifp;
865 
866 	/* Case 4: Skip loopback interfaces */
867 	if ((ifp->if_flags & IFF_LOOPBACK) ||
868 	    (ia->ia_addr.sin_addr.s_addr == INADDR_ANY))
869 		return (false);
870 
871 	/* Clash avoidance: Skip p2p interfaces with both addresses are equal */
872 	if ((ifp->if_flags & IFF_POINTOPOINT) &&
873 	    ia->ia_dstaddr.sin_addr.s_addr == ia->ia_addr.sin_addr.s_addr)
874 		return (false);
875 
876 	/* Case 2: skip /32 prefixes */
877 	if (!(ifp->if_flags & IFF_POINTOPOINT) &&
878 	    (ia->ia_sockmask.sin_addr.s_addr == INADDR_BROADCAST))
879 		return (false);
880 
881 	return (true);
882 }
883 
884 /*
885  * Calculate "prefix" route corresponding to @ia.
886  */
887 static void
888 ia_getrtprefix(const struct in_ifaddr *ia, struct in_addr *prefix, struct in_addr *mask)
889 {
890 
891 	if (ia->ia_ifp->if_flags & IFF_POINTOPOINT) {
892 		/* Case 3: return host route for dstaddr */
893 		*prefix = ia->ia_dstaddr.sin_addr;
894 		mask->s_addr = INADDR_BROADCAST;
895 	} else if (ia->ia_ifp->if_flags & IFF_LOOPBACK) {
896 		/* Case 4: return host route for ifaddr */
897 		*prefix = ia->ia_addr.sin_addr;
898 		mask->s_addr = INADDR_BROADCAST;
899 	} else {
900 		/* Cases 1,2: return actual ia prefix */
901 		*prefix = ia->ia_addr.sin_addr;
902 		*mask = ia->ia_sockmask.sin_addr;
903 		prefix->s_addr &= mask->s_addr;
904 	}
905 }
906 
907 /*
908  * Adds or delete interface "prefix" route corresponding to @ifa.
909  *  Returns 0 on success or errno.
910  */
911 int
912 in_handle_ifaddr_route(int cmd, struct in_ifaddr *ia)
913 {
914 	struct ifaddr *ifa = &ia->ia_ifa;
915 	struct in_addr daddr, maddr;
916 	struct sockaddr_in *pmask;
917 	struct epoch_tracker et;
918 	int error;
919 
920 	ia_getrtprefix(ia, &daddr, &maddr);
921 
922 	struct sockaddr_in mask = {
923 		.sin_family = AF_INET,
924 		.sin_len = sizeof(struct sockaddr_in),
925 		.sin_addr = maddr,
926 	};
927 
928 	pmask = (maddr.s_addr != INADDR_BROADCAST) ? &mask : NULL;
929 
930 	struct sockaddr_in dst = {
931 		.sin_family = AF_INET,
932 		.sin_len = sizeof(struct sockaddr_in),
933 		.sin_addr.s_addr = daddr.s_addr & maddr.s_addr,
934 	};
935 
936 	struct ifnet *ifp = ia->ia_ifp;
937 
938 	if ((maddr.s_addr == INADDR_BROADCAST) &&
939 	    (!(ia->ia_ifp->if_flags & (IFF_POINTOPOINT|IFF_LOOPBACK)))) {
940 		/* Case 2: host route on broadcast interface */
941 		ifp = V_loif;
942 	}
943 
944 	uint32_t fibnum = ifa->ifa_ifp->if_fib;
945 	NET_EPOCH_ENTER(et);
946 	error = in_handle_prefix_route(fibnum, cmd, &dst, pmask, ifa, ifp);
947 	NET_EPOCH_EXIT(et);
948 
949 	return (error);
950 }
951 
952 /*
953  * Check if we have a route for the given prefix already.
954  */
955 static bool
956 in_hasrtprefix(struct in_ifaddr *target)
957 {
958 	struct epoch_tracker et;
959 	struct in_ifaddr *ia;
960 	struct in_addr prefix, mask, p, m;
961 	bool result = false;
962 
963 	ia_getrtprefix(target, &prefix, &mask);
964 
965 	/* Look for an existing address with the same prefix, mask, and fib */
966 	NET_EPOCH_ENTER(et);
967 	CK_STAILQ_FOREACH(ia, &V_in_ifaddrhead, ia_link) {
968 		ia_getrtprefix(ia, &p, &m);
969 
970 		if (prefix.s_addr != p.s_addr ||
971 		    mask.s_addr != m.s_addr)
972 			continue;
973 
974 		if (target->ia_ifp->if_fib != ia->ia_ifp->if_fib)
975 			continue;
976 
977 		/*
978 		 * If we got a matching prefix route inserted by other
979 		 * interface address, we are done here.
980 		 */
981 		if (ia->ia_flags & IFA_ROUTE) {
982 			result = true;
983 			break;
984 		}
985 	}
986 	NET_EPOCH_EXIT(et);
987 
988 	return (result);
989 }
990 
991 int
992 in_addprefix(struct in_ifaddr *target)
993 {
994 	int error;
995 
996 	if (in_hasrtprefix(target)) {
997 		if (V_nosameprefix)
998 			return (EEXIST);
999 		else {
1000 			rt_addrmsg(RTM_ADD, &target->ia_ifa,
1001 			    target->ia_ifp->if_fib);
1002 			return (0);
1003 		}
1004 	}
1005 
1006 	/*
1007 	 * No-one seem to have this prefix route, so we try to insert it.
1008 	 */
1009 	rt_addrmsg(RTM_ADD, &target->ia_ifa, target->ia_ifp->if_fib);
1010 	error = in_handle_ifaddr_route(RTM_ADD, target);
1011 	if (!error)
1012 		target->ia_flags |= IFA_ROUTE;
1013 	return (error);
1014 }
1015 
1016 /*
1017  * Removes either all lle entries for given @ia, or lle
1018  * corresponding to @ia address.
1019  */
1020 static void
1021 in_scrubprefixlle(struct in_ifaddr *ia, int all, u_int flags)
1022 {
1023 	struct sockaddr_in addr, mask;
1024 	struct sockaddr *saddr, *smask;
1025 	struct ifnet *ifp;
1026 
1027 	saddr = (struct sockaddr *)&addr;
1028 	bzero(&addr, sizeof(addr));
1029 	addr.sin_len = sizeof(addr);
1030 	addr.sin_family = AF_INET;
1031 	smask = (struct sockaddr *)&mask;
1032 	bzero(&mask, sizeof(mask));
1033 	mask.sin_len = sizeof(mask);
1034 	mask.sin_family = AF_INET;
1035 	mask.sin_addr.s_addr = ia->ia_subnetmask;
1036 	ifp = ia->ia_ifp;
1037 
1038 	if (all) {
1039 		/*
1040 		 * Remove all L2 entries matching given prefix.
1041 		 * Convert address to host representation to avoid
1042 		 * doing this on every callback. ia_subnetmask is already
1043 		 * stored in host representation.
1044 		 */
1045 		addr.sin_addr.s_addr = ntohl(ia->ia_addr.sin_addr.s_addr);
1046 		lltable_prefix_free(AF_INET, saddr, smask, flags);
1047 	} else {
1048 		/* Remove interface address only */
1049 		addr.sin_addr.s_addr = ia->ia_addr.sin_addr.s_addr;
1050 		lltable_delete_addr(LLTABLE(ifp), LLE_IFADDR, saddr);
1051 	}
1052 }
1053 
1054 /*
1055  * If there is no other address in the system that can serve a route to the
1056  * same prefix, remove the route.  Hand over the route to the new address
1057  * otherwise.
1058  */
1059 int
1060 in_scrubprefix(struct in_ifaddr *target, u_int flags)
1061 {
1062 	struct epoch_tracker et;
1063 	struct in_ifaddr *ia;
1064 	struct in_addr prefix, mask, p, m;
1065 	int error = 0;
1066 
1067 	/*
1068 	 * Remove the loopback route to the interface address.
1069 	 */
1070 	if (ia_need_loopback_route(target) && (flags & LLE_STATIC)) {
1071 		struct in_ifaddr *eia;
1072 
1073 		eia = in_localip_more(target);
1074 
1075 		if (eia != NULL) {
1076 			error = ifa_switch_loopback_route((struct ifaddr *)eia,
1077 			    (struct sockaddr *)&target->ia_addr);
1078 			ifa_free(&eia->ia_ifa);
1079 		} else {
1080 			error = ifa_del_loopback_route((struct ifaddr *)target,
1081 			    (struct sockaddr *)&target->ia_addr);
1082 		}
1083 	}
1084 
1085 	ia_getrtprefix(target, &prefix, &mask);
1086 
1087 	if ((target->ia_flags & IFA_ROUTE) == 0) {
1088 		rt_addrmsg(RTM_DELETE, &target->ia_ifa, target->ia_ifp->if_fib);
1089 
1090 		/*
1091 		 * Removing address from !IFF_UP interface or
1092 		 * prefix which exists on other interface (along with route).
1093 		 * No entries should exist here except target addr.
1094 		 * Given that, delete this entry only.
1095 		 */
1096 		in_scrubprefixlle(target, 0, flags);
1097 		return (0);
1098 	}
1099 
1100 	NET_EPOCH_ENTER(et);
1101 	CK_STAILQ_FOREACH(ia, &V_in_ifaddrhead, ia_link) {
1102 		ia_getrtprefix(ia, &p, &m);
1103 
1104 		if (prefix.s_addr != p.s_addr ||
1105 		    mask.s_addr != m.s_addr)
1106 			continue;
1107 
1108 		if ((ia->ia_ifp->if_flags & IFF_UP) == 0)
1109 			continue;
1110 
1111 		/*
1112 		 * If we got a matching prefix address, move IFA_ROUTE and
1113 		 * the route itself to it.  Make sure that routing daemons
1114 		 * get a heads-up.
1115 		 */
1116 		if ((ia->ia_flags & IFA_ROUTE) == 0) {
1117 			ifa_ref(&ia->ia_ifa);
1118 			NET_EPOCH_EXIT(et);
1119 			error = in_handle_ifaddr_route(RTM_DELETE, target);
1120 			if (error == 0)
1121 				target->ia_flags &= ~IFA_ROUTE;
1122 			else
1123 				log(LOG_INFO, "in_scrubprefix: err=%d, old prefix delete failed\n",
1124 					error);
1125 			/* Scrub all entries IFF interface is different */
1126 			in_scrubprefixlle(target, target->ia_ifp != ia->ia_ifp,
1127 			    flags);
1128 			error = in_handle_ifaddr_route(RTM_ADD, ia);
1129 			if (error == 0)
1130 				ia->ia_flags |= IFA_ROUTE;
1131 			else
1132 				log(LOG_INFO, "in_scrubprefix: err=%d, new prefix add failed\n",
1133 					error);
1134 			ifa_free(&ia->ia_ifa);
1135 			return (error);
1136 		}
1137 	}
1138 	NET_EPOCH_EXIT(et);
1139 
1140 	/*
1141 	 * remove all L2 entries on the given prefix
1142 	 */
1143 	in_scrubprefixlle(target, 1, flags);
1144 
1145 	/*
1146 	 * As no-one seem to have this prefix, we can remove the route.
1147 	 */
1148 	rt_addrmsg(RTM_DELETE, &target->ia_ifa, target->ia_ifp->if_fib);
1149 	error = in_handle_ifaddr_route(RTM_DELETE, target);
1150 	if (error == 0)
1151 		target->ia_flags &= ~IFA_ROUTE;
1152 	else
1153 		log(LOG_INFO, "in_scrubprefix: err=%d, prefix delete failed\n", error);
1154 	return (error);
1155 }
1156 
1157 void
1158 in_ifscrub_all(void)
1159 {
1160 	struct ifnet *ifp;
1161 	struct ifaddr *ifa, *nifa;
1162 	struct ifaliasreq ifr;
1163 
1164 	IFNET_RLOCK();
1165 	CK_STAILQ_FOREACH(ifp, &V_ifnet, if_link) {
1166 		/* Cannot lock here - lock recursion. */
1167 		/* NET_EPOCH_ENTER(et); */
1168 		CK_STAILQ_FOREACH_SAFE(ifa, &ifp->if_addrhead, ifa_link, nifa) {
1169 			if (ifa->ifa_addr->sa_family != AF_INET)
1170 				continue;
1171 
1172 			/*
1173 			 * This is ugly but the only way for legacy IP to
1174 			 * cleanly remove addresses and everything attached.
1175 			 */
1176 			bzero(&ifr, sizeof(ifr));
1177 			ifr.ifra_addr = *ifa->ifa_addr;
1178 			if (ifa->ifa_dstaddr)
1179 			ifr.ifra_broadaddr = *ifa->ifa_dstaddr;
1180 			(void)in_control(NULL, SIOCDIFADDR, (caddr_t)&ifr,
1181 			    ifp, NULL);
1182 		}
1183 		/* NET_EPOCH_EXIT(et); */
1184 		in_purgemaddrs(ifp);
1185 		igmp_domifdetach(ifp);
1186 	}
1187 	IFNET_RUNLOCK();
1188 }
1189 
1190 int
1191 in_ifaddr_broadcast(struct in_addr in, struct in_ifaddr *ia)
1192 {
1193 
1194 	return ((in.s_addr == ia->ia_broadaddr.sin_addr.s_addr ||
1195 	     /*
1196 	      * Optionally check for old-style (host 0) broadcast, but
1197 	      * taking into account that RFC 3021 obsoletes it.
1198 	      */
1199 	    (V_broadcast_lowest && ia->ia_subnetmask != IN_RFC3021_MASK &&
1200 	    ntohl(in.s_addr) == ia->ia_subnet)) &&
1201 	     /*
1202 	      * Check for an all one subnetmask. These
1203 	      * only exist when an interface gets a secondary
1204 	      * address.
1205 	      */
1206 	    ia->ia_subnetmask != (u_long)0xffffffff);
1207 }
1208 
1209 /*
1210  * Return 1 if the address might be a local broadcast address.
1211  */
1212 int
1213 in_broadcast(struct in_addr in, struct ifnet *ifp)
1214 {
1215 	struct ifaddr *ifa;
1216 	int found;
1217 
1218 	NET_EPOCH_ASSERT();
1219 
1220 	if (in.s_addr == INADDR_BROADCAST ||
1221 	    in.s_addr == INADDR_ANY)
1222 		return (1);
1223 	if ((ifp->if_flags & IFF_BROADCAST) == 0)
1224 		return (0);
1225 	found = 0;
1226 	/*
1227 	 * Look through the list of addresses for a match
1228 	 * with a broadcast address.
1229 	 */
1230 	CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link)
1231 		if (ifa->ifa_addr->sa_family == AF_INET &&
1232 		    in_ifaddr_broadcast(in, (struct in_ifaddr *)ifa)) {
1233 			found = 1;
1234 			break;
1235 		}
1236 	return (found);
1237 }
1238 
1239 /*
1240  * On interface removal, clean up IPv4 data structures hung off of the ifnet.
1241  */
1242 void
1243 in_ifdetach(struct ifnet *ifp)
1244 {
1245 	IN_MULTI_LOCK();
1246 	in_pcbpurgeif0(&V_ripcbinfo, ifp);
1247 	in_pcbpurgeif0(&V_udbinfo, ifp);
1248 	in_pcbpurgeif0(&V_ulitecbinfo, ifp);
1249 	in_purgemaddrs(ifp);
1250 	IN_MULTI_UNLOCK();
1251 
1252 	/*
1253 	 * Make sure all multicast deletions invoking if_ioctl() are
1254 	 * completed before returning. Else we risk accessing a freed
1255 	 * ifnet structure pointer.
1256 	 */
1257 	inm_release_wait(NULL);
1258 }
1259 
1260 /*
1261  * Delete all IPv4 multicast address records, and associated link-layer
1262  * multicast address records, associated with ifp.
1263  * XXX It looks like domifdetach runs AFTER the link layer cleanup.
1264  * XXX This should not race with ifma_protospec being set during
1265  * a new allocation, if it does, we have bigger problems.
1266  */
1267 static void
1268 in_purgemaddrs(struct ifnet *ifp)
1269 {
1270 	struct in_multi_head purgeinms;
1271 	struct in_multi		*inm;
1272 	struct ifmultiaddr	*ifma, *next;
1273 
1274 	SLIST_INIT(&purgeinms);
1275 	IN_MULTI_LIST_LOCK();
1276 
1277 	/*
1278 	 * Extract list of in_multi associated with the detaching ifp
1279 	 * which the PF_INET layer is about to release.
1280 	 * We need to do this as IF_ADDR_LOCK() may be re-acquired
1281 	 * by code further down.
1282 	 */
1283 	IF_ADDR_WLOCK(ifp);
1284  restart:
1285 	CK_STAILQ_FOREACH_SAFE(ifma, &ifp->if_multiaddrs, ifma_link, next) {
1286 		if (ifma->ifma_addr->sa_family != AF_INET ||
1287 		    ifma->ifma_protospec == NULL)
1288 			continue;
1289 		inm = (struct in_multi *)ifma->ifma_protospec;
1290 		inm_rele_locked(&purgeinms, inm);
1291 		if (__predict_false(ifma_restart)) {
1292 			ifma_restart = true;
1293 			goto restart;
1294 		}
1295 	}
1296 	IF_ADDR_WUNLOCK(ifp);
1297 
1298 	inm_release_list_deferred(&purgeinms);
1299 	igmp_ifdetach(ifp);
1300 	IN_MULTI_LIST_UNLOCK();
1301 }
1302 
1303 struct in_llentry {
1304 	struct llentry		base;
1305 };
1306 
1307 #define	IN_LLTBL_DEFAULT_HSIZE	32
1308 #define	IN_LLTBL_HASH(k, h) \
1309 	(((((((k >> 8) ^ k) >> 8) ^ k) >> 8) ^ k) & ((h) - 1))
1310 
1311 /*
1312  * Do actual deallocation of @lle.
1313  */
1314 static void
1315 in_lltable_destroy_lle_unlocked(epoch_context_t ctx)
1316 {
1317 	struct llentry *lle;
1318 
1319 	lle = __containerof(ctx, struct llentry, lle_epoch_ctx);
1320 	LLE_LOCK_DESTROY(lle);
1321 	LLE_REQ_DESTROY(lle);
1322 	free(lle, M_LLTABLE);
1323 }
1324 
1325 /*
1326  * Called by LLE_FREE_LOCKED when number of references
1327  * drops to zero.
1328  */
1329 static void
1330 in_lltable_destroy_lle(struct llentry *lle)
1331 {
1332 
1333 	LLE_WUNLOCK(lle);
1334 	NET_EPOCH_CALL(in_lltable_destroy_lle_unlocked, &lle->lle_epoch_ctx);
1335 }
1336 
1337 static struct llentry *
1338 in_lltable_new(struct in_addr addr4, u_int flags)
1339 {
1340 	struct in_llentry *lle;
1341 
1342 	lle = malloc(sizeof(struct in_llentry), M_LLTABLE, M_NOWAIT | M_ZERO);
1343 	if (lle == NULL)		/* NB: caller generates msg */
1344 		return NULL;
1345 
1346 	/*
1347 	 * For IPv4 this will trigger "arpresolve" to generate
1348 	 * an ARP request.
1349 	 */
1350 	lle->base.la_expire = time_uptime; /* mark expired */
1351 	lle->base.r_l3addr.addr4 = addr4;
1352 	lle->base.lle_refcnt = 1;
1353 	lle->base.lle_free = in_lltable_destroy_lle;
1354 	LLE_LOCK_INIT(&lle->base);
1355 	LLE_REQ_INIT(&lle->base);
1356 	callout_init(&lle->base.lle_timer, 1);
1357 
1358 	return (&lle->base);
1359 }
1360 
1361 #define IN_ARE_MASKED_ADDR_EQUAL(d, a, m)	(		\
1362 	((((d).s_addr ^ (a).s_addr) & (m).s_addr)) == 0 )
1363 
1364 static int
1365 in_lltable_match_prefix(const struct sockaddr *saddr,
1366     const struct sockaddr *smask, u_int flags, struct llentry *lle)
1367 {
1368 	struct in_addr addr, mask, lle_addr;
1369 
1370 	addr = ((const struct sockaddr_in *)saddr)->sin_addr;
1371 	mask = ((const struct sockaddr_in *)smask)->sin_addr;
1372 	lle_addr.s_addr = ntohl(lle->r_l3addr.addr4.s_addr);
1373 
1374 	if (IN_ARE_MASKED_ADDR_EQUAL(lle_addr, addr, mask) == 0)
1375 		return (0);
1376 
1377 	if (lle->la_flags & LLE_IFADDR) {
1378 		/*
1379 		 * Delete LLE_IFADDR records IFF address & flag matches.
1380 		 * Note that addr is the interface address within prefix
1381 		 * being matched.
1382 		 * Note also we should handle 'ifdown' cases without removing
1383 		 * ifaddr macs.
1384 		 */
1385 		if (addr.s_addr == lle_addr.s_addr && (flags & LLE_STATIC) != 0)
1386 			return (1);
1387 		return (0);
1388 	}
1389 
1390 	/* flags & LLE_STATIC means deleting both dynamic and static entries */
1391 	if ((flags & LLE_STATIC) || !(lle->la_flags & LLE_STATIC))
1392 		return (1);
1393 
1394 	return (0);
1395 }
1396 
1397 static void
1398 in_lltable_free_entry(struct lltable *llt, struct llentry *lle)
1399 {
1400 	size_t pkts_dropped;
1401 
1402 	LLE_WLOCK_ASSERT(lle);
1403 	KASSERT(llt != NULL, ("lltable is NULL"));
1404 
1405 	/* Unlink entry from table if not already */
1406 	if ((lle->la_flags & LLE_LINKED) != 0) {
1407 		IF_AFDATA_WLOCK_ASSERT(llt->llt_ifp);
1408 		lltable_unlink_entry(llt, lle);
1409 	}
1410 
1411 	/* Drop hold queue */
1412 	pkts_dropped = llentry_free(lle);
1413 	ARPSTAT_ADD(dropped, pkts_dropped);
1414 }
1415 
1416 static int
1417 in_lltable_rtcheck(struct ifnet *ifp, u_int flags, const struct sockaddr *l3addr)
1418 {
1419 	struct nhop_object *nh;
1420 	struct in_addr addr;
1421 
1422 	KASSERT(l3addr->sa_family == AF_INET,
1423 	    ("sin_family %d", l3addr->sa_family));
1424 
1425 	addr = ((const struct sockaddr_in *)l3addr)->sin_addr;
1426 
1427 	nh = fib4_lookup(ifp->if_fib, addr, 0, NHR_NONE, 0);
1428 	if (nh == NULL)
1429 		return (EINVAL);
1430 
1431 	/*
1432 	 * If the gateway for an existing host route matches the target L3
1433 	 * address, which is a special route inserted by some implementation
1434 	 * such as MANET, and the interface is of the correct type, then
1435 	 * allow for ARP to proceed.
1436 	 */
1437 	if (nh->nh_flags & NHF_GATEWAY) {
1438 		if (!(nh->nh_flags & NHF_HOST) || nh->nh_ifp->if_type != IFT_ETHER ||
1439 		    (nh->nh_ifp->if_flags & (IFF_NOARP | IFF_STATICARP)) != 0 ||
1440 		    memcmp(nh->gw_sa.sa_data, l3addr->sa_data,
1441 		    sizeof(in_addr_t)) != 0) {
1442 			return (EINVAL);
1443 		}
1444 	}
1445 
1446 	/*
1447 	 * Make sure that at least the destination address is covered
1448 	 * by the route. This is for handling the case where 2 or more
1449 	 * interfaces have the same prefix. An incoming packet arrives
1450 	 * on one interface and the corresponding outgoing packet leaves
1451 	 * another interface.
1452 	 */
1453 	if ((nh->nh_ifp != ifp) && (nh->nh_flags & NHF_HOST) == 0) {
1454 		struct in_ifaddr *ia = (struct in_ifaddr *)ifaof_ifpforaddr(l3addr, ifp);
1455 		struct in_addr dst_addr, mask_addr;
1456 
1457 		if (ia == NULL)
1458 			return (EINVAL);
1459 
1460 		/*
1461 		 * ifaof_ifpforaddr() returns _best matching_ IFA.
1462 		 * It is possible that ifa prefix does not cover our address.
1463 		 * Explicitly verify and fail if that's the case.
1464 		 */
1465 		dst_addr = IA_SIN(ia)->sin_addr;
1466 		mask_addr.s_addr = htonl(ia->ia_subnetmask);
1467 
1468 		if (!IN_ARE_MASKED_ADDR_EQUAL(dst_addr, addr, mask_addr))
1469 			return (EINVAL);
1470 	}
1471 
1472 	return (0);
1473 }
1474 
1475 static inline uint32_t
1476 in_lltable_hash_dst(const struct in_addr dst, uint32_t hsize)
1477 {
1478 
1479 	return (IN_LLTBL_HASH(dst.s_addr, hsize));
1480 }
1481 
1482 static uint32_t
1483 in_lltable_hash(const struct llentry *lle, uint32_t hsize)
1484 {
1485 
1486 	return (in_lltable_hash_dst(lle->r_l3addr.addr4, hsize));
1487 }
1488 
1489 static void
1490 in_lltable_fill_sa_entry(const struct llentry *lle, struct sockaddr *sa)
1491 {
1492 	struct sockaddr_in *sin;
1493 
1494 	sin = (struct sockaddr_in *)sa;
1495 	bzero(sin, sizeof(*sin));
1496 	sin->sin_family = AF_INET;
1497 	sin->sin_len = sizeof(*sin);
1498 	sin->sin_addr = lle->r_l3addr.addr4;
1499 }
1500 
1501 static inline struct llentry *
1502 in_lltable_find_dst(struct lltable *llt, struct in_addr dst)
1503 {
1504 	struct llentry *lle;
1505 	struct llentries *lleh;
1506 	u_int hashidx;
1507 
1508 	hashidx = in_lltable_hash_dst(dst, llt->llt_hsize);
1509 	lleh = &llt->lle_head[hashidx];
1510 	CK_LIST_FOREACH(lle, lleh, lle_next) {
1511 		if (lle->la_flags & LLE_DELETED)
1512 			continue;
1513 		if (lle->r_l3addr.addr4.s_addr == dst.s_addr)
1514 			break;
1515 	}
1516 
1517 	return (lle);
1518 }
1519 
1520 static void
1521 in_lltable_delete_entry(struct lltable *llt, struct llentry *lle)
1522 {
1523 
1524 	lle->la_flags |= LLE_DELETED;
1525 	EVENTHANDLER_INVOKE(lle_event, lle, LLENTRY_DELETED);
1526 #ifdef DIAGNOSTIC
1527 	log(LOG_INFO, "ifaddr cache = %p is deleted\n", lle);
1528 #endif
1529 	llentry_free(lle);
1530 }
1531 
1532 static struct llentry *
1533 in_lltable_alloc(struct lltable *llt, u_int flags, const struct sockaddr *l3addr)
1534 {
1535 	const struct sockaddr_in *sin = (const struct sockaddr_in *)l3addr;
1536 	struct ifnet *ifp = llt->llt_ifp;
1537 	struct llentry *lle;
1538 	char linkhdr[LLE_MAX_LINKHDR];
1539 	size_t linkhdrsize;
1540 	int lladdr_off;
1541 
1542 	KASSERT(l3addr->sa_family == AF_INET,
1543 	    ("sin_family %d", l3addr->sa_family));
1544 
1545 	/*
1546 	 * A route that covers the given address must have
1547 	 * been installed 1st because we are doing a resolution,
1548 	 * verify this.
1549 	 */
1550 	if (!(flags & LLE_IFADDR) &&
1551 	    in_lltable_rtcheck(ifp, flags, l3addr) != 0)
1552 		return (NULL);
1553 
1554 	lle = in_lltable_new(sin->sin_addr, flags);
1555 	if (lle == NULL) {
1556 		log(LOG_INFO, "lla_lookup: new lle malloc failed\n");
1557 		return (NULL);
1558 	}
1559 	lle->la_flags = flags;
1560 	if (flags & LLE_STATIC)
1561 		lle->r_flags |= RLLE_VALID;
1562 	if ((flags & LLE_IFADDR) == LLE_IFADDR) {
1563 		linkhdrsize = LLE_MAX_LINKHDR;
1564 		if (lltable_calc_llheader(ifp, AF_INET, IF_LLADDR(ifp),
1565 		    linkhdr, &linkhdrsize, &lladdr_off) != 0) {
1566 			NET_EPOCH_CALL(in_lltable_destroy_lle_unlocked, &lle->lle_epoch_ctx);
1567 			return (NULL);
1568 		}
1569 		lltable_set_entry_addr(ifp, lle, linkhdr, linkhdrsize,
1570 		    lladdr_off);
1571 		lle->la_flags |= LLE_STATIC;
1572 		lle->r_flags |= (RLLE_VALID | RLLE_IFADDR);
1573 	}
1574 
1575 	return (lle);
1576 }
1577 
1578 /*
1579  * Return NULL if not found or marked for deletion.
1580  * If found return lle read locked.
1581  */
1582 static struct llentry *
1583 in_lltable_lookup(struct lltable *llt, u_int flags, const struct sockaddr *l3addr)
1584 {
1585 	const struct sockaddr_in *sin = (const struct sockaddr_in *)l3addr;
1586 	struct llentry *lle;
1587 
1588 	IF_AFDATA_LOCK_ASSERT(llt->llt_ifp);
1589 	KASSERT(l3addr->sa_family == AF_INET,
1590 	    ("sin_family %d", l3addr->sa_family));
1591 	KASSERT((flags & (LLE_UNLOCKED | LLE_EXCLUSIVE)) !=
1592 	    (LLE_UNLOCKED | LLE_EXCLUSIVE),
1593 	    ("wrong lle request flags: %#x", flags));
1594 
1595 	lle = in_lltable_find_dst(llt, sin->sin_addr);
1596 	if (lle == NULL)
1597 		return (NULL);
1598 	if (flags & LLE_UNLOCKED)
1599 		return (lle);
1600 
1601 	if (flags & LLE_EXCLUSIVE)
1602 		LLE_WLOCK(lle);
1603 	else
1604 		LLE_RLOCK(lle);
1605 
1606 	/*
1607 	 * If the afdata lock is not held, the LLE may have been unlinked while
1608 	 * we were blocked on the LLE lock.  Check for this case.
1609 	 */
1610 	if (__predict_false((lle->la_flags & LLE_LINKED) == 0)) {
1611 		if (flags & LLE_EXCLUSIVE)
1612 			LLE_WUNLOCK(lle);
1613 		else
1614 			LLE_RUNLOCK(lle);
1615 		return (NULL);
1616 	}
1617 	return (lle);
1618 }
1619 
1620 static int
1621 in_lltable_dump_entry(struct lltable *llt, struct llentry *lle,
1622     struct sysctl_req *wr)
1623 {
1624 	struct ifnet *ifp = llt->llt_ifp;
1625 	/* XXX stack use */
1626 	struct {
1627 		struct rt_msghdr	rtm;
1628 		struct sockaddr_in	sin;
1629 		struct sockaddr_dl	sdl;
1630 	} arpc;
1631 	struct sockaddr_dl *sdl;
1632 	int error;
1633 
1634 	bzero(&arpc, sizeof(arpc));
1635 	/* skip deleted entries */
1636 	if ((lle->la_flags & LLE_DELETED) == LLE_DELETED)
1637 		return (0);
1638 	/* Skip if jailed and not a valid IP of the prison. */
1639 	lltable_fill_sa_entry(lle,(struct sockaddr *)&arpc.sin);
1640 	if (prison_if(wr->td->td_ucred, (struct sockaddr *)&arpc.sin) != 0)
1641 		return (0);
1642 	/*
1643 	 * produce a msg made of:
1644 	 *  struct rt_msghdr;
1645 	 *  struct sockaddr_in; (IPv4)
1646 	 *  struct sockaddr_dl;
1647 	 */
1648 	arpc.rtm.rtm_msglen = sizeof(arpc);
1649 	arpc.rtm.rtm_version = RTM_VERSION;
1650 	arpc.rtm.rtm_type = RTM_GET;
1651 	arpc.rtm.rtm_flags = RTF_UP;
1652 	arpc.rtm.rtm_addrs = RTA_DST | RTA_GATEWAY;
1653 
1654 	/* publish */
1655 	if (lle->la_flags & LLE_PUB)
1656 		arpc.rtm.rtm_flags |= RTF_ANNOUNCE;
1657 
1658 	sdl = &arpc.sdl;
1659 	sdl->sdl_family = AF_LINK;
1660 	sdl->sdl_len = sizeof(*sdl);
1661 	sdl->sdl_index = ifp->if_index;
1662 	sdl->sdl_type = ifp->if_type;
1663 	if ((lle->la_flags & LLE_VALID) == LLE_VALID) {
1664 		sdl->sdl_alen = ifp->if_addrlen;
1665 		bcopy(lle->ll_addr, LLADDR(sdl), ifp->if_addrlen);
1666 	} else {
1667 		sdl->sdl_alen = 0;
1668 		bzero(LLADDR(sdl), ifp->if_addrlen);
1669 	}
1670 
1671 	arpc.rtm.rtm_rmx.rmx_expire =
1672 	    lle->la_flags & LLE_STATIC ? 0 : lle->la_expire;
1673 	arpc.rtm.rtm_flags |= (RTF_HOST | RTF_LLDATA);
1674 	if (lle->la_flags & LLE_STATIC)
1675 		arpc.rtm.rtm_flags |= RTF_STATIC;
1676 	if (lle->la_flags & LLE_IFADDR)
1677 		arpc.rtm.rtm_flags |= RTF_PINNED;
1678 	arpc.rtm.rtm_index = ifp->if_index;
1679 	error = SYSCTL_OUT(wr, &arpc, sizeof(arpc));
1680 
1681 	return (error);
1682 }
1683 
1684 static struct lltable *
1685 in_lltattach(struct ifnet *ifp)
1686 {
1687 	struct lltable *llt;
1688 
1689 	llt = lltable_allocate_htbl(IN_LLTBL_DEFAULT_HSIZE);
1690  	llt->llt_af = AF_INET;
1691  	llt->llt_ifp = ifp;
1692 
1693 	llt->llt_lookup = in_lltable_lookup;
1694 	llt->llt_alloc_entry = in_lltable_alloc;
1695 	llt->llt_delete_entry = in_lltable_delete_entry;
1696 	llt->llt_dump_entry = in_lltable_dump_entry;
1697 	llt->llt_hash = in_lltable_hash;
1698 	llt->llt_fill_sa_entry = in_lltable_fill_sa_entry;
1699 	llt->llt_free_entry = in_lltable_free_entry;
1700 	llt->llt_match_prefix = in_lltable_match_prefix;
1701 	llt->llt_mark_used = llentry_mark_used;
1702  	lltable_link(llt);
1703 
1704 	return (llt);
1705 }
1706 
1707 struct lltable *
1708 in_lltable_get(struct ifnet *ifp)
1709 {
1710 	struct lltable *llt = NULL;
1711 
1712 	void *afdata_ptr = ifp->if_afdata[AF_INET];
1713 	if (afdata_ptr != NULL)
1714 		llt = ((struct in_ifinfo *)afdata_ptr)->ii_llt;
1715 	return (llt);
1716 }
1717 
1718 void *
1719 in_domifattach(struct ifnet *ifp)
1720 {
1721 	struct in_ifinfo *ii;
1722 
1723 	ii = malloc(sizeof(struct in_ifinfo), M_IFADDR, M_WAITOK|M_ZERO);
1724 
1725 	ii->ii_llt = in_lltattach(ifp);
1726 	ii->ii_igmp = igmp_domifattach(ifp);
1727 
1728 	return (ii);
1729 }
1730 
1731 void
1732 in_domifdetach(struct ifnet *ifp, void *aux)
1733 {
1734 	struct in_ifinfo *ii = (struct in_ifinfo *)aux;
1735 
1736 	igmp_domifdetach(ifp);
1737 	lltable_free(ii->ii_llt);
1738 	free(ii, M_IFADDR);
1739 }
1740