Home | History | Annotate | Line # | Download | only in netinet
ip_output.c revision 1.83.2.1
      1 /*	$NetBSD: ip_output.c,v 1.83.2.1 2001/03/05 22:49:56 nathanw 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  * 3. All advertising materials mentioning features or use of this software
     49  *    must display the following acknowledgement:
     50  *	This product includes software developed by the NetBSD
     51  *	Foundation, Inc. and its contributors.
     52  * 4. Neither the name of The NetBSD Foundation nor the names of its
     53  *    contributors may be used to endorse or promote products derived
     54  *    from this software without specific prior written permission.
     55  *
     56  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     57  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     58  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     59  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     60  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     61  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     62  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     63  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     64  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     65  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     66  * POSSIBILITY OF SUCH DAMAGE.
     67  */
     68 
     69 /*
     70  * Copyright (c) 1982, 1986, 1988, 1990, 1993
     71  *	The Regents of the University of California.  All rights reserved.
     72  *
     73  * Redistribution and use in source and binary forms, with or without
     74  * modification, are permitted provided that the following conditions
     75  * are met:
     76  * 1. Redistributions of source code must retain the above copyright
     77  *    notice, this list of conditions and the following disclaimer.
     78  * 2. Redistributions in binary form must reproduce the above copyright
     79  *    notice, this list of conditions and the following disclaimer in the
     80  *    documentation and/or other materials provided with the distribution.
     81  * 3. All advertising materials mentioning features or use of this software
     82  *    must display the following acknowledgement:
     83  *	This product includes software developed by the University of
     84  *	California, Berkeley and its contributors.
     85  * 4. Neither the name of the University nor the names of its contributors
     86  *    may be used to endorse or promote products derived from this software
     87  *    without specific prior written permission.
     88  *
     89  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     90  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     91  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     92  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     93  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     94  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     95  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     96  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     97  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     98  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     99  * SUCH DAMAGE.
    100  *
    101  *	@(#)ip_output.c	8.3 (Berkeley) 1/21/94
    102  */
    103 
    104 #include "opt_pfil_hooks.h"
    105 #include "opt_ipsec.h"
    106 #include "opt_mrouting.h"
    107 
    108 #include <sys/param.h>
    109 #include <sys/malloc.h>
    110 #include <sys/mbuf.h>
    111 #include <sys/errno.h>
    112 #include <sys/protosw.h>
    113 #include <sys/socket.h>
    114 #include <sys/socketvar.h>
    115 #include <sys/systm.h>
    116 #include <sys/lwp.h>
    117 #include <sys/proc.h>
    118 
    119 #include <net/if.h>
    120 #include <net/route.h>
    121 #include <net/pfil.h>
    122 
    123 #include <netinet/in.h>
    124 #include <netinet/in_systm.h>
    125 #include <netinet/ip.h>
    126 #include <netinet/in_pcb.h>
    127 #include <netinet/in_var.h>
    128 #include <netinet/ip_var.h>
    129 
    130 #ifdef MROUTING
    131 #include <netinet/ip_mroute.h>
    132 #endif
    133 
    134 #ifdef __vax__
    135 #include <machine/mtpr.h>
    136 #endif
    137 
    138 #include <machine/stdarg.h>
    139 
    140 #ifdef IPSEC
    141 #include <netinet6/ipsec.h>
    142 #include <netkey/key.h>
    143 #include <netkey/key_debug.h>
    144 #endif /*IPSEC*/
    145 
    146 static struct mbuf *ip_insertoptions __P((struct mbuf *, struct mbuf *, int *));
    147 static struct ifnet *ip_multicast_if __P((struct in_addr *, int *));
    148 static void ip_mloopback
    149 	__P((struct ifnet *, struct mbuf *, struct sockaddr_in *));
    150 
    151 #ifdef PFIL_HOOKS
    152 extern struct pfil_head inet_pfil_hook;			/* XXX */
    153 #endif
    154 
    155 /*
    156  * IP output.  The packet in mbuf chain m contains a skeletal IP
    157  * header (with len, off, ttl, proto, tos, src, dst).
    158  * The mbuf chain containing the packet will be freed.
    159  * The mbuf opt, if present, will not be freed.
    160  */
    161 int
    162 #if __STDC__
    163 ip_output(struct mbuf *m0, ...)
    164 #else
    165 ip_output(m0, va_alist)
    166 	struct mbuf *m0;
    167 	va_dcl
    168 #endif
    169 {
    170 	struct ip *ip, *mhip;
    171 	struct ifnet *ifp;
    172 	struct mbuf *m = m0;
    173 	int hlen = sizeof (struct ip);
    174 	int len, off, error = 0;
    175 	struct route iproute;
    176 	struct sockaddr_in *dst;
    177 	struct in_ifaddr *ia;
    178 	struct mbuf *opt;
    179 	struct route *ro;
    180 	int flags;
    181 	int *mtu_p;
    182 	int mtu;
    183 	struct ip_moptions *imo;
    184 	va_list ap;
    185 #ifdef IPSEC
    186 	struct socket *so;
    187 	struct secpolicy *sp = NULL;
    188 #endif /*IPSEC*/
    189 	u_int16_t ip_len;
    190 
    191 	va_start(ap, m0);
    192 	opt = va_arg(ap, struct mbuf *);
    193 	ro = va_arg(ap, struct route *);
    194 	flags = va_arg(ap, int);
    195 	imo = va_arg(ap, struct ip_moptions *);
    196 	if (flags & IP_RETURNMTU)
    197 		mtu_p = va_arg(ap, int *);
    198 	else
    199 		mtu_p = NULL;
    200 	va_end(ap);
    201 
    202 #ifdef IPSEC
    203 	so = ipsec_getsocket(m);
    204 	(void)ipsec_setsocket(m, NULL);
    205 #endif /*IPSEC*/
    206 
    207 #ifdef	DIAGNOSTIC
    208 	if ((m->m_flags & M_PKTHDR) == 0)
    209 		panic("ip_output no HDR");
    210 #endif
    211 	if (opt) {
    212 		m = ip_insertoptions(m, opt, &len);
    213 		hlen = len;
    214 	}
    215 	ip = mtod(m, struct ip *);
    216 	/*
    217 	 * Fill in IP header.
    218 	 */
    219 	if ((flags & (IP_FORWARDING|IP_RAWOUTPUT)) == 0) {
    220 		ip->ip_v = IPVERSION;
    221 		ip->ip_off &= IP_DF;
    222 		ip->ip_id = htons(ip_id++);
    223 		ip->ip_hl = hlen >> 2;
    224 		ipstat.ips_localout++;
    225 	} else {
    226 		hlen = ip->ip_hl << 2;
    227 	}
    228 	/*
    229 	 * Route packet.
    230 	 */
    231 	if (ro == 0) {
    232 		ro = &iproute;
    233 		bzero((caddr_t)ro, sizeof (*ro));
    234 	}
    235 	dst = satosin(&ro->ro_dst);
    236 	/*
    237 	 * If there is a cached route,
    238 	 * check that it is to the same destination
    239 	 * and is still up.  If not, free it and try again.
    240 	 */
    241 	if (ro->ro_rt && ((ro->ro_rt->rt_flags & RTF_UP) == 0 ||
    242 	    !in_hosteq(dst->sin_addr, ip->ip_dst))) {
    243 		RTFREE(ro->ro_rt);
    244 		ro->ro_rt = (struct rtentry *)0;
    245 	}
    246 	if (ro->ro_rt == 0) {
    247 		dst->sin_family = AF_INET;
    248 		dst->sin_len = sizeof(*dst);
    249 		dst->sin_addr = ip->ip_dst;
    250 	}
    251 	/*
    252 	 * If routing to interface only,
    253 	 * short circuit routing lookup.
    254 	 */
    255 	if (flags & IP_ROUTETOIF) {
    256 		if ((ia = ifatoia(ifa_ifwithladdr(sintosa(dst)))) == 0) {
    257 			ipstat.ips_noroute++;
    258 			error = ENETUNREACH;
    259 			goto bad;
    260 		}
    261 		ifp = ia->ia_ifp;
    262 		mtu = ifp->if_mtu;
    263 		ip->ip_ttl = 1;
    264 	} else {
    265 		if (ro->ro_rt == 0)
    266 			rtalloc(ro);
    267 		if (ro->ro_rt == 0) {
    268 			ipstat.ips_noroute++;
    269 			error = EHOSTUNREACH;
    270 			goto bad;
    271 		}
    272 		ia = ifatoia(ro->ro_rt->rt_ifa);
    273 		ifp = ro->ro_rt->rt_ifp;
    274 		if ((mtu = ro->ro_rt->rt_rmx.rmx_mtu) == 0)
    275 			mtu = ifp->if_mtu;
    276 		ro->ro_rt->rt_use++;
    277 		if (ro->ro_rt->rt_flags & RTF_GATEWAY)
    278 			dst = satosin(ro->ro_rt->rt_gateway);
    279 	}
    280 	if (IN_MULTICAST(ip->ip_dst.s_addr) ||
    281 	    (ip->ip_dst.s_addr == INADDR_BROADCAST)) {
    282 		struct in_multi *inm;
    283 
    284 		m->m_flags |= (ip->ip_dst.s_addr == INADDR_BROADCAST) ?
    285 			M_BCAST : M_MCAST;
    286 		/*
    287 		 * IP destination address is multicast.  Make sure "dst"
    288 		 * still points to the address in "ro".  (It may have been
    289 		 * changed to point to a gateway address, above.)
    290 		 */
    291 		dst = satosin(&ro->ro_dst);
    292 		/*
    293 		 * See if the caller provided any multicast options
    294 		 */
    295 		if (imo != NULL) {
    296 			ip->ip_ttl = imo->imo_multicast_ttl;
    297 			if (imo->imo_multicast_ifp != NULL) {
    298 				ifp = imo->imo_multicast_ifp;
    299 				mtu = ifp->if_mtu;
    300 			}
    301 		} else
    302 			ip->ip_ttl = IP_DEFAULT_MULTICAST_TTL;
    303 		/*
    304 		 * Confirm that the outgoing interface supports multicast.
    305 		 */
    306 		if (((m->m_flags & M_MCAST) &&
    307 		     (ifp->if_flags & IFF_MULTICAST) == 0) ||
    308 		    ((m->m_flags & M_BCAST) &&
    309 		     (ifp->if_flags & IFF_BROADCAST) == 0))  {
    310 			ipstat.ips_noroute++;
    311 			error = ENETUNREACH;
    312 			goto bad;
    313 		}
    314 		/*
    315 		 * If source address not specified yet, use an address
    316 		 * of outgoing interface.
    317 		 */
    318 		if (in_nullhost(ip->ip_src)) {
    319 			struct in_ifaddr *ia;
    320 
    321 			IFP_TO_IA(ifp, ia);
    322 			ip->ip_src = ia->ia_addr.sin_addr;
    323 		}
    324 
    325 		IN_LOOKUP_MULTI(ip->ip_dst, ifp, inm);
    326 		if (inm != NULL &&
    327 		   (imo == NULL || imo->imo_multicast_loop)) {
    328 			/*
    329 			 * If we belong to the destination multicast group
    330 			 * on the outgoing interface, and the caller did not
    331 			 * forbid loopback, loop back a copy.
    332 			 */
    333 			ip_mloopback(ifp, m, dst);
    334 		}
    335 #ifdef MROUTING
    336 		else {
    337 			/*
    338 			 * If we are acting as a multicast router, perform
    339 			 * multicast forwarding as if the packet had just
    340 			 * arrived on the interface to which we are about
    341 			 * to send.  The multicast forwarding function
    342 			 * recursively calls this function, using the
    343 			 * IP_FORWARDING flag to prevent infinite recursion.
    344 			 *
    345 			 * Multicasts that are looped back by ip_mloopback(),
    346 			 * above, will be forwarded by the ip_input() routine,
    347 			 * if necessary.
    348 			 */
    349 			extern struct socket *ip_mrouter;
    350 
    351 			if (ip_mrouter && (flags & IP_FORWARDING) == 0) {
    352 				if (ip_mforward(m, ifp) != 0) {
    353 					m_freem(m);
    354 					goto done;
    355 				}
    356 			}
    357 		}
    358 #endif
    359 		/*
    360 		 * Multicasts with a time-to-live of zero may be looped-
    361 		 * back, above, but must not be transmitted on a network.
    362 		 * Also, multicasts addressed to the loopback interface
    363 		 * are not sent -- the above call to ip_mloopback() will
    364 		 * loop back a copy if this host actually belongs to the
    365 		 * destination group on the loopback interface.
    366 		 */
    367 		if (ip->ip_ttl == 0 || (ifp->if_flags & IFF_LOOPBACK) != 0) {
    368 			m_freem(m);
    369 			goto done;
    370 		}
    371 
    372 		goto sendit;
    373 	}
    374 #ifndef notdef
    375 	/*
    376 	 * If source address not specified yet, use address
    377 	 * of outgoing interface.
    378 	 */
    379 	if (in_nullhost(ip->ip_src))
    380 		ip->ip_src = ia->ia_addr.sin_addr;
    381 #endif
    382 
    383 	/*
    384 	 * packets with Class-D address as source are not valid per
    385 	 * RFC 1112
    386 	 */
    387 	if (IN_MULTICAST(ip->ip_src.s_addr)) {
    388 		ipstat.ips_odropped++;
    389 		error = EADDRNOTAVAIL;
    390 		goto bad;
    391 	}
    392 
    393 	/*
    394 	 * Look for broadcast address and
    395 	 * and verify user is allowed to send
    396 	 * such a packet.
    397 	 */
    398 	if (in_broadcast(dst->sin_addr, ifp)) {
    399 		if ((ifp->if_flags & IFF_BROADCAST) == 0) {
    400 			error = EADDRNOTAVAIL;
    401 			goto bad;
    402 		}
    403 		if ((flags & IP_ALLOWBROADCAST) == 0) {
    404 			error = EACCES;
    405 			goto bad;
    406 		}
    407 		/* don't allow broadcast messages to be fragmented */
    408 		if ((u_int16_t)ip->ip_len > ifp->if_mtu) {
    409 			error = EMSGSIZE;
    410 			goto bad;
    411 		}
    412 		m->m_flags |= M_BCAST;
    413 	} else
    414 		m->m_flags &= ~M_BCAST;
    415 
    416 sendit:
    417 	/*
    418 	 * If we're doing Path MTU Discovery, we need to set DF unless
    419 	 * the route's MTU is locked.
    420 	 */
    421 	if ((flags & IP_MTUDISC) != 0 && ro->ro_rt != NULL &&
    422 	    (ro->ro_rt->rt_rmx.rmx_locks & RTV_MTU) == 0)
    423 		ip->ip_off |= IP_DF;
    424 
    425 	/*
    426 	 * Remember the current ip_len and ip_off, and swap them into
    427 	 * network order.
    428 	 */
    429 	ip_len = ip->ip_len;
    430 
    431 	HTONS(ip->ip_len);
    432 	HTONS(ip->ip_off);
    433 
    434 #ifdef IPSEC
    435 	/* get SP for this packet */
    436 	if (so == NULL)
    437 		sp = ipsec4_getpolicybyaddr(m, IPSEC_DIR_OUTBOUND, flags, &error);
    438 	else
    439 		sp = ipsec4_getpolicybysock(m, IPSEC_DIR_OUTBOUND, so, &error);
    440 
    441 	if (sp == NULL) {
    442 		ipsecstat.out_inval++;
    443 		goto bad;
    444 	}
    445 
    446 	error = 0;
    447 
    448 	/* check policy */
    449 	switch (sp->policy) {
    450 	case IPSEC_POLICY_DISCARD:
    451 		/*
    452 		 * This packet is just discarded.
    453 		 */
    454 		ipsecstat.out_polvio++;
    455 		goto bad;
    456 
    457 	case IPSEC_POLICY_BYPASS:
    458 	case IPSEC_POLICY_NONE:
    459 		/* no need to do IPsec. */
    460 		goto skip_ipsec;
    461 
    462 	case IPSEC_POLICY_IPSEC:
    463 		if (sp->req == NULL) {
    464 			/* XXX should be panic ? */
    465 			printf("ip_output: No IPsec request specified.\n");
    466 			error = EINVAL;
    467 			goto bad;
    468 		}
    469 		break;
    470 
    471 	case IPSEC_POLICY_ENTRUST:
    472 	default:
    473 		printf("ip_output: Invalid policy found. %d\n", sp->policy);
    474 	}
    475 
    476 	/*
    477 	 * ipsec4_output() expects ip_len and ip_off in network
    478 	 * order.  They have been set to network order above.
    479 	 */
    480 
    481     {
    482 	struct ipsec_output_state state;
    483 	bzero(&state, sizeof(state));
    484 	state.m = m;
    485 	if (flags & IP_ROUTETOIF) {
    486 		state.ro = &iproute;
    487 		bzero(&iproute, sizeof(iproute));
    488 	} else
    489 		state.ro = ro;
    490 	state.dst = (struct sockaddr *)dst;
    491 
    492 	error = ipsec4_output(&state, sp, flags);
    493 
    494 	m = state.m;
    495 	if (flags & IP_ROUTETOIF) {
    496 		/*
    497 		 * if we have tunnel mode SA, we may need to ignore
    498 		 * IP_ROUTETOIF.
    499 		 */
    500 		if (state.ro != &iproute || state.ro->ro_rt != NULL) {
    501 			flags &= ~IP_ROUTETOIF;
    502 			ro = state.ro;
    503 		}
    504 	} else
    505 		ro = state.ro;
    506 	dst = (struct sockaddr_in *)state.dst;
    507 	if (error) {
    508 		/* mbuf is already reclaimed in ipsec4_output. */
    509 		m0 = NULL;
    510 		switch (error) {
    511 		case EHOSTUNREACH:
    512 		case ENETUNREACH:
    513 		case EMSGSIZE:
    514 		case ENOBUFS:
    515 		case ENOMEM:
    516 			break;
    517 		default:
    518 			printf("ip4_output (ipsec): error code %d\n", error);
    519 			/*fall through*/
    520 		case ENOENT:
    521 			/* don't show these error codes to the user */
    522 			error = 0;
    523 			break;
    524 		}
    525 		goto bad;
    526 	}
    527     }
    528 
    529 	/* be sure to update variables that are affected by ipsec4_output() */
    530 	ip = mtod(m, struct ip *);
    531 #ifdef _IP_VHL
    532 	hlen = IP_VHL_HL(ip->ip_vhl) << 2;
    533 #else
    534 	hlen = ip->ip_hl << 2;
    535 #endif
    536 	ip_len = ntohs(ip->ip_len);
    537 
    538 	if (ro->ro_rt == NULL) {
    539 		if ((flags & IP_ROUTETOIF) == 0) {
    540 			printf("ip_output: "
    541 				"can't update route after IPsec processing\n");
    542 			error = EHOSTUNREACH;	/*XXX*/
    543 			goto bad;
    544 		}
    545 	} else {
    546 		/* nobody uses ia beyond here */
    547 		ifp = ro->ro_rt->rt_ifp;
    548 	}
    549 
    550 skip_ipsec:
    551 #endif /*IPSEC*/
    552 
    553 #ifdef PFIL_HOOKS
    554 	/*
    555 	 * Run through list of hooks for output packets.
    556 	 */
    557 	if ((error = pfil_run_hooks(&inet_pfil_hook, &m, ifp,
    558 				    PFIL_OUT)) != 0)
    559 		goto done;
    560 	if (m == NULL)
    561 		goto done;
    562 
    563 	ip = mtod(m, struct ip *);
    564 #endif /* PFIL_HOOKS */
    565 
    566 	/*
    567 	 * If small enough for mtu of path, can just send directly.
    568 	 */
    569 	if (ip_len <= mtu) {
    570 #if IFA_STATS
    571 		/*
    572 		 * search for the source address structure to
    573 		 * maintain output statistics.
    574 		 */
    575 		INADDR_TO_IA(ip->ip_src, ia);
    576 		if (ia)
    577 			ia->ia_ifa.ifa_data.ifad_outbytes += ip_len;
    578 #endif
    579 		ip->ip_sum = 0;
    580 		ip->ip_sum = in_cksum(m, hlen);
    581 #ifdef IPSEC
    582 		/* clean ipsec history once it goes out of the node */
    583 		ipsec_delaux(m);
    584 #endif
    585 		error = (*ifp->if_output)(ifp, m, sintosa(dst), ro->ro_rt);
    586 		goto done;
    587 	}
    588 
    589 	/*
    590 	 * Too large for interface; fragment if possible.
    591 	 * Must be able to put at least 8 bytes per fragment.
    592 	 *
    593 	 * Note we swap ip_len and ip_off into host order to make
    594 	 * the logic below a little simpler.
    595 	 */
    596 
    597 	NTOHS(ip->ip_len);
    598 	NTOHS(ip->ip_off);
    599 
    600 	if (ip->ip_off & IP_DF) {
    601 		if (flags & IP_RETURNMTU)
    602 			*mtu_p = mtu;
    603 		error = EMSGSIZE;
    604 		ipstat.ips_cantfrag++;
    605 		goto bad;
    606 	}
    607 	len = (mtu - hlen) &~ 7;
    608 	if (len < 8) {
    609 		error = EMSGSIZE;
    610 		goto bad;
    611 	}
    612 
    613     {
    614 	int mhlen, firstlen = len;
    615 	struct mbuf **mnext = &m->m_nextpkt;
    616 	int fragments = 0;
    617 	int s;
    618 
    619 	/*
    620 	 * Loop through length of segment after first fragment,
    621 	 * make new header and copy data of each part and link onto chain.
    622 	 */
    623 	m0 = m;
    624 	mhlen = sizeof (struct ip);
    625 	for (off = hlen + len; off < (u_int16_t)ip->ip_len; off += len) {
    626 		MGETHDR(m, M_DONTWAIT, MT_HEADER);
    627 		if (m == 0) {
    628 			error = ENOBUFS;
    629 			ipstat.ips_odropped++;
    630 			goto sendorfree;
    631 		}
    632 		*mnext = m;
    633 		mnext = &m->m_nextpkt;
    634 		m->m_data += max_linkhdr;
    635 		mhip = mtod(m, struct ip *);
    636 		*mhip = *ip;
    637 		/* we must inherit MCAST and BCAST flags */
    638 		m->m_flags |= m0->m_flags & (M_MCAST|M_BCAST);
    639 		if (hlen > sizeof (struct ip)) {
    640 			mhlen = ip_optcopy(ip, mhip) + sizeof (struct ip);
    641 			mhip->ip_hl = mhlen >> 2;
    642 		}
    643 		m->m_len = mhlen;
    644 		mhip->ip_off = ((off - hlen) >> 3) + (ip->ip_off & ~IP_MF);
    645 		if (ip->ip_off & IP_MF)
    646 			mhip->ip_off |= IP_MF;
    647 		if (off + len >= (u_int16_t)ip->ip_len)
    648 			len = (u_int16_t)ip->ip_len - off;
    649 		else
    650 			mhip->ip_off |= IP_MF;
    651 		mhip->ip_len = htons((u_int16_t)(len + mhlen));
    652 		m->m_next = m_copy(m0, off, len);
    653 		if (m->m_next == 0) {
    654 			error = ENOBUFS;	/* ??? */
    655 			ipstat.ips_odropped++;
    656 			goto sendorfree;
    657 		}
    658 		m->m_pkthdr.len = mhlen + len;
    659 		m->m_pkthdr.rcvif = (struct ifnet *)0;
    660 		HTONS(mhip->ip_off);
    661 		mhip->ip_sum = 0;
    662 		mhip->ip_sum = in_cksum(m, mhlen);
    663 		ipstat.ips_ofragments++;
    664 		fragments++;
    665 	}
    666 	/*
    667 	 * Update first fragment by trimming what's been copied out
    668 	 * and updating header, then send each fragment (in order).
    669 	 */
    670 	m = m0;
    671 	m_adj(m, hlen + firstlen - (u_int16_t)ip->ip_len);
    672 	m->m_pkthdr.len = hlen + firstlen;
    673 	ip->ip_len = htons((u_int16_t)m->m_pkthdr.len);
    674 	ip->ip_off |= IP_MF;
    675 	HTONS(ip->ip_off);
    676 	ip->ip_sum = 0;
    677 	ip->ip_sum = in_cksum(m, hlen);
    678 sendorfree:
    679 	/*
    680 	 * If there is no room for all the fragments, don't queue
    681 	 * any of them.
    682 	 */
    683 	s = splimp();
    684 	if (ifp->if_snd.ifq_maxlen - ifp->if_snd.ifq_len < fragments)
    685 		error = ENOBUFS;
    686 	splx(s);
    687 	for (m = m0; m; m = m0) {
    688 		m0 = m->m_nextpkt;
    689 		m->m_nextpkt = 0;
    690 		if (error == 0) {
    691 #if IFA_STATS
    692 			/*
    693 			 * search for the source address structure to
    694 			 * maintain output statistics.
    695 			 */
    696 			INADDR_TO_IA(ip->ip_src, ia);
    697 			if (ia) {
    698 				ia->ia_ifa.ifa_data.ifad_outbytes +=
    699 					ntohs(ip->ip_len);
    700 			}
    701 #endif
    702 #ifdef IPSEC
    703 			/* clean ipsec history once it goes out of the node */
    704 			ipsec_delaux(m);
    705 #endif
    706 			error = (*ifp->if_output)(ifp, m, sintosa(dst),
    707 			    ro->ro_rt);
    708 		} else
    709 			m_freem(m);
    710 	}
    711 
    712 	if (error == 0)
    713 		ipstat.ips_fragmented++;
    714     }
    715 done:
    716 	if (ro == &iproute && (flags & IP_ROUTETOIF) == 0 && ro->ro_rt) {
    717 		RTFREE(ro->ro_rt);
    718 		ro->ro_rt = 0;
    719 	}
    720 
    721 #ifdef IPSEC
    722 	if (sp != NULL) {
    723 		KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
    724 			printf("DP ip_output call free SP:%p\n", sp));
    725 		key_freesp(sp);
    726 	}
    727 #endif /* IPSEC */
    728 
    729 	return (error);
    730 bad:
    731 	m_freem(m);
    732 	goto done;
    733 }
    734 
    735 /*
    736  * Determine the maximum length of the options to be inserted;
    737  * we would far rather allocate too much space rather than too little.
    738  */
    739 
    740 u_int
    741 ip_optlen(inp)
    742 	struct inpcb *inp;
    743 {
    744 	struct mbuf *m = inp->inp_options;
    745 
    746 	if (m && m->m_len > offsetof(struct ipoption, ipopt_dst))
    747 		return(m->m_len - offsetof(struct ipoption, ipopt_dst));
    748 	else
    749 		return 0;
    750 }
    751 
    752 
    753 /*
    754  * Insert IP options into preformed packet.
    755  * Adjust IP destination as required for IP source routing,
    756  * as indicated by a non-zero in_addr at the start of the options.
    757  */
    758 static struct mbuf *
    759 ip_insertoptions(m, opt, phlen)
    760 	struct mbuf *m;
    761 	struct mbuf *opt;
    762 	int *phlen;
    763 {
    764 	struct ipoption *p = mtod(opt, struct ipoption *);
    765 	struct mbuf *n;
    766 	struct ip *ip = mtod(m, struct ip *);
    767 	unsigned optlen;
    768 
    769 	optlen = opt->m_len - sizeof(p->ipopt_dst);
    770 	if (optlen + (u_int16_t)ip->ip_len > IP_MAXPACKET)
    771 		return (m);		/* XXX should fail */
    772 	if (!in_nullhost(p->ipopt_dst))
    773 		ip->ip_dst = p->ipopt_dst;
    774 	if (m->m_flags & M_EXT || m->m_data - optlen < m->m_pktdat) {
    775 		MGETHDR(n, M_DONTWAIT, MT_HEADER);
    776 		if (n == 0)
    777 			return (m);
    778 		n->m_pkthdr.len = m->m_pkthdr.len + optlen;
    779 		m->m_len -= sizeof(struct ip);
    780 		m->m_data += sizeof(struct ip);
    781 		n->m_next = m;
    782 		m = n;
    783 		m->m_len = optlen + sizeof(struct ip);
    784 		m->m_data += max_linkhdr;
    785 		bcopy((caddr_t)ip, mtod(m, caddr_t), sizeof(struct ip));
    786 	} else {
    787 		m->m_data -= optlen;
    788 		m->m_len += optlen;
    789 		m->m_pkthdr.len += optlen;
    790 		memmove(mtod(m, caddr_t), ip, sizeof(struct ip));
    791 	}
    792 	ip = mtod(m, struct ip *);
    793 	bcopy((caddr_t)p->ipopt_list, (caddr_t)(ip + 1), (unsigned)optlen);
    794 	*phlen = sizeof(struct ip) + optlen;
    795 	ip->ip_len += optlen;
    796 	return (m);
    797 }
    798 
    799 /*
    800  * Copy options from ip to jp,
    801  * omitting those not copied during fragmentation.
    802  */
    803 int
    804 ip_optcopy(ip, jp)
    805 	struct ip *ip, *jp;
    806 {
    807 	u_char *cp, *dp;
    808 	int opt, optlen, cnt;
    809 
    810 	cp = (u_char *)(ip + 1);
    811 	dp = (u_char *)(jp + 1);
    812 	cnt = (ip->ip_hl << 2) - sizeof (struct ip);
    813 	for (; cnt > 0; cnt -= optlen, cp += optlen) {
    814 		opt = cp[0];
    815 		if (opt == IPOPT_EOL)
    816 			break;
    817 		if (opt == IPOPT_NOP) {
    818 			/* Preserve for IP mcast tunnel's LSRR alignment. */
    819 			*dp++ = IPOPT_NOP;
    820 			optlen = 1;
    821 			continue;
    822 		}
    823 #ifdef DIAGNOSTIC
    824 		if (cnt < IPOPT_OLEN + sizeof(*cp))
    825 			panic("malformed IPv4 option passed to ip_optcopy");
    826 #endif
    827 		optlen = cp[IPOPT_OLEN];
    828 #ifdef DIAGNOSTIC
    829 		if (optlen < IPOPT_OLEN + sizeof(*cp) || optlen > cnt)
    830 			panic("malformed IPv4 option passed to ip_optcopy");
    831 #endif
    832 		/* bogus lengths should have been caught by ip_dooptions */
    833 		if (optlen > cnt)
    834 			optlen = cnt;
    835 		if (IPOPT_COPIED(opt)) {
    836 			bcopy((caddr_t)cp, (caddr_t)dp, (unsigned)optlen);
    837 			dp += optlen;
    838 		}
    839 	}
    840 	for (optlen = dp - (u_char *)(jp+1); optlen & 0x3; optlen++)
    841 		*dp++ = IPOPT_EOL;
    842 	return (optlen);
    843 }
    844 
    845 /*
    846  * IP socket option processing.
    847  */
    848 int
    849 ip_ctloutput(op, so, level, optname, mp)
    850 	int op;
    851 	struct socket *so;
    852 	int level, optname;
    853 	struct mbuf **mp;
    854 {
    855 	struct inpcb *inp = sotoinpcb(so);
    856 	struct mbuf *m = *mp;
    857 	int optval = 0;
    858 	int error = 0;
    859 #ifdef IPSEC
    860 #ifdef __NetBSD__
    861 	struct proc *p = curproc->l_proc;	/*XXX*/
    862 #endif
    863 #endif
    864 
    865 	if (level != IPPROTO_IP) {
    866 		error = EINVAL;
    867 		if (op == PRCO_SETOPT && *mp)
    868 			(void) m_free(*mp);
    869 	} else switch (op) {
    870 
    871 	case PRCO_SETOPT:
    872 		switch (optname) {
    873 		case IP_OPTIONS:
    874 #ifdef notyet
    875 		case IP_RETOPTS:
    876 			return (ip_pcbopts(optname, &inp->inp_options, m));
    877 #else
    878 			return (ip_pcbopts(&inp->inp_options, m));
    879 #endif
    880 
    881 		case IP_TOS:
    882 		case IP_TTL:
    883 		case IP_RECVOPTS:
    884 		case IP_RECVRETOPTS:
    885 		case IP_RECVDSTADDR:
    886 		case IP_RECVIF:
    887 			if (m == NULL || m->m_len != sizeof(int))
    888 				error = EINVAL;
    889 			else {
    890 				optval = *mtod(m, int *);
    891 				switch (optname) {
    892 
    893 				case IP_TOS:
    894 					inp->inp_ip.ip_tos = optval;
    895 					break;
    896 
    897 				case IP_TTL:
    898 					inp->inp_ip.ip_ttl = optval;
    899 					break;
    900 #define	OPTSET(bit) \
    901 	if (optval) \
    902 		inp->inp_flags |= bit; \
    903 	else \
    904 		inp->inp_flags &= ~bit;
    905 
    906 				case IP_RECVOPTS:
    907 					OPTSET(INP_RECVOPTS);
    908 					break;
    909 
    910 				case IP_RECVRETOPTS:
    911 					OPTSET(INP_RECVRETOPTS);
    912 					break;
    913 
    914 				case IP_RECVDSTADDR:
    915 					OPTSET(INP_RECVDSTADDR);
    916 					break;
    917 
    918 				case IP_RECVIF:
    919 					OPTSET(INP_RECVIF);
    920 					break;
    921 				}
    922 			}
    923 			break;
    924 #undef OPTSET
    925 
    926 		case IP_MULTICAST_IF:
    927 		case IP_MULTICAST_TTL:
    928 		case IP_MULTICAST_LOOP:
    929 		case IP_ADD_MEMBERSHIP:
    930 		case IP_DROP_MEMBERSHIP:
    931 			error = ip_setmoptions(optname, &inp->inp_moptions, m);
    932 			break;
    933 
    934 		case IP_PORTRANGE:
    935 			if (m == 0 || m->m_len != sizeof(int))
    936 				error = EINVAL;
    937 			else {
    938 				optval = *mtod(m, int *);
    939 
    940 				switch (optval) {
    941 
    942 				case IP_PORTRANGE_DEFAULT:
    943 				case IP_PORTRANGE_HIGH:
    944 					inp->inp_flags &= ~(INP_LOWPORT);
    945 					break;
    946 
    947 				case IP_PORTRANGE_LOW:
    948 					inp->inp_flags |= INP_LOWPORT;
    949 					break;
    950 
    951 				default:
    952 					error = EINVAL;
    953 					break;
    954 				}
    955 			}
    956 			break;
    957 
    958 #ifdef IPSEC
    959 		case IP_IPSEC_POLICY:
    960 		{
    961 			caddr_t req = NULL;
    962 			size_t len = 0;
    963 			int priv = 0;
    964 
    965 #ifdef __NetBSD__
    966 			if (p == 0 || suser(p->p_ucred, &p->p_acflag))
    967 				priv = 0;
    968 			else
    969 				priv = 1;
    970 #else
    971 			priv = (in6p->in6p_socket->so_state & SS_PRIV);
    972 #endif
    973 			if (m) {
    974 				req = mtod(m, caddr_t);
    975 				len = m->m_len;
    976 			}
    977 			error = ipsec4_set_policy(inp, optname, req, len, priv);
    978 			break;
    979 		    }
    980 #endif /*IPSEC*/
    981 
    982 		default:
    983 			error = ENOPROTOOPT;
    984 			break;
    985 		}
    986 		if (m)
    987 			(void)m_free(m);
    988 		break;
    989 
    990 	case PRCO_GETOPT:
    991 		switch (optname) {
    992 		case IP_OPTIONS:
    993 		case IP_RETOPTS:
    994 			*mp = m = m_get(M_WAIT, MT_SOOPTS);
    995 			if (inp->inp_options) {
    996 				m->m_len = inp->inp_options->m_len;
    997 				bcopy(mtod(inp->inp_options, caddr_t),
    998 				    mtod(m, caddr_t), (unsigned)m->m_len);
    999 			} else
   1000 				m->m_len = 0;
   1001 			break;
   1002 
   1003 		case IP_TOS:
   1004 		case IP_TTL:
   1005 		case IP_RECVOPTS:
   1006 		case IP_RECVRETOPTS:
   1007 		case IP_RECVDSTADDR:
   1008 		case IP_RECVIF:
   1009 		case IP_ERRORMTU:
   1010 			*mp = m = m_get(M_WAIT, MT_SOOPTS);
   1011 			m->m_len = sizeof(int);
   1012 			switch (optname) {
   1013 
   1014 			case IP_TOS:
   1015 				optval = inp->inp_ip.ip_tos;
   1016 				break;
   1017 
   1018 			case IP_TTL:
   1019 				optval = inp->inp_ip.ip_ttl;
   1020 				break;
   1021 
   1022 			case IP_ERRORMTU:
   1023 				optval = inp->inp_errormtu;
   1024 				break;
   1025 
   1026 #define	OPTBIT(bit)	(inp->inp_flags & bit ? 1 : 0)
   1027 
   1028 			case IP_RECVOPTS:
   1029 				optval = OPTBIT(INP_RECVOPTS);
   1030 				break;
   1031 
   1032 			case IP_RECVRETOPTS:
   1033 				optval = OPTBIT(INP_RECVRETOPTS);
   1034 				break;
   1035 
   1036 			case IP_RECVDSTADDR:
   1037 				optval = OPTBIT(INP_RECVDSTADDR);
   1038 				break;
   1039 
   1040 			case IP_RECVIF:
   1041 				optval = OPTBIT(INP_RECVIF);
   1042 				break;
   1043 			}
   1044 			*mtod(m, int *) = optval;
   1045 			break;
   1046 
   1047 #ifdef IPSEC
   1048 		case IP_IPSEC_POLICY:
   1049 		{
   1050 			caddr_t req = NULL;
   1051 			size_t len = 0;
   1052 
   1053 			if (m) {
   1054 				req = mtod(m, caddr_t);
   1055 				len = m->m_len;
   1056 			}
   1057 			error = ipsec4_get_policy(inp, req, len, mp);
   1058 			break;
   1059 		}
   1060 #endif /*IPSEC*/
   1061 
   1062 		case IP_MULTICAST_IF:
   1063 		case IP_MULTICAST_TTL:
   1064 		case IP_MULTICAST_LOOP:
   1065 		case IP_ADD_MEMBERSHIP:
   1066 		case IP_DROP_MEMBERSHIP:
   1067 			error = ip_getmoptions(optname, inp->inp_moptions, mp);
   1068 			break;
   1069 
   1070 		case IP_PORTRANGE:
   1071 			*mp = m = m_get(M_WAIT, MT_SOOPTS);
   1072 			m->m_len = sizeof(int);
   1073 
   1074 			if (inp->inp_flags & INP_LOWPORT)
   1075 				optval = IP_PORTRANGE_LOW;
   1076 			else
   1077 				optval = IP_PORTRANGE_DEFAULT;
   1078 
   1079 			*mtod(m, int *) = optval;
   1080 			break;
   1081 
   1082 		default:
   1083 			error = ENOPROTOOPT;
   1084 			break;
   1085 		}
   1086 		break;
   1087 	}
   1088 	return (error);
   1089 }
   1090 
   1091 /*
   1092  * Set up IP options in pcb for insertion in output packets.
   1093  * Store in mbuf with pointer in pcbopt, adding pseudo-option
   1094  * with destination address if source routed.
   1095  */
   1096 int
   1097 #ifdef notyet
   1098 ip_pcbopts(optname, pcbopt, m)
   1099 	int optname;
   1100 #else
   1101 ip_pcbopts(pcbopt, m)
   1102 #endif
   1103 	struct mbuf **pcbopt;
   1104 	struct mbuf *m;
   1105 {
   1106 	int cnt, optlen;
   1107 	u_char *cp;
   1108 	u_char opt;
   1109 
   1110 	/* turn off any old options */
   1111 	if (*pcbopt)
   1112 		(void)m_free(*pcbopt);
   1113 	*pcbopt = 0;
   1114 	if (m == (struct mbuf *)0 || m->m_len == 0) {
   1115 		/*
   1116 		 * Only turning off any previous options.
   1117 		 */
   1118 		if (m)
   1119 			(void)m_free(m);
   1120 		return (0);
   1121 	}
   1122 
   1123 #ifndef	vax
   1124 	if (m->m_len % sizeof(int32_t))
   1125 		goto bad;
   1126 #endif
   1127 	/*
   1128 	 * IP first-hop destination address will be stored before
   1129 	 * actual options; move other options back
   1130 	 * and clear it when none present.
   1131 	 */
   1132 	if (m->m_data + m->m_len + sizeof(struct in_addr) >= &m->m_dat[MLEN])
   1133 		goto bad;
   1134 	cnt = m->m_len;
   1135 	m->m_len += sizeof(struct in_addr);
   1136 	cp = mtod(m, u_char *) + sizeof(struct in_addr);
   1137 	memmove(cp, mtod(m, caddr_t), (unsigned)cnt);
   1138 	bzero(mtod(m, caddr_t), sizeof(struct in_addr));
   1139 
   1140 	for (; cnt > 0; cnt -= optlen, cp += optlen) {
   1141 		opt = cp[IPOPT_OPTVAL];
   1142 		if (opt == IPOPT_EOL)
   1143 			break;
   1144 		if (opt == IPOPT_NOP)
   1145 			optlen = 1;
   1146 		else {
   1147 			if (cnt < IPOPT_OLEN + sizeof(*cp))
   1148 				goto bad;
   1149 			optlen = cp[IPOPT_OLEN];
   1150 			if (optlen < IPOPT_OLEN  + sizeof(*cp) || optlen > cnt)
   1151 				goto bad;
   1152 		}
   1153 		switch (opt) {
   1154 
   1155 		default:
   1156 			break;
   1157 
   1158 		case IPOPT_LSRR:
   1159 		case IPOPT_SSRR:
   1160 			/*
   1161 			 * user process specifies route as:
   1162 			 *	->A->B->C->D
   1163 			 * D must be our final destination (but we can't
   1164 			 * check that since we may not have connected yet).
   1165 			 * A is first hop destination, which doesn't appear in
   1166 			 * actual IP option, but is stored before the options.
   1167 			 */
   1168 			if (optlen < IPOPT_MINOFF - 1 + sizeof(struct in_addr))
   1169 				goto bad;
   1170 			m->m_len -= sizeof(struct in_addr);
   1171 			cnt -= sizeof(struct in_addr);
   1172 			optlen -= sizeof(struct in_addr);
   1173 			cp[IPOPT_OLEN] = optlen;
   1174 			/*
   1175 			 * Move first hop before start of options.
   1176 			 */
   1177 			bcopy((caddr_t)&cp[IPOPT_OFFSET+1], mtod(m, caddr_t),
   1178 			    sizeof(struct in_addr));
   1179 			/*
   1180 			 * Then copy rest of options back
   1181 			 * to close up the deleted entry.
   1182 			 */
   1183 			memmove(&cp[IPOPT_OFFSET+1],
   1184                             (caddr_t)(&cp[IPOPT_OFFSET+1] + sizeof(struct in_addr)),
   1185 			    (unsigned)cnt + sizeof(struct in_addr));
   1186 			break;
   1187 		}
   1188 	}
   1189 	if (m->m_len > MAX_IPOPTLEN + sizeof(struct in_addr))
   1190 		goto bad;
   1191 	*pcbopt = m;
   1192 	return (0);
   1193 
   1194 bad:
   1195 	(void)m_free(m);
   1196 	return (EINVAL);
   1197 }
   1198 
   1199 /*
   1200  * following RFC1724 section 3.3, 0.0.0.0/8 is interpreted as interface index.
   1201  */
   1202 static struct ifnet *
   1203 ip_multicast_if(a, ifindexp)
   1204 	struct in_addr *a;
   1205 	int *ifindexp;
   1206 {
   1207 	int ifindex;
   1208 	struct ifnet *ifp;
   1209 
   1210 	if (ifindexp)
   1211 		*ifindexp = 0;
   1212 	if (ntohl(a->s_addr) >> 24 == 0) {
   1213 		ifindex = ntohl(a->s_addr) & 0xffffff;
   1214 		if (ifindex < 0 || if_index < ifindex)
   1215 			return NULL;
   1216 		ifp = ifindex2ifnet[ifindex];
   1217 		if (ifindexp)
   1218 			*ifindexp = ifindex;
   1219 	} else {
   1220 		INADDR_TO_IFP(*a, ifp);
   1221 	}
   1222 	return ifp;
   1223 }
   1224 
   1225 /*
   1226  * Set the IP multicast options in response to user setsockopt().
   1227  */
   1228 int
   1229 ip_setmoptions(optname, imop, m)
   1230 	int optname;
   1231 	struct ip_moptions **imop;
   1232 	struct mbuf *m;
   1233 {
   1234 	int error = 0;
   1235 	u_char loop;
   1236 	int i;
   1237 	struct in_addr addr;
   1238 	struct ip_mreq *mreq;
   1239 	struct ifnet *ifp;
   1240 	struct ip_moptions *imo = *imop;
   1241 	struct route ro;
   1242 	struct sockaddr_in *dst;
   1243 	int ifindex;
   1244 
   1245 	if (imo == NULL) {
   1246 		/*
   1247 		 * No multicast option buffer attached to the pcb;
   1248 		 * allocate one and initialize to default values.
   1249 		 */
   1250 		imo = (struct ip_moptions *)malloc(sizeof(*imo), M_IPMOPTS,
   1251 		    M_WAITOK);
   1252 
   1253 		if (imo == NULL)
   1254 			return (ENOBUFS);
   1255 		*imop = imo;
   1256 		imo->imo_multicast_ifp = NULL;
   1257 		imo->imo_multicast_addr.s_addr = INADDR_ANY;
   1258 		imo->imo_multicast_ttl = IP_DEFAULT_MULTICAST_TTL;
   1259 		imo->imo_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
   1260 		imo->imo_num_memberships = 0;
   1261 	}
   1262 
   1263 	switch (optname) {
   1264 
   1265 	case IP_MULTICAST_IF:
   1266 		/*
   1267 		 * Select the interface for outgoing multicast packets.
   1268 		 */
   1269 		if (m == NULL || m->m_len != sizeof(struct in_addr)) {
   1270 			error = EINVAL;
   1271 			break;
   1272 		}
   1273 		addr = *(mtod(m, struct in_addr *));
   1274 		/*
   1275 		 * INADDR_ANY is used to remove a previous selection.
   1276 		 * When no interface is selected, a default one is
   1277 		 * chosen every time a multicast packet is sent.
   1278 		 */
   1279 		if (in_nullhost(addr)) {
   1280 			imo->imo_multicast_ifp = NULL;
   1281 			break;
   1282 		}
   1283 		/*
   1284 		 * The selected interface is identified by its local
   1285 		 * IP address.  Find the interface and confirm that
   1286 		 * it supports multicasting.
   1287 		 */
   1288 		ifp = ip_multicast_if(&addr, &ifindex);
   1289 		if (ifp == NULL || (ifp->if_flags & IFF_MULTICAST) == 0) {
   1290 			error = EADDRNOTAVAIL;
   1291 			break;
   1292 		}
   1293 		imo->imo_multicast_ifp = ifp;
   1294 		if (ifindex)
   1295 			imo->imo_multicast_addr = addr;
   1296 		else
   1297 			imo->imo_multicast_addr.s_addr = INADDR_ANY;
   1298 		break;
   1299 
   1300 	case IP_MULTICAST_TTL:
   1301 		/*
   1302 		 * Set the IP time-to-live for outgoing multicast packets.
   1303 		 */
   1304 		if (m == NULL || m->m_len != 1) {
   1305 			error = EINVAL;
   1306 			break;
   1307 		}
   1308 		imo->imo_multicast_ttl = *(mtod(m, u_char *));
   1309 		break;
   1310 
   1311 	case IP_MULTICAST_LOOP:
   1312 		/*
   1313 		 * Set the loopback flag for outgoing multicast packets.
   1314 		 * Must be zero or one.
   1315 		 */
   1316 		if (m == NULL || m->m_len != 1 ||
   1317 		   (loop = *(mtod(m, u_char *))) > 1) {
   1318 			error = EINVAL;
   1319 			break;
   1320 		}
   1321 		imo->imo_multicast_loop = loop;
   1322 		break;
   1323 
   1324 	case IP_ADD_MEMBERSHIP:
   1325 		/*
   1326 		 * Add a multicast group membership.
   1327 		 * Group must be a valid IP multicast address.
   1328 		 */
   1329 		if (m == NULL || m->m_len != sizeof(struct ip_mreq)) {
   1330 			error = EINVAL;
   1331 			break;
   1332 		}
   1333 		mreq = mtod(m, struct ip_mreq *);
   1334 		if (!IN_MULTICAST(mreq->imr_multiaddr.s_addr)) {
   1335 			error = EINVAL;
   1336 			break;
   1337 		}
   1338 		/*
   1339 		 * If no interface address was provided, use the interface of
   1340 		 * the route to the given multicast address.
   1341 		 */
   1342 		if (in_nullhost(mreq->imr_interface)) {
   1343 			bzero((caddr_t)&ro, sizeof(ro));
   1344 			ro.ro_rt = NULL;
   1345 			dst = satosin(&ro.ro_dst);
   1346 			dst->sin_len = sizeof(*dst);
   1347 			dst->sin_family = AF_INET;
   1348 			dst->sin_addr = mreq->imr_multiaddr;
   1349 			rtalloc(&ro);
   1350 			if (ro.ro_rt == NULL) {
   1351 				error = EADDRNOTAVAIL;
   1352 				break;
   1353 			}
   1354 			ifp = ro.ro_rt->rt_ifp;
   1355 			rtfree(ro.ro_rt);
   1356 		} else {
   1357 			ifp = ip_multicast_if(&mreq->imr_interface, NULL);
   1358 		}
   1359 		/*
   1360 		 * See if we found an interface, and confirm that it
   1361 		 * supports multicast.
   1362 		 */
   1363 		if (ifp == NULL || (ifp->if_flags & IFF_MULTICAST) == 0) {
   1364 			error = EADDRNOTAVAIL;
   1365 			break;
   1366 		}
   1367 		/*
   1368 		 * See if the membership already exists or if all the
   1369 		 * membership slots are full.
   1370 		 */
   1371 		for (i = 0; i < imo->imo_num_memberships; ++i) {
   1372 			if (imo->imo_membership[i]->inm_ifp == ifp &&
   1373 			    in_hosteq(imo->imo_membership[i]->inm_addr,
   1374 				      mreq->imr_multiaddr))
   1375 				break;
   1376 		}
   1377 		if (i < imo->imo_num_memberships) {
   1378 			error = EADDRINUSE;
   1379 			break;
   1380 		}
   1381 		if (i == IP_MAX_MEMBERSHIPS) {
   1382 			error = ETOOMANYREFS;
   1383 			break;
   1384 		}
   1385 		/*
   1386 		 * Everything looks good; add a new record to the multicast
   1387 		 * address list for the given interface.
   1388 		 */
   1389 		if ((imo->imo_membership[i] =
   1390 		    in_addmulti(&mreq->imr_multiaddr, ifp)) == NULL) {
   1391 			error = ENOBUFS;
   1392 			break;
   1393 		}
   1394 		++imo->imo_num_memberships;
   1395 		break;
   1396 
   1397 	case IP_DROP_MEMBERSHIP:
   1398 		/*
   1399 		 * Drop a multicast group membership.
   1400 		 * Group must be a valid IP multicast address.
   1401 		 */
   1402 		if (m == NULL || m->m_len != sizeof(struct ip_mreq)) {
   1403 			error = EINVAL;
   1404 			break;
   1405 		}
   1406 		mreq = mtod(m, struct ip_mreq *);
   1407 		if (!IN_MULTICAST(mreq->imr_multiaddr.s_addr)) {
   1408 			error = EINVAL;
   1409 			break;
   1410 		}
   1411 		/*
   1412 		 * If an interface address was specified, get a pointer
   1413 		 * to its ifnet structure.
   1414 		 */
   1415 		if (in_nullhost(mreq->imr_interface))
   1416 			ifp = NULL;
   1417 		else {
   1418 			ifp = ip_multicast_if(&mreq->imr_interface, NULL);
   1419 			if (ifp == NULL) {
   1420 				error = EADDRNOTAVAIL;
   1421 				break;
   1422 			}
   1423 		}
   1424 		/*
   1425 		 * Find the membership in the membership array.
   1426 		 */
   1427 		for (i = 0; i < imo->imo_num_memberships; ++i) {
   1428 			if ((ifp == NULL ||
   1429 			     imo->imo_membership[i]->inm_ifp == ifp) &&
   1430 			     in_hosteq(imo->imo_membership[i]->inm_addr,
   1431 				       mreq->imr_multiaddr))
   1432 				break;
   1433 		}
   1434 		if (i == imo->imo_num_memberships) {
   1435 			error = EADDRNOTAVAIL;
   1436 			break;
   1437 		}
   1438 		/*
   1439 		 * Give up the multicast address record to which the
   1440 		 * membership points.
   1441 		 */
   1442 		in_delmulti(imo->imo_membership[i]);
   1443 		/*
   1444 		 * Remove the gap in the membership array.
   1445 		 */
   1446 		for (++i; i < imo->imo_num_memberships; ++i)
   1447 			imo->imo_membership[i-1] = imo->imo_membership[i];
   1448 		--imo->imo_num_memberships;
   1449 		break;
   1450 
   1451 	default:
   1452 		error = EOPNOTSUPP;
   1453 		break;
   1454 	}
   1455 
   1456 	/*
   1457 	 * If all options have default values, no need to keep the mbuf.
   1458 	 */
   1459 	if (imo->imo_multicast_ifp == NULL &&
   1460 	    imo->imo_multicast_ttl == IP_DEFAULT_MULTICAST_TTL &&
   1461 	    imo->imo_multicast_loop == IP_DEFAULT_MULTICAST_LOOP &&
   1462 	    imo->imo_num_memberships == 0) {
   1463 		free(*imop, M_IPMOPTS);
   1464 		*imop = NULL;
   1465 	}
   1466 
   1467 	return (error);
   1468 }
   1469 
   1470 /*
   1471  * Return the IP multicast options in response to user getsockopt().
   1472  */
   1473 int
   1474 ip_getmoptions(optname, imo, mp)
   1475 	int optname;
   1476 	struct ip_moptions *imo;
   1477 	struct mbuf **mp;
   1478 {
   1479 	u_char *ttl;
   1480 	u_char *loop;
   1481 	struct in_addr *addr;
   1482 	struct in_ifaddr *ia;
   1483 
   1484 	*mp = m_get(M_WAIT, MT_SOOPTS);
   1485 
   1486 	switch (optname) {
   1487 
   1488 	case IP_MULTICAST_IF:
   1489 		addr = mtod(*mp, struct in_addr *);
   1490 		(*mp)->m_len = sizeof(struct in_addr);
   1491 		if (imo == NULL || imo->imo_multicast_ifp == NULL)
   1492 			*addr = zeroin_addr;
   1493 		else if (imo->imo_multicast_addr.s_addr) {
   1494 			/* return the value user has set */
   1495 			*addr = imo->imo_multicast_addr;
   1496 		} else {
   1497 			IFP_TO_IA(imo->imo_multicast_ifp, ia);
   1498 			*addr = ia ? ia->ia_addr.sin_addr : zeroin_addr;
   1499 		}
   1500 		return (0);
   1501 
   1502 	case IP_MULTICAST_TTL:
   1503 		ttl = mtod(*mp, u_char *);
   1504 		(*mp)->m_len = 1;
   1505 		*ttl = imo ? imo->imo_multicast_ttl
   1506 			   : IP_DEFAULT_MULTICAST_TTL;
   1507 		return (0);
   1508 
   1509 	case IP_MULTICAST_LOOP:
   1510 		loop = mtod(*mp, u_char *);
   1511 		(*mp)->m_len = 1;
   1512 		*loop = imo ? imo->imo_multicast_loop
   1513 			    : IP_DEFAULT_MULTICAST_LOOP;
   1514 		return (0);
   1515 
   1516 	default:
   1517 		return (EOPNOTSUPP);
   1518 	}
   1519 }
   1520 
   1521 /*
   1522  * Discard the IP multicast options.
   1523  */
   1524 void
   1525 ip_freemoptions(imo)
   1526 	struct ip_moptions *imo;
   1527 {
   1528 	int i;
   1529 
   1530 	if (imo != NULL) {
   1531 		for (i = 0; i < imo->imo_num_memberships; ++i)
   1532 			in_delmulti(imo->imo_membership[i]);
   1533 		free(imo, M_IPMOPTS);
   1534 	}
   1535 }
   1536 
   1537 /*
   1538  * Routine called from ip_output() to loop back a copy of an IP multicast
   1539  * packet to the input queue of a specified interface.  Note that this
   1540  * calls the output routine of the loopback "driver", but with an interface
   1541  * pointer that might NOT be &loif -- easier than replicating that code here.
   1542  */
   1543 static void
   1544 ip_mloopback(ifp, m, dst)
   1545 	struct ifnet *ifp;
   1546 	struct mbuf *m;
   1547 	struct sockaddr_in *dst;
   1548 {
   1549 	struct ip *ip;
   1550 	struct mbuf *copym;
   1551 
   1552 	copym = m_copy(m, 0, M_COPYALL);
   1553 	if (copym != NULL
   1554 	 && (copym->m_flags & M_EXT || copym->m_len < sizeof(struct ip)))
   1555 		copym = m_pullup(copym, sizeof(struct ip));
   1556 	if (copym != NULL) {
   1557 		/*
   1558 		 * We don't bother to fragment if the IP length is greater
   1559 		 * than the interface's MTU.  Can this possibly matter?
   1560 		 */
   1561 		ip = mtod(copym, struct ip *);
   1562 		HTONS(ip->ip_len);
   1563 		HTONS(ip->ip_off);
   1564 		ip->ip_sum = 0;
   1565 		ip->ip_sum = in_cksum(copym, ip->ip_hl << 2);
   1566 		(void) looutput(ifp, copym, sintosa(dst), NULL);
   1567 	}
   1568 }
   1569