Home | History | Annotate | Line # | Download | only in netinet
ip_output.c revision 1.149
      1 /*	$NetBSD: ip_output.c,v 1.149 2005/03/11 17:07:51 matt 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. Neither the name of the University nor the names of its contributors
     82  *    may be used to endorse or promote products derived from this software
     83  *    without specific prior written permission.
     84  *
     85  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     86  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     87  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     88  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     89  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     90  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     91  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     92  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     93  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     94  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     95  * SUCH DAMAGE.
     96  *
     97  *	@(#)ip_output.c	8.3 (Berkeley) 1/21/94
     98  */
     99 
    100 #include <sys/cdefs.h>
    101 __KERNEL_RCSID(0, "$NetBSD: ip_output.c,v 1.149 2005/03/11 17:07:51 matt Exp $");
    102 
    103 #include "opt_pfil_hooks.h"
    104 #include "opt_inet.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 #ifdef FAST_IPSEC
    116 #include <sys/domain.h>
    117 #endif
    118 #include <sys/systm.h>
    119 #include <sys/proc.h>
    120 
    121 #include <net/if.h>
    122 #include <net/route.h>
    123 #include <net/pfil.h>
    124 
    125 #include <netinet/in.h>
    126 #include <netinet/in_systm.h>
    127 #include <netinet/ip.h>
    128 #include <netinet/in_pcb.h>
    129 #include <netinet/in_var.h>
    130 #include <netinet/ip_var.h>
    131 
    132 #ifdef MROUTING
    133 #include <netinet/ip_mroute.h>
    134 #endif
    135 
    136 #include <machine/stdarg.h>
    137 
    138 #ifdef IPSEC
    139 #include <netinet6/ipsec.h>
    140 #include <netkey/key.h>
    141 #include <netkey/key_debug.h>
    142 #ifdef IPSEC_NAT_T
    143 #include <netinet/udp.h>
    144 #endif
    145 #endif /*IPSEC*/
    146 
    147 #ifdef FAST_IPSEC
    148 #include <netipsec/ipsec.h>
    149 #include <netipsec/key.h>
    150 #include <netipsec/xform.h>
    151 #endif	/* FAST_IPSEC*/
    152 
    153 static struct mbuf *ip_insertoptions(struct mbuf *, struct mbuf *, int *);
    154 static struct ifnet *ip_multicast_if(struct in_addr *, int *);
    155 static void ip_mloopback(struct ifnet *, struct mbuf *, struct sockaddr_in *);
    156 
    157 #ifdef PFIL_HOOKS
    158 extern struct pfil_head inet_pfil_hook;			/* XXX */
    159 #endif
    160 
    161 /*
    162  * IP output.  The packet in mbuf chain m contains a skeletal IP
    163  * header (with len, off, ttl, proto, tos, src, dst).
    164  * The mbuf chain containing the packet will be freed.
    165  * The mbuf opt, if present, will not be freed.
    166  */
    167 int
    168 ip_output(struct mbuf *m0, ...)
    169 {
    170 	struct ip *ip;
    171 	struct ifnet *ifp;
    172 	struct mbuf *m = m0;
    173 	int hlen = sizeof (struct ip);
    174 	int len, error = 0;
    175 	struct route iproute;
    176 	struct sockaddr_in *dst;
    177 	struct in_ifaddr *ia;
    178 	struct mbuf *opt;
    179 	struct route *ro;
    180 	int flags, sw_csum;
    181 	int *mtu_p;
    182 	u_long mtu;
    183 	struct ip_moptions *imo;
    184 	struct socket *so;
    185 	va_list ap;
    186 #ifdef IPSEC
    187 	struct secpolicy *sp = NULL;
    188 #ifdef IPSEC_NAT_T
    189 	int natt_frag = 0;
    190 #endif
    191 #endif /*IPSEC*/
    192 #ifdef FAST_IPSEC
    193 	struct inpcb *inp;
    194 	struct m_tag *mtag;
    195 	struct secpolicy *sp = NULL;
    196 	struct tdb_ident *tdbi;
    197 	int s;
    198 #endif
    199 	u_int16_t ip_len;
    200 
    201 	len = 0;
    202 	va_start(ap, m0);
    203 	opt = va_arg(ap, struct mbuf *);
    204 	ro = va_arg(ap, struct route *);
    205 	flags = va_arg(ap, int);
    206 	imo = va_arg(ap, struct ip_moptions *);
    207 	so = va_arg(ap, struct socket *);
    208 	if (flags & IP_RETURNMTU)
    209 		mtu_p = va_arg(ap, int *);
    210 	else
    211 		mtu_p = NULL;
    212 	va_end(ap);
    213 
    214 	MCLAIM(m, &ip_tx_mowner);
    215 #ifdef FAST_IPSEC
    216 	if (so != NULL && so->so_proto->pr_domain->dom_family == AF_INET)
    217 		inp = (struct inpcb *)so->so_pcb;
    218 	else
    219 		inp = NULL;
    220 #endif /* FAST_IPSEC */
    221 
    222 #ifdef	DIAGNOSTIC
    223 	if ((m->m_flags & M_PKTHDR) == 0)
    224 		panic("ip_output no HDR");
    225 #endif
    226 	if (opt) {
    227 		m = ip_insertoptions(m, opt, &len);
    228 		if (len >= sizeof(struct ip))
    229 			hlen = len;
    230 	}
    231 	ip = mtod(m, struct ip *);
    232 	/*
    233 	 * Fill in IP header.
    234 	 */
    235 	if ((flags & (IP_FORWARDING|IP_RAWOUTPUT)) == 0) {
    236 		ip->ip_v = IPVERSION;
    237 		ip->ip_off = htons(0);
    238 		ip->ip_id = ip_newid();
    239 		ip->ip_hl = hlen >> 2;
    240 		ipstat.ips_localout++;
    241 	} else {
    242 		hlen = ip->ip_hl << 2;
    243 	}
    244 	/*
    245 	 * Route packet.
    246 	 */
    247 	if (ro == 0) {
    248 		ro = &iproute;
    249 		bzero((caddr_t)ro, sizeof (*ro));
    250 	}
    251 	dst = satosin(&ro->ro_dst);
    252 	/*
    253 	 * If there is a cached route,
    254 	 * check that it is to the same destination
    255 	 * and is still up.  If not, free it and try again.
    256 	 * The address family should also be checked in case of sharing the
    257 	 * cache with IPv6.
    258 	 */
    259 	if (ro->ro_rt && ((ro->ro_rt->rt_flags & RTF_UP) == 0 ||
    260 	    dst->sin_family != AF_INET ||
    261 	    !in_hosteq(dst->sin_addr, ip->ip_dst))) {
    262 		RTFREE(ro->ro_rt);
    263 		ro->ro_rt = (struct rtentry *)0;
    264 	}
    265 	if (ro->ro_rt == 0) {
    266 		bzero(dst, sizeof(*dst));
    267 		dst->sin_family = AF_INET;
    268 		dst->sin_len = sizeof(*dst);
    269 		dst->sin_addr = ip->ip_dst;
    270 	}
    271 	/*
    272 	 * If routing to interface only,
    273 	 * short circuit routing lookup.
    274 	 */
    275 	if (flags & IP_ROUTETOIF) {
    276 		if ((ia = ifatoia(ifa_ifwithladdr(sintosa(dst)))) == 0) {
    277 			ipstat.ips_noroute++;
    278 			error = ENETUNREACH;
    279 			goto bad;
    280 		}
    281 		ifp = ia->ia_ifp;
    282 		mtu = ifp->if_mtu;
    283 		ip->ip_ttl = 1;
    284 	} else if ((IN_MULTICAST(ip->ip_dst.s_addr) ||
    285 	    ip->ip_dst.s_addr == INADDR_BROADCAST) &&
    286 	    imo != NULL && imo->imo_multicast_ifp != NULL) {
    287 		ifp = imo->imo_multicast_ifp;
    288 		mtu = ifp->if_mtu;
    289 		IFP_TO_IA(ifp, ia);
    290 	} else {
    291 		if (ro->ro_rt == 0)
    292 			rtalloc(ro);
    293 		if (ro->ro_rt == 0) {
    294 			ipstat.ips_noroute++;
    295 			error = EHOSTUNREACH;
    296 			goto bad;
    297 		}
    298 		ia = ifatoia(ro->ro_rt->rt_ifa);
    299 		ifp = ro->ro_rt->rt_ifp;
    300 		if ((mtu = ro->ro_rt->rt_rmx.rmx_mtu) == 0)
    301 			mtu = ifp->if_mtu;
    302 		ro->ro_rt->rt_use++;
    303 		if (ro->ro_rt->rt_flags & RTF_GATEWAY)
    304 			dst = satosin(ro->ro_rt->rt_gateway);
    305 	}
    306 	if (IN_MULTICAST(ip->ip_dst.s_addr) ||
    307 	    (ip->ip_dst.s_addr == INADDR_BROADCAST)) {
    308 		struct in_multi *inm;
    309 
    310 		m->m_flags |= (ip->ip_dst.s_addr == INADDR_BROADCAST) ?
    311 			M_BCAST : M_MCAST;
    312 		/*
    313 		 * IP destination address is multicast.  Make sure "dst"
    314 		 * still points to the address in "ro".  (It may have been
    315 		 * changed to point to a gateway address, above.)
    316 		 */
    317 		dst = satosin(&ro->ro_dst);
    318 		/*
    319 		 * See if the caller provided any multicast options
    320 		 */
    321 		if (imo != NULL)
    322 			ip->ip_ttl = imo->imo_multicast_ttl;
    323 		else
    324 			ip->ip_ttl = IP_DEFAULT_MULTICAST_TTL;
    325 
    326 		/*
    327 		 * if we don't know the outgoing ifp yet, we can't generate
    328 		 * output
    329 		 */
    330 		if (!ifp) {
    331 			ipstat.ips_noroute++;
    332 			error = ENETUNREACH;
    333 			goto bad;
    334 		}
    335 
    336 		/*
    337 		 * If the packet is multicast or broadcast, confirm that
    338 		 * the outgoing interface can transmit it.
    339 		 */
    340 		if (((m->m_flags & M_MCAST) &&
    341 		     (ifp->if_flags & IFF_MULTICAST) == 0) ||
    342 		    ((m->m_flags & M_BCAST) &&
    343 		     (ifp->if_flags & (IFF_BROADCAST|IFF_POINTOPOINT)) == 0))  {
    344 			ipstat.ips_noroute++;
    345 			error = ENETUNREACH;
    346 			goto bad;
    347 		}
    348 		/*
    349 		 * If source address not specified yet, use an address
    350 		 * of outgoing interface.
    351 		 */
    352 		if (in_nullhost(ip->ip_src)) {
    353 			struct in_ifaddr *ia;
    354 
    355 			IFP_TO_IA(ifp, ia);
    356 			if (!ia) {
    357 				error = EADDRNOTAVAIL;
    358 				goto bad;
    359 			}
    360 			ip->ip_src = ia->ia_addr.sin_addr;
    361 		}
    362 
    363 		IN_LOOKUP_MULTI(ip->ip_dst, ifp, inm);
    364 		if (inm != NULL &&
    365 		   (imo == NULL || imo->imo_multicast_loop)) {
    366 			/*
    367 			 * If we belong to the destination multicast group
    368 			 * on the outgoing interface, and the caller did not
    369 			 * forbid loopback, loop back a copy.
    370 			 */
    371 			ip_mloopback(ifp, m, dst);
    372 		}
    373 #ifdef MROUTING
    374 		else {
    375 			/*
    376 			 * If we are acting as a multicast router, perform
    377 			 * multicast forwarding as if the packet had just
    378 			 * arrived on the interface to which we are about
    379 			 * to send.  The multicast forwarding function
    380 			 * recursively calls this function, using the
    381 			 * IP_FORWARDING flag to prevent infinite recursion.
    382 			 *
    383 			 * Multicasts that are looped back by ip_mloopback(),
    384 			 * above, will be forwarded by the ip_input() routine,
    385 			 * if necessary.
    386 			 */
    387 			extern struct socket *ip_mrouter;
    388 
    389 			if (ip_mrouter && (flags & IP_FORWARDING) == 0) {
    390 				if (ip_mforward(m, ifp) != 0) {
    391 					m_freem(m);
    392 					goto done;
    393 				}
    394 			}
    395 		}
    396 #endif
    397 		/*
    398 		 * Multicasts with a time-to-live of zero may be looped-
    399 		 * back, above, but must not be transmitted on a network.
    400 		 * Also, multicasts addressed to the loopback interface
    401 		 * are not sent -- the above call to ip_mloopback() will
    402 		 * loop back a copy if this host actually belongs to the
    403 		 * destination group on the loopback interface.
    404 		 */
    405 		if (ip->ip_ttl == 0 || (ifp->if_flags & IFF_LOOPBACK) != 0) {
    406 			m_freem(m);
    407 			goto done;
    408 		}
    409 
    410 		goto sendit;
    411 	}
    412 #ifndef notdef
    413 	/*
    414 	 * If source address not specified yet, use address
    415 	 * of outgoing interface.
    416 	 */
    417 	if (in_nullhost(ip->ip_src))
    418 		ip->ip_src = ia->ia_addr.sin_addr;
    419 #endif
    420 
    421 	/*
    422 	 * packets with Class-D address as source are not valid per
    423 	 * RFC 1112
    424 	 */
    425 	if (IN_MULTICAST(ip->ip_src.s_addr)) {
    426 		ipstat.ips_odropped++;
    427 		error = EADDRNOTAVAIL;
    428 		goto bad;
    429 	}
    430 
    431 	/*
    432 	 * Look for broadcast address and
    433 	 * and verify user is allowed to send
    434 	 * such a packet.
    435 	 */
    436 	if (in_broadcast(dst->sin_addr, ifp)) {
    437 		if ((ifp->if_flags & IFF_BROADCAST) == 0) {
    438 			error = EADDRNOTAVAIL;
    439 			goto bad;
    440 		}
    441 		if ((flags & IP_ALLOWBROADCAST) == 0) {
    442 			error = EACCES;
    443 			goto bad;
    444 		}
    445 		/* don't allow broadcast messages to be fragmented */
    446 		if (ntohs(ip->ip_len) > ifp->if_mtu) {
    447 			error = EMSGSIZE;
    448 			goto bad;
    449 		}
    450 		m->m_flags |= M_BCAST;
    451 	} else
    452 		m->m_flags &= ~M_BCAST;
    453 
    454 sendit:
    455 	/*
    456 	 * If we're doing Path MTU Discovery, we need to set DF unless
    457 	 * the route's MTU is locked.
    458 	 */
    459 	if ((flags & IP_MTUDISC) != 0 && ro->ro_rt != NULL &&
    460 	    (ro->ro_rt->rt_rmx.rmx_locks & RTV_MTU) == 0)
    461 		ip->ip_off |= htons(IP_DF);
    462 
    463 	/* Remember the current ip_len */
    464 	ip_len = ntohs(ip->ip_len);
    465 
    466 #ifdef IPSEC
    467 	/* get SP for this packet */
    468 	if (so == NULL)
    469 		sp = ipsec4_getpolicybyaddr(m, IPSEC_DIR_OUTBOUND,
    470 		    flags, &error);
    471 	else {
    472 		if (IPSEC_PCB_SKIP_IPSEC(sotoinpcb_hdr(so)->inph_sp,
    473 					 IPSEC_DIR_OUTBOUND))
    474 			goto skip_ipsec;
    475 		sp = ipsec4_getpolicybysock(m, IPSEC_DIR_OUTBOUND, so, &error);
    476 	}
    477 
    478 	if (sp == NULL) {
    479 		ipsecstat.out_inval++;
    480 		goto bad;
    481 	}
    482 
    483 	error = 0;
    484 
    485 	/* check policy */
    486 	switch (sp->policy) {
    487 	case IPSEC_POLICY_DISCARD:
    488 		/*
    489 		 * This packet is just discarded.
    490 		 */
    491 		ipsecstat.out_polvio++;
    492 		goto bad;
    493 
    494 	case IPSEC_POLICY_BYPASS:
    495 	case IPSEC_POLICY_NONE:
    496 		/* no need to do IPsec. */
    497 		goto skip_ipsec;
    498 
    499 	case IPSEC_POLICY_IPSEC:
    500 		if (sp->req == NULL) {
    501 			/* XXX should be panic ? */
    502 			printf("ip_output: No IPsec request specified.\n");
    503 			error = EINVAL;
    504 			goto bad;
    505 		}
    506 		break;
    507 
    508 	case IPSEC_POLICY_ENTRUST:
    509 	default:
    510 		printf("ip_output: Invalid policy found. %d\n", sp->policy);
    511 	}
    512 
    513 #ifdef IPSEC_NAT_T
    514 	/*
    515 	 * NAT-T ESP fragmentation: don't do IPSec processing now,
    516 	 * we'll do it on each fragmented packet.
    517 	 */
    518 	if (sp->req->sav &&
    519 	    ((sp->req->sav->natt_type & UDP_ENCAP_ESPINUDP) ||
    520 	     (sp->req->sav->natt_type & UDP_ENCAP_ESPINUDP_NON_IKE))) {
    521 		if (ntohs(ip->ip_len) > sp->req->sav->esp_frag) {
    522 			natt_frag = 1;
    523 			mtu = sp->req->sav->esp_frag;
    524 			goto skip_ipsec;
    525 		}
    526 	}
    527 #endif /* IPSEC_NAT_T */
    528 
    529 	/*
    530 	 * ipsec4_output() expects ip_len and ip_off in network
    531 	 * order.  They have been set to network order above.
    532 	 */
    533 
    534     {
    535 	struct ipsec_output_state state;
    536 	bzero(&state, sizeof(state));
    537 	state.m = m;
    538 	if (flags & IP_ROUTETOIF) {
    539 		state.ro = &iproute;
    540 		bzero(&iproute, sizeof(iproute));
    541 	} else
    542 		state.ro = ro;
    543 	state.dst = (struct sockaddr *)dst;
    544 
    545 	/*
    546 	 * We can't defer the checksum of payload data if
    547 	 * we're about to encrypt/authenticate it.
    548 	 *
    549 	 * XXX When we support crypto offloading functions of
    550 	 * XXX network interfaces, we need to reconsider this,
    551 	 * XXX since it's likely that they'll support checksumming,
    552 	 * XXX as well.
    553 	 */
    554 	if (m->m_pkthdr.csum_flags & (M_CSUM_TCPv4|M_CSUM_UDPv4)) {
    555 		in_delayed_cksum(m);
    556 		m->m_pkthdr.csum_flags &= ~(M_CSUM_TCPv4|M_CSUM_UDPv4);
    557 	}
    558 
    559 	error = ipsec4_output(&state, sp, flags);
    560 
    561 	m = state.m;
    562 	if (flags & IP_ROUTETOIF) {
    563 		/*
    564 		 * if we have tunnel mode SA, we may need to ignore
    565 		 * IP_ROUTETOIF.
    566 		 */
    567 		if (state.ro != &iproute || state.ro->ro_rt != NULL) {
    568 			flags &= ~IP_ROUTETOIF;
    569 			ro = state.ro;
    570 		}
    571 	} else
    572 		ro = state.ro;
    573 	dst = (struct sockaddr_in *)state.dst;
    574 	if (error) {
    575 		/* mbuf is already reclaimed in ipsec4_output. */
    576 		m0 = NULL;
    577 		switch (error) {
    578 		case EHOSTUNREACH:
    579 		case ENETUNREACH:
    580 		case EMSGSIZE:
    581 		case ENOBUFS:
    582 		case ENOMEM:
    583 			break;
    584 		default:
    585 			printf("ip4_output (ipsec): error code %d\n", error);
    586 			/*fall through*/
    587 		case ENOENT:
    588 			/* don't show these error codes to the user */
    589 			error = 0;
    590 			break;
    591 		}
    592 		goto bad;
    593 	}
    594 
    595 	/* be sure to update variables that are affected by ipsec4_output() */
    596 	ip = mtod(m, struct ip *);
    597 	hlen = ip->ip_hl << 2;
    598 	ip_len = ntohs(ip->ip_len);
    599 
    600 	if (ro->ro_rt == NULL) {
    601 		if ((flags & IP_ROUTETOIF) == 0) {
    602 			printf("ip_output: "
    603 				"can't update route after IPsec processing\n");
    604 			error = EHOSTUNREACH;	/*XXX*/
    605 			goto bad;
    606 		}
    607 	} else {
    608 		/* nobody uses ia beyond here */
    609 		if (state.encap) {
    610 			ifp = ro->ro_rt->rt_ifp;
    611 			if ((mtu = ro->ro_rt->rt_rmx.rmx_mtu) == 0)
    612 				mtu = ifp->if_mtu;
    613 		}
    614 	}
    615     }
    616 skip_ipsec:
    617 #endif /*IPSEC*/
    618 #ifdef FAST_IPSEC
    619 	/*
    620 	 * Check the security policy (SP) for the packet and, if
    621 	 * required, do IPsec-related processing.  There are two
    622 	 * cases here; the first time a packet is sent through
    623 	 * it will be untagged and handled by ipsec4_checkpolicy.
    624 	 * If the packet is resubmitted to ip_output (e.g. after
    625 	 * AH, ESP, etc. processing), there will be a tag to bypass
    626 	 * the lookup and related policy checking.
    627 	 */
    628 	mtag = m_tag_find(m, PACKET_TAG_IPSEC_PENDING_TDB, NULL);
    629 	s = splsoftnet();
    630 	if (mtag != NULL) {
    631 		tdbi = (struct tdb_ident *)(mtag + 1);
    632 		sp = ipsec_getpolicy(tdbi, IPSEC_DIR_OUTBOUND);
    633 		if (sp == NULL)
    634 			error = -EINVAL;	/* force silent drop */
    635 		m_tag_delete(m, mtag);
    636 	} else {
    637 		if (inp != NULL &&
    638 		    IPSEC_PCB_SKIP_IPSEC(inp->inp_sp, IPSEC_DIR_OUTBOUND))
    639 			goto spd_done;
    640 		sp = ipsec4_checkpolicy(m, IPSEC_DIR_OUTBOUND, flags,
    641 					&error, inp);
    642 	}
    643 	/*
    644 	 * There are four return cases:
    645 	 *    sp != NULL	 	    apply IPsec policy
    646 	 *    sp == NULL, error == 0	    no IPsec handling needed
    647 	 *    sp == NULL, error == -EINVAL  discard packet w/o error
    648 	 *    sp == NULL, error != 0	    discard packet, report error
    649 	 */
    650 	if (sp != NULL) {
    651 		/* Loop detection, check if ipsec processing already done */
    652 		IPSEC_ASSERT(sp->req != NULL, ("ip_output: no ipsec request"));
    653 		for (mtag = m_tag_first(m); mtag != NULL;
    654 		     mtag = m_tag_next(m, mtag)) {
    655 #ifdef MTAG_ABI_COMPAT
    656 			if (mtag->m_tag_cookie != MTAG_ABI_COMPAT)
    657 				continue;
    658 #endif
    659 			if (mtag->m_tag_id != PACKET_TAG_IPSEC_OUT_DONE &&
    660 			    mtag->m_tag_id != PACKET_TAG_IPSEC_OUT_CRYPTO_NEEDED)
    661 				continue;
    662 			/*
    663 			 * Check if policy has an SA associated with it.
    664 			 * This can happen when an SP has yet to acquire
    665 			 * an SA; e.g. on first reference.  If it occurs,
    666 			 * then we let ipsec4_process_packet do its thing.
    667 			 */
    668 			if (sp->req->sav == NULL)
    669 				break;
    670 			tdbi = (struct tdb_ident *)(mtag + 1);
    671 			if (tdbi->spi == sp->req->sav->spi &&
    672 			    tdbi->proto == sp->req->sav->sah->saidx.proto &&
    673 			    bcmp(&tdbi->dst, &sp->req->sav->sah->saidx.dst,
    674 				 sizeof (union sockaddr_union)) == 0) {
    675 				/*
    676 				 * No IPsec processing is needed, free
    677 				 * reference to SP.
    678 				 *
    679 				 * NB: null pointer to avoid free at
    680 				 *     done: below.
    681 				 */
    682 				KEY_FREESP(&sp), sp = NULL;
    683 				splx(s);
    684 				goto spd_done;
    685 			}
    686 		}
    687 
    688 		/*
    689 		 * Do delayed checksums now because we send before
    690 		 * this is done in the normal processing path.
    691 		 */
    692 		if (m->m_pkthdr.csum_flags & (M_CSUM_TCPv4|M_CSUM_UDPv4)) {
    693 			in_delayed_cksum(m);
    694 			m->m_pkthdr.csum_flags &= ~(M_CSUM_TCPv4|M_CSUM_UDPv4);
    695 		}
    696 
    697 #ifdef __FreeBSD__
    698 		ip->ip_len = htons(ip->ip_len);
    699 		ip->ip_off = htons(ip->ip_off);
    700 #endif
    701 
    702 		/* NB: callee frees mbuf */
    703 		error = ipsec4_process_packet(m, sp->req, flags, 0);
    704 		/*
    705 		 * Preserve KAME behaviour: ENOENT can be returned
    706 		 * when an SA acquire is in progress.  Don't propagate
    707 		 * this to user-level; it confuses applications.
    708 		 *
    709 		 * XXX this will go away when the SADB is redone.
    710 		 */
    711 		if (error == ENOENT)
    712 			error = 0;
    713 		splx(s);
    714 		goto done;
    715 	} else {
    716 		splx(s);
    717 
    718 		if (error != 0) {
    719 			/*
    720 			 * Hack: -EINVAL is used to signal that a packet
    721 			 * should be silently discarded.  This is typically
    722 			 * because we asked key management for an SA and
    723 			 * it was delayed (e.g. kicked up to IKE).
    724 			 */
    725 			if (error == -EINVAL)
    726 				error = 0;
    727 			goto bad;
    728 		} else {
    729 			/* No IPsec processing for this packet. */
    730 		}
    731 #ifdef notyet
    732 		/*
    733 		 * If deferred crypto processing is needed, check that
    734 		 * the interface supports it.
    735 		 */
    736 		mtag = m_tag_find(m, PACKET_TAG_IPSEC_OUT_CRYPTO_NEEDED, NULL);
    737 		if (mtag != NULL && (ifp->if_capenable & IFCAP_IPSEC) == 0) {
    738 			/* notify IPsec to do its own crypto */
    739 			ipsp_skipcrypto_unmark((struct tdb_ident *)(mtag + 1));
    740 			error = EHOSTUNREACH;
    741 			goto bad;
    742 		}
    743 #endif
    744 	}
    745 spd_done:
    746 #endif /* FAST_IPSEC */
    747 
    748 #ifdef PFIL_HOOKS
    749 	/*
    750 	 * Run through list of hooks for output packets.
    751 	 */
    752 	if ((error = pfil_run_hooks(&inet_pfil_hook, &m, ifp, PFIL_OUT)) != 0)
    753 		goto done;
    754 	if (m == NULL)
    755 		goto done;
    756 
    757 	ip = mtod(m, struct ip *);
    758 	hlen = ip->ip_hl << 2;
    759 #endif /* PFIL_HOOKS */
    760 
    761 	m->m_pkthdr.csum_data |= hlen << 16;
    762 
    763 #if IFA_STATS
    764 	/*
    765 	 * search for the source address structure to
    766 	 * maintain output statistics.
    767 	 */
    768 	INADDR_TO_IA(ip->ip_src, ia);
    769 #endif
    770 
    771 	/* Maybe skip checksums on loopback interfaces. */
    772 	if (__predict_true(!(ifp->if_flags & IFF_LOOPBACK) ||
    773 			   ip_do_loopback_cksum))
    774 		m->m_pkthdr.csum_flags |= M_CSUM_IPv4;
    775 	sw_csum = m->m_pkthdr.csum_flags & ~ifp->if_csum_flags_tx;
    776 	/*
    777 	 * If small enough for mtu of path, or if using TCP segmentation
    778 	 * offload, can just send directly.
    779 	 */
    780 	if (ip_len <= mtu ||
    781 	    (m->m_pkthdr.csum_flags & M_CSUM_TSOv4) != 0) {
    782 #if IFA_STATS
    783 		if (ia)
    784 			ia->ia_ifa.ifa_data.ifad_outbytes += ip_len;
    785 #endif
    786 		/*
    787 		 * Always initialize the sum to 0!  Some HW assisted
    788 		 * checksumming requires this.
    789 		 */
    790 		ip->ip_sum = 0;
    791 
    792 		if ((m->m_pkthdr.csum_flags & M_CSUM_TSOv4) == 0) {
    793 			/*
    794 			 * Perform any checksums that the hardware can't do
    795 			 * for us.
    796 			 *
    797 			 * XXX Does any hardware require the {th,uh}_sum
    798 			 * XXX fields to be 0?
    799 			 */
    800 			if (sw_csum & M_CSUM_IPv4) {
    801 				ip->ip_sum = in_cksum(m, hlen);
    802 				m->m_pkthdr.csum_flags &= ~M_CSUM_IPv4;
    803 			}
    804 			if (sw_csum & (M_CSUM_TCPv4|M_CSUM_UDPv4)) {
    805 				in_delayed_cksum(m);
    806 				m->m_pkthdr.csum_flags &=
    807 				    ~(M_CSUM_TCPv4|M_CSUM_UDPv4);
    808 			}
    809 		}
    810 
    811 #ifdef IPSEC
    812 		/* clean ipsec history once it goes out of the node */
    813 		ipsec_delaux(m);
    814 #endif
    815 		error = (*ifp->if_output)(ifp, m, sintosa(dst), ro->ro_rt);
    816 		goto done;
    817 	}
    818 
    819 	/*
    820 	 * We can't use HW checksumming if we're about to
    821 	 * to fragment the packet.
    822 	 *
    823 	 * XXX Some hardware can do this.
    824 	 */
    825 	if (m->m_pkthdr.csum_flags & (M_CSUM_TCPv4|M_CSUM_UDPv4)) {
    826 		in_delayed_cksum(m);
    827 		m->m_pkthdr.csum_flags &= ~(M_CSUM_TCPv4|M_CSUM_UDPv4);
    828 	}
    829 
    830 	/*
    831 	 * Too large for interface; fragment if possible.
    832 	 * Must be able to put at least 8 bytes per fragment.
    833 	 */
    834 	if (ntohs(ip->ip_off) & IP_DF) {
    835 		if (flags & IP_RETURNMTU)
    836 			*mtu_p = mtu;
    837 		error = EMSGSIZE;
    838 		ipstat.ips_cantfrag++;
    839 		goto bad;
    840 	}
    841 
    842 	error = ip_fragment(m, ifp, mtu);
    843 	if (error) {
    844 		m = NULL;
    845 		goto bad;
    846 	}
    847 
    848 	for (; m; m = m0) {
    849 		m0 = m->m_nextpkt;
    850 		m->m_nextpkt = 0;
    851 		if (error == 0) {
    852 #if IFA_STATS
    853 			if (ia)
    854 				ia->ia_ifa.ifa_data.ifad_outbytes +=
    855 				    ntohs(ip->ip_len);
    856 #endif
    857 #ifdef IPSEC
    858 			/* clean ipsec history once it goes out of the node */
    859 			ipsec_delaux(m);
    860 
    861 #ifdef IPSEC_NAT_T
    862 			/*
    863 			 * If we get there, the packet has not been handeld by
    864 			 * IPSec whereas it should have. Now that it has been
    865 			 * fragmented, re-inject it in ip_output so that IPsec
    866 			 * processing can occur.
    867 			 */
    868 			if (natt_frag) {
    869 				error = ip_output(m, opt,
    870 				    ro, flags, imo, so, mtu_p);
    871 			} else
    872 #endif /* IPSEC_NAT_T */
    873 #endif /* IPSEC */
    874 			{
    875 				KASSERT((m->m_pkthdr.csum_flags &
    876 				    (M_CSUM_UDPv4 | M_CSUM_TCPv4)) == 0);
    877 				error = (*ifp->if_output)(ifp, m, sintosa(dst),
    878 				    ro->ro_rt);
    879 			}
    880 		} else
    881 			m_freem(m);
    882 	}
    883 
    884 	if (error == 0)
    885 		ipstat.ips_fragmented++;
    886 done:
    887 	if (ro == &iproute && (flags & IP_ROUTETOIF) == 0 && ro->ro_rt) {
    888 		RTFREE(ro->ro_rt);
    889 		ro->ro_rt = 0;
    890 	}
    891 
    892 #ifdef IPSEC
    893 	if (sp != NULL) {
    894 		KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
    895 			printf("DP ip_output call free SP:%p\n", sp));
    896 		key_freesp(sp);
    897 	}
    898 #endif /* IPSEC */
    899 #ifdef FAST_IPSEC
    900 	if (sp != NULL)
    901 		KEY_FREESP(&sp);
    902 #endif /* FAST_IPSEC */
    903 
    904 	return (error);
    905 bad:
    906 	m_freem(m);
    907 	goto done;
    908 }
    909 
    910 int
    911 ip_fragment(struct mbuf *m, struct ifnet *ifp, u_long mtu)
    912 {
    913 	struct ip *ip, *mhip;
    914 	struct mbuf *m0;
    915 	int len, hlen, off;
    916 	int mhlen, firstlen;
    917 	struct mbuf **mnext;
    918 	int sw_csum = m->m_pkthdr.csum_flags;
    919 	int fragments = 0;
    920 	int s;
    921 	int error = 0;
    922 
    923 	ip = mtod(m, struct ip *);
    924 	hlen = ip->ip_hl << 2;
    925 	if (ifp != NULL)
    926 		sw_csum &= ~ifp->if_csum_flags_tx;
    927 
    928 	len = (mtu - hlen) &~ 7;
    929 	if (len < 8) {
    930 		m_freem(m);
    931 		return (EMSGSIZE);
    932 	}
    933 
    934 	firstlen = len;
    935 	mnext = &m->m_nextpkt;
    936 
    937 	/*
    938 	 * Loop through length of segment after first fragment,
    939 	 * make new header and copy data of each part and link onto chain.
    940 	 */
    941 	m0 = m;
    942 	mhlen = sizeof (struct ip);
    943 	for (off = hlen + len; off < ntohs(ip->ip_len); off += len) {
    944 		MGETHDR(m, M_DONTWAIT, MT_HEADER);
    945 		if (m == 0) {
    946 			error = ENOBUFS;
    947 			ipstat.ips_odropped++;
    948 			goto sendorfree;
    949 		}
    950 		MCLAIM(m, m0->m_owner);
    951 		*mnext = m;
    952 		mnext = &m->m_nextpkt;
    953 		m->m_data += max_linkhdr;
    954 		mhip = mtod(m, struct ip *);
    955 		*mhip = *ip;
    956 		/* we must inherit MCAST and BCAST flags */
    957 		m->m_flags |= m0->m_flags & (M_MCAST|M_BCAST);
    958 		if (hlen > sizeof (struct ip)) {
    959 			mhlen = ip_optcopy(ip, mhip) + sizeof (struct ip);
    960 			mhip->ip_hl = mhlen >> 2;
    961 		}
    962 		m->m_len = mhlen;
    963 		mhip->ip_off = ((off - hlen) >> 3) +
    964 		    (ntohs(ip->ip_off) & ~IP_MF);
    965 		if (ip->ip_off & htons(IP_MF))
    966 			mhip->ip_off |= IP_MF;
    967 		if (off + len >= ntohs(ip->ip_len))
    968 			len = ntohs(ip->ip_len) - off;
    969 		else
    970 			mhip->ip_off |= IP_MF;
    971 		HTONS(mhip->ip_off);
    972 		mhip->ip_len = htons((u_int16_t)(len + mhlen));
    973 		m->m_next = m_copy(m0, off, len);
    974 		if (m->m_next == 0) {
    975 			error = ENOBUFS;	/* ??? */
    976 			ipstat.ips_odropped++;
    977 			goto sendorfree;
    978 		}
    979 		m->m_pkthdr.len = mhlen + len;
    980 		m->m_pkthdr.rcvif = (struct ifnet *)0;
    981 		mhip->ip_sum = 0;
    982 		if (sw_csum & M_CSUM_IPv4) {
    983 			mhip->ip_sum = in_cksum(m, mhlen);
    984 			KASSERT((m->m_pkthdr.csum_flags & M_CSUM_IPv4) == 0);
    985 		} else {
    986 			m->m_pkthdr.csum_flags |= M_CSUM_IPv4;
    987 			m->m_pkthdr.csum_data |= mhlen << 16;
    988 		}
    989 		ipstat.ips_ofragments++;
    990 		fragments++;
    991 	}
    992 	/*
    993 	 * Update first fragment by trimming what's been copied out
    994 	 * and updating header, then send each fragment (in order).
    995 	 */
    996 	m = m0;
    997 	m_adj(m, hlen + firstlen - ntohs(ip->ip_len));
    998 	m->m_pkthdr.len = hlen + firstlen;
    999 	ip->ip_len = htons((u_int16_t)m->m_pkthdr.len);
   1000 	ip->ip_off |= htons(IP_MF);
   1001 	ip->ip_sum = 0;
   1002 	if (sw_csum & M_CSUM_IPv4) {
   1003 		ip->ip_sum = in_cksum(m, hlen);
   1004 		m->m_pkthdr.csum_flags &= ~M_CSUM_IPv4;
   1005 	} else {
   1006 		KASSERT(m->m_pkthdr.csum_flags & M_CSUM_IPv4);
   1007 		KASSERT(M_CSUM_DATA_IPv4_IPHL(m->m_pkthdr.csum_data) >=
   1008 			sizeof(struct ip));
   1009 	}
   1010 sendorfree:
   1011 	/*
   1012 	 * If there is no room for all the fragments, don't queue
   1013 	 * any of them.
   1014 	 */
   1015 	if (ifp != NULL) {
   1016 		s = splnet();
   1017 		if (ifp->if_snd.ifq_maxlen - ifp->if_snd.ifq_len < fragments &&
   1018 		    error == 0) {
   1019 			error = ENOBUFS;
   1020 			ipstat.ips_odropped++;
   1021 			IFQ_INC_DROPS(&ifp->if_snd);
   1022 		}
   1023 		splx(s);
   1024 	}
   1025 	if (error) {
   1026 		for (m = m0; m; m = m0) {
   1027 			m0 = m->m_nextpkt;
   1028 			m->m_nextpkt = NULL;
   1029 			m_freem(m);
   1030 		}
   1031 	}
   1032 	return (error);
   1033 }
   1034 
   1035 /*
   1036  * Process a delayed payload checksum calculation.
   1037  */
   1038 void
   1039 in_delayed_cksum(struct mbuf *m)
   1040 {
   1041 	struct ip *ip;
   1042 	u_int16_t csum, offset;
   1043 
   1044 	ip = mtod(m, struct ip *);
   1045 	offset = ip->ip_hl << 2;
   1046 	csum = in4_cksum(m, 0, offset, ntohs(ip->ip_len) - offset);
   1047 	if (csum == 0 && (m->m_pkthdr.csum_flags & M_CSUM_UDPv4) != 0)
   1048 		csum = 0xffff;
   1049 
   1050 	offset += M_CSUM_DATA_IPv4_OFFSET(m->m_pkthdr.csum_data);
   1051 
   1052 	if ((offset + sizeof(u_int16_t)) > m->m_len) {
   1053 		/* This happen when ip options were inserted
   1054 		printf("in_delayed_cksum: pullup len %d off %d proto %d\n",
   1055 		    m->m_len, offset, ip->ip_p);
   1056 		 */
   1057 		m_copyback(m, offset, sizeof(csum), (caddr_t) &csum);
   1058 	} else
   1059 		*(u_int16_t *)(mtod(m, caddr_t) + offset) = csum;
   1060 }
   1061 
   1062 /*
   1063  * Determine the maximum length of the options to be inserted;
   1064  * we would far rather allocate too much space rather than too little.
   1065  */
   1066 
   1067 u_int
   1068 ip_optlen(struct inpcb *inp)
   1069 {
   1070 	struct mbuf *m = inp->inp_options;
   1071 
   1072 	if (m && m->m_len > offsetof(struct ipoption, ipopt_dst))
   1073 		return (m->m_len - offsetof(struct ipoption, ipopt_dst));
   1074 	else
   1075 		return 0;
   1076 }
   1077 
   1078 
   1079 /*
   1080  * Insert IP options into preformed packet.
   1081  * Adjust IP destination as required for IP source routing,
   1082  * as indicated by a non-zero in_addr at the start of the options.
   1083  */
   1084 static struct mbuf *
   1085 ip_insertoptions(struct mbuf *m, struct mbuf *opt, int *phlen)
   1086 {
   1087 	struct ipoption *p = mtod(opt, struct ipoption *);
   1088 	struct mbuf *n;
   1089 	struct ip *ip = mtod(m, struct ip *);
   1090 	unsigned optlen;
   1091 
   1092 	optlen = opt->m_len - sizeof(p->ipopt_dst);
   1093 	if (optlen + ntohs(ip->ip_len) > IP_MAXPACKET)
   1094 		return (m);		/* XXX should fail */
   1095 	if (!in_nullhost(p->ipopt_dst))
   1096 		ip->ip_dst = p->ipopt_dst;
   1097 	if (M_READONLY(m) || M_LEADINGSPACE(m) < optlen) {
   1098 		MGETHDR(n, M_DONTWAIT, MT_HEADER);
   1099 		if (n == 0)
   1100 			return (m);
   1101 		MCLAIM(n, m->m_owner);
   1102 		M_COPY_PKTHDR(n, m);
   1103 		m_tag_delete_chain(m, NULL);
   1104 		m->m_flags &= ~M_PKTHDR;
   1105 		m->m_len -= sizeof(struct ip);
   1106 		m->m_data += sizeof(struct ip);
   1107 		n->m_next = m;
   1108 		m = n;
   1109 		m->m_len = optlen + sizeof(struct ip);
   1110 		m->m_data += max_linkhdr;
   1111 		bcopy((caddr_t)ip, mtod(m, caddr_t), sizeof(struct ip));
   1112 	} else {
   1113 		m->m_data -= optlen;
   1114 		m->m_len += optlen;
   1115 		memmove(mtod(m, caddr_t), ip, sizeof(struct ip));
   1116 	}
   1117 	m->m_pkthdr.len += optlen;
   1118 	ip = mtod(m, struct ip *);
   1119 	bcopy((caddr_t)p->ipopt_list, (caddr_t)(ip + 1), (unsigned)optlen);
   1120 	*phlen = sizeof(struct ip) + optlen;
   1121 	ip->ip_len = htons(ntohs(ip->ip_len) + optlen);
   1122 	return (m);
   1123 }
   1124 
   1125 /*
   1126  * Copy options from ip to jp,
   1127  * omitting those not copied during fragmentation.
   1128  */
   1129 int
   1130 ip_optcopy(struct ip *ip, struct ip *jp)
   1131 {
   1132 	u_char *cp, *dp;
   1133 	int opt, optlen, cnt;
   1134 
   1135 	cp = (u_char *)(ip + 1);
   1136 	dp = (u_char *)(jp + 1);
   1137 	cnt = (ip->ip_hl << 2) - sizeof (struct ip);
   1138 	for (; cnt > 0; cnt -= optlen, cp += optlen) {
   1139 		opt = cp[0];
   1140 		if (opt == IPOPT_EOL)
   1141 			break;
   1142 		if (opt == IPOPT_NOP) {
   1143 			/* Preserve for IP mcast tunnel's LSRR alignment. */
   1144 			*dp++ = IPOPT_NOP;
   1145 			optlen = 1;
   1146 			continue;
   1147 		}
   1148 #ifdef DIAGNOSTIC
   1149 		if (cnt < IPOPT_OLEN + sizeof(*cp))
   1150 			panic("malformed IPv4 option passed to ip_optcopy");
   1151 #endif
   1152 		optlen = cp[IPOPT_OLEN];
   1153 #ifdef DIAGNOSTIC
   1154 		if (optlen < IPOPT_OLEN + sizeof(*cp) || optlen > cnt)
   1155 			panic("malformed IPv4 option passed to ip_optcopy");
   1156 #endif
   1157 		/* bogus lengths should have been caught by ip_dooptions */
   1158 		if (optlen > cnt)
   1159 			optlen = cnt;
   1160 		if (IPOPT_COPIED(opt)) {
   1161 			bcopy((caddr_t)cp, (caddr_t)dp, (unsigned)optlen);
   1162 			dp += optlen;
   1163 		}
   1164 	}
   1165 	for (optlen = dp - (u_char *)(jp+1); optlen & 0x3; optlen++)
   1166 		*dp++ = IPOPT_EOL;
   1167 	return (optlen);
   1168 }
   1169 
   1170 /*
   1171  * IP socket option processing.
   1172  */
   1173 int
   1174 ip_ctloutput(int op, struct socket *so, int level, int optname,
   1175     struct mbuf **mp)
   1176 {
   1177 	struct inpcb *inp = sotoinpcb(so);
   1178 	struct mbuf *m = *mp;
   1179 	int optval = 0;
   1180 	int error = 0;
   1181 #if defined(IPSEC) || defined(FAST_IPSEC)
   1182 	struct proc *p = curproc;	/*XXX*/
   1183 #endif
   1184 
   1185 	if (level != IPPROTO_IP) {
   1186 		error = EINVAL;
   1187 		if (op == PRCO_SETOPT && *mp)
   1188 			(void) m_free(*mp);
   1189 	} else switch (op) {
   1190 
   1191 	case PRCO_SETOPT:
   1192 		switch (optname) {
   1193 		case IP_OPTIONS:
   1194 #ifdef notyet
   1195 		case IP_RETOPTS:
   1196 			return (ip_pcbopts(optname, &inp->inp_options, m));
   1197 #else
   1198 			return (ip_pcbopts(&inp->inp_options, m));
   1199 #endif
   1200 
   1201 		case IP_TOS:
   1202 		case IP_TTL:
   1203 		case IP_RECVOPTS:
   1204 		case IP_RECVRETOPTS:
   1205 		case IP_RECVDSTADDR:
   1206 		case IP_RECVIF:
   1207 			if (m == NULL || m->m_len != sizeof(int))
   1208 				error = EINVAL;
   1209 			else {
   1210 				optval = *mtod(m, int *);
   1211 				switch (optname) {
   1212 
   1213 				case IP_TOS:
   1214 					inp->inp_ip.ip_tos = optval;
   1215 					break;
   1216 
   1217 				case IP_TTL:
   1218 					inp->inp_ip.ip_ttl = optval;
   1219 					break;
   1220 #define	OPTSET(bit) \
   1221 	if (optval) \
   1222 		inp->inp_flags |= bit; \
   1223 	else \
   1224 		inp->inp_flags &= ~bit;
   1225 
   1226 				case IP_RECVOPTS:
   1227 					OPTSET(INP_RECVOPTS);
   1228 					break;
   1229 
   1230 				case IP_RECVRETOPTS:
   1231 					OPTSET(INP_RECVRETOPTS);
   1232 					break;
   1233 
   1234 				case IP_RECVDSTADDR:
   1235 					OPTSET(INP_RECVDSTADDR);
   1236 					break;
   1237 
   1238 				case IP_RECVIF:
   1239 					OPTSET(INP_RECVIF);
   1240 					break;
   1241 				}
   1242 			}
   1243 			break;
   1244 #undef OPTSET
   1245 
   1246 		case IP_MULTICAST_IF:
   1247 		case IP_MULTICAST_TTL:
   1248 		case IP_MULTICAST_LOOP:
   1249 		case IP_ADD_MEMBERSHIP:
   1250 		case IP_DROP_MEMBERSHIP:
   1251 			error = ip_setmoptions(optname, &inp->inp_moptions, m);
   1252 			break;
   1253 
   1254 		case IP_PORTRANGE:
   1255 			if (m == 0 || m->m_len != sizeof(int))
   1256 				error = EINVAL;
   1257 			else {
   1258 				optval = *mtod(m, int *);
   1259 
   1260 				switch (optval) {
   1261 
   1262 				case IP_PORTRANGE_DEFAULT:
   1263 				case IP_PORTRANGE_HIGH:
   1264 					inp->inp_flags &= ~(INP_LOWPORT);
   1265 					break;
   1266 
   1267 				case IP_PORTRANGE_LOW:
   1268 					inp->inp_flags |= INP_LOWPORT;
   1269 					break;
   1270 
   1271 				default:
   1272 					error = EINVAL;
   1273 					break;
   1274 				}
   1275 			}
   1276 			break;
   1277 
   1278 #if defined(IPSEC) || defined(FAST_IPSEC)
   1279 		case IP_IPSEC_POLICY:
   1280 		{
   1281 			caddr_t req = NULL;
   1282 			size_t len = 0;
   1283 			int priv = 0;
   1284 
   1285 #ifdef __NetBSD__
   1286 			if (p == 0 || suser(p->p_ucred, &p->p_acflag))
   1287 				priv = 0;
   1288 			else
   1289 				priv = 1;
   1290 #else
   1291 			priv = (in6p->in6p_socket->so_state & SS_PRIV);
   1292 #endif
   1293 			if (m) {
   1294 				req = mtod(m, caddr_t);
   1295 				len = m->m_len;
   1296 			}
   1297 			error = ipsec4_set_policy(inp, optname, req, len, priv);
   1298 			break;
   1299 		    }
   1300 #endif /*IPSEC*/
   1301 
   1302 		default:
   1303 			error = ENOPROTOOPT;
   1304 			break;
   1305 		}
   1306 		if (m)
   1307 			(void)m_free(m);
   1308 		break;
   1309 
   1310 	case PRCO_GETOPT:
   1311 		switch (optname) {
   1312 		case IP_OPTIONS:
   1313 		case IP_RETOPTS:
   1314 			*mp = m = m_get(M_WAIT, MT_SOOPTS);
   1315 			MCLAIM(m, so->so_mowner);
   1316 			if (inp->inp_options) {
   1317 				m->m_len = inp->inp_options->m_len;
   1318 				bcopy(mtod(inp->inp_options, caddr_t),
   1319 				    mtod(m, caddr_t), (unsigned)m->m_len);
   1320 			} else
   1321 				m->m_len = 0;
   1322 			break;
   1323 
   1324 		case IP_TOS:
   1325 		case IP_TTL:
   1326 		case IP_RECVOPTS:
   1327 		case IP_RECVRETOPTS:
   1328 		case IP_RECVDSTADDR:
   1329 		case IP_RECVIF:
   1330 		case IP_ERRORMTU:
   1331 			*mp = m = m_get(M_WAIT, MT_SOOPTS);
   1332 			MCLAIM(m, so->so_mowner);
   1333 			m->m_len = sizeof(int);
   1334 			switch (optname) {
   1335 
   1336 			case IP_TOS:
   1337 				optval = inp->inp_ip.ip_tos;
   1338 				break;
   1339 
   1340 			case IP_TTL:
   1341 				optval = inp->inp_ip.ip_ttl;
   1342 				break;
   1343 
   1344 			case IP_ERRORMTU:
   1345 				optval = inp->inp_errormtu;
   1346 				break;
   1347 
   1348 #define	OPTBIT(bit)	(inp->inp_flags & bit ? 1 : 0)
   1349 
   1350 			case IP_RECVOPTS:
   1351 				optval = OPTBIT(INP_RECVOPTS);
   1352 				break;
   1353 
   1354 			case IP_RECVRETOPTS:
   1355 				optval = OPTBIT(INP_RECVRETOPTS);
   1356 				break;
   1357 
   1358 			case IP_RECVDSTADDR:
   1359 				optval = OPTBIT(INP_RECVDSTADDR);
   1360 				break;
   1361 
   1362 			case IP_RECVIF:
   1363 				optval = OPTBIT(INP_RECVIF);
   1364 				break;
   1365 			}
   1366 			*mtod(m, int *) = optval;
   1367 			break;
   1368 
   1369 #if 0	/* defined(IPSEC) || defined(FAST_IPSEC) */
   1370 		/* XXX: code broken */
   1371 		case IP_IPSEC_POLICY:
   1372 		{
   1373 			caddr_t req = NULL;
   1374 			size_t len = 0;
   1375 
   1376 			if (m) {
   1377 				req = mtod(m, caddr_t);
   1378 				len = m->m_len;
   1379 			}
   1380 			error = ipsec4_get_policy(inp, req, len, mp);
   1381 			break;
   1382 		}
   1383 #endif /*IPSEC*/
   1384 
   1385 		case IP_MULTICAST_IF:
   1386 		case IP_MULTICAST_TTL:
   1387 		case IP_MULTICAST_LOOP:
   1388 		case IP_ADD_MEMBERSHIP:
   1389 		case IP_DROP_MEMBERSHIP:
   1390 			error = ip_getmoptions(optname, inp->inp_moptions, mp);
   1391 			if (*mp)
   1392 				MCLAIM(*mp, so->so_mowner);
   1393 			break;
   1394 
   1395 		case IP_PORTRANGE:
   1396 			*mp = m = m_get(M_WAIT, MT_SOOPTS);
   1397 			MCLAIM(m, so->so_mowner);
   1398 			m->m_len = sizeof(int);
   1399 
   1400 			if (inp->inp_flags & INP_LOWPORT)
   1401 				optval = IP_PORTRANGE_LOW;
   1402 			else
   1403 				optval = IP_PORTRANGE_DEFAULT;
   1404 
   1405 			*mtod(m, int *) = optval;
   1406 			break;
   1407 
   1408 		default:
   1409 			error = ENOPROTOOPT;
   1410 			break;
   1411 		}
   1412 		break;
   1413 	}
   1414 	return (error);
   1415 }
   1416 
   1417 /*
   1418  * Set up IP options in pcb for insertion in output packets.
   1419  * Store in mbuf with pointer in pcbopt, adding pseudo-option
   1420  * with destination address if source routed.
   1421  */
   1422 int
   1423 #ifdef notyet
   1424 ip_pcbopts(int optname, struct mbuf **pcbopt, struct mbuf *m)
   1425 #else
   1426 ip_pcbopts(struct mbuf **pcbopt, struct mbuf *m)
   1427 #endif
   1428 {
   1429 	int cnt, optlen;
   1430 	u_char *cp;
   1431 	u_char opt;
   1432 
   1433 	/* turn off any old options */
   1434 	if (*pcbopt)
   1435 		(void)m_free(*pcbopt);
   1436 	*pcbopt = 0;
   1437 	if (m == (struct mbuf *)0 || m->m_len == 0) {
   1438 		/*
   1439 		 * Only turning off any previous options.
   1440 		 */
   1441 		if (m)
   1442 			(void)m_free(m);
   1443 		return (0);
   1444 	}
   1445 
   1446 #ifndef	__vax__
   1447 	if (m->m_len % sizeof(int32_t))
   1448 		goto bad;
   1449 #endif
   1450 	/*
   1451 	 * IP first-hop destination address will be stored before
   1452 	 * actual options; move other options back
   1453 	 * and clear it when none present.
   1454 	 */
   1455 	if (m->m_data + m->m_len + sizeof(struct in_addr) >= &m->m_dat[MLEN])
   1456 		goto bad;
   1457 	cnt = m->m_len;
   1458 	m->m_len += sizeof(struct in_addr);
   1459 	cp = mtod(m, u_char *) + sizeof(struct in_addr);
   1460 	memmove(cp, mtod(m, caddr_t), (unsigned)cnt);
   1461 	bzero(mtod(m, caddr_t), sizeof(struct in_addr));
   1462 
   1463 	for (; cnt > 0; cnt -= optlen, cp += optlen) {
   1464 		opt = cp[IPOPT_OPTVAL];
   1465 		if (opt == IPOPT_EOL)
   1466 			break;
   1467 		if (opt == IPOPT_NOP)
   1468 			optlen = 1;
   1469 		else {
   1470 			if (cnt < IPOPT_OLEN + sizeof(*cp))
   1471 				goto bad;
   1472 			optlen = cp[IPOPT_OLEN];
   1473 			if (optlen < IPOPT_OLEN  + sizeof(*cp) || optlen > cnt)
   1474 				goto bad;
   1475 		}
   1476 		switch (opt) {
   1477 
   1478 		default:
   1479 			break;
   1480 
   1481 		case IPOPT_LSRR:
   1482 		case IPOPT_SSRR:
   1483 			/*
   1484 			 * user process specifies route as:
   1485 			 *	->A->B->C->D
   1486 			 * D must be our final destination (but we can't
   1487 			 * check that since we may not have connected yet).
   1488 			 * A is first hop destination, which doesn't appear in
   1489 			 * actual IP option, but is stored before the options.
   1490 			 */
   1491 			if (optlen < IPOPT_MINOFF - 1 + sizeof(struct in_addr))
   1492 				goto bad;
   1493 			m->m_len -= sizeof(struct in_addr);
   1494 			cnt -= sizeof(struct in_addr);
   1495 			optlen -= sizeof(struct in_addr);
   1496 			cp[IPOPT_OLEN] = optlen;
   1497 			/*
   1498 			 * Move first hop before start of options.
   1499 			 */
   1500 			bcopy((caddr_t)&cp[IPOPT_OFFSET+1], mtod(m, caddr_t),
   1501 			    sizeof(struct in_addr));
   1502 			/*
   1503 			 * Then copy rest of options back
   1504 			 * to close up the deleted entry.
   1505 			 */
   1506 			(void)memmove(&cp[IPOPT_OFFSET+1],
   1507 			    &cp[IPOPT_OFFSET+1] + sizeof(struct in_addr),
   1508 			    (unsigned)cnt - (IPOPT_MINOFF - 1));
   1509 			break;
   1510 		}
   1511 	}
   1512 	if (m->m_len > MAX_IPOPTLEN + sizeof(struct in_addr))
   1513 		goto bad;
   1514 	*pcbopt = m;
   1515 	return (0);
   1516 
   1517 bad:
   1518 	(void)m_free(m);
   1519 	return (EINVAL);
   1520 }
   1521 
   1522 /*
   1523  * following RFC1724 section 3.3, 0.0.0.0/8 is interpreted as interface index.
   1524  */
   1525 static struct ifnet *
   1526 ip_multicast_if(struct in_addr *a, int *ifindexp)
   1527 {
   1528 	int ifindex;
   1529 	struct ifnet *ifp = NULL;
   1530 	struct in_ifaddr *ia;
   1531 
   1532 	if (ifindexp)
   1533 		*ifindexp = 0;
   1534 	if (ntohl(a->s_addr) >> 24 == 0) {
   1535 		ifindex = ntohl(a->s_addr) & 0xffffff;
   1536 		if (ifindex < 0 || if_indexlim <= ifindex)
   1537 			return NULL;
   1538 		ifp = ifindex2ifnet[ifindex];
   1539 		if (!ifp)
   1540 			return NULL;
   1541 		if (ifindexp)
   1542 			*ifindexp = ifindex;
   1543 	} else {
   1544 		LIST_FOREACH(ia, &IN_IFADDR_HASH(a->s_addr), ia_hash) {
   1545 			if (in_hosteq(ia->ia_addr.sin_addr, *a) &&
   1546 			    (ia->ia_ifp->if_flags & IFF_MULTICAST) != 0) {
   1547 				ifp = ia->ia_ifp;
   1548 				break;
   1549 			}
   1550 		}
   1551 	}
   1552 	return ifp;
   1553 }
   1554 
   1555 /*
   1556  * Set the IP multicast options in response to user setsockopt().
   1557  */
   1558 int
   1559 ip_setmoptions(int optname, struct ip_moptions **imop, struct mbuf *m)
   1560 {
   1561 	int error = 0;
   1562 	u_char loop;
   1563 	int i;
   1564 	struct in_addr addr;
   1565 	struct ip_mreq *mreq;
   1566 	struct ifnet *ifp;
   1567 	struct ip_moptions *imo = *imop;
   1568 	struct route ro;
   1569 	struct sockaddr_in *dst;
   1570 	int ifindex;
   1571 
   1572 	if (imo == NULL) {
   1573 		/*
   1574 		 * No multicast option buffer attached to the pcb;
   1575 		 * allocate one and initialize to default values.
   1576 		 */
   1577 		imo = (struct ip_moptions *)malloc(sizeof(*imo), M_IPMOPTS,
   1578 		    M_WAITOK);
   1579 
   1580 		if (imo == NULL)
   1581 			return (ENOBUFS);
   1582 		*imop = imo;
   1583 		imo->imo_multicast_ifp = NULL;
   1584 		imo->imo_multicast_addr.s_addr = INADDR_ANY;
   1585 		imo->imo_multicast_ttl = IP_DEFAULT_MULTICAST_TTL;
   1586 		imo->imo_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
   1587 		imo->imo_num_memberships = 0;
   1588 	}
   1589 
   1590 	switch (optname) {
   1591 
   1592 	case IP_MULTICAST_IF:
   1593 		/*
   1594 		 * Select the interface for outgoing multicast packets.
   1595 		 */
   1596 		if (m == NULL || m->m_len != sizeof(struct in_addr)) {
   1597 			error = EINVAL;
   1598 			break;
   1599 		}
   1600 		addr = *(mtod(m, struct in_addr *));
   1601 		/*
   1602 		 * INADDR_ANY is used to remove a previous selection.
   1603 		 * When no interface is selected, a default one is
   1604 		 * chosen every time a multicast packet is sent.
   1605 		 */
   1606 		if (in_nullhost(addr)) {
   1607 			imo->imo_multicast_ifp = NULL;
   1608 			break;
   1609 		}
   1610 		/*
   1611 		 * The selected interface is identified by its local
   1612 		 * IP address.  Find the interface and confirm that
   1613 		 * it supports multicasting.
   1614 		 */
   1615 		ifp = ip_multicast_if(&addr, &ifindex);
   1616 		if (ifp == NULL || (ifp->if_flags & IFF_MULTICAST) == 0) {
   1617 			error = EADDRNOTAVAIL;
   1618 			break;
   1619 		}
   1620 		imo->imo_multicast_ifp = ifp;
   1621 		if (ifindex)
   1622 			imo->imo_multicast_addr = addr;
   1623 		else
   1624 			imo->imo_multicast_addr.s_addr = INADDR_ANY;
   1625 		break;
   1626 
   1627 	case IP_MULTICAST_TTL:
   1628 		/*
   1629 		 * Set the IP time-to-live for outgoing multicast packets.
   1630 		 */
   1631 		if (m == NULL || m->m_len != 1) {
   1632 			error = EINVAL;
   1633 			break;
   1634 		}
   1635 		imo->imo_multicast_ttl = *(mtod(m, u_char *));
   1636 		break;
   1637 
   1638 	case IP_MULTICAST_LOOP:
   1639 		/*
   1640 		 * Set the loopback flag for outgoing multicast packets.
   1641 		 * Must be zero or one.
   1642 		 */
   1643 		if (m == NULL || m->m_len != 1 ||
   1644 		   (loop = *(mtod(m, u_char *))) > 1) {
   1645 			error = EINVAL;
   1646 			break;
   1647 		}
   1648 		imo->imo_multicast_loop = loop;
   1649 		break;
   1650 
   1651 	case IP_ADD_MEMBERSHIP:
   1652 		/*
   1653 		 * Add a multicast group membership.
   1654 		 * Group must be a valid IP multicast address.
   1655 		 */
   1656 		if (m == NULL || m->m_len != sizeof(struct ip_mreq)) {
   1657 			error = EINVAL;
   1658 			break;
   1659 		}
   1660 		mreq = mtod(m, struct ip_mreq *);
   1661 		if (!IN_MULTICAST(mreq->imr_multiaddr.s_addr)) {
   1662 			error = EINVAL;
   1663 			break;
   1664 		}
   1665 		/*
   1666 		 * If no interface address was provided, use the interface of
   1667 		 * the route to the given multicast address.
   1668 		 */
   1669 		if (in_nullhost(mreq->imr_interface)) {
   1670 			bzero((caddr_t)&ro, sizeof(ro));
   1671 			ro.ro_rt = NULL;
   1672 			dst = satosin(&ro.ro_dst);
   1673 			dst->sin_len = sizeof(*dst);
   1674 			dst->sin_family = AF_INET;
   1675 			dst->sin_addr = mreq->imr_multiaddr;
   1676 			rtalloc(&ro);
   1677 			if (ro.ro_rt == NULL) {
   1678 				error = EADDRNOTAVAIL;
   1679 				break;
   1680 			}
   1681 			ifp = ro.ro_rt->rt_ifp;
   1682 			rtfree(ro.ro_rt);
   1683 		} else {
   1684 			ifp = ip_multicast_if(&mreq->imr_interface, NULL);
   1685 		}
   1686 		/*
   1687 		 * See if we found an interface, and confirm that it
   1688 		 * supports multicast.
   1689 		 */
   1690 		if (ifp == NULL || (ifp->if_flags & IFF_MULTICAST) == 0) {
   1691 			error = EADDRNOTAVAIL;
   1692 			break;
   1693 		}
   1694 		/*
   1695 		 * See if the membership already exists or if all the
   1696 		 * membership slots are full.
   1697 		 */
   1698 		for (i = 0; i < imo->imo_num_memberships; ++i) {
   1699 			if (imo->imo_membership[i]->inm_ifp == ifp &&
   1700 			    in_hosteq(imo->imo_membership[i]->inm_addr,
   1701 				      mreq->imr_multiaddr))
   1702 				break;
   1703 		}
   1704 		if (i < imo->imo_num_memberships) {
   1705 			error = EADDRINUSE;
   1706 			break;
   1707 		}
   1708 		if (i == IP_MAX_MEMBERSHIPS) {
   1709 			error = ETOOMANYREFS;
   1710 			break;
   1711 		}
   1712 		/*
   1713 		 * Everything looks good; add a new record to the multicast
   1714 		 * address list for the given interface.
   1715 		 */
   1716 		if ((imo->imo_membership[i] =
   1717 		    in_addmulti(&mreq->imr_multiaddr, ifp)) == NULL) {
   1718 			error = ENOBUFS;
   1719 			break;
   1720 		}
   1721 		++imo->imo_num_memberships;
   1722 		break;
   1723 
   1724 	case IP_DROP_MEMBERSHIP:
   1725 		/*
   1726 		 * Drop a multicast group membership.
   1727 		 * Group must be a valid IP multicast address.
   1728 		 */
   1729 		if (m == NULL || m->m_len != sizeof(struct ip_mreq)) {
   1730 			error = EINVAL;
   1731 			break;
   1732 		}
   1733 		mreq = mtod(m, struct ip_mreq *);
   1734 		if (!IN_MULTICAST(mreq->imr_multiaddr.s_addr)) {
   1735 			error = EINVAL;
   1736 			break;
   1737 		}
   1738 		/*
   1739 		 * If an interface address was specified, get a pointer
   1740 		 * to its ifnet structure.
   1741 		 */
   1742 		if (in_nullhost(mreq->imr_interface))
   1743 			ifp = NULL;
   1744 		else {
   1745 			ifp = ip_multicast_if(&mreq->imr_interface, NULL);
   1746 			if (ifp == NULL) {
   1747 				error = EADDRNOTAVAIL;
   1748 				break;
   1749 			}
   1750 		}
   1751 		/*
   1752 		 * Find the membership in the membership array.
   1753 		 */
   1754 		for (i = 0; i < imo->imo_num_memberships; ++i) {
   1755 			if ((ifp == NULL ||
   1756 			     imo->imo_membership[i]->inm_ifp == ifp) &&
   1757 			     in_hosteq(imo->imo_membership[i]->inm_addr,
   1758 				       mreq->imr_multiaddr))
   1759 				break;
   1760 		}
   1761 		if (i == imo->imo_num_memberships) {
   1762 			error = EADDRNOTAVAIL;
   1763 			break;
   1764 		}
   1765 		/*
   1766 		 * Give up the multicast address record to which the
   1767 		 * membership points.
   1768 		 */
   1769 		in_delmulti(imo->imo_membership[i]);
   1770 		/*
   1771 		 * Remove the gap in the membership array.
   1772 		 */
   1773 		for (++i; i < imo->imo_num_memberships; ++i)
   1774 			imo->imo_membership[i-1] = imo->imo_membership[i];
   1775 		--imo->imo_num_memberships;
   1776 		break;
   1777 
   1778 	default:
   1779 		error = EOPNOTSUPP;
   1780 		break;
   1781 	}
   1782 
   1783 	/*
   1784 	 * If all options have default values, no need to keep the mbuf.
   1785 	 */
   1786 	if (imo->imo_multicast_ifp == NULL &&
   1787 	    imo->imo_multicast_ttl == IP_DEFAULT_MULTICAST_TTL &&
   1788 	    imo->imo_multicast_loop == IP_DEFAULT_MULTICAST_LOOP &&
   1789 	    imo->imo_num_memberships == 0) {
   1790 		free(*imop, M_IPMOPTS);
   1791 		*imop = NULL;
   1792 	}
   1793 
   1794 	return (error);
   1795 }
   1796 
   1797 /*
   1798  * Return the IP multicast options in response to user getsockopt().
   1799  */
   1800 int
   1801 ip_getmoptions(int optname, struct ip_moptions *imo, struct mbuf **mp)
   1802 {
   1803 	u_char *ttl;
   1804 	u_char *loop;
   1805 	struct in_addr *addr;
   1806 	struct in_ifaddr *ia;
   1807 
   1808 	*mp = m_get(M_WAIT, MT_SOOPTS);
   1809 
   1810 	switch (optname) {
   1811 
   1812 	case IP_MULTICAST_IF:
   1813 		addr = mtod(*mp, struct in_addr *);
   1814 		(*mp)->m_len = sizeof(struct in_addr);
   1815 		if (imo == NULL || imo->imo_multicast_ifp == NULL)
   1816 			*addr = zeroin_addr;
   1817 		else if (imo->imo_multicast_addr.s_addr) {
   1818 			/* return the value user has set */
   1819 			*addr = imo->imo_multicast_addr;
   1820 		} else {
   1821 			IFP_TO_IA(imo->imo_multicast_ifp, ia);
   1822 			*addr = ia ? ia->ia_addr.sin_addr : zeroin_addr;
   1823 		}
   1824 		return (0);
   1825 
   1826 	case IP_MULTICAST_TTL:
   1827 		ttl = mtod(*mp, u_char *);
   1828 		(*mp)->m_len = 1;
   1829 		*ttl = imo ? imo->imo_multicast_ttl
   1830 			   : IP_DEFAULT_MULTICAST_TTL;
   1831 		return (0);
   1832 
   1833 	case IP_MULTICAST_LOOP:
   1834 		loop = mtod(*mp, u_char *);
   1835 		(*mp)->m_len = 1;
   1836 		*loop = imo ? imo->imo_multicast_loop
   1837 			    : IP_DEFAULT_MULTICAST_LOOP;
   1838 		return (0);
   1839 
   1840 	default:
   1841 		return (EOPNOTSUPP);
   1842 	}
   1843 }
   1844 
   1845 /*
   1846  * Discard the IP multicast options.
   1847  */
   1848 void
   1849 ip_freemoptions(struct ip_moptions *imo)
   1850 {
   1851 	int i;
   1852 
   1853 	if (imo != NULL) {
   1854 		for (i = 0; i < imo->imo_num_memberships; ++i)
   1855 			in_delmulti(imo->imo_membership[i]);
   1856 		free(imo, M_IPMOPTS);
   1857 	}
   1858 }
   1859 
   1860 /*
   1861  * Routine called from ip_output() to loop back a copy of an IP multicast
   1862  * packet to the input queue of a specified interface.  Note that this
   1863  * calls the output routine of the loopback "driver", but with an interface
   1864  * pointer that might NOT be lo0ifp -- easier than replicating that code here.
   1865  */
   1866 static void
   1867 ip_mloopback(struct ifnet *ifp, struct mbuf *m, struct sockaddr_in *dst)
   1868 {
   1869 	struct ip *ip;
   1870 	struct mbuf *copym;
   1871 
   1872 	copym = m_copy(m, 0, M_COPYALL);
   1873 	if (copym != NULL
   1874 	 && (copym->m_flags & M_EXT || copym->m_len < sizeof(struct ip)))
   1875 		copym = m_pullup(copym, sizeof(struct ip));
   1876 	if (copym != NULL) {
   1877 		/*
   1878 		 * We don't bother to fragment if the IP length is greater
   1879 		 * than the interface's MTU.  Can this possibly matter?
   1880 		 */
   1881 		ip = mtod(copym, struct ip *);
   1882 
   1883 		if (copym->m_pkthdr.csum_flags & (M_CSUM_TCPv4|M_CSUM_UDPv4)) {
   1884 			in_delayed_cksum(copym);
   1885 			copym->m_pkthdr.csum_flags &=
   1886 			    ~(M_CSUM_TCPv4|M_CSUM_UDPv4);
   1887 		}
   1888 
   1889 		ip->ip_sum = 0;
   1890 		ip->ip_sum = in_cksum(copym, ip->ip_hl << 2);
   1891 		(void) looutput(ifp, copym, sintosa(dst), NULL);
   1892 	}
   1893 }
   1894