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