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