Home | History | Annotate | Line # | Download | only in netinet
in.c revision 1.156
      1 /*	$NetBSD: in.c,v 1.156 2015/05/16 12:12:46 roy Exp $	*/
      2 
      3 /*
      4  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
      5  * All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  * 1. Redistributions of source code must retain the above copyright
     11  *    notice, this list of conditions and the following disclaimer.
     12  * 2. Redistributions in binary form must reproduce the above copyright
     13  *    notice, this list of conditions and the following disclaimer in the
     14  *    documentation and/or other materials provided with the distribution.
     15  * 3. Neither the name of the project nor the names of its contributors
     16  *    may be used to endorse or promote products derived from this software
     17  *    without specific prior written permission.
     18  *
     19  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
     20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
     23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     29  * SUCH DAMAGE.
     30  */
     31 
     32 /*-
     33  * Copyright (c) 1998 The NetBSD Foundation, Inc.
     34  * All rights reserved.
     35  *
     36  * This code is derived from software contributed to The NetBSD Foundation
     37  * by Public Access Networks Corporation ("Panix").  It was developed under
     38  * contract to Panix by Eric Haszlakiewicz and Thor Lancelot Simon.
     39  *
     40  * Redistribution and use in source and binary forms, with or without
     41  * modification, are permitted provided that the following conditions
     42  * are met:
     43  * 1. Redistributions of source code must retain the above copyright
     44  *    notice, this list of conditions and the following disclaimer.
     45  * 2. Redistributions in binary form must reproduce the above copyright
     46  *    notice, this list of conditions and the following disclaimer in the
     47  *    documentation and/or other materials provided with the distribution.
     48  *
     49  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     50  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     51  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     52  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     53  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     54  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     55  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     56  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     57  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     58  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     59  * POSSIBILITY OF SUCH DAMAGE.
     60  */
     61 
     62 /*
     63  * Copyright (c) 1982, 1986, 1991, 1993
     64  *	The Regents of the University of California.  All rights reserved.
     65  *
     66  * Redistribution and use in source and binary forms, with or without
     67  * modification, are permitted provided that the following conditions
     68  * are met:
     69  * 1. Redistributions of source code must retain the above copyright
     70  *    notice, this list of conditions and the following disclaimer.
     71  * 2. Redistributions in binary form must reproduce the above copyright
     72  *    notice, this list of conditions and the following disclaimer in the
     73  *    documentation and/or other materials provided with the distribution.
     74  * 3. Neither the name of the University nor the names of its contributors
     75  *    may be used to endorse or promote products derived from this software
     76  *    without specific prior written permission.
     77  *
     78  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     79  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     80  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     81  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     82  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     83  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     84  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     85  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     86  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     87  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     88  * SUCH DAMAGE.
     89  *
     90  *	@(#)in.c	8.4 (Berkeley) 1/9/95
     91  */
     92 
     93 #include <sys/cdefs.h>
     94 __KERNEL_RCSID(0, "$NetBSD: in.c,v 1.156 2015/05/16 12:12:46 roy Exp $");
     95 
     96 #include "arp.h"
     97 #include "opt_inet.h"
     98 #include "opt_inet_conf.h"
     99 #include "opt_mrouting.h"
    100 
    101 #include <sys/param.h>
    102 #include <sys/ioctl.h>
    103 #include <sys/errno.h>
    104 #include <sys/kernel.h>
    105 #include <sys/malloc.h>
    106 #include <sys/socket.h>
    107 #include <sys/socketvar.h>
    108 #include <sys/sysctl.h>
    109 #include <sys/systm.h>
    110 #include <sys/proc.h>
    111 #include <sys/syslog.h>
    112 #include <sys/kauth.h>
    113 
    114 #include <sys/cprng.h>
    115 
    116 #include <net/if.h>
    117 #include <net/route.h>
    118 #include <net/pfil.h>
    119 
    120 #include <net/if_ether.h>
    121 
    122 #include <netinet/in_systm.h>
    123 #include <netinet/in.h>
    124 #include <netinet/in_var.h>
    125 #include <netinet/ip.h>
    126 #include <netinet/ip_var.h>
    127 #include <netinet/in_ifattach.h>
    128 #include <netinet/in_pcb.h>
    129 #include <netinet/if_inarp.h>
    130 #include <netinet/ip_mroute.h>
    131 #include <netinet/igmp_var.h>
    132 
    133 #ifdef IPSELSRC
    134 #include <netinet/in_selsrc.h>
    135 #endif
    136 
    137 static u_int	in_mask2len(struct in_addr *);
    138 static void	in_len2mask(struct in_addr *, u_int);
    139 static int	in_lifaddr_ioctl(struct socket *, u_long, void *,
    140 	struct ifnet *);
    141 
    142 static int	in_addprefix(struct in_ifaddr *, int);
    143 static int	in_scrubprefix(struct in_ifaddr *);
    144 static void	in_sysctl_init(struct sysctllog **);
    145 
    146 #ifndef SUBNETSARELOCAL
    147 #define	SUBNETSARELOCAL	1
    148 #endif
    149 
    150 #ifndef HOSTZEROBROADCAST
    151 #define HOSTZEROBROADCAST 1
    152 #endif
    153 
    154 /* Note: 61, 127, 251, 509, 1021, 2039 are good. */
    155 #ifndef IN_MULTI_HASH_SIZE
    156 #define IN_MULTI_HASH_SIZE	509
    157 #endif
    158 
    159 static int			subnetsarelocal = SUBNETSARELOCAL;
    160 static int			hostzeroisbroadcast = HOSTZEROBROADCAST;
    161 
    162 /*
    163  * This list is used to keep track of in_multi chains which belong to
    164  * deleted interface addresses.  We use in_ifaddr so that a chain head
    165  * won't be deallocated until all multicast address record are deleted.
    166  */
    167 
    168 LIST_HEAD(in_multihashhead, in_multi);		/* Type of the hash head */
    169 
    170 static struct pool		inmulti_pool;
    171 static u_int			in_multientries;
    172 static struct in_multihashhead *in_multihashtbl;
    173 static u_long			in_multihash;
    174 static krwlock_t		in_multilock;
    175 
    176 #define IN_MULTI_HASH(x, ifp) \
    177     (in_multihashtbl[(u_long)((x) ^ (ifp->if_index)) % IN_MULTI_HASH_SIZE])
    178 
    179 struct in_ifaddrhashhead *	in_ifaddrhashtbl;
    180 u_long				in_ifaddrhash;
    181 struct in_ifaddrhead		in_ifaddrhead;
    182 
    183 void
    184 in_init(void)
    185 {
    186 	pool_init(&inmulti_pool, sizeof(struct in_multi), 0, 0, 0, "inmltpl",
    187 	    NULL, IPL_SOFTNET);
    188 	TAILQ_INIT(&in_ifaddrhead);
    189 
    190 	in_ifaddrhashtbl = hashinit(IN_IFADDR_HASH_SIZE, HASH_LIST, true,
    191 	    &in_ifaddrhash);
    192 	in_multihashtbl = hashinit(IN_IFADDR_HASH_SIZE, HASH_LIST, true,
    193 	    &in_multihash);
    194 	rw_init(&in_multilock);
    195 
    196 	in_sysctl_init(NULL);
    197 }
    198 
    199 /*
    200  * Return 1 if an internet address is for a ``local'' host
    201  * (one to which we have a connection).  If subnetsarelocal
    202  * is true, this includes other subnets of the local net.
    203  * Otherwise, it includes only the directly-connected (sub)nets.
    204  */
    205 int
    206 in_localaddr(struct in_addr in)
    207 {
    208 	struct in_ifaddr *ia;
    209 
    210 	if (subnetsarelocal) {
    211 		TAILQ_FOREACH(ia, &in_ifaddrhead, ia_list)
    212 			if ((in.s_addr & ia->ia_netmask) == ia->ia_net)
    213 				return (1);
    214 	} else {
    215 		TAILQ_FOREACH(ia, &in_ifaddrhead, ia_list)
    216 			if ((in.s_addr & ia->ia_subnetmask) == ia->ia_subnet)
    217 				return (1);
    218 	}
    219 	return (0);
    220 }
    221 
    222 /*
    223  * Determine whether an IP address is in a reserved set of addresses
    224  * that may not be forwarded, or whether datagrams to that destination
    225  * may be forwarded.
    226  */
    227 int
    228 in_canforward(struct in_addr in)
    229 {
    230 	u_int32_t net;
    231 
    232 	if (IN_EXPERIMENTAL(in.s_addr) || IN_MULTICAST(in.s_addr))
    233 		return (0);
    234 	if (IN_CLASSA(in.s_addr)) {
    235 		net = in.s_addr & IN_CLASSA_NET;
    236 		if (net == 0 || net == htonl(IN_LOOPBACKNET << IN_CLASSA_NSHIFT))
    237 			return (0);
    238 	}
    239 	return (1);
    240 }
    241 
    242 /*
    243  * Trim a mask in a sockaddr
    244  */
    245 void
    246 in_socktrim(struct sockaddr_in *ap)
    247 {
    248 	char *cplim = (char *) &ap->sin_addr;
    249 	char *cp = (char *) (&ap->sin_addr + 1);
    250 
    251 	ap->sin_len = 0;
    252 	while (--cp >= cplim)
    253 		if (*cp) {
    254 			(ap)->sin_len = cp - (char *) (ap) + 1;
    255 			break;
    256 		}
    257 }
    258 
    259 /*
    260  *  Routine to take an Internet address and convert into a
    261  *  "dotted quad" representation for printing.
    262  */
    263 const char *
    264 in_fmtaddr(struct in_addr addr)
    265 {
    266 	static char buf[sizeof("123.456.789.123")];
    267 
    268 	addr.s_addr = ntohl(addr.s_addr);
    269 
    270 	snprintf(buf, sizeof(buf), "%d.%d.%d.%d",
    271 		(addr.s_addr >> 24) & 0xFF,
    272 		(addr.s_addr >> 16) & 0xFF,
    273 		(addr.s_addr >>  8) & 0xFF,
    274 		(addr.s_addr >>  0) & 0xFF);
    275 	return buf;
    276 }
    277 
    278 /*
    279  * Maintain the "in_maxmtu" variable, which is the largest
    280  * mtu for non-local interfaces with AF_INET addresses assigned
    281  * to them that are up.
    282  */
    283 unsigned long in_maxmtu;
    284 
    285 void
    286 in_setmaxmtu(void)
    287 {
    288 	struct in_ifaddr *ia;
    289 	struct ifnet *ifp;
    290 	unsigned long maxmtu = 0;
    291 
    292 	TAILQ_FOREACH(ia, &in_ifaddrhead, ia_list) {
    293 		if ((ifp = ia->ia_ifp) == 0)
    294 			continue;
    295 		if ((ifp->if_flags & (IFF_UP|IFF_LOOPBACK)) != IFF_UP)
    296 			continue;
    297 		if (ifp->if_mtu > maxmtu)
    298 			maxmtu = ifp->if_mtu;
    299 	}
    300 	if (maxmtu)
    301 		in_maxmtu = maxmtu;
    302 }
    303 
    304 static u_int
    305 in_mask2len(struct in_addr *mask)
    306 {
    307 	u_int x, y;
    308 	u_char *p;
    309 
    310 	p = (u_char *)mask;
    311 	for (x = 0; x < sizeof(*mask); x++) {
    312 		if (p[x] != 0xff)
    313 			break;
    314 	}
    315 	y = 0;
    316 	if (x < sizeof(*mask)) {
    317 		for (y = 0; y < NBBY; y++) {
    318 			if ((p[x] & (0x80 >> y)) == 0)
    319 				break;
    320 		}
    321 	}
    322 	return x * NBBY + y;
    323 }
    324 
    325 static void
    326 in_len2mask(struct in_addr *mask, u_int len)
    327 {
    328 	u_int i;
    329 	u_char *p;
    330 
    331 	p = (u_char *)mask;
    332 	memset(mask, 0, sizeof(*mask));
    333 	for (i = 0; i < len / NBBY; i++)
    334 		p[i] = 0xff;
    335 	if (len % NBBY)
    336 		p[i] = (0xff00 >> (len % NBBY)) & 0xff;
    337 }
    338 
    339 /*
    340  * Generic internet control operations (ioctl's).
    341  * Ifp is 0 if not an interface-specific ioctl.
    342  */
    343 /* ARGSUSED */
    344 int
    345 in_control(struct socket *so, u_long cmd, void *data, struct ifnet *ifp)
    346 {
    347 	struct ifreq *ifr = (struct ifreq *)data;
    348 	struct in_ifaddr *ia = NULL;
    349 	struct in_aliasreq *ifra = (struct in_aliasreq *)data;
    350 	struct sockaddr_in oldaddr;
    351 	int error, hostIsNew, maskIsNew;
    352 	int newifaddr = 0;
    353 
    354 	switch (cmd) {
    355 	case SIOCALIFADDR:
    356 	case SIOCDLIFADDR:
    357 	case SIOCGLIFADDR:
    358 		if (ifp == NULL)
    359 			return EINVAL;
    360 		return in_lifaddr_ioctl(so, cmd, data, ifp);
    361 	case SIOCGIFADDRPREF:
    362 	case SIOCSIFADDRPREF:
    363 		if (ifp == NULL)
    364 			return EINVAL;
    365 		return ifaddrpref_ioctl(so, cmd, data, ifp);
    366 	}
    367 
    368 	/*
    369 	 * Find address for this interface, if it exists.
    370 	 */
    371 	if (ifp != NULL)
    372 		IFP_TO_IA(ifp, ia);
    373 
    374 	hostIsNew = 1;		/* moved here to appease gcc */
    375 	switch (cmd) {
    376 	case SIOCAIFADDR:
    377 	case SIOCDIFADDR:
    378 	case SIOCGIFALIAS:
    379 	case SIOCGIFAFLAG_IN:
    380 		if (ifra->ifra_addr.sin_family == AF_INET)
    381 			LIST_FOREACH(ia,
    382 			    &IN_IFADDR_HASH(ifra->ifra_addr.sin_addr.s_addr),
    383 			    ia_hash) {
    384 				if (ia->ia_ifp == ifp &&
    385 				    in_hosteq(ia->ia_addr.sin_addr,
    386 				    ifra->ifra_addr.sin_addr))
    387 					break;
    388 			}
    389 		if ((cmd == SIOCDIFADDR ||
    390 		    cmd == SIOCGIFALIAS ||
    391 		    cmd == SIOCGIFAFLAG_IN) &&
    392 		    ia == NULL)
    393 			return (EADDRNOTAVAIL);
    394 
    395 		if (cmd == SIOCDIFADDR &&
    396 		    ifra->ifra_addr.sin_family == AF_UNSPEC) {
    397 			ifra->ifra_addr.sin_family = AF_INET;
    398 		}
    399 		/* FALLTHROUGH */
    400 	case SIOCSIFADDR:
    401 		if (ia == NULL || ia->ia_addr.sin_family != AF_INET)
    402 			;
    403 		else if (ifra->ifra_addr.sin_len == 0) {
    404 			ifra->ifra_addr = ia->ia_addr;
    405 			hostIsNew = 0;
    406 		} else if (in_hosteq(ia->ia_addr.sin_addr,
    407 		           ifra->ifra_addr.sin_addr))
    408 			hostIsNew = 0;
    409 		/* FALLTHROUGH */
    410 	case SIOCSIFDSTADDR:
    411 		if (ifra->ifra_addr.sin_family != AF_INET)
    412 			return (EAFNOSUPPORT);
    413 		/* FALLTHROUGH */
    414 	case SIOCSIFNETMASK:
    415 		if (ifp == NULL)
    416 			panic("in_control");
    417 
    418 		if (cmd == SIOCGIFALIAS || cmd == SIOCGIFAFLAG_IN)
    419 			break;
    420 
    421 		if (ia == NULL &&
    422 		    (cmd == SIOCSIFNETMASK || cmd == SIOCSIFDSTADDR))
    423 			return (EADDRNOTAVAIL);
    424 
    425 		if (kauth_authorize_network(curlwp->l_cred, KAUTH_NETWORK_INTERFACE,
    426 		    KAUTH_REQ_NETWORK_INTERFACE_SETPRIV, ifp, (void *)cmd,
    427 		    NULL) != 0)
    428 			return (EPERM);
    429 
    430 		if (ia == NULL) {
    431 			ia = malloc(sizeof(*ia), M_IFADDR, M_WAITOK|M_ZERO);
    432 			if (ia == NULL)
    433 				return (ENOBUFS);
    434 			TAILQ_INSERT_TAIL(&in_ifaddrhead, ia, ia_list);
    435 			ifaref(&ia->ia_ifa);
    436 			ifa_insert(ifp, &ia->ia_ifa);
    437 			ia->ia_ifa.ifa_addr = sintosa(&ia->ia_addr);
    438 			ia->ia_ifa.ifa_dstaddr = sintosa(&ia->ia_dstaddr);
    439 			ia->ia_ifa.ifa_netmask = sintosa(&ia->ia_sockmask);
    440 #ifdef IPSELSRC
    441 			ia->ia_ifa.ifa_getifa = in_getifa;
    442 #else /* IPSELSRC */
    443 			ia->ia_ifa.ifa_getifa = NULL;
    444 #endif /* IPSELSRC */
    445 			ia->ia_sockmask.sin_len = 8;
    446 			ia->ia_sockmask.sin_family = AF_INET;
    447 			if (ifp->if_flags & IFF_BROADCAST) {
    448 				ia->ia_broadaddr.sin_len = sizeof(ia->ia_addr);
    449 				ia->ia_broadaddr.sin_family = AF_INET;
    450 			}
    451 			ia->ia_ifp = ifp;
    452 			ia->ia_idsalt = cprng_fast32() % 65535;
    453 			LIST_INIT(&ia->ia_multiaddrs);
    454 			newifaddr = 1;
    455 		}
    456 		break;
    457 
    458 	case SIOCSIFBRDADDR:
    459 		if (kauth_authorize_network(curlwp->l_cred, KAUTH_NETWORK_INTERFACE,
    460 		    KAUTH_REQ_NETWORK_INTERFACE_SETPRIV, ifp, (void *)cmd,
    461 		    NULL) != 0)
    462 			return (EPERM);
    463 		/* FALLTHROUGH */
    464 
    465 	case SIOCGIFADDR:
    466 	case SIOCGIFNETMASK:
    467 	case SIOCGIFDSTADDR:
    468 	case SIOCGIFBRDADDR:
    469 		if (ia == NULL)
    470 			return (EADDRNOTAVAIL);
    471 		break;
    472 	}
    473 	error = 0;
    474 	switch (cmd) {
    475 
    476 	case SIOCGIFADDR:
    477 		ifreq_setaddr(cmd, ifr, sintocsa(&ia->ia_addr));
    478 		break;
    479 
    480 	case SIOCGIFBRDADDR:
    481 		if ((ifp->if_flags & IFF_BROADCAST) == 0)
    482 			return (EINVAL);
    483 		ifreq_setdstaddr(cmd, ifr, sintocsa(&ia->ia_broadaddr));
    484 		break;
    485 
    486 	case SIOCGIFDSTADDR:
    487 		if ((ifp->if_flags & IFF_POINTOPOINT) == 0)
    488 			return (EINVAL);
    489 		ifreq_setdstaddr(cmd, ifr, sintocsa(&ia->ia_dstaddr));
    490 		break;
    491 
    492 	case SIOCGIFNETMASK:
    493 		/*
    494 		 * We keep the number of trailing zero bytes the sin_len field
    495 		 * of ia_sockmask, so we fix this before we pass it back to
    496 		 * userland.
    497 		 */
    498 		oldaddr = ia->ia_sockmask;
    499 		oldaddr.sin_len = sizeof(struct sockaddr_in);
    500 		ifreq_setaddr(cmd, ifr, (const void *)&oldaddr);
    501 		break;
    502 
    503 	case SIOCSIFDSTADDR:
    504 		if ((ifp->if_flags & IFF_POINTOPOINT) == 0)
    505 			return (EINVAL);
    506 		oldaddr = ia->ia_dstaddr;
    507 		ia->ia_dstaddr = *satocsin(ifreq_getdstaddr(cmd, ifr));
    508 		if ((error = if_addr_init(ifp, &ia->ia_ifa, false)) != 0) {
    509 			ia->ia_dstaddr = oldaddr;
    510 			return error;
    511 		}
    512 		if (ia->ia_flags & IFA_ROUTE) {
    513 			ia->ia_ifa.ifa_dstaddr = sintosa(&oldaddr);
    514 			rtinit(&ia->ia_ifa, RTM_DELETE, RTF_HOST);
    515 			ia->ia_ifa.ifa_dstaddr = sintosa(&ia->ia_dstaddr);
    516 			rtinit(&ia->ia_ifa, RTM_ADD, RTF_HOST|RTF_UP);
    517 		}
    518 		break;
    519 
    520 	case SIOCSIFBRDADDR:
    521 		if ((ifp->if_flags & IFF_BROADCAST) == 0)
    522 			return EINVAL;
    523 		ia->ia_broadaddr = *satocsin(ifreq_getbroadaddr(cmd, ifr));
    524 		break;
    525 
    526 	case SIOCSIFADDR:
    527 		error = in_ifinit(ifp, ia, satocsin(ifreq_getaddr(cmd, ifr)),
    528 		    1, hostIsNew);
    529 		if (error == 0) {
    530 			(void)pfil_run_hooks(if_pfil,
    531 			    (struct mbuf **)SIOCSIFADDR, ifp, PFIL_IFADDR);
    532 		}
    533 		break;
    534 
    535 	case SIOCSIFNETMASK:
    536 		in_ifscrub(ifp, ia);
    537 		ia->ia_sockmask = *satocsin(ifreq_getaddr(cmd, ifr));
    538 		ia->ia_subnetmask = ia->ia_sockmask.sin_addr.s_addr;
    539 		error = in_ifinit(ifp, ia, NULL, 0, 0);
    540 		break;
    541 
    542 	case SIOCAIFADDR:
    543 		maskIsNew = 0;
    544 		if (ifra->ifra_mask.sin_len) {
    545 			/* Only scrub if we control the prefix route,
    546 			 * otherwise userland gets a bogus message */
    547 			if ((ia->ia_flags & IFA_ROUTE))
    548 				in_ifscrub(ifp, ia);
    549 			ia->ia_sockmask = ifra->ifra_mask;
    550 			ia->ia_subnetmask = ia->ia_sockmask.sin_addr.s_addr;
    551 			maskIsNew = 1;
    552 		}
    553 		if ((ifp->if_flags & IFF_POINTOPOINT) &&
    554 		    (ifra->ifra_dstaddr.sin_family == AF_INET)) {
    555 			/* Only scrub if we control the prefix route,
    556 			 * otherwise userland gets a bogus message */
    557 			if ((ia->ia_flags & IFA_ROUTE))
    558 				in_ifscrub(ifp, ia);
    559 			ia->ia_dstaddr = ifra->ifra_dstaddr;
    560 			maskIsNew  = 1; /* We lie; but the effect's the same */
    561 		}
    562 		if (ifra->ifra_addr.sin_family == AF_INET &&
    563 		    (hostIsNew || maskIsNew)) {
    564 			error = in_ifinit(ifp, ia, &ifra->ifra_addr, 0,
    565 			    hostIsNew);
    566 		}
    567 		if ((ifp->if_flags & IFF_BROADCAST) &&
    568 		    (ifra->ifra_broadaddr.sin_family == AF_INET))
    569 			ia->ia_broadaddr = ifra->ifra_broadaddr;
    570 		if (error == 0)
    571 			(void)pfil_run_hooks(if_pfil,
    572 			    (struct mbuf **)SIOCAIFADDR, ifp, PFIL_IFADDR);
    573 		break;
    574 
    575 	case SIOCGIFALIAS:
    576 		ifra->ifra_mask = ia->ia_sockmask;
    577 		if ((ifp->if_flags & IFF_POINTOPOINT) &&
    578 		    (ia->ia_dstaddr.sin_family == AF_INET))
    579 			ifra->ifra_dstaddr = ia->ia_dstaddr;
    580 		else if ((ifp->if_flags & IFF_BROADCAST) &&
    581 		    (ia->ia_broadaddr.sin_family == AF_INET))
    582 			ifra->ifra_broadaddr = ia->ia_broadaddr;
    583 		else
    584 			memset(&ifra->ifra_broadaddr, 0,
    585 			      sizeof(ifra->ifra_broadaddr));
    586 		break;
    587 
    588 	case SIOCGIFAFLAG_IN:
    589 		ifr->ifr_addrflags = ia->ia4_flags;
    590 		break;
    591 
    592 	case SIOCDIFADDR:
    593 		in_purgeaddr(&ia->ia_ifa);
    594 		(void)pfil_run_hooks(if_pfil, (struct mbuf **)SIOCDIFADDR,
    595 		    ifp, PFIL_IFADDR);
    596 		break;
    597 
    598 #ifdef MROUTING
    599 	case SIOCGETVIFCNT:
    600 	case SIOCGETSGCNT:
    601 		error = mrt_ioctl(so, cmd, data);
    602 		break;
    603 #endif /* MROUTING */
    604 
    605 	default:
    606 		return ENOTTY;
    607 	}
    608 
    609 	if (error != 0 && newifaddr) {
    610 		KASSERT(ia != NULL);
    611 		in_purgeaddr(&ia->ia_ifa);
    612 	}
    613 
    614 	return error;
    615 }
    616 
    617 /* Add ownaddr as loopback rtentry. */
    618 static void
    619 in_ifaddlocal(struct ifaddr *ifa)
    620 {
    621 	struct in_ifaddr *ia;
    622 
    623 	ia = (struct in_ifaddr *)ifa;
    624 	if (ia->ia_addr.sin_addr.s_addr == INADDR_ANY ||
    625 	    (ia->ia_ifp->if_flags & IFF_POINTOPOINT &&
    626 	    in_hosteq(ia->ia_dstaddr.sin_addr, ia->ia_addr.sin_addr)))
    627 	{
    628 		rt_newaddrmsg(RTM_NEWADDR, ifa, 0, NULL);
    629 		return;
    630 	}
    631 
    632 	rt_ifa_addlocal(ifa);
    633 }
    634 
    635 /* Rempve loopback entry of ownaddr */
    636 static void
    637 in_ifremlocal(struct ifaddr *ifa)
    638 {
    639 	struct in_ifaddr *ia, *p;
    640 	struct ifaddr *alt_ifa = NULL;
    641 	int ia_count = 0;
    642 
    643 	ia = (struct in_ifaddr *)ifa;
    644 	/* Delete the entry if exactly one ifaddr matches the
    645 	 * address, ifa->ifa_addr. */
    646 	TAILQ_FOREACH(p, &in_ifaddrhead, ia_list) {
    647 		if (!in_hosteq(p->ia_addr.sin_addr, ia->ia_addr.sin_addr))
    648 			continue;
    649 		if (p->ia_ifp != ia->ia_ifp)
    650 			alt_ifa = &p->ia_ifa;
    651 		if (++ia_count > 1 && alt_ifa != NULL)
    652 			break;
    653 	}
    654 
    655 	if (ia_count == 0)
    656 		return;
    657 
    658 	rt_ifa_remlocal(ifa, ia_count == 1 ? NULL : alt_ifa);
    659 }
    660 
    661 void
    662 in_purgeaddr(struct ifaddr *ifa)
    663 {
    664 	struct ifnet *ifp = ifa->ifa_ifp;
    665 	struct in_ifaddr *ia = (void *) ifa;
    666 
    667 	/* stop DAD processing */
    668 	if (ia->ia_dad_stop != NULL)
    669 		ia->ia_dad_stop(ifa);
    670 
    671 	in_ifscrub(ifp, ia);
    672 	in_ifremlocal(ifa);
    673 	LIST_REMOVE(ia, ia_hash);
    674 	ifa_remove(ifp, &ia->ia_ifa);
    675 	TAILQ_REMOVE(&in_ifaddrhead, ia, ia_list);
    676 	if (ia->ia_allhosts != NULL)
    677 		in_delmulti(ia->ia_allhosts);
    678 	ifafree(&ia->ia_ifa);
    679 	in_setmaxmtu();
    680 }
    681 
    682 void
    683 in_purgeif(struct ifnet *ifp)		/* MUST be called at splsoftnet() */
    684 {
    685 	if_purgeaddrs(ifp, AF_INET, in_purgeaddr);
    686 	igmp_purgeif(ifp);		/* manipulates pools */
    687 #ifdef MROUTING
    688 	ip_mrouter_detach(ifp);
    689 #endif
    690 }
    691 
    692 /*
    693  * SIOC[GAD]LIFADDR.
    694  *	SIOCGLIFADDR: get first address. (???)
    695  *	SIOCGLIFADDR with IFLR_PREFIX:
    696  *		get first address that matches the specified prefix.
    697  *	SIOCALIFADDR: add the specified address.
    698  *	SIOCALIFADDR with IFLR_PREFIX:
    699  *		EINVAL since we can't deduce hostid part of the address.
    700  *	SIOCDLIFADDR: delete the specified address.
    701  *	SIOCDLIFADDR with IFLR_PREFIX:
    702  *		delete the first address that matches the specified prefix.
    703  * return values:
    704  *	EINVAL on invalid parameters
    705  *	EADDRNOTAVAIL on prefix match failed/specified address not found
    706  *	other values may be returned from in_ioctl()
    707  */
    708 static int
    709 in_lifaddr_ioctl(struct socket *so, u_long cmd, void *data,
    710     struct ifnet *ifp)
    711 {
    712 	struct if_laddrreq *iflr = (struct if_laddrreq *)data;
    713 	struct ifaddr *ifa;
    714 	struct sockaddr *sa;
    715 
    716 	/* sanity checks */
    717 	if (data == NULL || ifp == NULL) {
    718 		panic("invalid argument to in_lifaddr_ioctl");
    719 		/*NOTRECHED*/
    720 	}
    721 
    722 	switch (cmd) {
    723 	case SIOCGLIFADDR:
    724 		/* address must be specified on GET with IFLR_PREFIX */
    725 		if ((iflr->flags & IFLR_PREFIX) == 0)
    726 			break;
    727 		/*FALLTHROUGH*/
    728 	case SIOCALIFADDR:
    729 	case SIOCDLIFADDR:
    730 		/* address must be specified on ADD and DELETE */
    731 		sa = (struct sockaddr *)&iflr->addr;
    732 		if (sa->sa_family != AF_INET)
    733 			return EINVAL;
    734 		if (sa->sa_len != sizeof(struct sockaddr_in))
    735 			return EINVAL;
    736 		/* XXX need improvement */
    737 		sa = (struct sockaddr *)&iflr->dstaddr;
    738 		if (sa->sa_family != AF_UNSPEC && sa->sa_family != AF_INET)
    739 			return EINVAL;
    740 		if (sa->sa_len != 0 && sa->sa_len != sizeof(struct sockaddr_in))
    741 			return EINVAL;
    742 		break;
    743 	default: /*shouldn't happen*/
    744 #if 0
    745 		panic("invalid cmd to in_lifaddr_ioctl");
    746 		/*NOTREACHED*/
    747 #else
    748 		return EOPNOTSUPP;
    749 #endif
    750 	}
    751 	if (sizeof(struct in_addr) * NBBY < iflr->prefixlen)
    752 		return EINVAL;
    753 
    754 	switch (cmd) {
    755 	case SIOCALIFADDR:
    756 	    {
    757 		struct in_aliasreq ifra;
    758 
    759 		if (iflr->flags & IFLR_PREFIX)
    760 			return EINVAL;
    761 
    762 		/* copy args to in_aliasreq, perform ioctl(SIOCAIFADDR). */
    763 		memset(&ifra, 0, sizeof(ifra));
    764 		memcpy(ifra.ifra_name, iflr->iflr_name,
    765 			sizeof(ifra.ifra_name));
    766 
    767 		memcpy(&ifra.ifra_addr, &iflr->addr,
    768 			((struct sockaddr *)&iflr->addr)->sa_len);
    769 
    770 		if (((struct sockaddr *)&iflr->dstaddr)->sa_family) {	/*XXX*/
    771 			memcpy(&ifra.ifra_dstaddr, &iflr->dstaddr,
    772 				((struct sockaddr *)&iflr->dstaddr)->sa_len);
    773 		}
    774 
    775 		ifra.ifra_mask.sin_family = AF_INET;
    776 		ifra.ifra_mask.sin_len = sizeof(struct sockaddr_in);
    777 		in_len2mask(&ifra.ifra_mask.sin_addr, iflr->prefixlen);
    778 
    779 		return in_control(so, SIOCAIFADDR, &ifra, ifp);
    780 	    }
    781 	case SIOCGLIFADDR:
    782 	case SIOCDLIFADDR:
    783 	    {
    784 		struct in_ifaddr *ia;
    785 		struct in_addr mask, candidate, match;
    786 		struct sockaddr_in *sin;
    787 		int cmp;
    788 
    789 		memset(&mask, 0, sizeof(mask));
    790 		memset(&match, 0, sizeof(match));	/* XXX gcc */
    791 		if (iflr->flags & IFLR_PREFIX) {
    792 			/* lookup a prefix rather than address. */
    793 			in_len2mask(&mask, iflr->prefixlen);
    794 
    795 			sin = (struct sockaddr_in *)&iflr->addr;
    796 			match.s_addr = sin->sin_addr.s_addr;
    797 			match.s_addr &= mask.s_addr;
    798 
    799 			/* if you set extra bits, that's wrong */
    800 			if (match.s_addr != sin->sin_addr.s_addr)
    801 				return EINVAL;
    802 
    803 			cmp = 1;
    804 		} else {
    805 			if (cmd == SIOCGLIFADDR) {
    806 				/* on getting an address, take the 1st match */
    807 				cmp = 0;	/*XXX*/
    808 			} else {
    809 				/* on deleting an address, do exact match */
    810 				in_len2mask(&mask, 32);
    811 				sin = (struct sockaddr_in *)&iflr->addr;
    812 				match.s_addr = sin->sin_addr.s_addr;
    813 
    814 				cmp = 1;
    815 			}
    816 		}
    817 
    818 		IFADDR_FOREACH(ifa, ifp) {
    819 			if (ifa->ifa_addr->sa_family != AF_INET)
    820 				continue;
    821 			if (cmp == 0)
    822 				break;
    823 			candidate.s_addr = ((struct sockaddr_in *)ifa->ifa_addr)->sin_addr.s_addr;
    824 			candidate.s_addr &= mask.s_addr;
    825 			if (candidate.s_addr == match.s_addr)
    826 				break;
    827 		}
    828 		if (ifa == NULL)
    829 			return EADDRNOTAVAIL;
    830 		ia = (struct in_ifaddr *)ifa;
    831 
    832 		if (cmd == SIOCGLIFADDR) {
    833 			/* fill in the if_laddrreq structure */
    834 			memcpy(&iflr->addr, &ia->ia_addr, ia->ia_addr.sin_len);
    835 
    836 			if ((ifp->if_flags & IFF_POINTOPOINT) != 0) {
    837 				memcpy(&iflr->dstaddr, &ia->ia_dstaddr,
    838 					ia->ia_dstaddr.sin_len);
    839 			} else
    840 				memset(&iflr->dstaddr, 0, sizeof(iflr->dstaddr));
    841 
    842 			iflr->prefixlen =
    843 				in_mask2len(&ia->ia_sockmask.sin_addr);
    844 
    845 			iflr->flags = 0;	/*XXX*/
    846 
    847 			return 0;
    848 		} else {
    849 			struct in_aliasreq ifra;
    850 
    851 			/* fill in_aliasreq and do ioctl(SIOCDIFADDR) */
    852 			memset(&ifra, 0, sizeof(ifra));
    853 			memcpy(ifra.ifra_name, iflr->iflr_name,
    854 				sizeof(ifra.ifra_name));
    855 
    856 			memcpy(&ifra.ifra_addr, &ia->ia_addr,
    857 				ia->ia_addr.sin_len);
    858 			if ((ifp->if_flags & IFF_POINTOPOINT) != 0) {
    859 				memcpy(&ifra.ifra_dstaddr, &ia->ia_dstaddr,
    860 					ia->ia_dstaddr.sin_len);
    861 			}
    862 			memcpy(&ifra.ifra_dstaddr, &ia->ia_sockmask,
    863 				ia->ia_sockmask.sin_len);
    864 
    865 			return in_control(so, SIOCDIFADDR, &ifra, ifp);
    866 		}
    867 	    }
    868 	}
    869 
    870 	return EOPNOTSUPP;	/*just for safety*/
    871 }
    872 
    873 /*
    874  * Delete any existing route for an interface.
    875  */
    876 void
    877 in_ifscrub(struct ifnet *ifp, struct in_ifaddr *ia)
    878 {
    879 
    880 	in_scrubprefix(ia);
    881 }
    882 
    883 /*
    884  * Initialize an interface's internet address
    885  * and routing table entry.
    886  */
    887 int
    888 in_ifinit(struct ifnet *ifp, struct in_ifaddr *ia,
    889     const struct sockaddr_in *sin, int scrub, int hostIsNew)
    890 {
    891 	u_int32_t i;
    892 	struct sockaddr_in oldaddr;
    893 	int s = splnet(), flags = RTF_UP, error;
    894 
    895 	if (sin == NULL)
    896 		sin = &ia->ia_addr;
    897 
    898 	/*
    899 	 * Set up new addresses.
    900 	 */
    901 	oldaddr = ia->ia_addr;
    902 	if (ia->ia_addr.sin_family == AF_INET)
    903 		LIST_REMOVE(ia, ia_hash);
    904 	ia->ia_addr = *sin;
    905 	LIST_INSERT_HEAD(&IN_IFADDR_HASH(ia->ia_addr.sin_addr.s_addr), ia, ia_hash);
    906 
    907 	/* Set IN_IFF flags early for if_addr_init() */
    908 	if (hostIsNew && if_do_dad(ifp) && !in_nullhost(ia->ia_addr.sin_addr)) {
    909 		if (ifp->if_link_state == LINK_STATE_DOWN)
    910 			ia->ia4_flags |= IN_IFF_DETACHED;
    911 		else
    912 			/* State the intent to try DAD if possible */
    913 			ia->ia4_flags |= IN_IFF_TRYTENTATIVE;
    914 	}
    915 
    916 	/*
    917 	 * Give the interface a chance to initialize
    918 	 * if this is its first address,
    919 	 * and to validate the address if necessary.
    920 	 */
    921 	if ((error = if_addr_init(ifp, &ia->ia_ifa, true)) != 0)
    922 		goto bad;
    923 	/* Now clear the try tentative flag, it's job is done. */
    924 	ia->ia4_flags &= ~IN_IFF_TRYTENTATIVE;
    925 	splx(s);
    926 
    927 	if (scrub) {
    928 		ia->ia_ifa.ifa_addr = sintosa(&oldaddr);
    929 		in_ifscrub(ifp, ia);
    930 		ia->ia_ifa.ifa_addr = sintosa(&ia->ia_addr);
    931 	}
    932 
    933 	/* Add the local route to the address */
    934 	in_ifaddlocal(&ia->ia_ifa);
    935 
    936 	i = ia->ia_addr.sin_addr.s_addr;
    937 	if (IN_CLASSA(i))
    938 		ia->ia_netmask = IN_CLASSA_NET;
    939 	else if (IN_CLASSB(i))
    940 		ia->ia_netmask = IN_CLASSB_NET;
    941 	else
    942 		ia->ia_netmask = IN_CLASSC_NET;
    943 	/*
    944 	 * The subnet mask usually includes at least the standard network part,
    945 	 * but may may be smaller in the case of supernetting.
    946 	 * If it is set, we believe it.
    947 	 */
    948 	if (ia->ia_subnetmask == 0) {
    949 		ia->ia_subnetmask = ia->ia_netmask;
    950 		ia->ia_sockmask.sin_addr.s_addr = ia->ia_subnetmask;
    951 	} else
    952 		ia->ia_netmask &= ia->ia_subnetmask;
    953 
    954 	ia->ia_net = i & ia->ia_netmask;
    955 	ia->ia_subnet = i & ia->ia_subnetmask;
    956 	in_socktrim(&ia->ia_sockmask);
    957 	/* re-calculate the "in_maxmtu" value */
    958 	in_setmaxmtu();
    959 	/*
    960 	 * Add route for the network.
    961 	 */
    962 	ia->ia_ifa.ifa_metric = ifp->if_metric;
    963 	if (ifp->if_flags & IFF_BROADCAST) {
    964 		ia->ia_broadaddr.sin_addr.s_addr =
    965 			ia->ia_subnet | ~ia->ia_subnetmask;
    966 		ia->ia_netbroadcast.s_addr =
    967 			ia->ia_net | ~ia->ia_netmask;
    968 	} else if (ifp->if_flags & IFF_LOOPBACK) {
    969 		ia->ia_dstaddr = ia->ia_addr;
    970 		flags |= RTF_HOST;
    971 	} else if (ifp->if_flags & IFF_POINTOPOINT) {
    972 		if (ia->ia_dstaddr.sin_family != AF_INET)
    973 			return (0);
    974 		flags |= RTF_HOST;
    975 	}
    976 	error = in_addprefix(ia, flags);
    977 	/*
    978 	 * If the interface supports multicast, join the "all hosts"
    979 	 * multicast group on that interface.
    980 	 */
    981 	if ((ifp->if_flags & IFF_MULTICAST) != 0 && ia->ia_allhosts == NULL) {
    982 		struct in_addr addr;
    983 
    984 		addr.s_addr = INADDR_ALLHOSTS_GROUP;
    985 		ia->ia_allhosts = in_addmulti(&addr, ifp);
    986 	}
    987 
    988 	if (hostIsNew && if_do_dad(ifp) &&
    989 	    !in_nullhost(ia->ia_addr.sin_addr) &&
    990 	    ia->ia4_flags & IN_IFF_TENTATIVE)
    991 		ia->ia_dad_start((struct ifaddr *)ia);
    992 
    993 	return (error);
    994 bad:
    995 	splx(s);
    996 	LIST_REMOVE(ia, ia_hash);
    997 	ia->ia_addr = oldaddr;
    998 	if (ia->ia_addr.sin_family == AF_INET)
    999 		LIST_INSERT_HEAD(&IN_IFADDR_HASH(ia->ia_addr.sin_addr.s_addr),
   1000 		    ia, ia_hash);
   1001 	return (error);
   1002 }
   1003 
   1004 #define rtinitflags(x) \
   1005 	((((x)->ia_ifp->if_flags & (IFF_LOOPBACK | IFF_POINTOPOINT)) != 0) \
   1006 	    ? RTF_HOST : 0)
   1007 
   1008 /*
   1009  * add a route to prefix ("connected route" in cisco terminology).
   1010  * does nothing if there's some interface address with the same prefix already.
   1011  */
   1012 static int
   1013 in_addprefix(struct in_ifaddr *target, int flags)
   1014 {
   1015 	struct in_ifaddr *ia;
   1016 	struct in_addr prefix, mask, p;
   1017 	int error;
   1018 
   1019 	if ((flags & RTF_HOST) != 0)
   1020 		prefix = target->ia_dstaddr.sin_addr;
   1021 	else {
   1022 		prefix = target->ia_addr.sin_addr;
   1023 		mask = target->ia_sockmask.sin_addr;
   1024 		prefix.s_addr &= mask.s_addr;
   1025 	}
   1026 
   1027 	TAILQ_FOREACH(ia, &in_ifaddrhead, ia_list) {
   1028 		if (rtinitflags(ia))
   1029 			p = ia->ia_dstaddr.sin_addr;
   1030 		else {
   1031 			p = ia->ia_addr.sin_addr;
   1032 			p.s_addr &= ia->ia_sockmask.sin_addr.s_addr;
   1033 		}
   1034 
   1035 		if (prefix.s_addr != p.s_addr)
   1036 			continue;
   1037 
   1038 		/*
   1039 		 * if we got a matching prefix route inserted by other
   1040 		 * interface address, we don't need to bother
   1041 		 *
   1042 		 * XXX RADIX_MPATH implications here? -dyoung
   1043 		 */
   1044 		if (ia->ia_flags & IFA_ROUTE)
   1045 			return 0;
   1046 	}
   1047 
   1048 	/*
   1049 	 * noone seem to have prefix route.  insert it.
   1050 	 */
   1051 	error = rtinit(&target->ia_ifa, RTM_ADD, flags);
   1052 	if (error == 0)
   1053 		target->ia_flags |= IFA_ROUTE;
   1054 	else if (error == EEXIST) {
   1055 		/*
   1056 		 * the fact the route already exists is not an error.
   1057 		 */
   1058 		error = 0;
   1059 	}
   1060 	return error;
   1061 }
   1062 
   1063 /*
   1064  * remove a route to prefix ("connected route" in cisco terminology).
   1065  * re-installs the route by using another interface address, if there's one
   1066  * with the same prefix (otherwise we lose the route mistakenly).
   1067  */
   1068 static int
   1069 in_scrubprefix(struct in_ifaddr *target)
   1070 {
   1071 	struct in_ifaddr *ia;
   1072 	struct in_addr prefix, mask, p;
   1073 	int error;
   1074 
   1075 	/* If we don't have IFA_ROUTE we should still inform userland */
   1076 	if ((target->ia_flags & IFA_ROUTE) == 0)
   1077 		return 0;
   1078 
   1079 	if (rtinitflags(target))
   1080 		prefix = target->ia_dstaddr.sin_addr;
   1081 	else {
   1082 		prefix = target->ia_addr.sin_addr;
   1083 		mask = target->ia_sockmask.sin_addr;
   1084 		prefix.s_addr &= mask.s_addr;
   1085 	}
   1086 
   1087 	TAILQ_FOREACH(ia, &in_ifaddrhead, ia_list) {
   1088 		if (rtinitflags(ia))
   1089 			p = ia->ia_dstaddr.sin_addr;
   1090 		else {
   1091 			p = ia->ia_addr.sin_addr;
   1092 			p.s_addr &= ia->ia_sockmask.sin_addr.s_addr;
   1093 		}
   1094 
   1095 		if (prefix.s_addr != p.s_addr)
   1096 			continue;
   1097 
   1098 		/*
   1099 		 * if we got a matching prefix route, move IFA_ROUTE to him
   1100 		 */
   1101 		if ((ia->ia_flags & IFA_ROUTE) == 0) {
   1102 			rtinit(&target->ia_ifa, RTM_DELETE,
   1103 			    rtinitflags(target));
   1104 			target->ia_flags &= ~IFA_ROUTE;
   1105 
   1106 			error = rtinit(&ia->ia_ifa, RTM_ADD,
   1107 			    rtinitflags(ia) | RTF_UP);
   1108 			if (error == 0)
   1109 				ia->ia_flags |= IFA_ROUTE;
   1110 			return error;
   1111 		}
   1112 	}
   1113 
   1114 	/*
   1115 	 * noone seem to have prefix route.  remove it.
   1116 	 */
   1117 	rtinit(&target->ia_ifa, RTM_DELETE, rtinitflags(target));
   1118 	target->ia_flags &= ~IFA_ROUTE;
   1119 	return 0;
   1120 }
   1121 
   1122 #undef rtinitflags
   1123 
   1124 /*
   1125  * Return 1 if the address might be a local broadcast address.
   1126  */
   1127 int
   1128 in_broadcast(struct in_addr in, struct ifnet *ifp)
   1129 {
   1130 	struct ifaddr *ifa;
   1131 
   1132 	if (in.s_addr == INADDR_BROADCAST ||
   1133 	    in_nullhost(in))
   1134 		return 1;
   1135 	if ((ifp->if_flags & IFF_BROADCAST) == 0)
   1136 		return 0;
   1137 	/*
   1138 	 * Look through the list of addresses for a match
   1139 	 * with a broadcast address.
   1140 	 */
   1141 #define ia (ifatoia(ifa))
   1142 	IFADDR_FOREACH(ifa, ifp)
   1143 		if (ifa->ifa_addr->sa_family == AF_INET &&
   1144 		    !in_hosteq(in, ia->ia_addr.sin_addr) &&
   1145 		    (in_hosteq(in, ia->ia_broadaddr.sin_addr) ||
   1146 		     in_hosteq(in, ia->ia_netbroadcast) ||
   1147 		     (hostzeroisbroadcast &&
   1148 		      /*
   1149 		       * Check for old-style (host 0) broadcast.
   1150 		       */
   1151 		      (in.s_addr == ia->ia_subnet ||
   1152 		       in.s_addr == ia->ia_net))))
   1153 			return 1;
   1154 	return (0);
   1155 #undef ia
   1156 }
   1157 
   1158 /*
   1159  * perform DAD when interface becomes IFF_UP.
   1160  */
   1161 void
   1162 in_if_link_up(struct ifnet *ifp)
   1163 {
   1164 	struct ifaddr *ifa;
   1165 	struct in_ifaddr *ia;
   1166 
   1167 	/* Ensure it's sane to run DAD */
   1168 	if (ifp->if_link_state == LINK_STATE_DOWN)
   1169 		return;
   1170 	if ((ifp->if_flags & (IFF_UP|IFF_RUNNING)) != (IFF_UP|IFF_RUNNING))
   1171 		return;
   1172 
   1173 	IFADDR_FOREACH(ifa, ifp) {
   1174 		if (ifa->ifa_addr->sa_family != AF_INET)
   1175 			continue;
   1176 		ia = (struct in_ifaddr *)ifa;
   1177 
   1178 		/* If detached then mark as tentative */
   1179 		if (ia->ia4_flags & IN_IFF_DETACHED) {
   1180 			ia->ia4_flags &= ~IN_IFF_DETACHED;
   1181 			if (if_do_dad(ifp) && ia->ia_dad_start != NULL)
   1182 				ia->ia4_flags |= IN_IFF_TENTATIVE;
   1183 			else if ((ia->ia4_flags & IN_IFF_TENTATIVE) == 0)
   1184 				rt_newaddrmsg(RTM_NEWADDR, ifa, 0, NULL);
   1185 		}
   1186 
   1187 		if (ia->ia4_flags & IN_IFF_TENTATIVE) {
   1188 			/* Clear the duplicated flag as we're starting DAD. */
   1189 			ia->ia4_flags &= ~IN_IFF_DUPLICATED;
   1190 			ia->ia_dad_start(ifa);
   1191 		}
   1192 	}
   1193 }
   1194 
   1195 void
   1196 in_if_up(struct ifnet *ifp)
   1197 {
   1198 
   1199 	/* interface may not support link state, so bring it up also */
   1200 	in_if_link_up(ifp);
   1201 }
   1202 
   1203 /*
   1204  * Mark all addresses as detached.
   1205  */
   1206 void
   1207 in_if_link_down(struct ifnet *ifp)
   1208 {
   1209 	struct ifaddr *ifa;
   1210 	struct in_ifaddr *ia;
   1211 
   1212 	IFADDR_FOREACH(ifa, ifp) {
   1213 		if (ifa->ifa_addr->sa_family != AF_INET)
   1214 			continue;
   1215 		ia = (struct in_ifaddr *)ifa;
   1216 
   1217 		/* Stop DAD processing */
   1218 		if (ia->ia_dad_stop != NULL)
   1219 			ia->ia_dad_stop(ifa);
   1220 
   1221 		/*
   1222 		 * Mark the address as detached.
   1223 		 */
   1224 		if (!(ia->ia4_flags & IN_IFF_DETACHED)) {
   1225 			ia->ia4_flags |= IN_IFF_DETACHED;
   1226 			ia->ia4_flags &=
   1227 			    ~(IN_IFF_TENTATIVE | IN_IFF_DUPLICATED);
   1228 			rt_newaddrmsg(RTM_NEWADDR, ifa, 0, NULL);
   1229 		}
   1230 	}
   1231 }
   1232 
   1233 void
   1234 in_if_down(struct ifnet *ifp)
   1235 {
   1236 
   1237 	in_if_link_down(ifp);
   1238 }
   1239 
   1240 void
   1241 in_if_link_state_change(struct ifnet *ifp, int link_state)
   1242 {
   1243 
   1244 	switch (link_state) {
   1245 	case LINK_STATE_DOWN:
   1246 		in_if_link_down(ifp);
   1247 		break;
   1248 	case LINK_STATE_UP:
   1249 		in_if_link_up(ifp);
   1250 		break;
   1251 	}
   1252 }
   1253 
   1254 /*
   1255  * in_lookup_multi: look up the in_multi record for a given IP
   1256  * multicast address on a given interface.  If no matching record is
   1257  * found, return NULL.
   1258  */
   1259 struct in_multi *
   1260 in_lookup_multi(struct in_addr addr, ifnet_t *ifp)
   1261 {
   1262 	struct in_multi *inm;
   1263 
   1264 	KASSERT(rw_lock_held(&in_multilock));
   1265 
   1266 	LIST_FOREACH(inm, &IN_MULTI_HASH(addr.s_addr, ifp), inm_list) {
   1267 		if (in_hosteq(inm->inm_addr, addr) && inm->inm_ifp == ifp)
   1268 			break;
   1269 	}
   1270 	return inm;
   1271 }
   1272 
   1273 /*
   1274  * in_multi_group: check whether the address belongs to an IP multicast
   1275  * group we are joined on this interface.  Returns true or false.
   1276  */
   1277 bool
   1278 in_multi_group(struct in_addr addr, ifnet_t *ifp, int flags)
   1279 {
   1280 	bool ingroup;
   1281 
   1282 	if (__predict_true(flags & IP_IGMP_MCAST) == 0) {
   1283 		rw_enter(&in_multilock, RW_READER);
   1284 		ingroup = in_lookup_multi(addr, ifp) != NULL;
   1285 		rw_exit(&in_multilock);
   1286 	} else {
   1287 		/* XXX Recursive call from ip_output(). */
   1288 		KASSERT(rw_lock_held(&in_multilock));
   1289 		ingroup = in_lookup_multi(addr, ifp) != NULL;
   1290 	}
   1291 	return ingroup;
   1292 }
   1293 
   1294 /*
   1295  * Add an address to the list of IP multicast addresses for a given interface.
   1296  */
   1297 struct in_multi *
   1298 in_addmulti(struct in_addr *ap, ifnet_t *ifp)
   1299 {
   1300 	struct sockaddr_in sin;
   1301 	struct in_multi *inm;
   1302 
   1303 	/*
   1304 	 * See if address already in list.
   1305 	 */
   1306 	rw_enter(&in_multilock, RW_WRITER);
   1307 	inm = in_lookup_multi(*ap, ifp);
   1308 	if (inm != NULL) {
   1309 		/*
   1310 		 * Found it; just increment the reference count.
   1311 		 */
   1312 		inm->inm_refcount++;
   1313 		rw_exit(&in_multilock);
   1314 		return inm;
   1315 	}
   1316 
   1317 	/*
   1318 	 * New address; allocate a new multicast record.
   1319 	 */
   1320 	inm = pool_get(&inmulti_pool, PR_NOWAIT);
   1321 	if (inm == NULL) {
   1322 		rw_exit(&in_multilock);
   1323 		return NULL;
   1324 	}
   1325 	inm->inm_addr = *ap;
   1326 	inm->inm_ifp = ifp;
   1327 	inm->inm_refcount = 1;
   1328 
   1329 	/*
   1330 	 * Ask the network driver to update its multicast reception
   1331 	 * filter appropriately for the new address.
   1332 	 */
   1333 	sockaddr_in_init(&sin, ap, 0);
   1334 	if (if_mcast_op(ifp, SIOCADDMULTI, sintosa(&sin)) != 0) {
   1335 		rw_exit(&in_multilock);
   1336 		pool_put(&inmulti_pool, inm);
   1337 		return NULL;
   1338 	}
   1339 
   1340 	/*
   1341 	 * Let IGMP know that we have joined a new IP multicast group.
   1342 	 */
   1343 	if (igmp_joingroup(inm) != 0) {
   1344 		rw_exit(&in_multilock);
   1345 		pool_put(&inmulti_pool, inm);
   1346 		return NULL;
   1347 	}
   1348 	LIST_INSERT_HEAD(
   1349 	    &IN_MULTI_HASH(inm->inm_addr.s_addr, ifp),
   1350 	    inm, inm_list);
   1351 	in_multientries++;
   1352 	rw_exit(&in_multilock);
   1353 
   1354 	return inm;
   1355 }
   1356 
   1357 /*
   1358  * Delete a multicast address record.
   1359  */
   1360 void
   1361 in_delmulti(struct in_multi *inm)
   1362 {
   1363 	struct sockaddr_in sin;
   1364 
   1365 	rw_enter(&in_multilock, RW_WRITER);
   1366 	if (--inm->inm_refcount > 0) {
   1367 		rw_exit(&in_multilock);
   1368 		return;
   1369 	}
   1370 
   1371 	/*
   1372 	 * No remaining claims to this record; let IGMP know that
   1373 	 * we are leaving the multicast group.
   1374 	 */
   1375 	igmp_leavegroup(inm);
   1376 
   1377 	/*
   1378 	 * Notify the network driver to update its multicast reception
   1379 	 * filter.
   1380 	 */
   1381 	sockaddr_in_init(&sin, &inm->inm_addr, 0);
   1382 	if_mcast_op(inm->inm_ifp, SIOCDELMULTI, sintosa(&sin));
   1383 
   1384 	/*
   1385 	 * Unlink from list.
   1386 	 */
   1387 	LIST_REMOVE(inm, inm_list);
   1388 	in_multientries--;
   1389 	rw_exit(&in_multilock);
   1390 
   1391 	pool_put(&inmulti_pool, inm);
   1392 }
   1393 
   1394 /*
   1395  * in_next_multi: step through all of the in_multi records, one at a time.
   1396  * The current position is remembered in "step", which the caller must
   1397  * provide.  in_first_multi(), below, must be called to initialize "step"
   1398  * and get the first record.  Both macros return a NULL "inm" when there
   1399  * are no remaining records.
   1400  */
   1401 struct in_multi *
   1402 in_next_multi(struct in_multistep *step)
   1403 {
   1404 	struct in_multi *inm;
   1405 
   1406 	KASSERT(rw_lock_held(&in_multilock));
   1407 
   1408 	while (step->i_inm == NULL && step->i_n < IN_MULTI_HASH_SIZE) {
   1409 		step->i_inm = LIST_FIRST(&in_multihashtbl[++step->i_n]);
   1410 	}
   1411 	if ((inm = step->i_inm) != NULL) {
   1412 		step->i_inm = LIST_NEXT(inm, inm_list);
   1413 	}
   1414 	return inm;
   1415 }
   1416 
   1417 struct in_multi *
   1418 in_first_multi(struct in_multistep *step)
   1419 {
   1420 	KASSERT(rw_lock_held(&in_multilock));
   1421 
   1422 	step->i_n = 0;
   1423 	step->i_inm = LIST_FIRST(&in_multihashtbl[0]);
   1424 	return in_next_multi(step);
   1425 }
   1426 
   1427 void
   1428 in_multi_lock(int op)
   1429 {
   1430 	rw_enter(&in_multilock, op);
   1431 }
   1432 
   1433 void
   1434 in_multi_unlock(void)
   1435 {
   1436 	rw_exit(&in_multilock);
   1437 }
   1438 
   1439 int
   1440 in_multi_lock_held(void)
   1441 {
   1442 	return rw_lock_held(&in_multilock);
   1443 }
   1444 
   1445 struct sockaddr_in *
   1446 in_selectsrc(struct sockaddr_in *sin, struct route *ro,
   1447     int soopts, struct ip_moptions *mopts, int *errorp)
   1448 {
   1449 	struct rtentry *rt = NULL;
   1450 	struct in_ifaddr *ia = NULL;
   1451 
   1452 	/*
   1453          * If route is known or can be allocated now, take the
   1454          * source address from the interface.  Otherwise, punt.
   1455 	 */
   1456 	if ((soopts & SO_DONTROUTE) != 0)
   1457 		rtcache_free(ro);
   1458 	else {
   1459 		union {
   1460 			struct sockaddr		dst;
   1461 			struct sockaddr_in	dst4;
   1462 		} u;
   1463 
   1464 		sockaddr_in_init(&u.dst4, &sin->sin_addr, 0);
   1465 		rt = rtcache_lookup(ro, &u.dst);
   1466 	}
   1467 	/*
   1468 	 * If we found a route, use the address
   1469 	 * corresponding to the outgoing interface
   1470 	 * unless it is the loopback (in case a route
   1471 	 * to our address on another net goes to loopback).
   1472 	 *
   1473 	 * XXX Is this still true?  Do we care?
   1474 	 */
   1475 	if (rt != NULL && (rt->rt_ifp->if_flags & IFF_LOOPBACK) == 0)
   1476 		ia = ifatoia(rt->rt_ifa);
   1477 	if (ia == NULL) {
   1478 		u_int16_t fport = sin->sin_port;
   1479 
   1480 		sin->sin_port = 0;
   1481 		ia = ifatoia(ifa_ifwithladdr(sintosa(sin)));
   1482 		sin->sin_port = fport;
   1483 		if (ia == NULL) {
   1484 			/* Find 1st non-loopback AF_INET address */
   1485 			TAILQ_FOREACH(ia, &in_ifaddrhead, ia_list) {
   1486 				if (!(ia->ia_ifp->if_flags & IFF_LOOPBACK))
   1487 					break;
   1488 			}
   1489 		}
   1490 		if (ia == NULL) {
   1491 			*errorp = EADDRNOTAVAIL;
   1492 			return NULL;
   1493 		}
   1494 	}
   1495 	/*
   1496 	 * If the destination address is multicast and an outgoing
   1497 	 * interface has been set as a multicast option, use the
   1498 	 * address of that interface as our source address.
   1499 	 */
   1500 	if (IN_MULTICAST(sin->sin_addr.s_addr) && mopts != NULL) {
   1501 		struct ip_moptions *imo;
   1502 		struct ifnet *ifp;
   1503 
   1504 		imo = mopts;
   1505 		if (imo->imo_multicast_ifp != NULL) {
   1506 			ifp = imo->imo_multicast_ifp;
   1507 			IFP_TO_IA(ifp, ia);		/* XXX */
   1508 			if (ia == 0 || ia->ia4_flags & IN_IFF_NOTREADY) {
   1509 				*errorp = EADDRNOTAVAIL;
   1510 				return NULL;
   1511 			}
   1512 		}
   1513 	}
   1514 	if (ia->ia_ifa.ifa_getifa != NULL) {
   1515 		ia = ifatoia((*ia->ia_ifa.ifa_getifa)(&ia->ia_ifa,
   1516 		                                      sintosa(sin)));
   1517 		if (ia == NULL) {
   1518 			*errorp = EADDRNOTAVAIL;
   1519 			return NULL;
   1520 		}
   1521 	}
   1522 #ifdef GETIFA_DEBUG
   1523 	else
   1524 		printf("%s: missing ifa_getifa\n", __func__);
   1525 #endif
   1526 	return satosin(&ia->ia_addr);
   1527 }
   1528 
   1529 static void
   1530 in_sysctl_init(struct sysctllog **clog)
   1531 {
   1532 	sysctl_createv(clog, 0, NULL, NULL,
   1533 		       CTLFLAG_PERMANENT,
   1534 		       CTLTYPE_NODE, "inet",
   1535 		       SYSCTL_DESCR("PF_INET related settings"),
   1536 		       NULL, 0, NULL, 0,
   1537 		       CTL_NET, PF_INET, CTL_EOL);
   1538 	sysctl_createv(clog, 0, NULL, NULL,
   1539 		       CTLFLAG_PERMANENT,
   1540 		       CTLTYPE_NODE, "ip",
   1541 		       SYSCTL_DESCR("IPv4 related settings"),
   1542 		       NULL, 0, NULL, 0,
   1543 		       CTL_NET, PF_INET, IPPROTO_IP, CTL_EOL);
   1544 
   1545 	sysctl_createv(clog, 0, NULL, NULL,
   1546 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   1547 		       CTLTYPE_INT, "subnetsarelocal",
   1548 		       SYSCTL_DESCR("Whether logical subnets are considered "
   1549 				    "local"),
   1550 		       NULL, 0, &subnetsarelocal, 0,
   1551 		       CTL_NET, PF_INET, IPPROTO_IP,
   1552 		       IPCTL_SUBNETSARELOCAL, CTL_EOL);
   1553 	sysctl_createv(clog, 0, NULL, NULL,
   1554 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   1555 		       CTLTYPE_INT, "hostzerobroadcast",
   1556 		       SYSCTL_DESCR("All zeroes address is broadcast address"),
   1557 		       NULL, 0, &hostzeroisbroadcast, 0,
   1558 		       CTL_NET, PF_INET, IPPROTO_IP,
   1559 		       IPCTL_HOSTZEROBROADCAST, CTL_EOL);
   1560 }
   1561