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