xref: /netbsd-src/sys/netinet/in.c (revision fc4f42693f9b1c31f39f9cf50af1bf2010325808)
1 /*	$NetBSD: in.c,v 1.228 2018/04/08 13:52:22 christos 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.228 2018/04/08 13:52:22 christos 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 #include "opt_net_mpsafe.h"
103 #endif
104 
105 #include <sys/param.h>
106 #include <sys/ioctl.h>
107 #include <sys/errno.h>
108 #include <sys/kernel.h>
109 #include <sys/malloc.h>
110 #include <sys/socket.h>
111 #include <sys/socketvar.h>
112 #include <sys/sysctl.h>
113 #include <sys/systm.h>
114 #include <sys/proc.h>
115 #include <sys/syslog.h>
116 #include <sys/kauth.h>
117 #include <sys/kmem.h>
118 
119 #include <sys/cprng.h>
120 
121 #include <net/if.h>
122 #include <net/route.h>
123 #include <net/pfil.h>
124 
125 #include <net/if_arp.h>
126 #include <net/if_ether.h>
127 #include <net/if_types.h>
128 #include <net/if_llatbl.h>
129 #include <net/if_dl.h>
130 
131 #include <netinet/in_systm.h>
132 #include <netinet/in.h>
133 #include <netinet/in_var.h>
134 #include <netinet/ip.h>
135 #include <netinet/ip_var.h>
136 #include <netinet/in_ifattach.h>
137 #include <netinet/in_pcb.h>
138 #include <netinet/in_selsrc.h>
139 #include <netinet/if_inarp.h>
140 #include <netinet/ip_mroute.h>
141 #include <netinet/igmp_var.h>
142 
143 #ifdef IPSELSRC
144 #include <netinet/in_selsrc.h>
145 #endif
146 
147 static u_int	in_mask2len(struct in_addr *);
148 static void	in_len2mask(struct in_addr *, u_int);
149 static int	in_lifaddr_ioctl(struct socket *, u_long, void *,
150 	struct ifnet *);
151 
152 static void	in_addrhash_insert_locked(struct in_ifaddr *);
153 static void	in_addrhash_remove_locked(struct in_ifaddr *);
154 
155 static int	in_addprefix(struct in_ifaddr *, int);
156 static void	in_scrubaddr(struct in_ifaddr *);
157 static int	in_scrubprefix(struct in_ifaddr *);
158 static void	in_sysctl_init(struct sysctllog **);
159 
160 #ifndef SUBNETSARELOCAL
161 #define	SUBNETSARELOCAL	1
162 #endif
163 
164 #ifndef HOSTZEROBROADCAST
165 #define HOSTZEROBROADCAST 0
166 #endif
167 
168 /* Note: 61, 127, 251, 509, 1021, 2039 are good. */
169 #ifndef IN_MULTI_HASH_SIZE
170 #define IN_MULTI_HASH_SIZE	509
171 #endif
172 
173 static int			subnetsarelocal = SUBNETSARELOCAL;
174 static int			hostzeroisbroadcast = HOSTZEROBROADCAST;
175 
176 /*
177  * This list is used to keep track of in_multi chains which belong to
178  * deleted interface addresses.  We use in_ifaddr so that a chain head
179  * won't be deallocated until all multicast address record are deleted.
180  */
181 
182 LIST_HEAD(in_multihashhead, in_multi);		/* Type of the hash head */
183 
184 static struct pool		inmulti_pool;
185 static u_int			in_multientries;
186 static struct in_multihashhead *in_multihashtbl;
187 static u_long			in_multihash;
188 static krwlock_t		in_multilock;
189 
190 #define IN_MULTI_HASH(x, ifp) \
191     (in_multihashtbl[(u_long)((x) ^ (ifp->if_index)) % IN_MULTI_HASH_SIZE])
192 
193 /* XXX DEPRECATED. Keep them to avoid breaking kvm(3) users. */
194 struct in_ifaddrhashhead *	in_ifaddrhashtbl;
195 u_long				in_ifaddrhash;
196 struct in_ifaddrhead		in_ifaddrhead;
197 static kmutex_t			in_ifaddr_lock;
198 
199 pserialize_t			in_ifaddrhash_psz;
200 struct pslist_head *		in_ifaddrhashtbl_pslist;
201 u_long				in_ifaddrhash_pslist;
202 struct pslist_head		in_ifaddrhead_pslist;
203 
204 void
205 in_init(void)
206 {
207 	pool_init(&inmulti_pool, sizeof(struct in_multi), 0, 0, 0, "inmltpl",
208 	    NULL, IPL_SOFTNET);
209 	TAILQ_INIT(&in_ifaddrhead);
210 	PSLIST_INIT(&in_ifaddrhead_pslist);
211 
212 	in_ifaddrhashtbl = hashinit(IN_IFADDR_HASH_SIZE, HASH_LIST, true,
213 	    &in_ifaddrhash);
214 
215 	in_ifaddrhash_psz = pserialize_create();
216 	in_ifaddrhashtbl_pslist = hashinit(IN_IFADDR_HASH_SIZE, HASH_PSLIST,
217 	    true, &in_ifaddrhash_pslist);
218 	mutex_init(&in_ifaddr_lock, MUTEX_DEFAULT, IPL_NONE);
219 
220 	in_multihashtbl = hashinit(IN_IFADDR_HASH_SIZE, HASH_LIST, true,
221 	    &in_multihash);
222 	rw_init(&in_multilock);
223 
224 	in_sysctl_init(NULL);
225 }
226 
227 /*
228  * Return 1 if an internet address is for a ``local'' host
229  * (one to which we have a connection).  If subnetsarelocal
230  * is true, this includes other subnets of the local net.
231  * Otherwise, it includes only the directly-connected (sub)nets.
232  */
233 int
234 in_localaddr(struct in_addr in)
235 {
236 	struct in_ifaddr *ia;
237 	int localaddr = 0;
238 	int s = pserialize_read_enter();
239 
240 	if (subnetsarelocal) {
241 		IN_ADDRLIST_READER_FOREACH(ia) {
242 			if ((in.s_addr & ia->ia_netmask) == ia->ia_net) {
243 				localaddr = 1;
244 				break;
245 			}
246 		}
247 	} else {
248 		IN_ADDRLIST_READER_FOREACH(ia) {
249 			if ((in.s_addr & ia->ia_subnetmask) == ia->ia_subnet) {
250 				localaddr = 1;
251 				break;
252 			}
253 		}
254 	}
255 	pserialize_read_exit(s);
256 
257 	return localaddr;
258 }
259 
260 /*
261  * like in_localaddr() but can specify ifp.
262  */
263 int
264 in_direct(struct in_addr in, struct ifnet *ifp)
265 {
266 	struct ifaddr *ifa;
267 	int localaddr = 0;
268 	int s;
269 
270 	KASSERT(ifp != NULL);
271 
272 #define ia (ifatoia(ifa))
273 	s = pserialize_read_enter();
274 	if (subnetsarelocal) {
275 		IFADDR_READER_FOREACH(ifa, ifp) {
276 			if (ifa->ifa_addr->sa_family == AF_INET &&
277 			    ((in.s_addr & ia->ia_netmask) == ia->ia_net)) {
278 				localaddr = 1;
279 				break;
280 			}
281 		}
282 	} else {
283 		IFADDR_READER_FOREACH(ifa, ifp) {
284 			if (ifa->ifa_addr->sa_family == AF_INET &&
285 			    (in.s_addr & ia->ia_subnetmask) == ia->ia_subnet) {
286 				localaddr = 1;
287 				break;
288 			}
289 		}
290 	}
291 	pserialize_read_exit(s);
292 
293 	return localaddr;
294 #undef ia
295 }
296 
297 /*
298  * Determine whether an IP address is in a reserved set of addresses
299  * that may not be forwarded, or whether datagrams to that destination
300  * may be forwarded.
301  */
302 int
303 in_canforward(struct in_addr in)
304 {
305 	u_int32_t net;
306 
307 	if (IN_EXPERIMENTAL(in.s_addr) || IN_MULTICAST(in.s_addr))
308 		return (0);
309 	if (IN_CLASSA(in.s_addr)) {
310 		net = in.s_addr & IN_CLASSA_NET;
311 		if (net == 0 || net == htonl(IN_LOOPBACKNET << IN_CLASSA_NSHIFT))
312 			return (0);
313 	}
314 	return (1);
315 }
316 
317 /*
318  * Trim a mask in a sockaddr
319  */
320 void
321 in_socktrim(struct sockaddr_in *ap)
322 {
323 	char *cplim = (char *) &ap->sin_addr;
324 	char *cp = (char *) (&ap->sin_addr + 1);
325 
326 	ap->sin_len = 0;
327 	while (--cp >= cplim)
328 		if (*cp) {
329 			(ap)->sin_len = cp - (char *) (ap) + 1;
330 			break;
331 		}
332 }
333 
334 /*
335  * Maintain the "in_maxmtu" variable, which is the largest
336  * mtu for non-local interfaces with AF_INET addresses assigned
337  * to them that are up.
338  */
339 unsigned long in_maxmtu;
340 
341 void
342 in_setmaxmtu(void)
343 {
344 	struct in_ifaddr *ia;
345 	struct ifnet *ifp;
346 	unsigned long maxmtu = 0;
347 	int s = pserialize_read_enter();
348 
349 	IN_ADDRLIST_READER_FOREACH(ia) {
350 		if ((ifp = ia->ia_ifp) == 0)
351 			continue;
352 		if ((ifp->if_flags & (IFF_UP|IFF_LOOPBACK)) != IFF_UP)
353 			continue;
354 		if (ifp->if_mtu > maxmtu)
355 			maxmtu = ifp->if_mtu;
356 	}
357 	if (maxmtu)
358 		in_maxmtu = maxmtu;
359 	pserialize_read_exit(s);
360 }
361 
362 static u_int
363 in_mask2len(struct in_addr *mask)
364 {
365 	u_int x, y;
366 	u_char *p;
367 
368 	p = (u_char *)mask;
369 	for (x = 0; x < sizeof(*mask); x++) {
370 		if (p[x] != 0xff)
371 			break;
372 	}
373 	y = 0;
374 	if (x < sizeof(*mask)) {
375 		for (y = 0; y < NBBY; y++) {
376 			if ((p[x] & (0x80 >> y)) == 0)
377 				break;
378 		}
379 	}
380 	return x * NBBY + y;
381 }
382 
383 static void
384 in_len2mask(struct in_addr *mask, u_int len)
385 {
386 	u_int i;
387 	u_char *p;
388 
389 	p = (u_char *)mask;
390 	memset(mask, 0, sizeof(*mask));
391 	for (i = 0; i < len / NBBY; i++)
392 		p[i] = 0xff;
393 	if (len % NBBY)
394 		p[i] = (0xff00 >> (len % NBBY)) & 0xff;
395 }
396 
397 /*
398  * Generic internet control operations (ioctl's).
399  * Ifp is 0 if not an interface-specific ioctl.
400  */
401 /* ARGSUSED */
402 static int
403 in_control0(struct socket *so, u_long cmd, void *data, struct ifnet *ifp)
404 {
405 	struct ifreq *ifr = (struct ifreq *)data;
406 	struct in_ifaddr *ia = NULL;
407 	struct in_aliasreq *ifra = (struct in_aliasreq *)data;
408 	struct sockaddr_in oldaddr, *new_dstaddr;
409 	int error, hostIsNew, maskIsNew;
410 	int newifaddr = 0;
411 	bool run_hook = false;
412 	bool need_reinsert = false;
413 	struct psref psref;
414 	int bound;
415 
416 	switch (cmd) {
417 	case SIOCALIFADDR:
418 	case SIOCDLIFADDR:
419 	case SIOCGLIFADDR:
420 		if (ifp == NULL)
421 			return EINVAL;
422 		return in_lifaddr_ioctl(so, cmd, data, ifp);
423 	case SIOCGIFADDRPREF:
424 	case SIOCSIFADDRPREF:
425 		if (ifp == NULL)
426 			return EINVAL;
427 		return ifaddrpref_ioctl(so, cmd, data, ifp);
428 	}
429 
430 	bound = curlwp_bind();
431 	/*
432 	 * Find address for this interface, if it exists.
433 	 */
434 	if (ifp != NULL)
435 		ia = in_get_ia_from_ifp_psref(ifp, &psref);
436 
437 	hostIsNew = 1;		/* moved here to appease gcc */
438 	switch (cmd) {
439 	case SIOCAIFADDR:
440 	case SIOCDIFADDR:
441 	case SIOCGIFALIAS:
442 	case SIOCGIFAFLAG_IN:
443 		if (ifra->ifra_addr.sin_family == AF_INET) {
444 			int s;
445 
446 			if (ia != NULL)
447 				ia4_release(ia, &psref);
448 			s = pserialize_read_enter();
449 			IN_ADDRHASH_READER_FOREACH(ia,
450 			    ifra->ifra_addr.sin_addr.s_addr) {
451 				if (ia->ia_ifp == ifp &&
452 				    in_hosteq(ia->ia_addr.sin_addr,
453 				    ifra->ifra_addr.sin_addr))
454 					break;
455 			}
456 			if (ia != NULL)
457 				ia4_acquire(ia, &psref);
458 			pserialize_read_exit(s);
459 		}
460 		if ((cmd == SIOCDIFADDR ||
461 		    cmd == SIOCGIFALIAS ||
462 		    cmd == SIOCGIFAFLAG_IN) &&
463 		    ia == NULL) {
464 			error = EADDRNOTAVAIL;
465 			goto out;
466 		}
467 
468 		if (cmd == SIOCDIFADDR &&
469 		    ifra->ifra_addr.sin_family == AF_UNSPEC) {
470 			ifra->ifra_addr.sin_family = AF_INET;
471 		}
472 		/* FALLTHROUGH */
473 	case SIOCSIFADDR:
474 		if (ia == NULL || ia->ia_addr.sin_family != AF_INET)
475 			;
476 		else if (ifra->ifra_addr.sin_len == 0) {
477 			ifra->ifra_addr = ia->ia_addr;
478 			hostIsNew = 0;
479 		} else if (in_hosteq(ia->ia_addr.sin_addr,
480 		           ifra->ifra_addr.sin_addr))
481 			hostIsNew = 0;
482 		/* FALLTHROUGH */
483 	case SIOCSIFDSTADDR:
484 		if (ifra->ifra_addr.sin_family != AF_INET) {
485 			error = EAFNOSUPPORT;
486 			goto out;
487 		}
488 		/* FALLTHROUGH */
489 	case SIOCSIFNETMASK:
490 		if (ifp == NULL)
491 			panic("in_control");
492 
493 		if (cmd == SIOCGIFALIAS || cmd == SIOCGIFAFLAG_IN)
494 			break;
495 
496 		if (ia == NULL &&
497 		    (cmd == SIOCSIFNETMASK || cmd == SIOCSIFDSTADDR)) {
498 			error = EADDRNOTAVAIL;
499 			goto out;
500 		}
501 
502 		if (kauth_authorize_network(curlwp->l_cred, KAUTH_NETWORK_INTERFACE,
503 		    KAUTH_REQ_NETWORK_INTERFACE_SETPRIV, ifp, (void *)cmd,
504 		    NULL) != 0) {
505 			error = EPERM;
506 			goto out;
507 		}
508 
509 		if (ia == NULL) {
510 			ia = malloc(sizeof(*ia), M_IFADDR, M_WAITOK|M_ZERO);
511 			if (ia == NULL) {
512 				error = ENOBUFS;
513 				goto out;
514 			}
515 			ia->ia_ifa.ifa_addr = sintosa(&ia->ia_addr);
516 			ia->ia_ifa.ifa_dstaddr = sintosa(&ia->ia_dstaddr);
517 			ia->ia_ifa.ifa_netmask = sintosa(&ia->ia_sockmask);
518 #ifdef IPSELSRC
519 			ia->ia_ifa.ifa_getifa = in_getifa;
520 #else /* IPSELSRC */
521 			ia->ia_ifa.ifa_getifa = NULL;
522 #endif /* IPSELSRC */
523 			ia->ia_sockmask.sin_len = 8;
524 			ia->ia_sockmask.sin_family = AF_INET;
525 			if (ifp->if_flags & IFF_BROADCAST) {
526 				ia->ia_broadaddr.sin_len = sizeof(ia->ia_addr);
527 				ia->ia_broadaddr.sin_family = AF_INET;
528 			}
529 			ia->ia_ifp = ifp;
530 			ia->ia_idsalt = cprng_fast32() % 65535;
531 			LIST_INIT(&ia->ia_multiaddrs);
532 			IN_ADDRHASH_ENTRY_INIT(ia);
533 			IN_ADDRLIST_ENTRY_INIT(ia);
534 			ifa_psref_init(&ia->ia_ifa);
535 			/*
536 			 * We need a reference to make ia survive over in_ifinit
537 			 * that does ifaref and ifafree.
538 			 */
539 			ifaref(&ia->ia_ifa);
540 
541 			newifaddr = 1;
542 		}
543 		break;
544 
545 	case SIOCSIFBRDADDR:
546 		if (kauth_authorize_network(curlwp->l_cred, KAUTH_NETWORK_INTERFACE,
547 		    KAUTH_REQ_NETWORK_INTERFACE_SETPRIV, ifp, (void *)cmd,
548 		    NULL) != 0) {
549 			error = EPERM;
550 			goto out;
551 		}
552 		/* FALLTHROUGH */
553 
554 	case SIOCGIFADDR:
555 	case SIOCGIFNETMASK:
556 	case SIOCGIFDSTADDR:
557 	case SIOCGIFBRDADDR:
558 		if (ia == NULL) {
559 			error = EADDRNOTAVAIL;
560 			goto out;
561 		}
562 		break;
563 	}
564 	error = 0;
565 	switch (cmd) {
566 
567 	case SIOCGIFADDR:
568 		ifreq_setaddr(cmd, ifr, sintocsa(&ia->ia_addr));
569 		break;
570 
571 	case SIOCGIFBRDADDR:
572 		if ((ifp->if_flags & IFF_BROADCAST) == 0) {
573 			error = EINVAL;
574 			goto out;
575 		}
576 		ifreq_setdstaddr(cmd, ifr, sintocsa(&ia->ia_broadaddr));
577 		break;
578 
579 	case SIOCGIFDSTADDR:
580 		if ((ifp->if_flags & IFF_POINTOPOINT) == 0) {
581 			error = EINVAL;
582 			goto out;
583 		}
584 		ifreq_setdstaddr(cmd, ifr, sintocsa(&ia->ia_dstaddr));
585 		break;
586 
587 	case SIOCGIFNETMASK:
588 		/*
589 		 * We keep the number of trailing zero bytes the sin_len field
590 		 * of ia_sockmask, so we fix this before we pass it back to
591 		 * userland.
592 		 */
593 		oldaddr = ia->ia_sockmask;
594 		oldaddr.sin_len = sizeof(struct sockaddr_in);
595 		ifreq_setaddr(cmd, ifr, (const void *)&oldaddr);
596 		break;
597 
598 	case SIOCSIFDSTADDR:
599 		if ((ifp->if_flags & IFF_POINTOPOINT) == 0) {
600 			error = EINVAL;
601 			goto out;
602 		}
603 		oldaddr = ia->ia_dstaddr;
604 		ia->ia_dstaddr = *satocsin(ifreq_getdstaddr(cmd, ifr));
605 		if ((error = if_addr_init(ifp, &ia->ia_ifa, false)) != 0) {
606 			ia->ia_dstaddr = oldaddr;
607 			goto out;
608 		}
609 		if (ia->ia_flags & IFA_ROUTE) {
610 			ia->ia_ifa.ifa_dstaddr = sintosa(&oldaddr);
611 			rtinit(&ia->ia_ifa, RTM_DELETE, RTF_HOST);
612 			ia->ia_ifa.ifa_dstaddr = sintosa(&ia->ia_dstaddr);
613 			rtinit(&ia->ia_ifa, RTM_ADD, RTF_HOST|RTF_UP);
614 		}
615 		break;
616 
617 	case SIOCSIFBRDADDR:
618 		if ((ifp->if_flags & IFF_BROADCAST) == 0) {
619 			error = EINVAL;
620 			goto out;
621 		}
622 		ia->ia_broadaddr = *satocsin(ifreq_getbroadaddr(cmd, ifr));
623 		break;
624 
625 	case SIOCSIFADDR:
626 		if (!newifaddr) {
627 			in_addrhash_remove(ia);
628 			need_reinsert = true;
629 		}
630 		error = in_ifinit(ifp, ia, satocsin(ifreq_getaddr(cmd, ifr)),
631 		    NULL, 1);
632 
633 		run_hook = true;
634 		break;
635 
636 	case SIOCSIFNETMASK:
637 		in_scrubprefix(ia);
638 		ia->ia_sockmask = *satocsin(ifreq_getaddr(cmd, ifr));
639 		ia->ia_subnetmask = ia->ia_sockmask.sin_addr.s_addr;
640 		if (!newifaddr) {
641 			in_addrhash_remove(ia);
642 			need_reinsert = true;
643 		}
644 		error = in_ifinit(ifp, ia, NULL, NULL, 0);
645 		break;
646 
647 	case SIOCAIFADDR:
648 		maskIsNew = 0;
649 		if (ifra->ifra_mask.sin_len) {
650 			in_scrubprefix(ia);
651 			ia->ia_sockmask = ifra->ifra_mask;
652 			ia->ia_subnetmask = ia->ia_sockmask.sin_addr.s_addr;
653 			maskIsNew = 1;
654 		}
655 		if ((ifp->if_flags & IFF_POINTOPOINT) &&
656 		    (ifra->ifra_dstaddr.sin_family == AF_INET)) {
657 			new_dstaddr = &ifra->ifra_dstaddr;
658 			maskIsNew  = 1; /* We lie; but the effect's the same */
659 		} else
660 			new_dstaddr = NULL;
661 		if (ifra->ifra_addr.sin_family == AF_INET &&
662 		    (hostIsNew || maskIsNew)) {
663 			if (!newifaddr) {
664 				in_addrhash_remove(ia);
665 				need_reinsert = true;
666 			}
667 			error = in_ifinit(ifp, ia, &ifra->ifra_addr,
668 			    new_dstaddr, 0);
669 		}
670 		if ((ifp->if_flags & IFF_BROADCAST) &&
671 		    (ifra->ifra_broadaddr.sin_family == AF_INET))
672 			ia->ia_broadaddr = ifra->ifra_broadaddr;
673 		run_hook = true;
674 		break;
675 
676 	case SIOCGIFALIAS:
677 		ifra->ifra_mask = ia->ia_sockmask;
678 		if ((ifp->if_flags & IFF_POINTOPOINT) &&
679 		    (ia->ia_dstaddr.sin_family == AF_INET))
680 			ifra->ifra_dstaddr = ia->ia_dstaddr;
681 		else if ((ifp->if_flags & IFF_BROADCAST) &&
682 		    (ia->ia_broadaddr.sin_family == AF_INET))
683 			ifra->ifra_broadaddr = ia->ia_broadaddr;
684 		else
685 			memset(&ifra->ifra_broadaddr, 0,
686 			      sizeof(ifra->ifra_broadaddr));
687 		break;
688 
689 	case SIOCGIFAFLAG_IN:
690 		ifr->ifr_addrflags = ia->ia4_flags;
691 		break;
692 
693 	case SIOCDIFADDR:
694 		ia4_release(ia, &psref);
695 		ifaref(&ia->ia_ifa);
696 		in_purgeaddr(&ia->ia_ifa);
697 		pfil_run_addrhooks(if_pfil, cmd, &ia->ia_ifa);
698 		ifafree(&ia->ia_ifa);
699 		ia = NULL;
700 		break;
701 
702 #ifdef MROUTING
703 	case SIOCGETVIFCNT:
704 	case SIOCGETSGCNT:
705 		error = mrt_ioctl(so, cmd, data);
706 		break;
707 #endif /* MROUTING */
708 
709 	default:
710 		error = ENOTTY;
711 		goto out;
712 	}
713 
714 	/*
715 	 * XXX insert regardless of error to make in_purgeaddr below work.
716 	 * Need to improve.
717 	 */
718 	if (newifaddr) {
719 		ifaref(&ia->ia_ifa);
720 		ifa_insert(ifp, &ia->ia_ifa);
721 
722 		mutex_enter(&in_ifaddr_lock);
723 		TAILQ_INSERT_TAIL(&in_ifaddrhead, ia, ia_list);
724 		IN_ADDRLIST_WRITER_INSERT_TAIL(ia);
725 		in_addrhash_insert_locked(ia);
726 		/* Release a reference that is held just after creation. */
727 		ifafree(&ia->ia_ifa);
728 		mutex_exit(&in_ifaddr_lock);
729 	} else if (need_reinsert) {
730 		in_addrhash_insert(ia);
731 	}
732 
733 	if (error == 0) {
734 		if (run_hook)
735 			pfil_run_addrhooks(if_pfil, cmd, &ia->ia_ifa);
736 	} else if (newifaddr) {
737 		KASSERT(ia != NULL);
738 		in_purgeaddr(&ia->ia_ifa);
739 		ia = NULL;
740 	}
741 
742 out:
743 	if (!newifaddr && ia != NULL)
744 		ia4_release(ia, &psref);
745 	curlwp_bindx(bound);
746 	return error;
747 }
748 
749 int
750 in_control(struct socket *so, u_long cmd, void *data, struct ifnet *ifp)
751 {
752 	int error;
753 
754 #ifndef NET_MPSAFE
755 	KASSERT(KERNEL_LOCKED_P());
756 #endif
757 	error = in_control0(so, cmd, data, ifp);
758 
759 	return error;
760 }
761 
762 /* Add ownaddr as loopback rtentry. */
763 static void
764 in_ifaddlocal(struct ifaddr *ifa)
765 {
766 	struct in_ifaddr *ia;
767 
768 	ia = (struct in_ifaddr *)ifa;
769 	if (ia->ia_addr.sin_addr.s_addr == INADDR_ANY ||
770 	    (ia->ia_ifp->if_flags & IFF_POINTOPOINT &&
771 	    in_hosteq(ia->ia_dstaddr.sin_addr, ia->ia_addr.sin_addr)))
772 	{
773 		rt_newaddrmsg(RTM_NEWADDR, ifa, 0, NULL);
774 		return;
775 	}
776 
777 	rt_ifa_addlocal(ifa);
778 }
779 
780 /* Remove loopback entry of ownaddr */
781 static void
782 in_ifremlocal(struct ifaddr *ifa)
783 {
784 	struct in_ifaddr *ia, *p;
785 	struct ifaddr *alt_ifa = NULL;
786 	int ia_count = 0;
787 	int s;
788 	struct psref psref;
789 	int bound = curlwp_bind();
790 
791 	ia = (struct in_ifaddr *)ifa;
792 	/* Delete the entry if exactly one ifaddr matches the
793 	 * address, ifa->ifa_addr. */
794 	s = pserialize_read_enter();
795 	IN_ADDRLIST_READER_FOREACH(p) {
796 		if (!in_hosteq(p->ia_addr.sin_addr, ia->ia_addr.sin_addr))
797 			continue;
798 		if (p->ia_ifp != ia->ia_ifp)
799 			alt_ifa = &p->ia_ifa;
800 		if (++ia_count > 1 && alt_ifa != NULL)
801 			break;
802 	}
803 	if (alt_ifa != NULL && ia_count > 1)
804 		ifa_acquire(alt_ifa, &psref);
805 	pserialize_read_exit(s);
806 
807 	if (ia_count == 0)
808 		goto out;
809 
810 	rt_ifa_remlocal(ifa, ia_count == 1 ? NULL : alt_ifa);
811 	if (alt_ifa != NULL && ia_count > 1)
812 		ifa_release(alt_ifa, &psref);
813 out:
814 	curlwp_bindx(bound);
815 }
816 
817 static void
818 in_scrubaddr(struct in_ifaddr *ia)
819 {
820 
821 	/* stop DAD processing */
822 	if (ia->ia_dad_stop != NULL)
823 		ia->ia_dad_stop(&ia->ia_ifa);
824 
825 	in_scrubprefix(ia);
826 	in_ifremlocal(&ia->ia_ifa);
827 
828 	mutex_enter(&in_ifaddr_lock);
829 	if (ia->ia_allhosts != NULL) {
830 		in_delmulti(ia->ia_allhosts);
831 		ia->ia_allhosts = NULL;
832 	}
833 	mutex_exit(&in_ifaddr_lock);
834 }
835 
836 /*
837  * Depends on it isn't called in concurrent. It should be guaranteed
838  * by ifa->ifa_ifp's ioctl lock. The possible callers are in_control
839  * and if_purgeaddrs; the former is called iva ifa->ifa_ifp's ioctl
840  * and the latter is called via ifa->ifa_ifp's if_detach. The functions
841  * never be executed in concurrent.
842  */
843 void
844 in_purgeaddr(struct ifaddr *ifa)
845 {
846 	struct in_ifaddr *ia = (void *) ifa;
847 	struct ifnet *ifp = ifa->ifa_ifp;
848 
849 	/* KASSERT(!ifa_held(ifa)); XXX need ifa_not_held (psref_not_held) */
850 
851 	ifa->ifa_flags |= IFA_DESTROYING;
852 	in_scrubaddr(ia);
853 
854 	mutex_enter(&in_ifaddr_lock);
855 	in_addrhash_remove_locked(ia);
856 	TAILQ_REMOVE(&in_ifaddrhead, ia, ia_list);
857 	IN_ADDRLIST_WRITER_REMOVE(ia);
858 	ifa_remove(ifp, &ia->ia_ifa);
859 	/* Assume ifa_remove called pserialize_perform and psref_destroy */
860 	mutex_exit(&in_ifaddr_lock);
861 	IN_ADDRHASH_ENTRY_DESTROY(ia);
862 	IN_ADDRLIST_ENTRY_DESTROY(ia);
863 	ifafree(&ia->ia_ifa);
864 	in_setmaxmtu();
865 }
866 
867 static void
868 in_addrhash_insert_locked(struct in_ifaddr *ia)
869 {
870 
871 	KASSERT(mutex_owned(&in_ifaddr_lock));
872 
873 	LIST_INSERT_HEAD(&IN_IFADDR_HASH(ia->ia_addr.sin_addr.s_addr), ia,
874 	    ia_hash);
875 	IN_ADDRHASH_ENTRY_INIT(ia);
876 	IN_ADDRHASH_WRITER_INSERT_HEAD(ia);
877 }
878 
879 void
880 in_addrhash_insert(struct in_ifaddr *ia)
881 {
882 
883 	mutex_enter(&in_ifaddr_lock);
884 	in_addrhash_insert_locked(ia);
885 	mutex_exit(&in_ifaddr_lock);
886 }
887 
888 static void
889 in_addrhash_remove_locked(struct in_ifaddr *ia)
890 {
891 
892 	KASSERT(mutex_owned(&in_ifaddr_lock));
893 
894 	LIST_REMOVE(ia, ia_hash);
895 	IN_ADDRHASH_WRITER_REMOVE(ia);
896 }
897 
898 void
899 in_addrhash_remove(struct in_ifaddr *ia)
900 {
901 
902 	mutex_enter(&in_ifaddr_lock);
903 	in_addrhash_remove_locked(ia);
904 #ifdef NET_MPSAFE
905 	pserialize_perform(in_ifaddrhash_psz);
906 #endif
907 	mutex_exit(&in_ifaddr_lock);
908 	IN_ADDRHASH_ENTRY_DESTROY(ia);
909 }
910 
911 void
912 in_purgeif(struct ifnet *ifp)		/* MUST be called at splsoftnet() */
913 {
914 
915 	IFNET_LOCK(ifp);
916 	if_purgeaddrs(ifp, AF_INET, in_purgeaddr);
917 	igmp_purgeif(ifp);		/* manipulates pools */
918 #ifdef MROUTING
919 	ip_mrouter_detach(ifp);
920 #endif
921 	IFNET_UNLOCK(ifp);
922 }
923 
924 /*
925  * SIOC[GAD]LIFADDR.
926  *	SIOCGLIFADDR: get first address. (???)
927  *	SIOCGLIFADDR with IFLR_PREFIX:
928  *		get first address that matches the specified prefix.
929  *	SIOCALIFADDR: add the specified address.
930  *	SIOCALIFADDR with IFLR_PREFIX:
931  *		EINVAL since we can't deduce hostid part of the address.
932  *	SIOCDLIFADDR: delete the specified address.
933  *	SIOCDLIFADDR with IFLR_PREFIX:
934  *		delete the first address that matches the specified prefix.
935  * return values:
936  *	EINVAL on invalid parameters
937  *	EADDRNOTAVAIL on prefix match failed/specified address not found
938  *	other values may be returned from in_ioctl()
939  */
940 static int
941 in_lifaddr_ioctl(struct socket *so, u_long cmd, void *data,
942     struct ifnet *ifp)
943 {
944 	struct if_laddrreq *iflr = (struct if_laddrreq *)data;
945 	struct ifaddr *ifa;
946 	struct sockaddr *sa;
947 
948 	/* sanity checks */
949 	if (data == NULL || ifp == NULL) {
950 		panic("invalid argument to in_lifaddr_ioctl");
951 		/*NOTRECHED*/
952 	}
953 
954 	switch (cmd) {
955 	case SIOCGLIFADDR:
956 		/* address must be specified on GET with IFLR_PREFIX */
957 		if ((iflr->flags & IFLR_PREFIX) == 0)
958 			break;
959 		/*FALLTHROUGH*/
960 	case SIOCALIFADDR:
961 	case SIOCDLIFADDR:
962 		/* address must be specified on ADD and DELETE */
963 		sa = (struct sockaddr *)&iflr->addr;
964 		if (sa->sa_family != AF_INET)
965 			return EINVAL;
966 		if (sa->sa_len != sizeof(struct sockaddr_in))
967 			return EINVAL;
968 		/* XXX need improvement */
969 		sa = (struct sockaddr *)&iflr->dstaddr;
970 		if (sa->sa_family != AF_UNSPEC && sa->sa_family != AF_INET)
971 			return EINVAL;
972 		if (sa->sa_len != 0 && sa->sa_len != sizeof(struct sockaddr_in))
973 			return EINVAL;
974 		break;
975 	default: /*shouldn't happen*/
976 #if 0
977 		panic("invalid cmd to in_lifaddr_ioctl");
978 		/*NOTREACHED*/
979 #else
980 		return EOPNOTSUPP;
981 #endif
982 	}
983 	if (sizeof(struct in_addr) * NBBY < iflr->prefixlen)
984 		return EINVAL;
985 
986 	switch (cmd) {
987 	case SIOCALIFADDR:
988 	    {
989 		struct in_aliasreq ifra;
990 
991 		if (iflr->flags & IFLR_PREFIX)
992 			return EINVAL;
993 
994 		/* copy args to in_aliasreq, perform ioctl(SIOCAIFADDR). */
995 		memset(&ifra, 0, sizeof(ifra));
996 		memcpy(ifra.ifra_name, iflr->iflr_name,
997 			sizeof(ifra.ifra_name));
998 
999 		memcpy(&ifra.ifra_addr, &iflr->addr,
1000 			((struct sockaddr *)&iflr->addr)->sa_len);
1001 
1002 		if (((struct sockaddr *)&iflr->dstaddr)->sa_family) {	/*XXX*/
1003 			memcpy(&ifra.ifra_dstaddr, &iflr->dstaddr,
1004 				((struct sockaddr *)&iflr->dstaddr)->sa_len);
1005 		}
1006 
1007 		ifra.ifra_mask.sin_family = AF_INET;
1008 		ifra.ifra_mask.sin_len = sizeof(struct sockaddr_in);
1009 		in_len2mask(&ifra.ifra_mask.sin_addr, iflr->prefixlen);
1010 
1011 		return in_control(so, SIOCAIFADDR, &ifra, ifp);
1012 	    }
1013 	case SIOCGLIFADDR:
1014 	case SIOCDLIFADDR:
1015 	    {
1016 		struct in_ifaddr *ia;
1017 		struct in_addr mask, candidate, match;
1018 		struct sockaddr_in *sin;
1019 		int cmp, s;
1020 
1021 		memset(&mask, 0, sizeof(mask));
1022 		memset(&match, 0, sizeof(match));	/* XXX gcc */
1023 		if (iflr->flags & IFLR_PREFIX) {
1024 			/* lookup a prefix rather than address. */
1025 			in_len2mask(&mask, iflr->prefixlen);
1026 
1027 			sin = (struct sockaddr_in *)&iflr->addr;
1028 			match.s_addr = sin->sin_addr.s_addr;
1029 			match.s_addr &= mask.s_addr;
1030 
1031 			/* if you set extra bits, that's wrong */
1032 			if (match.s_addr != sin->sin_addr.s_addr)
1033 				return EINVAL;
1034 
1035 			cmp = 1;
1036 		} else {
1037 			if (cmd == SIOCGLIFADDR) {
1038 				/* on getting an address, take the 1st match */
1039 				cmp = 0;	/*XXX*/
1040 			} else {
1041 				/* on deleting an address, do exact match */
1042 				in_len2mask(&mask, 32);
1043 				sin = (struct sockaddr_in *)&iflr->addr;
1044 				match.s_addr = sin->sin_addr.s_addr;
1045 
1046 				cmp = 1;
1047 			}
1048 		}
1049 
1050 		s = pserialize_read_enter();
1051 		IFADDR_READER_FOREACH(ifa, ifp) {
1052 			if (ifa->ifa_addr->sa_family != AF_INET)
1053 				continue;
1054 			if (cmp == 0)
1055 				break;
1056 			candidate.s_addr = ((struct sockaddr_in *)ifa->ifa_addr)->sin_addr.s_addr;
1057 			candidate.s_addr &= mask.s_addr;
1058 			if (candidate.s_addr == match.s_addr)
1059 				break;
1060 		}
1061 		if (ifa == NULL) {
1062 			pserialize_read_exit(s);
1063 			return EADDRNOTAVAIL;
1064 		}
1065 		ia = (struct in_ifaddr *)ifa;
1066 
1067 		if (cmd == SIOCGLIFADDR) {
1068 			/* fill in the if_laddrreq structure */
1069 			memcpy(&iflr->addr, &ia->ia_addr, ia->ia_addr.sin_len);
1070 
1071 			if ((ifp->if_flags & IFF_POINTOPOINT) != 0) {
1072 				memcpy(&iflr->dstaddr, &ia->ia_dstaddr,
1073 					ia->ia_dstaddr.sin_len);
1074 			} else
1075 				memset(&iflr->dstaddr, 0, sizeof(iflr->dstaddr));
1076 
1077 			iflr->prefixlen =
1078 				in_mask2len(&ia->ia_sockmask.sin_addr);
1079 
1080 			iflr->flags = 0;	/*XXX*/
1081 			pserialize_read_exit(s);
1082 
1083 			return 0;
1084 		} else {
1085 			struct in_aliasreq ifra;
1086 
1087 			/* fill in_aliasreq and do ioctl(SIOCDIFADDR) */
1088 			memset(&ifra, 0, sizeof(ifra));
1089 			memcpy(ifra.ifra_name, iflr->iflr_name,
1090 				sizeof(ifra.ifra_name));
1091 
1092 			memcpy(&ifra.ifra_addr, &ia->ia_addr,
1093 				ia->ia_addr.sin_len);
1094 			if ((ifp->if_flags & IFF_POINTOPOINT) != 0) {
1095 				memcpy(&ifra.ifra_dstaddr, &ia->ia_dstaddr,
1096 					ia->ia_dstaddr.sin_len);
1097 			}
1098 			memcpy(&ifra.ifra_dstaddr, &ia->ia_sockmask,
1099 				ia->ia_sockmask.sin_len);
1100 			pserialize_read_exit(s);
1101 
1102 			return in_control(so, SIOCDIFADDR, &ifra, ifp);
1103 		}
1104 	    }
1105 	}
1106 
1107 	return EOPNOTSUPP;	/*just for safety*/
1108 }
1109 
1110 /*
1111  * Initialize an interface's internet address
1112  * and routing table entry.
1113  */
1114 int
1115 in_ifinit(struct ifnet *ifp, struct in_ifaddr *ia,
1116     const struct sockaddr_in *sin, const struct sockaddr_in *dst, int scrub)
1117 {
1118 	u_int32_t i;
1119 	struct sockaddr_in oldaddr, olddst;
1120 	int s, oldflags, flags = RTF_UP, error, hostIsNew;
1121 
1122 	if (sin == NULL)
1123 		sin = &ia->ia_addr;
1124 	if (dst == NULL)
1125 		dst = &ia->ia_dstaddr;
1126 
1127 	/*
1128 	 * Set up new addresses.
1129 	 */
1130 	oldaddr = ia->ia_addr;
1131 	olddst = ia->ia_dstaddr;
1132 	oldflags = ia->ia4_flags;
1133 	ia->ia_addr = *sin;
1134 	ia->ia_dstaddr = *dst;
1135 	hostIsNew = oldaddr.sin_family != AF_INET ||
1136 	    !in_hosteq(ia->ia_addr.sin_addr, oldaddr.sin_addr);
1137 	if (!scrub)
1138 		scrub = oldaddr.sin_family != ia->ia_dstaddr.sin_family ||
1139 		    !in_hosteq(ia->ia_dstaddr.sin_addr, olddst.sin_addr);
1140 
1141 	/*
1142 	 * Configure address flags.
1143 	 * We need to do this early because they maybe adjusted
1144 	 * by if_addr_init depending on the address.
1145 	 */
1146 	if (ia->ia4_flags & IN_IFF_DUPLICATED) {
1147 		ia->ia4_flags &= ~IN_IFF_DUPLICATED;
1148 		hostIsNew = 1;
1149 	}
1150 	if (ifp->if_link_state == LINK_STATE_DOWN) {
1151 		ia->ia4_flags |= IN_IFF_DETACHED;
1152 		ia->ia4_flags &= ~IN_IFF_TENTATIVE;
1153 	} else if (hostIsNew && if_do_dad(ifp)
1154 #if NARP > 0
1155 	    && ip_dad_count > 0
1156 #endif
1157 	)
1158 		ia->ia4_flags |= IN_IFF_TRYTENTATIVE;
1159 
1160 	/*
1161 	 * Give the interface a chance to initialize
1162 	 * if this is its first address,
1163 	 * and to validate the address if necessary.
1164 	 */
1165 	s = splsoftnet();
1166 	error = if_addr_init(ifp, &ia->ia_ifa, true);
1167 	splx(s);
1168 	/* Now clear the try tentative flag, its job is done. */
1169 	ia->ia4_flags &= ~IN_IFF_TRYTENTATIVE;
1170 	if (error != 0) {
1171 		ia->ia_addr = oldaddr;
1172 		ia->ia_dstaddr = olddst;
1173 		ia->ia4_flags = oldflags;
1174 		return error;
1175 	}
1176 
1177 	if (scrub || hostIsNew) {
1178 		int newflags = ia->ia4_flags;
1179 
1180 		ia->ia_ifa.ifa_addr = sintosa(&oldaddr);
1181 		ia->ia_ifa.ifa_dstaddr = sintosa(&olddst);
1182 		ia->ia4_flags = oldflags;
1183 		if (hostIsNew)
1184 			in_scrubaddr(ia);
1185 		else if (scrub)
1186 			in_scrubprefix(ia);
1187 		ia->ia_ifa.ifa_addr = sintosa(&ia->ia_addr);
1188 		ia->ia_ifa.ifa_dstaddr = sintosa(&ia->ia_dstaddr);
1189 		ia->ia4_flags = newflags;
1190 	}
1191 
1192 	i = ia->ia_addr.sin_addr.s_addr;
1193 	if (ifp->if_flags & IFF_POINTOPOINT)
1194 		ia->ia_netmask = INADDR_BROADCAST;	/* default to /32 */
1195 	else if (IN_CLASSA(i))
1196 		ia->ia_netmask = IN_CLASSA_NET;
1197 	else if (IN_CLASSB(i))
1198 		ia->ia_netmask = IN_CLASSB_NET;
1199 	else
1200 		ia->ia_netmask = IN_CLASSC_NET;
1201 	/*
1202 	 * The subnet mask usually includes at least the standard network part,
1203 	 * but may may be smaller in the case of supernetting.
1204 	 * If it is set, we believe it.
1205 	 */
1206 	if (ia->ia_subnetmask == 0) {
1207 		ia->ia_subnetmask = ia->ia_netmask;
1208 		ia->ia_sockmask.sin_addr.s_addr = ia->ia_subnetmask;
1209 	} else
1210 		ia->ia_netmask &= ia->ia_subnetmask;
1211 
1212 	ia->ia_net = i & ia->ia_netmask;
1213 	ia->ia_subnet = i & ia->ia_subnetmask;
1214 	in_socktrim(&ia->ia_sockmask);
1215 
1216 	/* re-calculate the "in_maxmtu" value */
1217 	in_setmaxmtu();
1218 
1219 	ia->ia_ifa.ifa_metric = ifp->if_metric;
1220 	if (ifp->if_flags & IFF_BROADCAST) {
1221 		ia->ia_broadaddr.sin_addr.s_addr =
1222 			ia->ia_subnet | ~ia->ia_subnetmask;
1223 		ia->ia_netbroadcast.s_addr =
1224 			ia->ia_net | ~ia->ia_netmask;
1225 	} else if (ifp->if_flags & IFF_LOOPBACK) {
1226 		ia->ia_dstaddr = ia->ia_addr;
1227 		flags |= RTF_HOST;
1228 	} else if (ifp->if_flags & IFF_POINTOPOINT) {
1229 		if (ia->ia_dstaddr.sin_family != AF_INET)
1230 			return (0);
1231 		flags |= RTF_HOST;
1232 	}
1233 
1234 	/* Add the local route to the address */
1235 	in_ifaddlocal(&ia->ia_ifa);
1236 
1237 	/* Add the prefix route for the address */
1238 	error = in_addprefix(ia, flags);
1239 
1240 	/*
1241 	 * If the interface supports multicast, join the "all hosts"
1242 	 * multicast group on that interface.
1243 	 */
1244 	mutex_enter(&in_ifaddr_lock);
1245 	if ((ifp->if_flags & IFF_MULTICAST) != 0 && ia->ia_allhosts == NULL) {
1246 		struct in_addr addr;
1247 
1248 		addr.s_addr = INADDR_ALLHOSTS_GROUP;
1249 		ia->ia_allhosts = in_addmulti(&addr, ifp);
1250 	}
1251 	mutex_exit(&in_ifaddr_lock);
1252 
1253 	if (hostIsNew &&
1254 	    ia->ia4_flags & IN_IFF_TENTATIVE &&
1255 	    if_do_dad(ifp))
1256 		ia->ia_dad_start((struct ifaddr *)ia);
1257 
1258 	return error;
1259 }
1260 
1261 #define rtinitflags(x) \
1262 	((((x)->ia_ifp->if_flags & (IFF_LOOPBACK | IFF_POINTOPOINT)) != 0) \
1263 	    ? RTF_HOST : 0)
1264 
1265 /*
1266  * add a route to prefix ("connected route" in cisco terminology).
1267  * does nothing if there's some interface address with the same prefix already.
1268  */
1269 static int
1270 in_addprefix(struct in_ifaddr *target, int flags)
1271 {
1272 	struct in_ifaddr *ia;
1273 	struct in_addr prefix, mask, p;
1274 	int error;
1275 	int s;
1276 
1277 	if ((flags & RTF_HOST) != 0)
1278 		prefix = target->ia_dstaddr.sin_addr;
1279 	else {
1280 		prefix = target->ia_addr.sin_addr;
1281 		mask = target->ia_sockmask.sin_addr;
1282 		prefix.s_addr &= mask.s_addr;
1283 	}
1284 
1285 	s = pserialize_read_enter();
1286 	IN_ADDRLIST_READER_FOREACH(ia) {
1287 		if (rtinitflags(ia))
1288 			p = ia->ia_dstaddr.sin_addr;
1289 		else {
1290 			p = ia->ia_addr.sin_addr;
1291 			p.s_addr &= ia->ia_sockmask.sin_addr.s_addr;
1292 		}
1293 
1294 		if (prefix.s_addr != p.s_addr)
1295 			continue;
1296 
1297 		/*
1298 		 * if we got a matching prefix route inserted by other
1299 		 * interface address, we don't need to bother
1300 		 *
1301 		 * XXX RADIX_MPATH implications here? -dyoung
1302 		 */
1303 		if (ia->ia_flags & IFA_ROUTE) {
1304 			pserialize_read_exit(s);
1305 			return 0;
1306 		}
1307 	}
1308 	pserialize_read_exit(s);
1309 
1310 	/*
1311 	 * noone seem to have prefix route.  insert it.
1312 	 */
1313 	error = rtinit(&target->ia_ifa, RTM_ADD, flags);
1314 	if (error == 0)
1315 		target->ia_flags |= IFA_ROUTE;
1316 	else if (error == EEXIST) {
1317 		/*
1318 		 * the fact the route already exists is not an error.
1319 		 */
1320 		error = 0;
1321 	}
1322 	return error;
1323 }
1324 
1325 /*
1326  * remove a route to prefix ("connected route" in cisco terminology).
1327  * re-installs the route by using another interface address, if there's one
1328  * with the same prefix (otherwise we lose the route mistakenly).
1329  */
1330 static int
1331 in_scrubprefix(struct in_ifaddr *target)
1332 {
1333 	struct in_ifaddr *ia;
1334 	struct in_addr prefix, mask, p;
1335 	int error;
1336 	int s;
1337 
1338 	/* If we don't have IFA_ROUTE we have nothing to do */
1339 	if ((target->ia_flags & IFA_ROUTE) == 0)
1340 		return 0;
1341 
1342 	if (rtinitflags(target))
1343 		prefix = target->ia_dstaddr.sin_addr;
1344 	else {
1345 		prefix = target->ia_addr.sin_addr;
1346 		mask = target->ia_sockmask.sin_addr;
1347 		prefix.s_addr &= mask.s_addr;
1348 	}
1349 
1350 	s = pserialize_read_enter();
1351 	IN_ADDRLIST_READER_FOREACH(ia) {
1352 		if (rtinitflags(ia))
1353 			p = ia->ia_dstaddr.sin_addr;
1354 		else {
1355 			p = ia->ia_addr.sin_addr;
1356 			p.s_addr &= ia->ia_sockmask.sin_addr.s_addr;
1357 		}
1358 
1359 		if (prefix.s_addr != p.s_addr)
1360 			continue;
1361 
1362 		/*
1363 		 * if we got a matching prefix route, move IFA_ROUTE to him
1364 		 */
1365 		if ((ia->ia_flags & IFA_ROUTE) == 0) {
1366 			struct psref psref;
1367 			int bound = curlwp_bind();
1368 
1369 			ia4_acquire(ia, &psref);
1370 			pserialize_read_exit(s);
1371 
1372 			rtinit(&target->ia_ifa, RTM_DELETE,
1373 			    rtinitflags(target));
1374 			target->ia_flags &= ~IFA_ROUTE;
1375 
1376 			error = rtinit(&ia->ia_ifa, RTM_ADD,
1377 			    rtinitflags(ia) | RTF_UP);
1378 			if (error == 0)
1379 				ia->ia_flags |= IFA_ROUTE;
1380 
1381 			ia4_release(ia, &psref);
1382 			curlwp_bindx(bound);
1383 
1384 			return error;
1385 		}
1386 	}
1387 	pserialize_read_exit(s);
1388 
1389 	/*
1390 	 * noone seem to have prefix route.  remove it.
1391 	 */
1392 	rtinit(&target->ia_ifa, RTM_DELETE, rtinitflags(target));
1393 	target->ia_flags &= ~IFA_ROUTE;
1394 	return 0;
1395 }
1396 
1397 #undef rtinitflags
1398 
1399 /*
1400  * Return 1 if the address might be a local broadcast address.
1401  */
1402 int
1403 in_broadcast(struct in_addr in, struct ifnet *ifp)
1404 {
1405 	struct ifaddr *ifa;
1406 	int s;
1407 
1408 	KASSERT(ifp != NULL);
1409 
1410 	if (in.s_addr == INADDR_BROADCAST ||
1411 	    in_nullhost(in))
1412 		return 1;
1413 	if ((ifp->if_flags & IFF_BROADCAST) == 0)
1414 		return 0;
1415 	/*
1416 	 * Look through the list of addresses for a match
1417 	 * with a broadcast address.
1418 	 */
1419 #define ia (ifatoia(ifa))
1420 	s = pserialize_read_enter();
1421 	IFADDR_READER_FOREACH(ifa, ifp) {
1422 		if (ifa->ifa_addr->sa_family == AF_INET &&
1423 		    !in_hosteq(in, ia->ia_addr.sin_addr) &&
1424 		    (in_hosteq(in, ia->ia_broadaddr.sin_addr) ||
1425 		     in_hosteq(in, ia->ia_netbroadcast) ||
1426 		     (hostzeroisbroadcast &&
1427 		      /*
1428 		       * Check for old-style (host 0) broadcast.
1429 		       */
1430 		      (in.s_addr == ia->ia_subnet ||
1431 		       in.s_addr == ia->ia_net)))) {
1432 			pserialize_read_exit(s);
1433 			return 1;
1434 		}
1435 	}
1436 	pserialize_read_exit(s);
1437 	return (0);
1438 #undef ia
1439 }
1440 
1441 /*
1442  * perform DAD when interface becomes IFF_UP.
1443  */
1444 void
1445 in_if_link_up(struct ifnet *ifp)
1446 {
1447 	struct ifaddr *ifa;
1448 	struct in_ifaddr *ia;
1449 	int s, bound;
1450 
1451 	/* Ensure it's sane to run DAD */
1452 	if (ifp->if_link_state == LINK_STATE_DOWN)
1453 		return;
1454 	if ((ifp->if_flags & (IFF_UP|IFF_RUNNING)) != (IFF_UP|IFF_RUNNING))
1455 		return;
1456 
1457 	bound = curlwp_bind();
1458 	s = pserialize_read_enter();
1459 	IFADDR_READER_FOREACH(ifa, ifp) {
1460 		struct psref psref;
1461 
1462 		if (ifa->ifa_addr->sa_family != AF_INET)
1463 			continue;
1464 		ifa_acquire(ifa, &psref);
1465 		pserialize_read_exit(s);
1466 
1467 		ia = (struct in_ifaddr *)ifa;
1468 
1469 		/* If detached then mark as tentative */
1470 		if (ia->ia4_flags & IN_IFF_DETACHED) {
1471 			ia->ia4_flags &= ~IN_IFF_DETACHED;
1472 			if (if_do_dad(ifp) && ia->ia_dad_start != NULL)
1473 				ia->ia4_flags |= IN_IFF_TENTATIVE;
1474 			else if ((ia->ia4_flags & IN_IFF_TENTATIVE) == 0)
1475 				rt_newaddrmsg(RTM_NEWADDR, ifa, 0, NULL);
1476 		}
1477 
1478 		if (ia->ia4_flags & IN_IFF_TENTATIVE) {
1479 			/* Clear the duplicated flag as we're starting DAD. */
1480 			ia->ia4_flags &= ~IN_IFF_DUPLICATED;
1481 			ia->ia_dad_start(ifa);
1482 		}
1483 
1484 		s = pserialize_read_enter();
1485 		ifa_release(ifa, &psref);
1486 	}
1487 	pserialize_read_exit(s);
1488 	curlwp_bindx(bound);
1489 }
1490 
1491 void
1492 in_if_up(struct ifnet *ifp)
1493 {
1494 
1495 	/* interface may not support link state, so bring it up also */
1496 	in_if_link_up(ifp);
1497 }
1498 
1499 /*
1500  * Mark all addresses as detached.
1501  */
1502 void
1503 in_if_link_down(struct ifnet *ifp)
1504 {
1505 	struct ifaddr *ifa;
1506 	struct in_ifaddr *ia;
1507 	int s, bound;
1508 
1509 	bound = curlwp_bind();
1510 	s = pserialize_read_enter();
1511 	IFADDR_READER_FOREACH(ifa, ifp) {
1512 		struct psref psref;
1513 
1514 		if (ifa->ifa_addr->sa_family != AF_INET)
1515 			continue;
1516 		ifa_acquire(ifa, &psref);
1517 		pserialize_read_exit(s);
1518 
1519 		ia = (struct in_ifaddr *)ifa;
1520 
1521 		/* Stop DAD processing */
1522 		if (ia->ia_dad_stop != NULL)
1523 			ia->ia_dad_stop(ifa);
1524 
1525 		/*
1526 		 * Mark the address as detached.
1527 		 */
1528 		if (!(ia->ia4_flags & IN_IFF_DETACHED)) {
1529 			ia->ia4_flags |= IN_IFF_DETACHED;
1530 			ia->ia4_flags &=
1531 			    ~(IN_IFF_TENTATIVE | IN_IFF_DUPLICATED);
1532 			rt_newaddrmsg(RTM_NEWADDR, ifa, 0, NULL);
1533 		}
1534 
1535 		s = pserialize_read_enter();
1536 		ifa_release(ifa, &psref);
1537 	}
1538 	pserialize_read_exit(s);
1539 	curlwp_bindx(bound);
1540 }
1541 
1542 void
1543 in_if_down(struct ifnet *ifp)
1544 {
1545 
1546 	in_if_link_down(ifp);
1547 #if NARP > 0
1548 	lltable_purge_entries(LLTABLE(ifp));
1549 #endif
1550 }
1551 
1552 void
1553 in_if_link_state_change(struct ifnet *ifp, int link_state)
1554 {
1555 
1556 	switch (link_state) {
1557 	case LINK_STATE_DOWN:
1558 		in_if_link_down(ifp);
1559 		break;
1560 	case LINK_STATE_UP:
1561 		in_if_link_up(ifp);
1562 		break;
1563 	}
1564 }
1565 
1566 /*
1567  * in_lookup_multi: look up the in_multi record for a given IP
1568  * multicast address on a given interface.  If no matching record is
1569  * found, return NULL.
1570  */
1571 struct in_multi *
1572 in_lookup_multi(struct in_addr addr, ifnet_t *ifp)
1573 {
1574 	struct in_multi *inm;
1575 
1576 	KASSERT(rw_lock_held(&in_multilock));
1577 
1578 	LIST_FOREACH(inm, &IN_MULTI_HASH(addr.s_addr, ifp), inm_list) {
1579 		if (in_hosteq(inm->inm_addr, addr) && inm->inm_ifp == ifp)
1580 			break;
1581 	}
1582 	return inm;
1583 }
1584 
1585 /*
1586  * in_multi_group: check whether the address belongs to an IP multicast
1587  * group we are joined on this interface.  Returns true or false.
1588  */
1589 bool
1590 in_multi_group(struct in_addr addr, ifnet_t *ifp, int flags)
1591 {
1592 	bool ingroup;
1593 
1594 	if (__predict_true(flags & IP_IGMP_MCAST) == 0) {
1595 		rw_enter(&in_multilock, RW_READER);
1596 		ingroup = in_lookup_multi(addr, ifp) != NULL;
1597 		rw_exit(&in_multilock);
1598 	} else {
1599 		/* XXX Recursive call from ip_output(). */
1600 		KASSERT(rw_lock_held(&in_multilock));
1601 		ingroup = in_lookup_multi(addr, ifp) != NULL;
1602 	}
1603 	return ingroup;
1604 }
1605 
1606 /*
1607  * Add an address to the list of IP multicast addresses for a given interface.
1608  */
1609 struct in_multi *
1610 in_addmulti(struct in_addr *ap, ifnet_t *ifp)
1611 {
1612 	struct sockaddr_in sin;
1613 	struct in_multi *inm;
1614 
1615 	/*
1616 	 * See if address already in list.
1617 	 */
1618 	rw_enter(&in_multilock, RW_WRITER);
1619 	inm = in_lookup_multi(*ap, ifp);
1620 	if (inm != NULL) {
1621 		/*
1622 		 * Found it; just increment the reference count.
1623 		 */
1624 		inm->inm_refcount++;
1625 		rw_exit(&in_multilock);
1626 		return inm;
1627 	}
1628 
1629 	/*
1630 	 * New address; allocate a new multicast record.
1631 	 */
1632 	inm = pool_get(&inmulti_pool, PR_NOWAIT);
1633 	if (inm == NULL) {
1634 		rw_exit(&in_multilock);
1635 		return NULL;
1636 	}
1637 	inm->inm_addr = *ap;
1638 	inm->inm_ifp = ifp;
1639 	inm->inm_refcount = 1;
1640 
1641 	/*
1642 	 * Ask the network driver to update its multicast reception
1643 	 * filter appropriately for the new address.
1644 	 */
1645 	sockaddr_in_init(&sin, ap, 0);
1646 	if (if_mcast_op(ifp, SIOCADDMULTI, sintosa(&sin)) != 0) {
1647 		rw_exit(&in_multilock);
1648 		pool_put(&inmulti_pool, inm);
1649 		return NULL;
1650 	}
1651 
1652 	/*
1653 	 * Let IGMP know that we have joined a new IP multicast group.
1654 	 */
1655 	if (igmp_joingroup(inm) != 0) {
1656 		rw_exit(&in_multilock);
1657 		pool_put(&inmulti_pool, inm);
1658 		return NULL;
1659 	}
1660 	LIST_INSERT_HEAD(
1661 	    &IN_MULTI_HASH(inm->inm_addr.s_addr, ifp),
1662 	    inm, inm_list);
1663 	in_multientries++;
1664 	rw_exit(&in_multilock);
1665 
1666 	return inm;
1667 }
1668 
1669 /*
1670  * Delete a multicast address record.
1671  */
1672 void
1673 in_delmulti(struct in_multi *inm)
1674 {
1675 	struct sockaddr_in sin;
1676 
1677 	rw_enter(&in_multilock, RW_WRITER);
1678 	if (--inm->inm_refcount > 0) {
1679 		rw_exit(&in_multilock);
1680 		return;
1681 	}
1682 
1683 	/*
1684 	 * No remaining claims to this record; let IGMP know that
1685 	 * we are leaving the multicast group.
1686 	 */
1687 	igmp_leavegroup(inm);
1688 
1689 	/*
1690 	 * Notify the network driver to update its multicast reception
1691 	 * filter.
1692 	 */
1693 	sockaddr_in_init(&sin, &inm->inm_addr, 0);
1694 	if_mcast_op(inm->inm_ifp, SIOCDELMULTI, sintosa(&sin));
1695 
1696 	/*
1697 	 * Unlink from list.
1698 	 */
1699 	LIST_REMOVE(inm, inm_list);
1700 	in_multientries--;
1701 	rw_exit(&in_multilock);
1702 
1703 	pool_put(&inmulti_pool, inm);
1704 }
1705 
1706 /*
1707  * in_next_multi: step through all of the in_multi records, one at a time.
1708  * The current position is remembered in "step", which the caller must
1709  * provide.  in_first_multi(), below, must be called to initialize "step"
1710  * and get the first record.  Both macros return a NULL "inm" when there
1711  * are no remaining records.
1712  */
1713 struct in_multi *
1714 in_next_multi(struct in_multistep *step)
1715 {
1716 	struct in_multi *inm;
1717 
1718 	KASSERT(rw_lock_held(&in_multilock));
1719 
1720 	while (step->i_inm == NULL && step->i_n < IN_MULTI_HASH_SIZE) {
1721 		step->i_inm = LIST_FIRST(&in_multihashtbl[++step->i_n]);
1722 	}
1723 	if ((inm = step->i_inm) != NULL) {
1724 		step->i_inm = LIST_NEXT(inm, inm_list);
1725 	}
1726 	return inm;
1727 }
1728 
1729 struct in_multi *
1730 in_first_multi(struct in_multistep *step)
1731 {
1732 	KASSERT(rw_lock_held(&in_multilock));
1733 
1734 	step->i_n = 0;
1735 	step->i_inm = LIST_FIRST(&in_multihashtbl[0]);
1736 	return in_next_multi(step);
1737 }
1738 
1739 void
1740 in_multi_lock(int op)
1741 {
1742 	rw_enter(&in_multilock, op);
1743 }
1744 
1745 void
1746 in_multi_unlock(void)
1747 {
1748 	rw_exit(&in_multilock);
1749 }
1750 
1751 int
1752 in_multi_lock_held(void)
1753 {
1754 	return rw_lock_held(&in_multilock);
1755 }
1756 
1757 struct in_ifaddr *
1758 in_selectsrc(struct sockaddr_in *sin, struct route *ro,
1759     int soopts, struct ip_moptions *mopts, int *errorp, struct psref *psref)
1760 {
1761 	struct rtentry *rt = NULL;
1762 	struct in_ifaddr *ia = NULL;
1763 
1764 	KASSERT(ISSET(curlwp->l_pflag, LP_BOUND));
1765 	/*
1766          * If route is known or can be allocated now, take the
1767          * source address from the interface.  Otherwise, punt.
1768 	 */
1769 	if ((soopts & SO_DONTROUTE) != 0)
1770 		rtcache_free(ro);
1771 	else {
1772 		union {
1773 			struct sockaddr		dst;
1774 			struct sockaddr_in	dst4;
1775 		} u;
1776 
1777 		sockaddr_in_init(&u.dst4, &sin->sin_addr, 0);
1778 		rt = rtcache_lookup(ro, &u.dst);
1779 	}
1780 	/*
1781 	 * If we found a route, use the address
1782 	 * corresponding to the outgoing interface
1783 	 * unless it is the loopback (in case a route
1784 	 * to our address on another net goes to loopback).
1785 	 *
1786 	 * XXX Is this still true?  Do we care?
1787 	 */
1788 	if (rt != NULL && (rt->rt_ifp->if_flags & IFF_LOOPBACK) == 0) {
1789 		int s;
1790 		struct ifaddr *ifa;
1791 		/*
1792 		 * Just in case. May not need to do this workaround.
1793 		 * Revisit when working on rtentry MP-ification.
1794 		 */
1795 		s = pserialize_read_enter();
1796 		IFADDR_READER_FOREACH(ifa, rt->rt_ifp) {
1797 			if (ifa == rt->rt_ifa)
1798 				break;
1799 		}
1800 		if (ifa != NULL)
1801 			ifa_acquire(ifa, psref);
1802 		pserialize_read_exit(s);
1803 
1804 		ia = ifatoia(ifa);
1805 	}
1806 	if (ia == NULL) {
1807 		u_int16_t fport = sin->sin_port;
1808 		struct ifaddr *ifa;
1809 		int s;
1810 
1811 		sin->sin_port = 0;
1812 		ifa = ifa_ifwithladdr_psref(sintosa(sin), psref);
1813 		sin->sin_port = fport;
1814 		if (ifa == NULL) {
1815 			/* Find 1st non-loopback AF_INET address */
1816 			s = pserialize_read_enter();
1817 			IN_ADDRLIST_READER_FOREACH(ia) {
1818 				if (!(ia->ia_ifp->if_flags & IFF_LOOPBACK))
1819 					break;
1820 			}
1821 			if (ia != NULL)
1822 				ia4_acquire(ia, psref);
1823 			pserialize_read_exit(s);
1824 		} else {
1825 			/* ia is already referenced by psref */
1826 			ia = ifatoia(ifa);
1827 		}
1828 		if (ia == NULL) {
1829 			*errorp = EADDRNOTAVAIL;
1830 			goto out;
1831 		}
1832 	}
1833 	/*
1834 	 * If the destination address is multicast and an outgoing
1835 	 * interface has been set as a multicast option, use the
1836 	 * address of that interface as our source address.
1837 	 */
1838 	if (IN_MULTICAST(sin->sin_addr.s_addr) && mopts != NULL) {
1839 		struct ip_moptions *imo;
1840 
1841 		imo = mopts;
1842 		if (imo->imo_multicast_if_index != 0) {
1843 			struct ifnet *ifp;
1844 			int s;
1845 
1846 			if (ia != NULL)
1847 				ia4_release(ia, psref);
1848 			s = pserialize_read_enter();
1849 			ifp = if_byindex(imo->imo_multicast_if_index);
1850 			if (ifp != NULL) {
1851 				/* XXX */
1852 				ia = in_get_ia_from_ifp_psref(ifp, psref);
1853 			} else
1854 				ia = NULL;
1855 			if (ia == NULL || ia->ia4_flags & IN_IFF_NOTREADY) {
1856 				pserialize_read_exit(s);
1857 				if (ia != NULL)
1858 					ia4_release(ia, psref);
1859 				*errorp = EADDRNOTAVAIL;
1860 				ia = NULL;
1861 				goto out;
1862 			}
1863 			pserialize_read_exit(s);
1864 		}
1865 	}
1866 	if (ia->ia_ifa.ifa_getifa != NULL) {
1867 		ia = ifatoia((*ia->ia_ifa.ifa_getifa)(&ia->ia_ifa,
1868 		                                      sintosa(sin)));
1869 		if (ia == NULL) {
1870 			*errorp = EADDRNOTAVAIL;
1871 			goto out;
1872 		}
1873 		/* FIXME NOMPSAFE */
1874 		ia4_acquire(ia, psref);
1875 	}
1876 #ifdef GETIFA_DEBUG
1877 	else
1878 		printf("%s: missing ifa_getifa\n", __func__);
1879 #endif
1880 out:
1881 	rtcache_unref(rt, ro);
1882 	return ia;
1883 }
1884 
1885 int
1886 in_tunnel_validate(const struct ip *ip, struct in_addr src, struct in_addr dst)
1887 {
1888 	struct in_ifaddr *ia4;
1889 	int s;
1890 
1891 	/* check for address match */
1892 	if (src.s_addr != ip->ip_dst.s_addr ||
1893 	    dst.s_addr != ip->ip_src.s_addr)
1894 		return 0;
1895 
1896 	/* martian filters on outer source - NOT done in ip_input! */
1897 	if (IN_MULTICAST(ip->ip_src.s_addr))
1898 		return 0;
1899 	switch ((ntohl(ip->ip_src.s_addr) & 0xff000000) >> 24) {
1900 	case 0:
1901 	case 127:
1902 	case 255:
1903 		return 0;
1904 	}
1905 	/* reject packets with broadcast on source */
1906 	s = pserialize_read_enter();
1907 	IN_ADDRLIST_READER_FOREACH(ia4) {
1908 		if ((ia4->ia_ifa.ifa_ifp->if_flags & IFF_BROADCAST) == 0)
1909 			continue;
1910 		if (ip->ip_src.s_addr == ia4->ia_broadaddr.sin_addr.s_addr) {
1911 			pserialize_read_exit(s);
1912 			return 0;
1913 		}
1914 	}
1915 	pserialize_read_exit(s);
1916 
1917 	/* NOTE: packet may dropped by uRPF */
1918 
1919 	/* return valid bytes length */
1920 	return sizeof(src) + sizeof(dst);
1921 }
1922 
1923 #if NARP > 0
1924 
1925 #define	IN_LLTBL_DEFAULT_HSIZE	32
1926 #define	IN_LLTBL_HASH(k, h) \
1927 	(((((((k >> 8) ^ k) >> 8) ^ k) >> 8) ^ k) & ((h) - 1))
1928 
1929 /*
1930  * Do actual deallocation of @lle.
1931  * Called by LLE_FREE_LOCKED when number of references
1932  * drops to zero.
1933  */
1934 static void
1935 in_lltable_destroy_lle(struct llentry *lle)
1936 {
1937 
1938 	KASSERT(lle->la_numheld == 0);
1939 
1940 	LLE_WUNLOCK(lle);
1941 	LLE_LOCK_DESTROY(lle);
1942 	llentry_pool_put(lle);
1943 }
1944 
1945 static struct llentry *
1946 in_lltable_new(struct in_addr addr4, u_int flags)
1947 {
1948 	struct llentry *lle;
1949 
1950 	lle = llentry_pool_get(PR_NOWAIT);
1951 	if (lle == NULL)		/* NB: caller generates msg */
1952 		return NULL;
1953 
1954 	/*
1955 	 * For IPv4 this will trigger "arpresolve" to generate
1956 	 * an ARP request.
1957 	 */
1958 	lle->la_expire = time_uptime; /* mark expired */
1959 	lle->r_l3addr.addr4 = addr4;
1960 	lle->lle_refcnt = 1;
1961 	lle->lle_free = in_lltable_destroy_lle;
1962 	LLE_LOCK_INIT(lle);
1963 	callout_init(&lle->la_timer, CALLOUT_MPSAFE);
1964 
1965 	return lle;
1966 }
1967 
1968 #define IN_ARE_MASKED_ADDR_EQUAL(d, a, m)	(			\
1969 	    (((ntohl((d).s_addr) ^ (a)->sin_addr.s_addr) & (m)->sin_addr.s_addr)) == 0 )
1970 
1971 static int
1972 in_lltable_match_prefix(const struct sockaddr *prefix,
1973     const struct sockaddr *mask, u_int flags, struct llentry *lle)
1974 {
1975 	const struct sockaddr_in *pfx = (const struct sockaddr_in *)prefix;
1976 	const struct sockaddr_in *msk = (const struct sockaddr_in *)mask;
1977 	struct in_addr lle_addr;
1978 
1979 	lle_addr.s_addr = ntohl(lle->r_l3addr.addr4.s_addr);
1980 
1981 	/*
1982 	 * (flags & LLE_STATIC) means deleting all entries
1983 	 * including static ARP entries.
1984 	 */
1985 	if (IN_ARE_MASKED_ADDR_EQUAL(lle_addr, pfx, msk) &&
1986 	    ((flags & LLE_STATIC) || !(lle->la_flags & LLE_STATIC)))
1987 		return (1);
1988 
1989 	return (0);
1990 }
1991 
1992 static void
1993 in_lltable_free_entry(struct lltable *llt, struct llentry *lle)
1994 {
1995 	size_t pkts_dropped;
1996 
1997 	LLE_WLOCK_ASSERT(lle);
1998 	KASSERT(llt != NULL);
1999 
2000 	pkts_dropped = llentry_free(lle);
2001 	arp_stat_add(ARP_STAT_DFRDROPPED, (uint64_t)pkts_dropped);
2002 }
2003 
2004 static int
2005 in_lltable_rtcheck(struct ifnet *ifp, u_int flags, const struct sockaddr *l3addr,
2006     const struct rtentry *rt)
2007 {
2008 	int error = EINVAL;
2009 
2010 	if (rt == NULL)
2011 		return error;
2012 
2013 	/*
2014 	 * If the gateway for an existing host route matches the target L3
2015 	 * address, which is a special route inserted by some implementation
2016 	 * such as MANET, and the interface is of the correct type, then
2017 	 * allow for ARP to proceed.
2018 	 */
2019 	if (rt->rt_flags & RTF_GATEWAY) {
2020 		if (!(rt->rt_flags & RTF_HOST) || !rt->rt_ifp ||
2021 		    rt->rt_ifp->if_type != IFT_ETHER ||
2022 		    (rt->rt_ifp->if_flags & IFF_NOARP) != 0 ||
2023 		    memcmp(rt->rt_gateway->sa_data, l3addr->sa_data,
2024 		    sizeof(in_addr_t)) != 0) {
2025 			goto error;
2026 		}
2027 	}
2028 
2029 	/*
2030 	 * Make sure that at least the destination address is covered
2031 	 * by the route. This is for handling the case where 2 or more
2032 	 * interfaces have the same prefix. An incoming packet arrives
2033 	 * on one interface and the corresponding outgoing packet leaves
2034 	 * another interface.
2035 	 */
2036 	if (!(rt->rt_flags & RTF_HOST) && rt->rt_ifp != ifp) {
2037 		const char *sa, *mask, *addr, *lim;
2038 		int len;
2039 
2040 		mask = (const char *)rt_mask(rt);
2041 		/*
2042 		 * Just being extra cautious to avoid some custom
2043 		 * code getting into trouble.
2044 		 */
2045 		if (mask == NULL)
2046 			goto error;
2047 
2048 		sa = (const char *)rt_getkey(rt);
2049 		addr = (const char *)l3addr;
2050 		len = ((const struct sockaddr_in *)l3addr)->sin_len;
2051 		lim = addr + len;
2052 
2053 		for ( ; addr < lim; sa++, mask++, addr++) {
2054 			if ((*sa ^ *addr) & *mask) {
2055 #ifdef DIAGNOSTIC
2056 				log(LOG_INFO, "IPv4 address: \"%s\" is not on the network\n",
2057 				    inet_ntoa(((const struct sockaddr_in *)l3addr)->sin_addr));
2058 #endif
2059 				goto error;
2060 			}
2061 		}
2062 	}
2063 
2064 	error = 0;
2065 error:
2066 	return error;
2067 }
2068 
2069 static inline uint32_t
2070 in_lltable_hash_dst(const struct in_addr dst, uint32_t hsize)
2071 {
2072 
2073 	return (IN_LLTBL_HASH(dst.s_addr, hsize));
2074 }
2075 
2076 static uint32_t
2077 in_lltable_hash(const struct llentry *lle, uint32_t hsize)
2078 {
2079 
2080 	return (in_lltable_hash_dst(lle->r_l3addr.addr4, hsize));
2081 }
2082 
2083 static void
2084 in_lltable_fill_sa_entry(const struct llentry *lle, struct sockaddr *sa)
2085 {
2086 	struct sockaddr_in *sin;
2087 
2088 	sin = (struct sockaddr_in *)sa;
2089 	memset(sin, 0, sizeof(*sin));
2090 	sin->sin_family = AF_INET;
2091 	sin->sin_len = sizeof(*sin);
2092 	sin->sin_addr = lle->r_l3addr.addr4;
2093 }
2094 
2095 static inline struct llentry *
2096 in_lltable_find_dst(struct lltable *llt, struct in_addr dst)
2097 {
2098 	struct llentry *lle;
2099 	struct llentries *lleh;
2100 	u_int hashidx;
2101 
2102 	hashidx = in_lltable_hash_dst(dst, llt->llt_hsize);
2103 	lleh = &llt->lle_head[hashidx];
2104 	LIST_FOREACH(lle, lleh, lle_next) {
2105 		if (lle->la_flags & LLE_DELETED)
2106 			continue;
2107 		if (lle->r_l3addr.addr4.s_addr == dst.s_addr)
2108 			break;
2109 	}
2110 
2111 	return (lle);
2112 }
2113 
2114 static int
2115 in_lltable_delete(struct lltable *llt, u_int flags,
2116     const struct sockaddr *l3addr)
2117 {
2118 	const struct sockaddr_in *sin = (const struct sockaddr_in *)l3addr;
2119 	struct ifnet *ifp __diagused = llt->llt_ifp;
2120 	struct llentry *lle;
2121 
2122 	IF_AFDATA_WLOCK_ASSERT(ifp);
2123 	KASSERTMSG(l3addr->sa_family == AF_INET,
2124 	    "sin_family %d", l3addr->sa_family);
2125 
2126 	lle = in_lltable_find_dst(llt, sin->sin_addr);
2127 	if (lle == NULL) {
2128 #ifdef LLTABLE_DEBUG
2129 		char buf[64];
2130 		sockaddr_format(l3addr, buf, sizeof(buf));
2131 		log(LOG_INFO, "%s: cache for %s is not found\n",
2132 		    __func__, buf);
2133 #endif
2134 		return (ENOENT);
2135 	}
2136 
2137 	LLE_WLOCK(lle);
2138 #ifdef LLTABLE_DEBUG
2139 	{
2140 		char buf[64];
2141 		sockaddr_format(l3addr, buf, sizeof(buf));
2142 		log(LOG_INFO, "%s: cache for %s (%p) is deleted\n",
2143 		    __func__, buf, lle);
2144 	}
2145 #endif
2146 	llentry_free(lle);
2147 
2148 	return (0);
2149 }
2150 
2151 static struct llentry *
2152 in_lltable_create(struct lltable *llt, u_int flags, const struct sockaddr *l3addr,
2153     const struct rtentry *rt)
2154 {
2155 	const struct sockaddr_in *sin = (const struct sockaddr_in *)l3addr;
2156 	struct ifnet *ifp = llt->llt_ifp;
2157 	struct llentry *lle;
2158 
2159 	IF_AFDATA_WLOCK_ASSERT(ifp);
2160 	KASSERTMSG(l3addr->sa_family == AF_INET,
2161 	    "sin_family %d", l3addr->sa_family);
2162 
2163 	lle = in_lltable_find_dst(llt, sin->sin_addr);
2164 
2165 	if (lle != NULL) {
2166 		LLE_WLOCK(lle);
2167 		return (lle);
2168 	}
2169 
2170 	/* no existing record, we need to create new one */
2171 
2172 	/*
2173 	 * A route that covers the given address must have
2174 	 * been installed 1st because we are doing a resolution,
2175 	 * verify this.
2176 	 */
2177 	if (!(flags & LLE_IFADDR) &&
2178 	    in_lltable_rtcheck(ifp, flags, l3addr, rt) != 0)
2179 		return (NULL);
2180 
2181 	lle = in_lltable_new(sin->sin_addr, flags);
2182 	if (lle == NULL) {
2183 		log(LOG_INFO, "lla_lookup: new lle malloc failed\n");
2184 		return (NULL);
2185 	}
2186 	lle->la_flags = flags;
2187 	if ((flags & LLE_IFADDR) == LLE_IFADDR) {
2188 		memcpy(&lle->ll_addr, CLLADDR(ifp->if_sadl), ifp->if_addrlen);
2189 		lle->la_flags |= (LLE_VALID | LLE_STATIC);
2190 	}
2191 
2192 	lltable_link_entry(llt, lle);
2193 	LLE_WLOCK(lle);
2194 
2195 	return (lle);
2196 }
2197 
2198 /*
2199  * Return NULL if not found or marked for deletion.
2200  * If found return lle read locked.
2201  */
2202 static struct llentry *
2203 in_lltable_lookup(struct lltable *llt, u_int flags, const struct sockaddr *l3addr)
2204 {
2205 	const struct sockaddr_in *sin = (const struct sockaddr_in *)l3addr;
2206 	struct llentry *lle;
2207 
2208 	IF_AFDATA_LOCK_ASSERT(llt->llt_ifp);
2209 	KASSERTMSG(l3addr->sa_family == AF_INET,
2210 	    "sin_family %d", l3addr->sa_family);
2211 
2212 	lle = in_lltable_find_dst(llt, sin->sin_addr);
2213 
2214 	if (lle == NULL)
2215 		return NULL;
2216 
2217 	if (flags & LLE_EXCLUSIVE)
2218 		LLE_WLOCK(lle);
2219 	else
2220 		LLE_RLOCK(lle);
2221 
2222 	return lle;
2223 }
2224 
2225 static int
2226 in_lltable_dump_entry(struct lltable *llt, struct llentry *lle,
2227     struct rt_walkarg *w)
2228 {
2229 	struct sockaddr_in sin;
2230 
2231 	LLTABLE_LOCK_ASSERT();
2232 
2233 	/* skip deleted entries */
2234 	if (lle->la_flags & LLE_DELETED)
2235 		return 0;
2236 
2237 	sockaddr_in_init(&sin, &lle->r_l3addr.addr4, 0);
2238 
2239 	return lltable_dump_entry(llt, lle, w, sintosa(&sin));
2240 }
2241 
2242 #endif /* NARP > 0 */
2243 
2244 static int
2245 in_multicast_sysctl(SYSCTLFN_ARGS)
2246 {
2247 	struct ifnet *ifp;
2248 	struct ifaddr *ifa;
2249 	struct in_ifaddr *ifa4;
2250 	struct in_multi *inm;
2251 	uint32_t tmp;
2252 	int error;
2253 	size_t written;
2254 	struct psref psref;
2255 	int bound;
2256 
2257 	if (namelen != 1)
2258 		return EINVAL;
2259 
2260 	bound = curlwp_bind();
2261 	ifp = if_get_byindex(name[0], &psref);
2262 	if (ifp == NULL) {
2263 		curlwp_bindx(bound);
2264 		return ENODEV;
2265 	}
2266 
2267 	if (oldp == NULL) {
2268 		*oldlenp = 0;
2269 		IFADDR_FOREACH(ifa, ifp) {
2270 			if (ifa->ifa_addr->sa_family != AF_INET)
2271 				continue;
2272 			ifa4 = (void *)ifa;
2273 			LIST_FOREACH(inm, &ifa4->ia_multiaddrs, inm_list) {
2274 				*oldlenp += 2 * sizeof(struct in_addr) +
2275 				    sizeof(uint32_t);
2276 			}
2277 		}
2278 		if_put(ifp, &psref);
2279 		curlwp_bindx(bound);
2280 		return 0;
2281 	}
2282 
2283 	error = 0;
2284 	written = 0;
2285 	IFADDR_FOREACH(ifa, ifp) {
2286 		if (ifa->ifa_addr->sa_family != AF_INET)
2287 			continue;
2288 		ifa4 = (void *)ifa;
2289 		LIST_FOREACH(inm, &ifa4->ia_multiaddrs, inm_list) {
2290 			if (written + 2 * sizeof(struct in_addr) +
2291 			    sizeof(uint32_t) > *oldlenp)
2292 				goto done;
2293 			error = sysctl_copyout(l, &ifa4->ia_addr.sin_addr,
2294 			    oldp, sizeof(struct in_addr));
2295 			if (error)
2296 				goto done;
2297 			oldp = (char *)oldp + sizeof(struct in_addr);
2298 			written += sizeof(struct in_addr);
2299 			error = sysctl_copyout(l, &inm->inm_addr,
2300 			    oldp, sizeof(struct in_addr));
2301 			if (error)
2302 				goto done;
2303 			oldp = (char *)oldp + sizeof(struct in_addr);
2304 			written += sizeof(struct in_addr);
2305 			tmp = inm->inm_refcount;
2306 			error = sysctl_copyout(l, &tmp, oldp, sizeof(tmp));
2307 			if (error)
2308 				goto done;
2309 			oldp = (char *)oldp + sizeof(tmp);
2310 			written += sizeof(tmp);
2311 		}
2312 	}
2313 done:
2314 	if_put(ifp, &psref);
2315 	curlwp_bindx(bound);
2316 	*oldlenp = written;
2317 	return error;
2318 }
2319 
2320 static void
2321 in_sysctl_init(struct sysctllog **clog)
2322 {
2323 	sysctl_createv(clog, 0, NULL, NULL,
2324 		       CTLFLAG_PERMANENT,
2325 		       CTLTYPE_NODE, "inet",
2326 		       SYSCTL_DESCR("PF_INET related settings"),
2327 		       NULL, 0, NULL, 0,
2328 		       CTL_NET, PF_INET, CTL_EOL);
2329 	sysctl_createv(clog, 0, NULL, NULL,
2330 		       CTLFLAG_PERMANENT,
2331 		       CTLTYPE_NODE, "multicast",
2332 		       SYSCTL_DESCR("Multicast information"),
2333 		       in_multicast_sysctl, 0, NULL, 0,
2334 		       CTL_NET, PF_INET, CTL_CREATE, CTL_EOL);
2335 	sysctl_createv(clog, 0, NULL, NULL,
2336 		       CTLFLAG_PERMANENT,
2337 		       CTLTYPE_NODE, "ip",
2338 		       SYSCTL_DESCR("IPv4 related settings"),
2339 		       NULL, 0, NULL, 0,
2340 		       CTL_NET, PF_INET, IPPROTO_IP, CTL_EOL);
2341 
2342 	sysctl_createv(clog, 0, NULL, NULL,
2343 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
2344 		       CTLTYPE_INT, "subnetsarelocal",
2345 		       SYSCTL_DESCR("Whether logical subnets are considered "
2346 				    "local"),
2347 		       NULL, 0, &subnetsarelocal, 0,
2348 		       CTL_NET, PF_INET, IPPROTO_IP,
2349 		       IPCTL_SUBNETSARELOCAL, CTL_EOL);
2350 	sysctl_createv(clog, 0, NULL, NULL,
2351 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
2352 		       CTLTYPE_INT, "hostzerobroadcast",
2353 		       SYSCTL_DESCR("All zeroes address is broadcast address"),
2354 		       NULL, 0, &hostzeroisbroadcast, 0,
2355 		       CTL_NET, PF_INET, IPPROTO_IP,
2356 		       IPCTL_HOSTZEROBROADCAST, CTL_EOL);
2357 }
2358 
2359 #if NARP > 0
2360 
2361 static struct lltable *
2362 in_lltattach(struct ifnet *ifp)
2363 {
2364 	struct lltable *llt;
2365 
2366 	llt = lltable_allocate_htbl(IN_LLTBL_DEFAULT_HSIZE);
2367 	llt->llt_af = AF_INET;
2368 	llt->llt_ifp = ifp;
2369 
2370 	llt->llt_lookup = in_lltable_lookup;
2371 	llt->llt_create = in_lltable_create;
2372 	llt->llt_delete = in_lltable_delete;
2373 	llt->llt_dump_entry = in_lltable_dump_entry;
2374 	llt->llt_hash = in_lltable_hash;
2375 	llt->llt_fill_sa_entry = in_lltable_fill_sa_entry;
2376 	llt->llt_free_entry = in_lltable_free_entry;
2377 	llt->llt_match_prefix = in_lltable_match_prefix;
2378 	lltable_link(llt);
2379 
2380 	return (llt);
2381 }
2382 
2383 #endif /* NARP > 0 */
2384 
2385 void *
2386 in_domifattach(struct ifnet *ifp)
2387 {
2388 	struct in_ifinfo *ii;
2389 
2390 	ii = kmem_zalloc(sizeof(struct in_ifinfo), KM_SLEEP);
2391 
2392 #if NARP > 0
2393 	ii->ii_llt = in_lltattach(ifp);
2394 #endif
2395 
2396 #ifdef IPSELSRC
2397 	ii->ii_selsrc = in_selsrc_domifattach(ifp);
2398 	KASSERT(ii->ii_selsrc != NULL);
2399 #endif
2400 
2401 	return ii;
2402 }
2403 
2404 void
2405 in_domifdetach(struct ifnet *ifp, void *aux)
2406 {
2407 	struct in_ifinfo *ii = aux;
2408 
2409 #ifdef IPSELSRC
2410 	in_selsrc_domifdetach(ifp, ii->ii_selsrc);
2411 #endif
2412 #if NARP > 0
2413 	lltable_free(ii->ii_llt);
2414 #endif
2415 	kmem_free(ii, sizeof(struct in_ifinfo));
2416 }
2417