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