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