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