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