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