xref: /freebsd/sys/netinet/in.c (revision ba00ec3d539f213abbda3a45ef8c539306cac098)
1 /*-
2  * Copyright (c) 1982, 1986, 1991, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  * Copyright (C) 2001 WIDE Project.  All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  * 4. Neither the name of the University nor the names of its contributors
15  *    may be used to endorse or promote products derived from this software
16  *    without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
19  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
22  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28  * SUCH DAMAGE.
29  *
30  *	@(#)in.c	8.4 (Berkeley) 1/9/95
31  */
32 
33 #include <sys/cdefs.h>
34 __FBSDID("$FreeBSD$");
35 
36 #include "opt_mpath.h"
37 
38 #include <sys/param.h>
39 #include <sys/systm.h>
40 #include <sys/sockio.h>
41 #include <sys/malloc.h>
42 #include <sys/priv.h>
43 #include <sys/socket.h>
44 #include <sys/jail.h>
45 #include <sys/kernel.h>
46 #include <sys/proc.h>
47 #include <sys/sysctl.h>
48 #include <sys/syslog.h>
49 
50 #include <net/if.h>
51 #include <net/if_var.h>
52 #include <net/if_arp.h>
53 #include <net/if_dl.h>
54 #include <net/if_llatbl.h>
55 #include <net/if_types.h>
56 #include <net/route.h>
57 #include <net/vnet.h>
58 
59 #include <netinet/if_ether.h>
60 #include <netinet/in.h>
61 #include <netinet/in_var.h>
62 #include <netinet/in_pcb.h>
63 #include <netinet/ip_var.h>
64 #include <netinet/ip_carp.h>
65 #include <netinet/igmp_var.h>
66 #include <netinet/udp.h>
67 #include <netinet/udp_var.h>
68 
69 static int in_mask2len(struct in_addr *);
70 static void in_len2mask(struct in_addr *, int);
71 static int in_lifaddr_ioctl(struct socket *, u_long, caddr_t,
72 	struct ifnet *, struct thread *);
73 
74 static void	in_socktrim(struct sockaddr_in *);
75 static int	in_ifinit(struct ifnet *, struct in_ifaddr *,
76 		    struct sockaddr_in *, int, int);
77 static void	in_purgemaddrs(struct ifnet *);
78 
79 static VNET_DEFINE(int, nosameprefix);
80 #define	V_nosameprefix			VNET(nosameprefix)
81 SYSCTL_VNET_INT(_net_inet_ip, OID_AUTO, no_same_prefix, CTLFLAG_RW,
82 	&VNET_NAME(nosameprefix), 0,
83 	"Refuse to create same prefixes on different interfaces");
84 
85 VNET_DECLARE(struct inpcbinfo, ripcbinfo);
86 #define	V_ripcbinfo			VNET(ripcbinfo)
87 
88 VNET_DECLARE(struct arpstat, arpstat);  /* ARP statistics, see if_arp.h */
89 #define	V_arpstat		VNET(arpstat)
90 
91 /*
92  * Return 1 if an internet address is for a ``local'' host
93  * (one to which we have a connection).
94  */
95 int
96 in_localaddr(struct in_addr in)
97 {
98 	register u_long i = ntohl(in.s_addr);
99 	register struct in_ifaddr *ia;
100 
101 	IN_IFADDR_RLOCK();
102 	TAILQ_FOREACH(ia, &V_in_ifaddrhead, ia_link) {
103 		if ((i & ia->ia_subnetmask) == ia->ia_subnet) {
104 			IN_IFADDR_RUNLOCK();
105 			return (1);
106 		}
107 	}
108 	IN_IFADDR_RUNLOCK();
109 	return (0);
110 }
111 
112 /*
113  * Return 1 if an internet address is for the local host and configured
114  * on one of its interfaces.
115  */
116 int
117 in_localip(struct in_addr in)
118 {
119 	struct in_ifaddr *ia;
120 
121 	IN_IFADDR_RLOCK();
122 	LIST_FOREACH(ia, INADDR_HASH(in.s_addr), ia_hash) {
123 		if (IA_SIN(ia)->sin_addr.s_addr == in.s_addr) {
124 			IN_IFADDR_RUNLOCK();
125 			return (1);
126 		}
127 	}
128 	IN_IFADDR_RUNLOCK();
129 	return (0);
130 }
131 
132 /*
133  * Determine whether an IP address is in a reserved set of addresses
134  * that may not be forwarded, or whether datagrams to that destination
135  * may be forwarded.
136  */
137 int
138 in_canforward(struct in_addr in)
139 {
140 	register u_long i = ntohl(in.s_addr);
141 	register u_long net;
142 
143 	if (IN_EXPERIMENTAL(i) || IN_MULTICAST(i) || IN_LINKLOCAL(i))
144 		return (0);
145 	if (IN_CLASSA(i)) {
146 		net = i & IN_CLASSA_NET;
147 		if (net == 0 || net == (IN_LOOPBACKNET << IN_CLASSA_NSHIFT))
148 			return (0);
149 	}
150 	return (1);
151 }
152 
153 /*
154  * Trim a mask in a sockaddr
155  */
156 static void
157 in_socktrim(struct sockaddr_in *ap)
158 {
159     register char *cplim = (char *) &ap->sin_addr;
160     register char *cp = (char *) (&ap->sin_addr + 1);
161 
162     ap->sin_len = 0;
163     while (--cp >= cplim)
164 	if (*cp) {
165 	    (ap)->sin_len = cp - (char *) (ap) + 1;
166 	    break;
167 	}
168 }
169 
170 static int
171 in_mask2len(mask)
172 	struct in_addr *mask;
173 {
174 	int x, y;
175 	u_char *p;
176 
177 	p = (u_char *)mask;
178 	for (x = 0; x < sizeof(*mask); x++) {
179 		if (p[x] != 0xff)
180 			break;
181 	}
182 	y = 0;
183 	if (x < sizeof(*mask)) {
184 		for (y = 0; y < 8; y++) {
185 			if ((p[x] & (0x80 >> y)) == 0)
186 				break;
187 		}
188 	}
189 	return (x * 8 + y);
190 }
191 
192 static void
193 in_len2mask(struct in_addr *mask, int len)
194 {
195 	int i;
196 	u_char *p;
197 
198 	p = (u_char *)mask;
199 	bzero(mask, sizeof(*mask));
200 	for (i = 0; i < len / 8; i++)
201 		p[i] = 0xff;
202 	if (len % 8)
203 		p[i] = (0xff00 >> (len % 8)) & 0xff;
204 }
205 
206 /*
207  * Generic internet control operations (ioctl's).
208  *
209  * ifp is NULL if not an interface-specific ioctl.
210  */
211 /* ARGSUSED */
212 int
213 in_control(struct socket *so, u_long cmd, caddr_t data, struct ifnet *ifp,
214     struct thread *td)
215 {
216 	register struct ifreq *ifr = (struct ifreq *)data;
217 	register struct in_ifaddr *ia, *iap;
218 	register struct ifaddr *ifa;
219 	struct in_addr allhosts_addr;
220 	struct in_addr dst;
221 	struct in_ifinfo *ii;
222 	struct in_aliasreq *ifra = (struct in_aliasreq *)data;
223 	int error, hostIsNew, iaIsNew, maskIsNew;
224 	int iaIsFirst;
225 	u_long ocmd = cmd;
226 
227 	/*
228 	 * Pre-10.x compat: OSIOCAIFADDR passes a shorter
229 	 * struct in_aliasreq, without ifra_vhid.
230 	 */
231 	if (cmd == OSIOCAIFADDR)
232 		cmd = SIOCAIFADDR;
233 
234 	ia = NULL;
235 	iaIsFirst = 0;
236 	iaIsNew = 0;
237 	allhosts_addr.s_addr = htonl(INADDR_ALLHOSTS_GROUP);
238 
239 	/*
240 	 * Filter out ioctls we implement directly; forward the rest on to
241 	 * in_lifaddr_ioctl() and ifp->if_ioctl().
242 	 */
243 	switch (cmd) {
244 	case SIOCGIFADDR:
245 	case SIOCGIFBRDADDR:
246 	case SIOCGIFDSTADDR:
247 	case SIOCGIFNETMASK:
248 	case SIOCDIFADDR:
249 		break;
250 	case SIOCAIFADDR:
251 		/*
252 		 * ifra_addr must be present and be of INET family.
253 		 * ifra_broadaddr and ifra_mask are optional.
254 		 */
255 		if (ifra->ifra_addr.sin_len != sizeof(struct sockaddr_in) ||
256 		    ifra->ifra_addr.sin_family != AF_INET)
257 			return (EINVAL);
258 		if (ifra->ifra_broadaddr.sin_len != 0 &&
259 		    (ifra->ifra_broadaddr.sin_len !=
260 		    sizeof(struct sockaddr_in) ||
261 		    ifra->ifra_broadaddr.sin_family != AF_INET))
262 			return (EINVAL);
263 #if 0
264 		/*
265 		 * ifconfig(8) in pre-10.x doesn't set sin_family for the
266 		 * mask. The code is disabled for the 10.x timeline, to
267 		 * make SIOCAIFADDR compatible with 9.x ifconfig(8).
268 		 * The code should be enabled in 11.x
269 		 */
270 		if (ifra->ifra_mask.sin_len != 0 &&
271 		    (ifra->ifra_mask.sin_len != sizeof(struct sockaddr_in) ||
272 		    ifra->ifra_mask.sin_family != AF_INET))
273 			return (EINVAL);
274 #endif
275 		break;
276 	case SIOCSIFADDR:
277 	case SIOCSIFBRDADDR:
278 	case SIOCSIFDSTADDR:
279 	case SIOCSIFNETMASK:
280 		/* We no longer support that old commands. */
281 		return (EINVAL);
282 
283 	case SIOCALIFADDR:
284 		if (td != NULL) {
285 			error = priv_check(td, PRIV_NET_ADDIFADDR);
286 			if (error)
287 				return (error);
288 		}
289 		if (ifp == NULL)
290 			return (EINVAL);
291 		return in_lifaddr_ioctl(so, cmd, data, ifp, td);
292 
293 	case SIOCDLIFADDR:
294 		if (td != NULL) {
295 			error = priv_check(td, PRIV_NET_DELIFADDR);
296 			if (error)
297 				return (error);
298 		}
299 		if (ifp == NULL)
300 			return (EINVAL);
301 		return in_lifaddr_ioctl(so, cmd, data, ifp, td);
302 
303 	case SIOCGLIFADDR:
304 		if (ifp == NULL)
305 			return (EINVAL);
306 		return in_lifaddr_ioctl(so, cmd, data, ifp, td);
307 
308 	default:
309 		if (ifp == NULL || ifp->if_ioctl == NULL)
310 			return (EOPNOTSUPP);
311 		return ((*ifp->if_ioctl)(ifp, cmd, data));
312 	}
313 
314 	if (ifp == NULL)
315 		return (EADDRNOTAVAIL);
316 
317 	/*
318 	 * Security checks before we get involved in any work.
319 	 */
320 	switch (cmd) {
321 	case SIOCAIFADDR:
322 		if (td != NULL) {
323 			error = priv_check(td, PRIV_NET_ADDIFADDR);
324 			if (error)
325 				return (error);
326 		}
327 		break;
328 
329 	case SIOCDIFADDR:
330 		if (td != NULL) {
331 			error = priv_check(td, PRIV_NET_DELIFADDR);
332 			if (error)
333 				return (error);
334 		}
335 		break;
336 	}
337 
338 	/*
339 	 * Find address for this interface, if it exists.
340 	 *
341 	 * If an alias address was specified, find that one instead of the
342 	 * first one on the interface, if possible.
343 	 */
344 	dst = ((struct sockaddr_in *)&ifr->ifr_addr)->sin_addr;
345 	IN_IFADDR_RLOCK();
346 	LIST_FOREACH(iap, INADDR_HASH(dst.s_addr), ia_hash) {
347 		if (iap->ia_ifp == ifp &&
348 		    iap->ia_addr.sin_addr.s_addr == dst.s_addr) {
349 			if (td == NULL || prison_check_ip4(td->td_ucred,
350 			    &dst) == 0)
351 				ia = iap;
352 			break;
353 		}
354 	}
355 	if (ia != NULL)
356 		ifa_ref(&ia->ia_ifa);
357 	IN_IFADDR_RUNLOCK();
358 	if (ia == NULL) {
359 		IF_ADDR_RLOCK(ifp);
360 		TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
361 			iap = ifatoia(ifa);
362 			if (iap->ia_addr.sin_family == AF_INET) {
363 				if (td != NULL &&
364 				    prison_check_ip4(td->td_ucred,
365 				    &iap->ia_addr.sin_addr) != 0)
366 					continue;
367 				ia = iap;
368 				break;
369 			}
370 		}
371 		if (ia != NULL)
372 			ifa_ref(&ia->ia_ifa);
373 		IF_ADDR_RUNLOCK(ifp);
374 	}
375 	if (ia == NULL)
376 		iaIsFirst = 1;
377 
378 	error = 0;
379 	switch (cmd) {
380 	case SIOCAIFADDR:
381 	case SIOCDIFADDR:
382 		if (ifra->ifra_addr.sin_family == AF_INET) {
383 			struct in_ifaddr *oia;
384 
385 			IN_IFADDR_RLOCK();
386 			for (oia = ia; ia; ia = TAILQ_NEXT(ia, ia_link)) {
387 				if (ia->ia_ifp == ifp  &&
388 				    ia->ia_addr.sin_addr.s_addr ==
389 				    ifra->ifra_addr.sin_addr.s_addr)
390 					break;
391 			}
392 			if (ia != NULL && ia != oia)
393 				ifa_ref(&ia->ia_ifa);
394 			if (oia != NULL && ia != oia)
395 				ifa_free(&oia->ia_ifa);
396 			IN_IFADDR_RUNLOCK();
397 			if ((ifp->if_flags & IFF_POINTOPOINT)
398 			    && (cmd == SIOCAIFADDR)
399 			    && (ifra->ifra_dstaddr.sin_addr.s_addr
400 				== INADDR_ANY)) {
401 				error = EDESTADDRREQ;
402 				goto out;
403 			}
404 		}
405 		if (cmd == SIOCDIFADDR && ia == NULL) {
406 			error = EADDRNOTAVAIL;
407 			goto out;
408 		}
409 		if (ia == NULL) {
410 			ia = (struct in_ifaddr *)
411 				malloc(sizeof *ia, M_IFADDR, M_NOWAIT |
412 				    M_ZERO);
413 			if (ia == NULL) {
414 				error = ENOBUFS;
415 				goto out;
416 			}
417 
418 			ifa = &ia->ia_ifa;
419 			ifa_init(ifa);
420 			ifa->ifa_addr = (struct sockaddr *)&ia->ia_addr;
421 			ifa->ifa_dstaddr = (struct sockaddr *)&ia->ia_dstaddr;
422 			ifa->ifa_netmask = (struct sockaddr *)&ia->ia_sockmask;
423 
424 			ia->ia_sockmask.sin_len = 8;
425 			ia->ia_sockmask.sin_family = AF_INET;
426 			if (ifp->if_flags & IFF_BROADCAST) {
427 				ia->ia_broadaddr.sin_len = sizeof(ia->ia_addr);
428 				ia->ia_broadaddr.sin_family = AF_INET;
429 			}
430 			ia->ia_ifp = ifp;
431 
432 			ifa_ref(ifa);			/* if_addrhead */
433 			IF_ADDR_WLOCK(ifp);
434 			TAILQ_INSERT_TAIL(&ifp->if_addrhead, ifa, ifa_link);
435 			IF_ADDR_WUNLOCK(ifp);
436 			ifa_ref(ifa);			/* in_ifaddrhead */
437 			IN_IFADDR_WLOCK();
438 			TAILQ_INSERT_TAIL(&V_in_ifaddrhead, ia, ia_link);
439 			IN_IFADDR_WUNLOCK();
440 			iaIsNew = 1;
441 		}
442 		break;
443 
444 	case SIOCGIFADDR:
445 	case SIOCGIFNETMASK:
446 	case SIOCGIFDSTADDR:
447 	case SIOCGIFBRDADDR:
448 		if (ia == NULL) {
449 			error = EADDRNOTAVAIL;
450 			goto out;
451 		}
452 		break;
453 	}
454 
455 	/*
456 	 * Most paths in this switch return directly or via out.  Only paths
457 	 * that remove the address break in order to hit common removal code.
458 	 */
459 	switch (cmd) {
460 	case SIOCGIFADDR:
461 		*((struct sockaddr_in *)&ifr->ifr_addr) = ia->ia_addr;
462 		goto out;
463 
464 	case SIOCGIFBRDADDR:
465 		if ((ifp->if_flags & IFF_BROADCAST) == 0) {
466 			error = EINVAL;
467 			goto out;
468 		}
469 		*((struct sockaddr_in *)&ifr->ifr_dstaddr) = ia->ia_broadaddr;
470 		goto out;
471 
472 	case SIOCGIFDSTADDR:
473 		if ((ifp->if_flags & IFF_POINTOPOINT) == 0) {
474 			error = EINVAL;
475 			goto out;
476 		}
477 		*((struct sockaddr_in *)&ifr->ifr_dstaddr) = ia->ia_dstaddr;
478 		goto out;
479 
480 	case SIOCGIFNETMASK:
481 		*((struct sockaddr_in *)&ifr->ifr_addr) = ia->ia_sockmask;
482 		goto out;
483 
484 	case SIOCAIFADDR:
485 		maskIsNew = 0;
486 		hostIsNew = 1;
487 		error = 0;
488 		if (ifra->ifra_addr.sin_addr.s_addr ==
489 			    ia->ia_addr.sin_addr.s_addr)
490 			hostIsNew = 0;
491 		if (ifra->ifra_mask.sin_len) {
492 			/*
493 			 * QL: XXX
494 			 * Need to scrub the prefix here in case
495 			 * the issued command is SIOCAIFADDR with
496 			 * the same address, but with a different
497 			 * prefix length. And if the prefix length
498 			 * is the same as before, then the call is
499 			 * un-necessarily executed here.
500 			 */
501 			in_ifscrub(ifp, ia, LLE_STATIC);
502 			ia->ia_sockmask = ifra->ifra_mask;
503 			ia->ia_sockmask.sin_family = AF_INET;
504 			ia->ia_subnetmask =
505 			    ntohl(ia->ia_sockmask.sin_addr.s_addr);
506 			maskIsNew = 1;
507 		}
508 		if ((ifp->if_flags & IFF_POINTOPOINT) &&
509 		    (ifra->ifra_dstaddr.sin_family == AF_INET)) {
510 			in_ifscrub(ifp, ia, LLE_STATIC);
511 			ia->ia_dstaddr = ifra->ifra_dstaddr;
512 			maskIsNew  = 1; /* We lie; but the effect's the same */
513 		}
514 		if (hostIsNew || maskIsNew)
515 			error = in_ifinit(ifp, ia, &ifra->ifra_addr, maskIsNew,
516 			    (ocmd == cmd ? ifra->ifra_vhid : 0));
517 		if (error != 0 && iaIsNew)
518 			break;
519 
520 		if ((ifp->if_flags & IFF_BROADCAST) &&
521 		    ifra->ifra_broadaddr.sin_len)
522 			ia->ia_broadaddr = ifra->ifra_broadaddr;
523 		if (error == 0) {
524 			ii = ((struct in_ifinfo *)ifp->if_afdata[AF_INET]);
525 			if (iaIsFirst &&
526 			    (ifp->if_flags & IFF_MULTICAST) != 0) {
527 				error = in_joingroup(ifp, &allhosts_addr,
528 				    NULL, &ii->ii_allhosts);
529 			}
530 			EVENTHANDLER_INVOKE(ifaddr_event, ifp);
531 		}
532 		goto out;
533 
534 	case SIOCDIFADDR:
535 		/*
536 		 * in_ifscrub kills the interface route.
537 		 */
538 		in_ifscrub(ifp, ia, LLE_STATIC);
539 
540 		/*
541 		 * in_ifadown gets rid of all the rest of
542 		 * the routes.  This is not quite the right
543 		 * thing to do, but at least if we are running
544 		 * a routing process they will come back.
545 		 */
546 		in_ifadown(&ia->ia_ifa, 1);
547 		EVENTHANDLER_INVOKE(ifaddr_event, ifp);
548 		error = 0;
549 		break;
550 
551 	default:
552 		panic("in_control: unsupported ioctl");
553 	}
554 
555 	if (ia->ia_ifa.ifa_carp)
556 		(*carp_detach_p)(&ia->ia_ifa);
557 
558 	IF_ADDR_WLOCK(ifp);
559 	/* Re-check that ia is still part of the list. */
560 	TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
561 		if (ifa == &ia->ia_ifa)
562 			break;
563 	}
564 	if (ifa == NULL) {
565 		/*
566 		 * If we lost the race with another thread, there is no need to
567 		 * try it again for the next loop as there is no other exit
568 		 * path between here and out.
569 		 */
570 		IF_ADDR_WUNLOCK(ifp);
571 		error = EADDRNOTAVAIL;
572 		goto out;
573 	}
574 	TAILQ_REMOVE(&ifp->if_addrhead, &ia->ia_ifa, ifa_link);
575 	IF_ADDR_WUNLOCK(ifp);
576 	ifa_free(&ia->ia_ifa);		      /* if_addrhead */
577 
578 	IN_IFADDR_WLOCK();
579 	TAILQ_REMOVE(&V_in_ifaddrhead, ia, ia_link);
580 
581 	LIST_REMOVE(ia, ia_hash);
582 	IN_IFADDR_WUNLOCK();
583 	/*
584 	 * If this is the last IPv4 address configured on this
585 	 * interface, leave the all-hosts group.
586 	 * No state-change report need be transmitted.
587 	 */
588 	IFP_TO_IA(ifp, iap);
589 	if (iap == NULL) {
590 		ii = ((struct in_ifinfo *)ifp->if_afdata[AF_INET]);
591 		IN_MULTI_LOCK();
592 		if (ii->ii_allhosts) {
593 			(void)in_leavegroup_locked(ii->ii_allhosts, NULL);
594 			ii->ii_allhosts = NULL;
595 		}
596 		IN_MULTI_UNLOCK();
597 	} else
598 		ifa_free(&iap->ia_ifa);
599 
600 	ifa_free(&ia->ia_ifa);				/* in_ifaddrhead */
601 out:
602 	if (ia != NULL)
603 		ifa_free(&ia->ia_ifa);
604 	return (error);
605 }
606 
607 /*
608  * SIOC[GAD]LIFADDR.
609  *	SIOCGLIFADDR: get first address. (?!?)
610  *	SIOCGLIFADDR with IFLR_PREFIX:
611  *		get first address that matches the specified prefix.
612  *	SIOCALIFADDR: add the specified address.
613  *	SIOCALIFADDR with IFLR_PREFIX:
614  *		EINVAL since we can't deduce hostid part of the address.
615  *	SIOCDLIFADDR: delete the specified address.
616  *	SIOCDLIFADDR with IFLR_PREFIX:
617  *		delete the first address that matches the specified prefix.
618  * return values:
619  *	EINVAL on invalid parameters
620  *	EADDRNOTAVAIL on prefix match failed/specified address not found
621  *	other values may be returned from in_ioctl()
622  */
623 static int
624 in_lifaddr_ioctl(struct socket *so, u_long cmd, caddr_t data,
625     struct ifnet *ifp, struct thread *td)
626 {
627 	struct if_laddrreq *iflr = (struct if_laddrreq *)data;
628 	struct ifaddr *ifa;
629 
630 	/* sanity checks */
631 	if (data == NULL || ifp == NULL) {
632 		panic("invalid argument to in_lifaddr_ioctl");
633 		/*NOTRECHED*/
634 	}
635 
636 	switch (cmd) {
637 	case SIOCGLIFADDR:
638 		/* address must be specified on GET with IFLR_PREFIX */
639 		if ((iflr->flags & IFLR_PREFIX) == 0)
640 			break;
641 		/*FALLTHROUGH*/
642 	case SIOCALIFADDR:
643 	case SIOCDLIFADDR:
644 		/* address must be specified on ADD and DELETE */
645 		if (iflr->addr.ss_family != AF_INET)
646 			return (EINVAL);
647 		if (iflr->addr.ss_len != sizeof(struct sockaddr_in))
648 			return (EINVAL);
649 		/* XXX need improvement */
650 		if (iflr->dstaddr.ss_family
651 		 && iflr->dstaddr.ss_family != AF_INET)
652 			return (EINVAL);
653 		if (iflr->dstaddr.ss_family
654 		 && iflr->dstaddr.ss_len != sizeof(struct sockaddr_in))
655 			return (EINVAL);
656 		break;
657 	default: /*shouldn't happen*/
658 		return (EOPNOTSUPP);
659 	}
660 	if (sizeof(struct in_addr) * 8 < iflr->prefixlen)
661 		return (EINVAL);
662 
663 	switch (cmd) {
664 	case SIOCALIFADDR:
665 	    {
666 		struct in_aliasreq ifra;
667 
668 		if (iflr->flags & IFLR_PREFIX)
669 			return (EINVAL);
670 
671 		/* copy args to in_aliasreq, perform ioctl(SIOCAIFADDR). */
672 		bzero(&ifra, sizeof(ifra));
673 		bcopy(iflr->iflr_name, ifra.ifra_name,
674 			sizeof(ifra.ifra_name));
675 
676 		bcopy(&iflr->addr, &ifra.ifra_addr, iflr->addr.ss_len);
677 
678 		if (iflr->dstaddr.ss_family) {	/*XXX*/
679 			bcopy(&iflr->dstaddr, &ifra.ifra_dstaddr,
680 				iflr->dstaddr.ss_len);
681 		}
682 
683 		ifra.ifra_mask.sin_family = AF_INET;
684 		ifra.ifra_mask.sin_len = sizeof(struct sockaddr_in);
685 		in_len2mask(&ifra.ifra_mask.sin_addr, iflr->prefixlen);
686 
687 		return (in_control(so, SIOCAIFADDR, (caddr_t)&ifra, ifp, td));
688 	    }
689 	case SIOCGLIFADDR:
690 	case SIOCDLIFADDR:
691 	    {
692 		struct in_ifaddr *ia;
693 		struct in_addr mask, candidate, match;
694 		struct sockaddr_in *sin;
695 
696 		bzero(&mask, sizeof(mask));
697 		bzero(&match, sizeof(match));
698 		if (iflr->flags & IFLR_PREFIX) {
699 			/* lookup a prefix rather than address. */
700 			in_len2mask(&mask, iflr->prefixlen);
701 
702 			sin = (struct sockaddr_in *)&iflr->addr;
703 			match.s_addr = sin->sin_addr.s_addr;
704 			match.s_addr &= mask.s_addr;
705 
706 			/* if you set extra bits, that's wrong */
707 			if (match.s_addr != sin->sin_addr.s_addr)
708 				return (EINVAL);
709 
710 		} else {
711 			/* on getting an address, take the 1st match */
712 			/* on deleting an address, do exact match */
713 			if (cmd != SIOCGLIFADDR) {
714 				in_len2mask(&mask, 32);
715 				sin = (struct sockaddr_in *)&iflr->addr;
716 				match.s_addr = sin->sin_addr.s_addr;
717 			}
718 		}
719 
720 		IF_ADDR_RLOCK(ifp);
721 		TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link)	{
722 			if (ifa->ifa_addr->sa_family != AF_INET)
723 				continue;
724 			if (match.s_addr == 0)
725 				break;
726 			sin = (struct sockaddr_in *)&ifa->ifa_addr;
727 			candidate.s_addr = sin->sin_addr.s_addr;
728 			candidate.s_addr &= mask.s_addr;
729 			if (candidate.s_addr == match.s_addr)
730 				break;
731 		}
732 		if (ifa != NULL)
733 			ifa_ref(ifa);
734 		IF_ADDR_RUNLOCK(ifp);
735 		if (ifa == NULL)
736 			return (EADDRNOTAVAIL);
737 		ia = (struct in_ifaddr *)ifa;
738 
739 		if (cmd == SIOCGLIFADDR) {
740 			/* fill in the if_laddrreq structure */
741 			bcopy(&ia->ia_addr, &iflr->addr, ia->ia_addr.sin_len);
742 
743 			if ((ifp->if_flags & IFF_POINTOPOINT) != 0) {
744 				bcopy(&ia->ia_dstaddr, &iflr->dstaddr,
745 					ia->ia_dstaddr.sin_len);
746 			} else
747 				bzero(&iflr->dstaddr, sizeof(iflr->dstaddr));
748 
749 			iflr->prefixlen =
750 				in_mask2len(&ia->ia_sockmask.sin_addr);
751 
752 			iflr->flags = 0;	/*XXX*/
753 			ifa_free(ifa);
754 
755 			return (0);
756 		} else {
757 			struct in_aliasreq ifra;
758 
759 			/* fill in_aliasreq and do ioctl(SIOCDIFADDR) */
760 			bzero(&ifra, sizeof(ifra));
761 			bcopy(iflr->iflr_name, ifra.ifra_name,
762 				sizeof(ifra.ifra_name));
763 
764 			bcopy(&ia->ia_addr, &ifra.ifra_addr,
765 				ia->ia_addr.sin_len);
766 			if ((ifp->if_flags & IFF_POINTOPOINT) != 0) {
767 				bcopy(&ia->ia_dstaddr, &ifra.ifra_dstaddr,
768 					ia->ia_dstaddr.sin_len);
769 			}
770 			bcopy(&ia->ia_sockmask, &ifra.ifra_dstaddr,
771 				ia->ia_sockmask.sin_len);
772 			ifa_free(ifa);
773 
774 			return (in_control(so, SIOCDIFADDR, (caddr_t)&ifra,
775 			    ifp, td));
776 		}
777 	    }
778 	}
779 
780 	return (EOPNOTSUPP);	/*just for safety*/
781 }
782 
783 /*
784  * Delete any existing route for an interface.
785  */
786 void
787 in_ifscrub(struct ifnet *ifp, struct in_ifaddr *ia, u_int flags)
788 {
789 
790 	in_scrubprefix(ia, flags);
791 }
792 
793 /*
794  * Initialize an interface's internet address
795  * and routing table entry.
796  */
797 static int
798 in_ifinit(struct ifnet *ifp, struct in_ifaddr *ia, struct sockaddr_in *sin,
799     int masksupplied, int vhid)
800 {
801 	register u_long i = ntohl(sin->sin_addr.s_addr);
802 	int flags, error = 0;
803 
804 	IN_IFADDR_WLOCK();
805 	if (ia->ia_addr.sin_family == AF_INET)
806 		LIST_REMOVE(ia, ia_hash);
807 	ia->ia_addr = *sin;
808 	LIST_INSERT_HEAD(INADDR_HASH(ia->ia_addr.sin_addr.s_addr),
809 	    ia, ia_hash);
810 	IN_IFADDR_WUNLOCK();
811 
812 	if (vhid > 0) {
813 		if (carp_attach_p != NULL)
814 			error = (*carp_attach_p)(&ia->ia_ifa, vhid);
815 		else
816 			error = EPROTONOSUPPORT;
817 	}
818 	if (error)
819 		return (error);
820 
821 	/*
822 	 * Give the interface a chance to initialize if this is its first
823 	 * address, and to validate the address if necessary.
824 	 *
825 	 * Historically, drivers managed IFF_UP flag theirselves, so we
826 	 * need to check whether driver did that.
827 	 */
828 	flags = ifp->if_flags;
829 	if (ifp->if_ioctl != NULL &&
830 	    (error = (*ifp->if_ioctl)(ifp, SIOCSIFADDR, (caddr_t)ia)) != 0)
831 			/* LIST_REMOVE(ia, ia_hash) is done in in_control */
832 			return (error);
833 	if ((ifp->if_flags & IFF_UP) && (flags & IFF_UP) == 0)
834 		if_up(ifp);
835 
836 	/*
837 	 * Be compatible with network classes, if netmask isn't supplied,
838 	 * guess it based on classes.
839 	 */
840 	if (!masksupplied) {
841 		if (IN_CLASSA(i))
842 			ia->ia_subnetmask = IN_CLASSA_NET;
843 		else if (IN_CLASSB(i))
844 			ia->ia_subnetmask = IN_CLASSB_NET;
845 		else
846 			ia->ia_subnetmask = IN_CLASSC_NET;
847 		ia->ia_sockmask.sin_addr.s_addr = htonl(ia->ia_subnetmask);
848 	}
849 	ia->ia_subnet = i & ia->ia_subnetmask;
850 	in_socktrim(&ia->ia_sockmask);
851 
852 	/*
853 	 * Add route for the network.
854 	 */
855 	flags = RTF_UP;
856 	ia->ia_ifa.ifa_metric = ifp->if_metric;
857 	if (ifp->if_flags & IFF_BROADCAST) {
858 		if (ia->ia_subnetmask == IN_RFC3021_MASK)
859 			ia->ia_broadaddr.sin_addr.s_addr = INADDR_BROADCAST;
860 		else
861 			ia->ia_broadaddr.sin_addr.s_addr =
862 			    htonl(ia->ia_subnet | ~ia->ia_subnetmask);
863 	} else if (ifp->if_flags & IFF_LOOPBACK) {
864 		ia->ia_dstaddr = ia->ia_addr;
865 		flags |= RTF_HOST;
866 	} else if (ifp->if_flags & IFF_POINTOPOINT) {
867 		if (ia->ia_dstaddr.sin_family != AF_INET)
868 			return (0);
869 		flags |= RTF_HOST;
870 	}
871 	if (!vhid && (error = in_addprefix(ia, flags)) != 0)
872 		return (error);
873 
874 	if (ia->ia_addr.sin_addr.s_addr == INADDR_ANY)
875 		return (0);
876 
877 	if (ifp->if_flags & IFF_POINTOPOINT &&
878 	    ia->ia_dstaddr.sin_addr.s_addr == ia->ia_addr.sin_addr.s_addr)
879 			return (0);
880 
881 	/*
882 	 * add a loopback route to self
883 	 */
884 	if (V_useloopback && !vhid && !(ifp->if_flags & IFF_LOOPBACK)) {
885 		struct route ia_ro;
886 
887 		bzero(&ia_ro, sizeof(ia_ro));
888 		*((struct sockaddr_in *)(&ia_ro.ro_dst)) = ia->ia_addr;
889 		rtalloc_ign_fib(&ia_ro, 0, RT_DEFAULT_FIB);
890 		if ((ia_ro.ro_rt != NULL) && (ia_ro.ro_rt->rt_ifp != NULL) &&
891 		    (ia_ro.ro_rt->rt_ifp == V_loif)) {
892 			RT_LOCK(ia_ro.ro_rt);
893 			RT_ADDREF(ia_ro.ro_rt);
894 			RTFREE_LOCKED(ia_ro.ro_rt);
895 		} else
896 			error = ifa_add_loopback_route((struct ifaddr *)ia,
897 			    (struct sockaddr *)&ia->ia_addr);
898 		if (error == 0)
899 			ia->ia_flags |= IFA_RTSELF;
900 		if (ia_ro.ro_rt != NULL)
901 			RTFREE(ia_ro.ro_rt);
902 	}
903 
904 	return (error);
905 }
906 
907 #define rtinitflags(x) \
908 	((((x)->ia_ifp->if_flags & (IFF_LOOPBACK | IFF_POINTOPOINT)) != 0) \
909 	    ? RTF_HOST : 0)
910 
911 /*
912  * Generate a routing message when inserting or deleting
913  * an interface address alias.
914  */
915 static void in_addralias_rtmsg(int cmd, struct in_addr *prefix,
916     struct in_ifaddr *target)
917 {
918 	struct route pfx_ro;
919 	struct sockaddr_in *pfx_addr;
920 	struct rtentry msg_rt;
921 
922 	/* QL: XXX
923 	 * This is a bit questionable because there is no
924 	 * additional route entry added/deleted for an address
925 	 * alias. Therefore this route report is inaccurate.
926 	 */
927 	bzero(&pfx_ro, sizeof(pfx_ro));
928 	pfx_addr = (struct sockaddr_in *)(&pfx_ro.ro_dst);
929 	pfx_addr->sin_len = sizeof(*pfx_addr);
930 	pfx_addr->sin_family = AF_INET;
931 	pfx_addr->sin_addr = *prefix;
932 	rtalloc_ign_fib(&pfx_ro, 0, 0);
933 	if (pfx_ro.ro_rt != NULL) {
934 		msg_rt = *pfx_ro.ro_rt;
935 
936 		/* QL: XXX
937 		 * Point the gateway to the new interface
938 		 * address as if a new prefix route entry has
939 		 * been added through the new address alias.
940 		 * All other parts of the rtentry is accurate,
941 		 * e.g., rt_key, rt_mask, rt_ifp etc.
942 		 */
943 		msg_rt.rt_gateway = (struct sockaddr *)&target->ia_addr;
944 		rt_newaddrmsg(cmd, (struct ifaddr *)target, 0, &msg_rt);
945 		RTFREE(pfx_ro.ro_rt);
946 	}
947 	return;
948 }
949 
950 /*
951  * Check if we have a route for the given prefix already or add one accordingly.
952  */
953 int
954 in_addprefix(struct in_ifaddr *target, int flags)
955 {
956 	struct in_ifaddr *ia;
957 	struct in_addr prefix, mask, p, m;
958 	int error;
959 
960 	if ((flags & RTF_HOST) != 0) {
961 		prefix = target->ia_dstaddr.sin_addr;
962 		mask.s_addr = 0;
963 	} else {
964 		prefix = target->ia_addr.sin_addr;
965 		mask = target->ia_sockmask.sin_addr;
966 		prefix.s_addr &= mask.s_addr;
967 	}
968 
969 	IN_IFADDR_RLOCK();
970 	TAILQ_FOREACH(ia, &V_in_ifaddrhead, ia_link) {
971 		if (rtinitflags(ia)) {
972 			p = ia->ia_dstaddr.sin_addr;
973 
974 			if (prefix.s_addr != p.s_addr)
975 				continue;
976 		} else {
977 			p = ia->ia_addr.sin_addr;
978 			m = ia->ia_sockmask.sin_addr;
979 			p.s_addr &= m.s_addr;
980 
981 			if (prefix.s_addr != p.s_addr ||
982 			    mask.s_addr != m.s_addr)
983 				continue;
984 		}
985 
986 		/*
987 		 * If we got a matching prefix route inserted by other
988 		 * interface address, we are done here.
989 		 */
990 		if (ia->ia_flags & IFA_ROUTE) {
991 #ifdef RADIX_MPATH
992 			if (ia->ia_addr.sin_addr.s_addr ==
993 			    target->ia_addr.sin_addr.s_addr) {
994 				IN_IFADDR_RUNLOCK();
995 				return (EEXIST);
996 			} else
997 				break;
998 #endif
999 			if (V_nosameprefix) {
1000 				IN_IFADDR_RUNLOCK();
1001 				return (EEXIST);
1002 			} else {
1003 				in_addralias_rtmsg(RTM_ADD, &prefix, target);
1004 				IN_IFADDR_RUNLOCK();
1005 				return (0);
1006 			}
1007 		}
1008 	}
1009 	IN_IFADDR_RUNLOCK();
1010 
1011 	/*
1012 	 * No-one seem to have this prefix route, so we try to insert it.
1013 	 */
1014 	error = rtinit(&target->ia_ifa, (int)RTM_ADD, flags);
1015 	if (!error)
1016 		target->ia_flags |= IFA_ROUTE;
1017 	return (error);
1018 }
1019 
1020 /*
1021  * If there is no other address in the system that can serve a route to the
1022  * same prefix, remove the route.  Hand over the route to the new address
1023  * otherwise.
1024  */
1025 int
1026 in_scrubprefix(struct in_ifaddr *target, u_int flags)
1027 {
1028 	struct in_ifaddr *ia;
1029 	struct in_addr prefix, mask, p, m;
1030 	int error = 0;
1031 	struct sockaddr_in prefix0, mask0;
1032 
1033 	/*
1034 	 * Remove the loopback route to the interface address.
1035 	 * The "useloopback" setting is not consulted because if the
1036 	 * user configures an interface address, turns off this
1037 	 * setting, and then tries to delete that interface address,
1038 	 * checking the current setting of "useloopback" would leave
1039 	 * that interface address loopback route untouched, which
1040 	 * would be wrong. Therefore the interface address loopback route
1041 	 * deletion is unconditional.
1042 	 */
1043 	if ((target->ia_addr.sin_addr.s_addr != INADDR_ANY) &&
1044 	    !(target->ia_ifp->if_flags & IFF_LOOPBACK) &&
1045 	    (target->ia_flags & IFA_RTSELF)) {
1046 		struct route ia_ro;
1047 		int freeit = 0;
1048 
1049 		bzero(&ia_ro, sizeof(ia_ro));
1050 		*((struct sockaddr_in *)(&ia_ro.ro_dst)) = target->ia_addr;
1051 		rtalloc_ign_fib(&ia_ro, 0, 0);
1052 		if ((ia_ro.ro_rt != NULL) && (ia_ro.ro_rt->rt_ifp != NULL) &&
1053 		    (ia_ro.ro_rt->rt_ifp == V_loif)) {
1054 			RT_LOCK(ia_ro.ro_rt);
1055 			if (ia_ro.ro_rt->rt_refcnt <= 1)
1056 				freeit = 1;
1057 			else if (flags & LLE_STATIC) {
1058 				RT_REMREF(ia_ro.ro_rt);
1059 				target->ia_flags &= ~IFA_RTSELF;
1060 			}
1061 			RTFREE_LOCKED(ia_ro.ro_rt);
1062 		}
1063 		if (freeit && (flags & LLE_STATIC)) {
1064 			error = ifa_del_loopback_route((struct ifaddr *)target,
1065 			    (struct sockaddr *)&target->ia_addr);
1066 			if (error == 0)
1067 				target->ia_flags &= ~IFA_RTSELF;
1068 		}
1069 		if ((flags & LLE_STATIC) &&
1070 			!(target->ia_ifp->if_flags & IFF_NOARP))
1071 			/* remove arp cache */
1072 			arp_ifscrub(target->ia_ifp, IA_SIN(target)->sin_addr.s_addr);
1073 	}
1074 
1075 	if (rtinitflags(target)) {
1076 		prefix = target->ia_dstaddr.sin_addr;
1077 		mask.s_addr = 0;
1078 	} else {
1079 		prefix = target->ia_addr.sin_addr;
1080 		mask = target->ia_sockmask.sin_addr;
1081 		prefix.s_addr &= mask.s_addr;
1082 	}
1083 
1084 	if ((target->ia_flags & IFA_ROUTE) == 0) {
1085 		in_addralias_rtmsg(RTM_DELETE, &prefix, target);
1086 		return (0);
1087 	}
1088 
1089 	IN_IFADDR_RLOCK();
1090 	TAILQ_FOREACH(ia, &V_in_ifaddrhead, ia_link) {
1091 		if (rtinitflags(ia)) {
1092 			p = ia->ia_dstaddr.sin_addr;
1093 
1094 			if (prefix.s_addr != p.s_addr)
1095 				continue;
1096 		} else {
1097 			p = ia->ia_addr.sin_addr;
1098 			m = ia->ia_sockmask.sin_addr;
1099 			p.s_addr &= m.s_addr;
1100 
1101 			if (prefix.s_addr != p.s_addr ||
1102 			    mask.s_addr != m.s_addr)
1103 				continue;
1104 		}
1105 
1106 		if ((ia->ia_ifp->if_flags & IFF_UP) == 0)
1107 			continue;
1108 
1109 		/*
1110 		 * If we got a matching prefix address, move IFA_ROUTE and
1111 		 * the route itself to it.  Make sure that routing daemons
1112 		 * get a heads-up.
1113 		 */
1114 		if ((ia->ia_flags & IFA_ROUTE) == 0) {
1115 			ifa_ref(&ia->ia_ifa);
1116 			IN_IFADDR_RUNLOCK();
1117 			error = rtinit(&(target->ia_ifa), (int)RTM_DELETE,
1118 			    rtinitflags(target));
1119 			if (error == 0)
1120 				target->ia_flags &= ~IFA_ROUTE;
1121 			else
1122 				log(LOG_INFO, "in_scrubprefix: err=%d, old prefix delete failed\n",
1123 					error);
1124 			error = rtinit(&ia->ia_ifa, (int)RTM_ADD,
1125 			    rtinitflags(ia) | RTF_UP);
1126 			if (error == 0)
1127 				ia->ia_flags |= IFA_ROUTE;
1128 			else
1129 				log(LOG_INFO, "in_scrubprefix: err=%d, new prefix add failed\n",
1130 					error);
1131 			ifa_free(&ia->ia_ifa);
1132 			return (error);
1133 		}
1134 	}
1135 	IN_IFADDR_RUNLOCK();
1136 
1137 	/*
1138 	 * remove all L2 entries on the given prefix
1139 	 */
1140 	bzero(&prefix0, sizeof(prefix0));
1141 	prefix0.sin_len = sizeof(prefix0);
1142 	prefix0.sin_family = AF_INET;
1143 	prefix0.sin_addr.s_addr = target->ia_subnet;
1144 	bzero(&mask0, sizeof(mask0));
1145 	mask0.sin_len = sizeof(mask0);
1146 	mask0.sin_family = AF_INET;
1147 	mask0.sin_addr.s_addr = target->ia_subnetmask;
1148 	lltable_prefix_free(AF_INET, (struct sockaddr *)&prefix0,
1149 	    (struct sockaddr *)&mask0, flags);
1150 
1151 	/*
1152 	 * As no-one seem to have this prefix, we can remove the route.
1153 	 */
1154 	error = rtinit(&(target->ia_ifa), (int)RTM_DELETE, rtinitflags(target));
1155 	if (error == 0)
1156 		target->ia_flags &= ~IFA_ROUTE;
1157 	else
1158 		log(LOG_INFO, "in_scrubprefix: err=%d, prefix delete failed\n", error);
1159 	return (error);
1160 }
1161 
1162 #undef rtinitflags
1163 
1164 /*
1165  * Return 1 if the address might be a local broadcast address.
1166  */
1167 int
1168 in_broadcast(struct in_addr in, struct ifnet *ifp)
1169 {
1170 	register struct ifaddr *ifa;
1171 	u_long t;
1172 
1173 	if (in.s_addr == INADDR_BROADCAST ||
1174 	    in.s_addr == INADDR_ANY)
1175 		return (1);
1176 	if ((ifp->if_flags & IFF_BROADCAST) == 0)
1177 		return (0);
1178 	t = ntohl(in.s_addr);
1179 	/*
1180 	 * Look through the list of addresses for a match
1181 	 * with a broadcast address.
1182 	 */
1183 #define ia ((struct in_ifaddr *)ifa)
1184 	TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link)
1185 		if (ifa->ifa_addr->sa_family == AF_INET &&
1186 		    (in.s_addr == ia->ia_broadaddr.sin_addr.s_addr ||
1187 		     /*
1188 		      * Check for old-style (host 0) broadcast, but
1189 		      * taking into account that RFC 3021 obsoletes it.
1190 		      */
1191 		    (ia->ia_subnetmask != IN_RFC3021_MASK &&
1192 		    t == ia->ia_subnet)) &&
1193 		     /*
1194 		      * Check for an all one subnetmask. These
1195 		      * only exist when an interface gets a secondary
1196 		      * address.
1197 		      */
1198 		    ia->ia_subnetmask != (u_long)0xffffffff)
1199 			    return (1);
1200 	return (0);
1201 #undef ia
1202 }
1203 
1204 /*
1205  * On interface removal, clean up IPv4 data structures hung off of the ifnet.
1206  */
1207 void
1208 in_ifdetach(struct ifnet *ifp)
1209 {
1210 
1211 	in_pcbpurgeif0(&V_ripcbinfo, ifp);
1212 	in_pcbpurgeif0(&V_udbinfo, ifp);
1213 	in_purgemaddrs(ifp);
1214 }
1215 
1216 /*
1217  * Delete all IPv4 multicast address records, and associated link-layer
1218  * multicast address records, associated with ifp.
1219  * XXX It looks like domifdetach runs AFTER the link layer cleanup.
1220  * XXX This should not race with ifma_protospec being set during
1221  * a new allocation, if it does, we have bigger problems.
1222  */
1223 static void
1224 in_purgemaddrs(struct ifnet *ifp)
1225 {
1226 	LIST_HEAD(,in_multi) purgeinms;
1227 	struct in_multi		*inm, *tinm;
1228 	struct ifmultiaddr	*ifma;
1229 
1230 	LIST_INIT(&purgeinms);
1231 	IN_MULTI_LOCK();
1232 
1233 	/*
1234 	 * Extract list of in_multi associated with the detaching ifp
1235 	 * which the PF_INET layer is about to release.
1236 	 * We need to do this as IF_ADDR_LOCK() may be re-acquired
1237 	 * by code further down.
1238 	 */
1239 	IF_ADDR_RLOCK(ifp);
1240 	TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
1241 		if (ifma->ifma_addr->sa_family != AF_INET ||
1242 		    ifma->ifma_protospec == NULL)
1243 			continue;
1244 #if 0
1245 		KASSERT(ifma->ifma_protospec != NULL,
1246 		    ("%s: ifma_protospec is NULL", __func__));
1247 #endif
1248 		inm = (struct in_multi *)ifma->ifma_protospec;
1249 		LIST_INSERT_HEAD(&purgeinms, inm, inm_link);
1250 	}
1251 	IF_ADDR_RUNLOCK(ifp);
1252 
1253 	LIST_FOREACH_SAFE(inm, &purgeinms, inm_link, tinm) {
1254 		LIST_REMOVE(inm, inm_link);
1255 		inm_release_locked(inm);
1256 	}
1257 	igmp_ifdetach(ifp);
1258 
1259 	IN_MULTI_UNLOCK();
1260 }
1261 
1262 struct in_llentry {
1263 	struct llentry		base;
1264 	struct sockaddr_in	l3_addr4;
1265 };
1266 
1267 /*
1268  * Deletes an address from the address table.
1269  * This function is called by the timer functions
1270  * such as arptimer() and nd6_llinfo_timer(), and
1271  * the caller does the locking.
1272  */
1273 static void
1274 in_lltable_free(struct lltable *llt, struct llentry *lle)
1275 {
1276 	LLE_WUNLOCK(lle);
1277 	LLE_LOCK_DESTROY(lle);
1278 	free(lle, M_LLTABLE);
1279 }
1280 
1281 static struct llentry *
1282 in_lltable_new(const struct sockaddr *l3addr, u_int flags)
1283 {
1284 	struct in_llentry *lle;
1285 
1286 	lle = malloc(sizeof(struct in_llentry), M_LLTABLE, M_NOWAIT | M_ZERO);
1287 	if (lle == NULL)		/* NB: caller generates msg */
1288 		return NULL;
1289 
1290 	/*
1291 	 * For IPv4 this will trigger "arpresolve" to generate
1292 	 * an ARP request.
1293 	 */
1294 	lle->base.la_expire = time_uptime; /* mark expired */
1295 	lle->l3_addr4 = *(const struct sockaddr_in *)l3addr;
1296 	lle->base.lle_refcnt = 1;
1297 	lle->base.lle_free = in_lltable_free;
1298 	LLE_LOCK_INIT(&lle->base);
1299 	callout_init_rw(&lle->base.la_timer, &lle->base.lle_lock,
1300 	    CALLOUT_RETURNUNLOCKED);
1301 
1302 	return (&lle->base);
1303 }
1304 
1305 #define IN_ARE_MASKED_ADDR_EQUAL(d, a, m)	(			\
1306 	    (((ntohl((d)->sin_addr.s_addr) ^ (a)->sin_addr.s_addr) & (m)->sin_addr.s_addr)) == 0 )
1307 
1308 static void
1309 in_lltable_prefix_free(struct lltable *llt, const struct sockaddr *prefix,
1310     const struct sockaddr *mask, u_int flags)
1311 {
1312 	const struct sockaddr_in *pfx = (const struct sockaddr_in *)prefix;
1313 	const struct sockaddr_in *msk = (const struct sockaddr_in *)mask;
1314 	struct llentry *lle, *next;
1315 	int i;
1316 	size_t pkts_dropped;
1317 
1318 	IF_AFDATA_WLOCK(llt->llt_ifp);
1319 	for (i = 0; i < LLTBL_HASHTBL_SIZE; i++) {
1320 		LIST_FOREACH_SAFE(lle, &llt->lle_head[i], lle_next, next) {
1321 			/*
1322 			 * (flags & LLE_STATIC) means deleting all entries
1323 			 * including static ARP entries.
1324 			 */
1325 			if (IN_ARE_MASKED_ADDR_EQUAL(satosin(L3_ADDR(lle)),
1326 			    pfx, msk) && ((flags & LLE_STATIC) ||
1327 			    !(lle->la_flags & LLE_STATIC))) {
1328 				LLE_WLOCK(lle);
1329 				if (callout_stop(&lle->la_timer))
1330 					LLE_REMREF(lle);
1331 				pkts_dropped = llentry_free(lle);
1332 				ARPSTAT_ADD(dropped, pkts_dropped);
1333 			}
1334 		}
1335 	}
1336 	IF_AFDATA_WUNLOCK(llt->llt_ifp);
1337 }
1338 
1339 
1340 static int
1341 in_lltable_rtcheck(struct ifnet *ifp, u_int flags, const struct sockaddr *l3addr)
1342 {
1343 	struct rtentry *rt;
1344 
1345 	KASSERT(l3addr->sa_family == AF_INET,
1346 	    ("sin_family %d", l3addr->sa_family));
1347 
1348 	/* XXX rtalloc1 should take a const param */
1349 	rt = rtalloc1(__DECONST(struct sockaddr *, l3addr), 0, 0);
1350 
1351 	if (rt == NULL)
1352 		return (EINVAL);
1353 
1354 	/*
1355 	 * If the gateway for an existing host route matches the target L3
1356 	 * address, which is a special route inserted by some implementation
1357 	 * such as MANET, and the interface is of the correct type, then
1358 	 * allow for ARP to proceed.
1359 	 */
1360 	if (rt->rt_flags & RTF_GATEWAY) {
1361 		if (!(rt->rt_flags & RTF_HOST) || !rt->rt_ifp ||
1362 		    rt->rt_ifp->if_type != IFT_ETHER ||
1363 		    (rt->rt_ifp->if_flags & (IFF_NOARP | IFF_STATICARP)) != 0 ||
1364 		    memcmp(rt->rt_gateway->sa_data, l3addr->sa_data,
1365 		    sizeof(in_addr_t)) != 0) {
1366 			RTFREE_LOCKED(rt);
1367 			return (EINVAL);
1368 		}
1369 	}
1370 
1371 	/*
1372 	 * Make sure that at least the destination address is covered
1373 	 * by the route. This is for handling the case where 2 or more
1374 	 * interfaces have the same prefix. An incoming packet arrives
1375 	 * on one interface and the corresponding outgoing packet leaves
1376 	 * another interface.
1377 	 */
1378 	if (!(rt->rt_flags & RTF_HOST) && rt->rt_ifp != ifp) {
1379 		const char *sa, *mask, *addr, *lim;
1380 		int len;
1381 
1382 		mask = (const char *)rt_mask(rt);
1383 		/*
1384 		 * Just being extra cautious to avoid some custom
1385 		 * code getting into trouble.
1386 		 */
1387 		if (mask == NULL) {
1388 			RTFREE_LOCKED(rt);
1389 			return (EINVAL);
1390 		}
1391 
1392 		sa = (const char *)rt_key(rt);
1393 		addr = (const char *)l3addr;
1394 		len = ((const struct sockaddr_in *)l3addr)->sin_len;
1395 		lim = addr + len;
1396 
1397 		for ( ; addr < lim; sa++, mask++, addr++) {
1398 			if ((*sa ^ *addr) & *mask) {
1399 #ifdef DIAGNOSTIC
1400 				log(LOG_INFO, "IPv4 address: \"%s\" is not on the network\n",
1401 				    inet_ntoa(((const struct sockaddr_in *)l3addr)->sin_addr));
1402 #endif
1403 				RTFREE_LOCKED(rt);
1404 				return (EINVAL);
1405 			}
1406 		}
1407 	}
1408 
1409 	RTFREE_LOCKED(rt);
1410 	return (0);
1411 }
1412 
1413 /*
1414  * Return NULL if not found or marked for deletion.
1415  * If found return lle read locked.
1416  */
1417 static struct llentry *
1418 in_lltable_lookup(struct lltable *llt, u_int flags, const struct sockaddr *l3addr)
1419 {
1420 	const struct sockaddr_in *sin = (const struct sockaddr_in *)l3addr;
1421 	struct ifnet *ifp = llt->llt_ifp;
1422 	struct llentry *lle;
1423 	struct llentries *lleh;
1424 	u_int hashkey;
1425 
1426 	IF_AFDATA_LOCK_ASSERT(ifp);
1427 	KASSERT(l3addr->sa_family == AF_INET,
1428 	    ("sin_family %d", l3addr->sa_family));
1429 
1430 	hashkey = sin->sin_addr.s_addr;
1431 	lleh = &llt->lle_head[LLATBL_HASH(hashkey, LLTBL_HASHMASK)];
1432 	LIST_FOREACH(lle, lleh, lle_next) {
1433 		struct sockaddr_in *sa2 = satosin(L3_ADDR(lle));
1434 		if (lle->la_flags & LLE_DELETED)
1435 			continue;
1436 		if (sa2->sin_addr.s_addr == sin->sin_addr.s_addr)
1437 			break;
1438 	}
1439 	if (lle == NULL) {
1440 #ifdef DIAGNOSTIC
1441 		if (flags & LLE_DELETE)
1442 			log(LOG_INFO, "interface address is missing from cache = %p  in delete\n", lle);
1443 #endif
1444 		if (!(flags & LLE_CREATE))
1445 			return (NULL);
1446 		/*
1447 		 * A route that covers the given address must have
1448 		 * been installed 1st because we are doing a resolution,
1449 		 * verify this.
1450 		 */
1451 		if (!(flags & LLE_IFADDR) &&
1452 		    in_lltable_rtcheck(ifp, flags, l3addr) != 0)
1453 			goto done;
1454 
1455 		lle = in_lltable_new(l3addr, flags);
1456 		if (lle == NULL) {
1457 			log(LOG_INFO, "lla_lookup: new lle malloc failed\n");
1458 			goto done;
1459 		}
1460 		lle->la_flags = flags & ~LLE_CREATE;
1461 		if ((flags & (LLE_CREATE | LLE_IFADDR)) == (LLE_CREATE | LLE_IFADDR)) {
1462 			bcopy(IF_LLADDR(ifp), &lle->ll_addr, ifp->if_addrlen);
1463 			lle->la_flags |= (LLE_VALID | LLE_STATIC);
1464 		}
1465 
1466 		lle->lle_tbl  = llt;
1467 		lle->lle_head = lleh;
1468 		lle->la_flags |= LLE_LINKED;
1469 		LIST_INSERT_HEAD(lleh, lle, lle_next);
1470 	} else if (flags & LLE_DELETE) {
1471 		if (!(lle->la_flags & LLE_IFADDR) || (flags & LLE_IFADDR)) {
1472 			LLE_WLOCK(lle);
1473 			lle->la_flags |= LLE_DELETED;
1474 			EVENTHANDLER_INVOKE(lle_event, lle, LLENTRY_DELETED);
1475 			LLE_WUNLOCK(lle);
1476 #ifdef DIAGNOSTIC
1477 			log(LOG_INFO, "ifaddr cache = %p  is deleted\n", lle);
1478 #endif
1479 		}
1480 		lle = (void *)-1;
1481 
1482 	}
1483 	if (LLE_IS_VALID(lle)) {
1484 		if (flags & LLE_EXCLUSIVE)
1485 			LLE_WLOCK(lle);
1486 		else
1487 			LLE_RLOCK(lle);
1488 	}
1489 done:
1490 	return (lle);
1491 }
1492 
1493 static int
1494 in_lltable_dump(struct lltable *llt, struct sysctl_req *wr)
1495 {
1496 #define	SIN(lle)	((struct sockaddr_in *) L3_ADDR(lle))
1497 	struct ifnet *ifp = llt->llt_ifp;
1498 	struct llentry *lle;
1499 	/* XXX stack use */
1500 	struct {
1501 		struct rt_msghdr	rtm;
1502 		struct sockaddr_inarp	sin;
1503 		struct sockaddr_dl	sdl;
1504 	} arpc;
1505 	int error, i;
1506 
1507 	LLTABLE_LOCK_ASSERT();
1508 
1509 	error = 0;
1510 	for (i = 0; i < LLTBL_HASHTBL_SIZE; i++) {
1511 		LIST_FOREACH(lle, &llt->lle_head[i], lle_next) {
1512 			struct sockaddr_dl *sdl;
1513 
1514 			/* skip deleted entries */
1515 			if ((lle->la_flags & LLE_DELETED) == LLE_DELETED)
1516 				continue;
1517 			/* Skip if jailed and not a valid IP of the prison. */
1518 			if (prison_if(wr->td->td_ucred, L3_ADDR(lle)) != 0)
1519 				continue;
1520 			/*
1521 			 * produce a msg made of:
1522 			 *  struct rt_msghdr;
1523 			 *  struct sockaddr_inarp; (IPv4)
1524 			 *  struct sockaddr_dl;
1525 			 */
1526 			bzero(&arpc, sizeof(arpc));
1527 			arpc.rtm.rtm_msglen = sizeof(arpc);
1528 			arpc.rtm.rtm_version = RTM_VERSION;
1529 			arpc.rtm.rtm_type = RTM_GET;
1530 			arpc.rtm.rtm_flags = RTF_UP;
1531 			arpc.rtm.rtm_addrs = RTA_DST | RTA_GATEWAY;
1532 			arpc.sin.sin_family = AF_INET;
1533 			arpc.sin.sin_len = sizeof(arpc.sin);
1534 			arpc.sin.sin_addr.s_addr = SIN(lle)->sin_addr.s_addr;
1535 
1536 			/* publish */
1537 			if (lle->la_flags & LLE_PUB) {
1538 				arpc.rtm.rtm_flags |= RTF_ANNOUNCE;
1539 				/* proxy only */
1540 				if (lle->la_flags & LLE_PROXY)
1541 					arpc.sin.sin_other = SIN_PROXY;
1542 			}
1543 
1544 			sdl = &arpc.sdl;
1545 			sdl->sdl_family = AF_LINK;
1546 			sdl->sdl_len = sizeof(*sdl);
1547 			sdl->sdl_index = ifp->if_index;
1548 			sdl->sdl_type = ifp->if_type;
1549 			if ((lle->la_flags & LLE_VALID) == LLE_VALID) {
1550 				sdl->sdl_alen = ifp->if_addrlen;
1551 				bcopy(&lle->ll_addr, LLADDR(sdl), ifp->if_addrlen);
1552 			} else {
1553 				sdl->sdl_alen = 0;
1554 				bzero(LLADDR(sdl), ifp->if_addrlen);
1555 			}
1556 
1557 			arpc.rtm.rtm_rmx.rmx_expire =
1558 			    lle->la_flags & LLE_STATIC ? 0 : lle->la_expire;
1559 			arpc.rtm.rtm_flags |= (RTF_HOST | RTF_LLDATA);
1560 			if (lle->la_flags & LLE_STATIC)
1561 				arpc.rtm.rtm_flags |= RTF_STATIC;
1562 			arpc.rtm.rtm_index = ifp->if_index;
1563 			error = SYSCTL_OUT(wr, &arpc, sizeof(arpc));
1564 			if (error)
1565 				break;
1566 		}
1567 	}
1568 	return error;
1569 #undef SIN
1570 }
1571 
1572 void *
1573 in_domifattach(struct ifnet *ifp)
1574 {
1575 	struct in_ifinfo *ii;
1576 	struct lltable *llt;
1577 
1578 	ii = malloc(sizeof(struct in_ifinfo), M_IFADDR, M_WAITOK|M_ZERO);
1579 
1580 	llt = lltable_init(ifp, AF_INET);
1581 	if (llt != NULL) {
1582 		llt->llt_prefix_free = in_lltable_prefix_free;
1583 		llt->llt_lookup = in_lltable_lookup;
1584 		llt->llt_dump = in_lltable_dump;
1585 	}
1586 	ii->ii_llt = llt;
1587 
1588 	ii->ii_igmp = igmp_domifattach(ifp);
1589 
1590 	return ii;
1591 }
1592 
1593 void
1594 in_domifdetach(struct ifnet *ifp, void *aux)
1595 {
1596 	struct in_ifinfo *ii = (struct in_ifinfo *)aux;
1597 
1598 	igmp_domifdetach(ifp);
1599 	lltable_free(ii->ii_llt);
1600 	free(ii, M_IFADDR);
1601 }
1602