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