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