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