Home | History | Annotate | Line # | Download | only in netinet
ip_output.c revision 1.180
      1 /*	$NetBSD: ip_output.c,v 1.180 2007/05/02 20:40:25 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.180 2007/05/02 20:40:25 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 *,
    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 #define	IN_NEED_CHECKSUM(ifp, csum_flags) \
    169 	(__predict_true(((ifp)->if_flags & IFF_LOOPBACK) == 0 || \
    170 	(((csum_flags) & M_CSUM_UDPv4) != 0 && udp_do_loopback_cksum) || \
    171 	(((csum_flags) & M_CSUM_TCPv4) != 0 && tcp_do_loopback_cksum) || \
    172 	(((csum_flags) & M_CSUM_IPv4) != 0 && ip_do_loopback_cksum)))
    173 
    174 /*
    175  * IP output.  The packet in mbuf chain m contains a skeletal IP
    176  * header (with len, off, ttl, proto, tos, src, dst).
    177  * The mbuf chain containing the packet will be freed.
    178  * The mbuf opt, if present, will not be freed.
    179  */
    180 int
    181 ip_output(struct mbuf *m0, ...)
    182 {
    183 	struct ip *ip;
    184 	struct ifnet *ifp;
    185 	struct mbuf *m = m0;
    186 	int hlen = sizeof (struct ip);
    187 	int len, error = 0;
    188 	struct route iproute;
    189 	const struct sockaddr_in *dst;
    190 	struct in_ifaddr *ia;
    191 	struct ifaddr *xifa;
    192 	struct mbuf *opt;
    193 	struct route *ro;
    194 	int flags, sw_csum;
    195 	int *mtu_p;
    196 	u_long mtu;
    197 	struct ip_moptions *imo;
    198 	struct socket *so;
    199 	va_list ap;
    200 #ifdef IPSEC_NAT_T
    201 	int natt_frag = 0;
    202 #endif
    203 #ifdef IPSEC
    204 	struct secpolicy *sp = NULL;
    205 #endif /*IPSEC*/
    206 #ifdef FAST_IPSEC
    207 	struct inpcb *inp;
    208 	struct m_tag *mtag;
    209 	struct secpolicy *sp = NULL;
    210 	struct tdb_ident *tdbi;
    211 	int s;
    212 #endif
    213 	u_int16_t ip_len;
    214 	union {
    215 		struct sockaddr		dst;
    216 		struct sockaddr_in	dst4;
    217 	} u;
    218 	struct sockaddr *rdst = &u.dst;	/* real IP destination, as opposed
    219 					 * to the nexthop
    220 					 */
    221 
    222 	len = 0;
    223 	va_start(ap, m0);
    224 	opt = va_arg(ap, struct mbuf *);
    225 	ro = va_arg(ap, struct route *);
    226 	flags = va_arg(ap, int);
    227 	imo = va_arg(ap, struct ip_moptions *);
    228 	so = va_arg(ap, struct socket *);
    229 	if (flags & IP_RETURNMTU)
    230 		mtu_p = va_arg(ap, int *);
    231 	else
    232 		mtu_p = NULL;
    233 	va_end(ap);
    234 
    235 	MCLAIM(m, &ip_tx_mowner);
    236 #ifdef FAST_IPSEC
    237 	if (so != NULL && so->so_proto->pr_domain->dom_family == AF_INET)
    238 		inp = (struct inpcb *)so->so_pcb;
    239 	else
    240 		inp = NULL;
    241 #endif /* FAST_IPSEC */
    242 
    243 #ifdef	DIAGNOSTIC
    244 	if ((m->m_flags & M_PKTHDR) == 0)
    245 		panic("ip_output: no HDR");
    246 
    247 	if ((m->m_pkthdr.csum_flags & (M_CSUM_TCPv6|M_CSUM_UDPv6)) != 0) {
    248 		panic("ip_output: IPv6 checksum offload flags: %d",
    249 		    m->m_pkthdr.csum_flags);
    250 	}
    251 
    252 	if ((m->m_pkthdr.csum_flags & (M_CSUM_TCPv4|M_CSUM_UDPv4)) ==
    253 	    (M_CSUM_TCPv4|M_CSUM_UDPv4)) {
    254 		panic("ip_output: conflicting checksum offload flags: %d",
    255 		    m->m_pkthdr.csum_flags);
    256 	}
    257 #endif
    258 	if (opt) {
    259 		m = ip_insertoptions(m, opt, &len);
    260 		if (len >= sizeof(struct ip))
    261 			hlen = len;
    262 	}
    263 	ip = mtod(m, struct ip *);
    264 	/*
    265 	 * Fill in IP header.
    266 	 */
    267 	if ((flags & (IP_FORWARDING|IP_RAWOUTPUT)) == 0) {
    268 		ip->ip_v = IPVERSION;
    269 		ip->ip_off = htons(0);
    270 		if ((m->m_pkthdr.csum_flags & M_CSUM_TSOv4) == 0) {
    271 			ip->ip_id = ip_newid();
    272 		} else {
    273 
    274 			/*
    275 			 * TSO capable interfaces (typically?) increment
    276 			 * ip_id for each segment.
    277 			 * "allocate" enough ids here to increase the chance
    278 			 * for them to be unique.
    279 			 *
    280 			 * note that the following calculation is not
    281 			 * needed to be precise.  wasting some ip_id is fine.
    282 			 */
    283 
    284 			unsigned int segsz = m->m_pkthdr.segsz;
    285 			unsigned int datasz = ntohs(ip->ip_len) - hlen;
    286 			unsigned int num = howmany(datasz, segsz);
    287 
    288 			ip->ip_id = ip_newid_range(num);
    289 		}
    290 		ip->ip_hl = hlen >> 2;
    291 		ipstat.ips_localout++;
    292 	} else {
    293 		hlen = ip->ip_hl << 2;
    294 	}
    295 	/*
    296 	 * Route packet.
    297 	 */
    298 	memset(&iproute, 0, sizeof(iproute));
    299 	if (ro == NULL)
    300 		ro = &iproute;
    301 	sockaddr_in_init(&u.dst4, &ip->ip_dst, 0);
    302 	dst = satocsin(rtcache_getdst(ro));
    303 	/*
    304 	 * If there is a cached route,
    305 	 * check that it is to the same destination
    306 	 * and is still up.  If not, free it and try again.
    307 	 * The address family should also be checked in case of sharing the
    308 	 * cache with IPv6.
    309 	 */
    310 	if (dst == NULL)
    311 		;
    312 	else if (dst->sin_family != AF_INET ||
    313 		 !in_hosteq(dst->sin_addr, ip->ip_dst))
    314 		rtcache_free(ro);
    315 	else
    316 		rtcache_check(ro);
    317 	if (ro->ro_rt == NULL) {
    318 		dst = &u.dst4;
    319 		rtcache_setdst(ro, &u.dst);
    320 	}
    321 	/*
    322 	 * If routing to interface only,
    323 	 * short circuit routing lookup.
    324 	 */
    325 	if (flags & IP_ROUTETOIF) {
    326 		if ((ia = ifatoia(ifa_ifwithladdr(sintocsa(dst)))) == NULL) {
    327 			ipstat.ips_noroute++;
    328 			error = ENETUNREACH;
    329 			goto bad;
    330 		}
    331 		ifp = ia->ia_ifp;
    332 		mtu = ifp->if_mtu;
    333 		ip->ip_ttl = 1;
    334 	} else if ((IN_MULTICAST(ip->ip_dst.s_addr) ||
    335 	    ip->ip_dst.s_addr == INADDR_BROADCAST) &&
    336 	    imo != NULL && imo->imo_multicast_ifp != NULL) {
    337 		ifp = imo->imo_multicast_ifp;
    338 		mtu = ifp->if_mtu;
    339 		IFP_TO_IA(ifp, ia);
    340 	} else {
    341 		if (ro->ro_rt == NULL)
    342 			rtcache_init(ro);
    343 		if (ro->ro_rt == NULL) {
    344 			ipstat.ips_noroute++;
    345 			error = EHOSTUNREACH;
    346 			goto bad;
    347 		}
    348 		ia = ifatoia(ro->ro_rt->rt_ifa);
    349 		ifp = ro->ro_rt->rt_ifp;
    350 		if ((mtu = ro->ro_rt->rt_rmx.rmx_mtu) == 0)
    351 			mtu = ifp->if_mtu;
    352 		ro->ro_rt->rt_use++;
    353 		if (ro->ro_rt->rt_flags & RTF_GATEWAY)
    354 			dst = satosin(ro->ro_rt->rt_gateway);
    355 	}
    356 	if (IN_MULTICAST(ip->ip_dst.s_addr) ||
    357 	    (ip->ip_dst.s_addr == INADDR_BROADCAST)) {
    358 		struct in_multi *inm;
    359 
    360 		m->m_flags |= (ip->ip_dst.s_addr == INADDR_BROADCAST) ?
    361 			M_BCAST : M_MCAST;
    362 		/*
    363 		 * See if the caller provided any multicast options
    364 		 */
    365 		if (imo != NULL)
    366 			ip->ip_ttl = imo->imo_multicast_ttl;
    367 		else
    368 			ip->ip_ttl = IP_DEFAULT_MULTICAST_TTL;
    369 
    370 		/*
    371 		 * if we don't know the outgoing ifp yet, we can't generate
    372 		 * output
    373 		 */
    374 		if (!ifp) {
    375 			ipstat.ips_noroute++;
    376 			error = ENETUNREACH;
    377 			goto bad;
    378 		}
    379 
    380 		/*
    381 		 * If the packet is multicast or broadcast, confirm that
    382 		 * the outgoing interface can transmit it.
    383 		 */
    384 		if (((m->m_flags & M_MCAST) &&
    385 		     (ifp->if_flags & IFF_MULTICAST) == 0) ||
    386 		    ((m->m_flags & M_BCAST) &&
    387 		     (ifp->if_flags & (IFF_BROADCAST|IFF_POINTOPOINT)) == 0))  {
    388 			ipstat.ips_noroute++;
    389 			error = ENETUNREACH;
    390 			goto bad;
    391 		}
    392 		/*
    393 		 * If source address not specified yet, use an address
    394 		 * of outgoing interface.
    395 		 */
    396 		if (in_nullhost(ip->ip_src)) {
    397 			struct in_ifaddr *xia;
    398 
    399 			IFP_TO_IA(ifp, xia);
    400 			if (!xia) {
    401 				error = EADDRNOTAVAIL;
    402 				goto bad;
    403 			}
    404 			xifa = &xia->ia_ifa;
    405 			if (xifa->ifa_getifa != NULL) {
    406 				xia = ifatoia((*xifa->ifa_getifa)(xifa, rdst));
    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, &u.dst4);
    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, rdst));
    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 		memset(&iproute, 0, sizeof(iproute));
    591 	} else
    592 		state.ro = ro;
    593 	state.dst = sintocsa(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 = satocsin(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 	ip_len = ntohs(ip->ip_len);
    825 #endif /* PFIL_HOOKS */
    826 
    827 	m->m_pkthdr.csum_data |= hlen << 16;
    828 
    829 #if IFA_STATS
    830 	/*
    831 	 * search for the source address structure to
    832 	 * maintain output statistics.
    833 	 */
    834 	INADDR_TO_IA(ip->ip_src, ia);
    835 #endif
    836 
    837 	/* Maybe skip checksums on loopback interfaces. */
    838 	if (IN_NEED_CHECKSUM(ifp, M_CSUM_IPv4)) {
    839 		m->m_pkthdr.csum_flags |= M_CSUM_IPv4;
    840 	}
    841 	sw_csum = m->m_pkthdr.csum_flags & ~ifp->if_csum_flags_tx;
    842 	/*
    843 	 * If small enough for mtu of path, or if using TCP segmentation
    844 	 * offload, can just send directly.
    845 	 */
    846 	if (ip_len <= mtu ||
    847 	    (m->m_pkthdr.csum_flags & M_CSUM_TSOv4) != 0) {
    848 #if IFA_STATS
    849 		if (ia)
    850 			ia->ia_ifa.ifa_data.ifad_outbytes += ip_len;
    851 #endif
    852 		/*
    853 		 * Always initialize the sum to 0!  Some HW assisted
    854 		 * checksumming requires this.
    855 		 */
    856 		ip->ip_sum = 0;
    857 
    858 		if ((m->m_pkthdr.csum_flags & M_CSUM_TSOv4) == 0) {
    859 			/*
    860 			 * Perform any checksums that the hardware can't do
    861 			 * for us.
    862 			 *
    863 			 * XXX Does any hardware require the {th,uh}_sum
    864 			 * XXX fields to be 0?
    865 			 */
    866 			if (sw_csum & M_CSUM_IPv4) {
    867 				KASSERT(IN_NEED_CHECKSUM(ifp, M_CSUM_IPv4));
    868 				ip->ip_sum = in_cksum(m, hlen);
    869 				m->m_pkthdr.csum_flags &= ~M_CSUM_IPv4;
    870 			}
    871 			if (sw_csum & (M_CSUM_TCPv4|M_CSUM_UDPv4)) {
    872 				if (IN_NEED_CHECKSUM(ifp,
    873 				    sw_csum & (M_CSUM_TCPv4|M_CSUM_UDPv4))) {
    874 					in_delayed_cksum(m);
    875 				}
    876 				m->m_pkthdr.csum_flags &=
    877 				    ~(M_CSUM_TCPv4|M_CSUM_UDPv4);
    878 			}
    879 		}
    880 
    881 #ifdef IPSEC
    882 		/* clean ipsec history once it goes out of the node */
    883 		ipsec_delaux(m);
    884 #endif
    885 
    886 		if (__predict_true(
    887 		    (m->m_pkthdr.csum_flags & M_CSUM_TSOv4) == 0 ||
    888 		    (ifp->if_capenable & IFCAP_TSOv4) != 0)) {
    889 			error =
    890 			    (*ifp->if_output)(ifp, m, sintocsa(dst), ro->ro_rt);
    891 		} else {
    892 			error =
    893 			    ip_tso_output(ifp, m, sintocsa(dst), ro->ro_rt);
    894 		}
    895 		goto done;
    896 	}
    897 
    898 	/*
    899 	 * We can't use HW checksumming if we're about to
    900 	 * to fragment the packet.
    901 	 *
    902 	 * XXX Some hardware can do this.
    903 	 */
    904 	if (m->m_pkthdr.csum_flags & (M_CSUM_TCPv4|M_CSUM_UDPv4)) {
    905 		if (IN_NEED_CHECKSUM(ifp,
    906 		    m->m_pkthdr.csum_flags & (M_CSUM_TCPv4|M_CSUM_UDPv4))) {
    907 			in_delayed_cksum(m);
    908 		}
    909 		m->m_pkthdr.csum_flags &= ~(M_CSUM_TCPv4|M_CSUM_UDPv4);
    910 	}
    911 
    912 	/*
    913 	 * Too large for interface; fragment if possible.
    914 	 * Must be able to put at least 8 bytes per fragment.
    915 	 */
    916 	if (ntohs(ip->ip_off) & IP_DF) {
    917 		if (flags & IP_RETURNMTU)
    918 			*mtu_p = mtu;
    919 		error = EMSGSIZE;
    920 		ipstat.ips_cantfrag++;
    921 		goto bad;
    922 	}
    923 
    924 	error = ip_fragment(m, ifp, mtu);
    925 	if (error) {
    926 		m = NULL;
    927 		goto bad;
    928 	}
    929 
    930 	for (; m; m = m0) {
    931 		m0 = m->m_nextpkt;
    932 		m->m_nextpkt = 0;
    933 		if (error == 0) {
    934 #if IFA_STATS
    935 			if (ia)
    936 				ia->ia_ifa.ifa_data.ifad_outbytes +=
    937 				    ntohs(ip->ip_len);
    938 #endif
    939 #ifdef IPSEC
    940 			/* clean ipsec history once it goes out of the node */
    941 			ipsec_delaux(m);
    942 #endif /* IPSEC */
    943 
    944 #ifdef IPSEC_NAT_T
    945 			/*
    946 			 * If we get there, the packet has not been handeld by
    947 			 * IPSec whereas it should have. Now that it has been
    948 			 * fragmented, re-inject it in ip_output so that IPsec
    949 			 * processing can occur.
    950 			 */
    951 			if (natt_frag) {
    952 				error = ip_output(m, opt,
    953 				    ro, flags, imo, so, mtu_p);
    954 			} else
    955 #endif /* IPSEC_NAT_T */
    956 			{
    957 				KASSERT((m->m_pkthdr.csum_flags &
    958 				    (M_CSUM_UDPv4 | M_CSUM_TCPv4)) == 0);
    959 				error = (*ifp->if_output)(ifp, m, sintocsa(dst),
    960 				    ro->ro_rt);
    961 			}
    962 		} else
    963 			m_freem(m);
    964 	}
    965 
    966 	if (error == 0)
    967 		ipstat.ips_fragmented++;
    968 done:
    969 	rtcache_free(&iproute);
    970 
    971 #ifdef IPSEC
    972 	if (sp != NULL) {
    973 		KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
    974 			printf("DP ip_output call free SP:%p\n", sp));
    975 		key_freesp(sp);
    976 	}
    977 #endif /* IPSEC */
    978 #ifdef FAST_IPSEC
    979 	if (sp != NULL)
    980 		KEY_FREESP(&sp);
    981 #endif /* FAST_IPSEC */
    982 
    983 	return (error);
    984 bad:
    985 	m_freem(m);
    986 	goto done;
    987 }
    988 
    989 int
    990 ip_fragment(struct mbuf *m, struct ifnet *ifp, u_long mtu)
    991 {
    992 	struct ip *ip, *mhip;
    993 	struct mbuf *m0;
    994 	int len, hlen, off;
    995 	int mhlen, firstlen;
    996 	struct mbuf **mnext;
    997 	int sw_csum = m->m_pkthdr.csum_flags;
    998 	int fragments = 0;
    999 	int s;
   1000 	int error = 0;
   1001 
   1002 	ip = mtod(m, struct ip *);
   1003 	hlen = ip->ip_hl << 2;
   1004 	if (ifp != NULL)
   1005 		sw_csum &= ~ifp->if_csum_flags_tx;
   1006 
   1007 	len = (mtu - hlen) &~ 7;
   1008 	if (len < 8) {
   1009 		m_freem(m);
   1010 		return (EMSGSIZE);
   1011 	}
   1012 
   1013 	firstlen = len;
   1014 	mnext = &m->m_nextpkt;
   1015 
   1016 	/*
   1017 	 * Loop through length of segment after first fragment,
   1018 	 * make new header and copy data of each part and link onto chain.
   1019 	 */
   1020 	m0 = m;
   1021 	mhlen = sizeof (struct ip);
   1022 	for (off = hlen + len; off < ntohs(ip->ip_len); off += len) {
   1023 		MGETHDR(m, M_DONTWAIT, MT_HEADER);
   1024 		if (m == 0) {
   1025 			error = ENOBUFS;
   1026 			ipstat.ips_odropped++;
   1027 			goto sendorfree;
   1028 		}
   1029 		MCLAIM(m, m0->m_owner);
   1030 		*mnext = m;
   1031 		mnext = &m->m_nextpkt;
   1032 		m->m_data += max_linkhdr;
   1033 		mhip = mtod(m, struct ip *);
   1034 		*mhip = *ip;
   1035 		/* we must inherit MCAST and BCAST flags */
   1036 		m->m_flags |= m0->m_flags & (M_MCAST|M_BCAST);
   1037 		if (hlen > sizeof (struct ip)) {
   1038 			mhlen = ip_optcopy(ip, mhip) + sizeof (struct ip);
   1039 			mhip->ip_hl = mhlen >> 2;
   1040 		}
   1041 		m->m_len = mhlen;
   1042 		mhip->ip_off = ((off - hlen) >> 3) +
   1043 		    (ntohs(ip->ip_off) & ~IP_MF);
   1044 		if (ip->ip_off & htons(IP_MF))
   1045 			mhip->ip_off |= IP_MF;
   1046 		if (off + len >= ntohs(ip->ip_len))
   1047 			len = ntohs(ip->ip_len) - off;
   1048 		else
   1049 			mhip->ip_off |= IP_MF;
   1050 		HTONS(mhip->ip_off);
   1051 		mhip->ip_len = htons((u_int16_t)(len + mhlen));
   1052 		m->m_next = m_copy(m0, off, len);
   1053 		if (m->m_next == 0) {
   1054 			error = ENOBUFS;	/* ??? */
   1055 			ipstat.ips_odropped++;
   1056 			goto sendorfree;
   1057 		}
   1058 		m->m_pkthdr.len = mhlen + len;
   1059 		m->m_pkthdr.rcvif = (struct ifnet *)0;
   1060 		mhip->ip_sum = 0;
   1061 		if (sw_csum & M_CSUM_IPv4) {
   1062 			mhip->ip_sum = in_cksum(m, mhlen);
   1063 			KASSERT((m->m_pkthdr.csum_flags & M_CSUM_IPv4) == 0);
   1064 		} else {
   1065 			m->m_pkthdr.csum_flags |= M_CSUM_IPv4;
   1066 			m->m_pkthdr.csum_data |= mhlen << 16;
   1067 		}
   1068 		ipstat.ips_ofragments++;
   1069 		fragments++;
   1070 	}
   1071 	/*
   1072 	 * Update first fragment by trimming what's been copied out
   1073 	 * and updating header, then send each fragment (in order).
   1074 	 */
   1075 	m = m0;
   1076 	m_adj(m, hlen + firstlen - ntohs(ip->ip_len));
   1077 	m->m_pkthdr.len = hlen + firstlen;
   1078 	ip->ip_len = htons((u_int16_t)m->m_pkthdr.len);
   1079 	ip->ip_off |= htons(IP_MF);
   1080 	ip->ip_sum = 0;
   1081 	if (sw_csum & M_CSUM_IPv4) {
   1082 		ip->ip_sum = in_cksum(m, hlen);
   1083 		m->m_pkthdr.csum_flags &= ~M_CSUM_IPv4;
   1084 	} else {
   1085 		KASSERT(m->m_pkthdr.csum_flags & M_CSUM_IPv4);
   1086 		KASSERT(M_CSUM_DATA_IPv4_IPHL(m->m_pkthdr.csum_data) >=
   1087 			sizeof(struct ip));
   1088 	}
   1089 sendorfree:
   1090 	/*
   1091 	 * If there is no room for all the fragments, don't queue
   1092 	 * any of them.
   1093 	 */
   1094 	if (ifp != NULL) {
   1095 		s = splnet();
   1096 		if (ifp->if_snd.ifq_maxlen - ifp->if_snd.ifq_len < fragments &&
   1097 		    error == 0) {
   1098 			error = ENOBUFS;
   1099 			ipstat.ips_odropped++;
   1100 			IFQ_INC_DROPS(&ifp->if_snd);
   1101 		}
   1102 		splx(s);
   1103 	}
   1104 	if (error) {
   1105 		for (m = m0; m; m = m0) {
   1106 			m0 = m->m_nextpkt;
   1107 			m->m_nextpkt = NULL;
   1108 			m_freem(m);
   1109 		}
   1110 	}
   1111 	return (error);
   1112 }
   1113 
   1114 /*
   1115  * Process a delayed payload checksum calculation.
   1116  */
   1117 void
   1118 in_delayed_cksum(struct mbuf *m)
   1119 {
   1120 	struct ip *ip;
   1121 	u_int16_t csum, offset;
   1122 
   1123 	ip = mtod(m, struct ip *);
   1124 	offset = ip->ip_hl << 2;
   1125 	csum = in4_cksum(m, 0, offset, ntohs(ip->ip_len) - offset);
   1126 	if (csum == 0 && (m->m_pkthdr.csum_flags & M_CSUM_UDPv4) != 0)
   1127 		csum = 0xffff;
   1128 
   1129 	offset += M_CSUM_DATA_IPv4_OFFSET(m->m_pkthdr.csum_data);
   1130 
   1131 	if ((offset + sizeof(u_int16_t)) > m->m_len) {
   1132 		/* This happen when ip options were inserted
   1133 		printf("in_delayed_cksum: pullup len %d off %d proto %d\n",
   1134 		    m->m_len, offset, ip->ip_p);
   1135 		 */
   1136 		m_copyback(m, offset, sizeof(csum), (void *) &csum);
   1137 	} else
   1138 		*(u_int16_t *)(mtod(m, char *) + offset) = csum;
   1139 }
   1140 
   1141 /*
   1142  * Determine the maximum length of the options to be inserted;
   1143  * we would far rather allocate too much space rather than too little.
   1144  */
   1145 
   1146 u_int
   1147 ip_optlen(struct inpcb *inp)
   1148 {
   1149 	struct mbuf *m = inp->inp_options;
   1150 
   1151 	if (m && m->m_len > offsetof(struct ipoption, ipopt_dst))
   1152 		return (m->m_len - offsetof(struct ipoption, ipopt_dst));
   1153 	else
   1154 		return 0;
   1155 }
   1156 
   1157 
   1158 /*
   1159  * Insert IP options into preformed packet.
   1160  * Adjust IP destination as required for IP source routing,
   1161  * as indicated by a non-zero in_addr at the start of the options.
   1162  */
   1163 static struct mbuf *
   1164 ip_insertoptions(struct mbuf *m, struct mbuf *opt, int *phlen)
   1165 {
   1166 	struct ipoption *p = mtod(opt, struct ipoption *);
   1167 	struct mbuf *n;
   1168 	struct ip *ip = mtod(m, struct ip *);
   1169 	unsigned optlen;
   1170 
   1171 	optlen = opt->m_len - sizeof(p->ipopt_dst);
   1172 	if (optlen + ntohs(ip->ip_len) > IP_MAXPACKET)
   1173 		return (m);		/* XXX should fail */
   1174 	if (!in_nullhost(p->ipopt_dst))
   1175 		ip->ip_dst = p->ipopt_dst;
   1176 	if (M_READONLY(m) || M_LEADINGSPACE(m) < optlen) {
   1177 		MGETHDR(n, M_DONTWAIT, MT_HEADER);
   1178 		if (n == 0)
   1179 			return (m);
   1180 		MCLAIM(n, m->m_owner);
   1181 		M_MOVE_PKTHDR(n, m);
   1182 		m->m_len -= sizeof(struct ip);
   1183 		m->m_data += sizeof(struct ip);
   1184 		n->m_next = m;
   1185 		m = n;
   1186 		m->m_len = optlen + sizeof(struct ip);
   1187 		m->m_data += max_linkhdr;
   1188 		bcopy((void *)ip, mtod(m, void *), sizeof(struct ip));
   1189 	} else {
   1190 		m->m_data -= optlen;
   1191 		m->m_len += optlen;
   1192 		memmove(mtod(m, void *), ip, sizeof(struct ip));
   1193 	}
   1194 	m->m_pkthdr.len += optlen;
   1195 	ip = mtod(m, struct ip *);
   1196 	bcopy((void *)p->ipopt_list, (void *)(ip + 1), (unsigned)optlen);
   1197 	*phlen = sizeof(struct ip) + optlen;
   1198 	ip->ip_len = htons(ntohs(ip->ip_len) + optlen);
   1199 	return (m);
   1200 }
   1201 
   1202 /*
   1203  * Copy options from ip to jp,
   1204  * omitting those not copied during fragmentation.
   1205  */
   1206 int
   1207 ip_optcopy(struct ip *ip, struct ip *jp)
   1208 {
   1209 	u_char *cp, *dp;
   1210 	int opt, optlen, cnt;
   1211 
   1212 	cp = (u_char *)(ip + 1);
   1213 	dp = (u_char *)(jp + 1);
   1214 	cnt = (ip->ip_hl << 2) - sizeof (struct ip);
   1215 	for (; cnt > 0; cnt -= optlen, cp += optlen) {
   1216 		opt = cp[0];
   1217 		if (opt == IPOPT_EOL)
   1218 			break;
   1219 		if (opt == IPOPT_NOP) {
   1220 			/* Preserve for IP mcast tunnel's LSRR alignment. */
   1221 			*dp++ = IPOPT_NOP;
   1222 			optlen = 1;
   1223 			continue;
   1224 		}
   1225 #ifdef DIAGNOSTIC
   1226 		if (cnt < IPOPT_OLEN + sizeof(*cp))
   1227 			panic("malformed IPv4 option passed to ip_optcopy");
   1228 #endif
   1229 		optlen = cp[IPOPT_OLEN];
   1230 #ifdef DIAGNOSTIC
   1231 		if (optlen < IPOPT_OLEN + sizeof(*cp) || optlen > cnt)
   1232 			panic("malformed IPv4 option passed to ip_optcopy");
   1233 #endif
   1234 		/* bogus lengths should have been caught by ip_dooptions */
   1235 		if (optlen > cnt)
   1236 			optlen = cnt;
   1237 		if (IPOPT_COPIED(opt)) {
   1238 			bcopy((void *)cp, (void *)dp, (unsigned)optlen);
   1239 			dp += optlen;
   1240 		}
   1241 	}
   1242 	for (optlen = dp - (u_char *)(jp+1); optlen & 0x3; optlen++)
   1243 		*dp++ = IPOPT_EOL;
   1244 	return (optlen);
   1245 }
   1246 
   1247 /*
   1248  * IP socket option processing.
   1249  */
   1250 int
   1251 ip_ctloutput(int op, struct socket *so, int level, int optname,
   1252     struct mbuf **mp)
   1253 {
   1254 	struct inpcb *inp = sotoinpcb(so);
   1255 	struct mbuf *m = *mp;
   1256 	int optval = 0;
   1257 	int error = 0;
   1258 #if defined(IPSEC) || defined(FAST_IPSEC)
   1259 	struct lwp *l = curlwp;	/*XXX*/
   1260 #endif
   1261 
   1262 	if (level != IPPROTO_IP) {
   1263 		error = EINVAL;
   1264 		if (op == PRCO_SETOPT && *mp)
   1265 			(void) m_free(*mp);
   1266 	} else switch (op) {
   1267 
   1268 	case PRCO_SETOPT:
   1269 		switch (optname) {
   1270 		case IP_OPTIONS:
   1271 #ifdef notyet
   1272 		case IP_RETOPTS:
   1273 			return (ip_pcbopts(optname, &inp->inp_options, m));
   1274 #else
   1275 			return (ip_pcbopts(&inp->inp_options, m));
   1276 #endif
   1277 
   1278 		case IP_TOS:
   1279 		case IP_TTL:
   1280 		case IP_RECVOPTS:
   1281 		case IP_RECVRETOPTS:
   1282 		case IP_RECVDSTADDR:
   1283 		case IP_RECVIF:
   1284 			if (m == NULL || m->m_len != sizeof(int))
   1285 				error = EINVAL;
   1286 			else {
   1287 				optval = *mtod(m, int *);
   1288 				switch (optname) {
   1289 
   1290 				case IP_TOS:
   1291 					inp->inp_ip.ip_tos = optval;
   1292 					break;
   1293 
   1294 				case IP_TTL:
   1295 					inp->inp_ip.ip_ttl = optval;
   1296 					break;
   1297 #define	OPTSET(bit) \
   1298 	if (optval) \
   1299 		inp->inp_flags |= bit; \
   1300 	else \
   1301 		inp->inp_flags &= ~bit;
   1302 
   1303 				case IP_RECVOPTS:
   1304 					OPTSET(INP_RECVOPTS);
   1305 					break;
   1306 
   1307 				case IP_RECVRETOPTS:
   1308 					OPTSET(INP_RECVRETOPTS);
   1309 					break;
   1310 
   1311 				case IP_RECVDSTADDR:
   1312 					OPTSET(INP_RECVDSTADDR);
   1313 					break;
   1314 
   1315 				case IP_RECVIF:
   1316 					OPTSET(INP_RECVIF);
   1317 					break;
   1318 				}
   1319 			}
   1320 			break;
   1321 #undef OPTSET
   1322 
   1323 		case IP_MULTICAST_IF:
   1324 		case IP_MULTICAST_TTL:
   1325 		case IP_MULTICAST_LOOP:
   1326 		case IP_ADD_MEMBERSHIP:
   1327 		case IP_DROP_MEMBERSHIP:
   1328 			error = ip_setmoptions(optname, &inp->inp_moptions, m);
   1329 			break;
   1330 
   1331 		case IP_PORTRANGE:
   1332 			if (m == 0 || m->m_len != sizeof(int))
   1333 				error = EINVAL;
   1334 			else {
   1335 				optval = *mtod(m, int *);
   1336 
   1337 				switch (optval) {
   1338 
   1339 				case IP_PORTRANGE_DEFAULT:
   1340 				case IP_PORTRANGE_HIGH:
   1341 					inp->inp_flags &= ~(INP_LOWPORT);
   1342 					break;
   1343 
   1344 				case IP_PORTRANGE_LOW:
   1345 					inp->inp_flags |= INP_LOWPORT;
   1346 					break;
   1347 
   1348 				default:
   1349 					error = EINVAL;
   1350 					break;
   1351 				}
   1352 			}
   1353 			break;
   1354 
   1355 #if defined(IPSEC) || defined(FAST_IPSEC)
   1356 		case IP_IPSEC_POLICY:
   1357 		{
   1358 			void *req = NULL;
   1359 			size_t len = 0;
   1360 			int priv = 0;
   1361 
   1362 #ifdef __NetBSD__
   1363 			if (l == 0 || kauth_authorize_generic(l->l_cred,
   1364 			    KAUTH_GENERIC_ISSUSER, NULL))
   1365 				priv = 0;
   1366 			else
   1367 				priv = 1;
   1368 #else
   1369 			priv = (in6p->in6p_socket->so_state & SS_PRIV);
   1370 #endif
   1371 			if (m) {
   1372 				req = mtod(m, void *);
   1373 				len = m->m_len;
   1374 			}
   1375 			error = ipsec4_set_policy(inp, optname, req, len, priv);
   1376 			break;
   1377 		    }
   1378 #endif /*IPSEC*/
   1379 
   1380 		default:
   1381 			error = ENOPROTOOPT;
   1382 			break;
   1383 		}
   1384 		if (m)
   1385 			(void)m_free(m);
   1386 		break;
   1387 
   1388 	case PRCO_GETOPT:
   1389 		switch (optname) {
   1390 		case IP_OPTIONS:
   1391 		case IP_RETOPTS:
   1392 			*mp = m = m_get(M_WAIT, MT_SOOPTS);
   1393 			MCLAIM(m, so->so_mowner);
   1394 			if (inp->inp_options) {
   1395 				m->m_len = inp->inp_options->m_len;
   1396 				bcopy(mtod(inp->inp_options, void *),
   1397 				    mtod(m, void *), (unsigned)m->m_len);
   1398 			} else
   1399 				m->m_len = 0;
   1400 			break;
   1401 
   1402 		case IP_TOS:
   1403 		case IP_TTL:
   1404 		case IP_RECVOPTS:
   1405 		case IP_RECVRETOPTS:
   1406 		case IP_RECVDSTADDR:
   1407 		case IP_RECVIF:
   1408 		case IP_ERRORMTU:
   1409 			*mp = m = m_get(M_WAIT, MT_SOOPTS);
   1410 			MCLAIM(m, so->so_mowner);
   1411 			m->m_len = sizeof(int);
   1412 			switch (optname) {
   1413 
   1414 			case IP_TOS:
   1415 				optval = inp->inp_ip.ip_tos;
   1416 				break;
   1417 
   1418 			case IP_TTL:
   1419 				optval = inp->inp_ip.ip_ttl;
   1420 				break;
   1421 
   1422 			case IP_ERRORMTU:
   1423 				optval = inp->inp_errormtu;
   1424 				break;
   1425 
   1426 #define	OPTBIT(bit)	(inp->inp_flags & bit ? 1 : 0)
   1427 
   1428 			case IP_RECVOPTS:
   1429 				optval = OPTBIT(INP_RECVOPTS);
   1430 				break;
   1431 
   1432 			case IP_RECVRETOPTS:
   1433 				optval = OPTBIT(INP_RECVRETOPTS);
   1434 				break;
   1435 
   1436 			case IP_RECVDSTADDR:
   1437 				optval = OPTBIT(INP_RECVDSTADDR);
   1438 				break;
   1439 
   1440 			case IP_RECVIF:
   1441 				optval = OPTBIT(INP_RECVIF);
   1442 				break;
   1443 			}
   1444 			*mtod(m, int *) = optval;
   1445 			break;
   1446 
   1447 #if 0	/* defined(IPSEC) || defined(FAST_IPSEC) */
   1448 		/* XXX: code broken */
   1449 		case IP_IPSEC_POLICY:
   1450 		{
   1451 			void *req = NULL;
   1452 			size_t len = 0;
   1453 
   1454 			if (m) {
   1455 				req = mtod(m, void *);
   1456 				len = m->m_len;
   1457 			}
   1458 			error = ipsec4_get_policy(inp, req, len, mp);
   1459 			break;
   1460 		}
   1461 #endif /*IPSEC*/
   1462 
   1463 		case IP_MULTICAST_IF:
   1464 		case IP_MULTICAST_TTL:
   1465 		case IP_MULTICAST_LOOP:
   1466 		case IP_ADD_MEMBERSHIP:
   1467 		case IP_DROP_MEMBERSHIP:
   1468 			error = ip_getmoptions(optname, inp->inp_moptions, mp);
   1469 			if (*mp)
   1470 				MCLAIM(*mp, so->so_mowner);
   1471 			break;
   1472 
   1473 		case IP_PORTRANGE:
   1474 			*mp = m = m_get(M_WAIT, MT_SOOPTS);
   1475 			MCLAIM(m, so->so_mowner);
   1476 			m->m_len = sizeof(int);
   1477 
   1478 			if (inp->inp_flags & INP_LOWPORT)
   1479 				optval = IP_PORTRANGE_LOW;
   1480 			else
   1481 				optval = IP_PORTRANGE_DEFAULT;
   1482 
   1483 			*mtod(m, int *) = optval;
   1484 			break;
   1485 
   1486 		default:
   1487 			error = ENOPROTOOPT;
   1488 			break;
   1489 		}
   1490 		break;
   1491 	}
   1492 	return (error);
   1493 }
   1494 
   1495 /*
   1496  * Set up IP options in pcb for insertion in output packets.
   1497  * Store in mbuf with pointer in pcbopt, adding pseudo-option
   1498  * with destination address if source routed.
   1499  */
   1500 int
   1501 #ifdef notyet
   1502 ip_pcbopts(int optname, struct mbuf **pcbopt, struct mbuf *m)
   1503 #else
   1504 ip_pcbopts(struct mbuf **pcbopt, struct mbuf *m)
   1505 #endif
   1506 {
   1507 	int cnt, optlen;
   1508 	u_char *cp;
   1509 	u_char opt;
   1510 
   1511 	/* turn off any old options */
   1512 	if (*pcbopt)
   1513 		(void)m_free(*pcbopt);
   1514 	*pcbopt = 0;
   1515 	if (m == (struct mbuf *)0 || m->m_len == 0) {
   1516 		/*
   1517 		 * Only turning off any previous options.
   1518 		 */
   1519 		if (m)
   1520 			(void)m_free(m);
   1521 		return (0);
   1522 	}
   1523 
   1524 #ifndef	__vax__
   1525 	if (m->m_len % sizeof(int32_t))
   1526 		goto bad;
   1527 #endif
   1528 	/*
   1529 	 * IP first-hop destination address will be stored before
   1530 	 * actual options; move other options back
   1531 	 * and clear it when none present.
   1532 	 */
   1533 	if (m->m_data + m->m_len + sizeof(struct in_addr) >= &m->m_dat[MLEN])
   1534 		goto bad;
   1535 	cnt = m->m_len;
   1536 	m->m_len += sizeof(struct in_addr);
   1537 	cp = mtod(m, u_char *) + sizeof(struct in_addr);
   1538 	memmove(cp, mtod(m, void *), (unsigned)cnt);
   1539 	bzero(mtod(m, void *), sizeof(struct in_addr));
   1540 
   1541 	for (; cnt > 0; cnt -= optlen, cp += optlen) {
   1542 		opt = cp[IPOPT_OPTVAL];
   1543 		if (opt == IPOPT_EOL)
   1544 			break;
   1545 		if (opt == IPOPT_NOP)
   1546 			optlen = 1;
   1547 		else {
   1548 			if (cnt < IPOPT_OLEN + sizeof(*cp))
   1549 				goto bad;
   1550 			optlen = cp[IPOPT_OLEN];
   1551 			if (optlen < IPOPT_OLEN  + sizeof(*cp) || optlen > cnt)
   1552 				goto bad;
   1553 		}
   1554 		switch (opt) {
   1555 
   1556 		default:
   1557 			break;
   1558 
   1559 		case IPOPT_LSRR:
   1560 		case IPOPT_SSRR:
   1561 			/*
   1562 			 * user process specifies route as:
   1563 			 *	->A->B->C->D
   1564 			 * D must be our final destination (but we can't
   1565 			 * check that since we may not have connected yet).
   1566 			 * A is first hop destination, which doesn't appear in
   1567 			 * actual IP option, but is stored before the options.
   1568 			 */
   1569 			if (optlen < IPOPT_MINOFF - 1 + sizeof(struct in_addr))
   1570 				goto bad;
   1571 			m->m_len -= sizeof(struct in_addr);
   1572 			cnt -= sizeof(struct in_addr);
   1573 			optlen -= sizeof(struct in_addr);
   1574 			cp[IPOPT_OLEN] = optlen;
   1575 			/*
   1576 			 * Move first hop before start of options.
   1577 			 */
   1578 			bcopy((void *)&cp[IPOPT_OFFSET+1], mtod(m, void *),
   1579 			    sizeof(struct in_addr));
   1580 			/*
   1581 			 * Then copy rest of options back
   1582 			 * to close up the deleted entry.
   1583 			 */
   1584 			(void)memmove(&cp[IPOPT_OFFSET+1],
   1585 			    &cp[IPOPT_OFFSET+1] + sizeof(struct in_addr),
   1586 			    (unsigned)cnt - (IPOPT_MINOFF - 1));
   1587 			break;
   1588 		}
   1589 	}
   1590 	if (m->m_len > MAX_IPOPTLEN + sizeof(struct in_addr))
   1591 		goto bad;
   1592 	*pcbopt = m;
   1593 	return (0);
   1594 
   1595 bad:
   1596 	(void)m_free(m);
   1597 	return (EINVAL);
   1598 }
   1599 
   1600 /*
   1601  * following RFC1724 section 3.3, 0.0.0.0/8 is interpreted as interface index.
   1602  */
   1603 static struct ifnet *
   1604 ip_multicast_if(struct in_addr *a, int *ifindexp)
   1605 {
   1606 	int ifindex;
   1607 	struct ifnet *ifp = NULL;
   1608 	struct in_ifaddr *ia;
   1609 
   1610 	if (ifindexp)
   1611 		*ifindexp = 0;
   1612 	if (ntohl(a->s_addr) >> 24 == 0) {
   1613 		ifindex = ntohl(a->s_addr) & 0xffffff;
   1614 		if (ifindex < 0 || if_indexlim <= ifindex)
   1615 			return NULL;
   1616 		ifp = ifindex2ifnet[ifindex];
   1617 		if (!ifp)
   1618 			return NULL;
   1619 		if (ifindexp)
   1620 			*ifindexp = ifindex;
   1621 	} else {
   1622 		LIST_FOREACH(ia, &IN_IFADDR_HASH(a->s_addr), ia_hash) {
   1623 			if (in_hosteq(ia->ia_addr.sin_addr, *a) &&
   1624 			    (ia->ia_ifp->if_flags & IFF_MULTICAST) != 0) {
   1625 				ifp = ia->ia_ifp;
   1626 				break;
   1627 			}
   1628 		}
   1629 	}
   1630 	return ifp;
   1631 }
   1632 
   1633 static int
   1634 ip_getoptval(struct mbuf *m, u_int8_t *val, u_int maxval)
   1635 {
   1636 	u_int tval;
   1637 
   1638 	if (m == NULL)
   1639 		return EINVAL;
   1640 
   1641 	switch (m->m_len) {
   1642 	case sizeof(u_char):
   1643 		tval = *(mtod(m, u_char *));
   1644 		break;
   1645 	case sizeof(u_int):
   1646 		tval = *(mtod(m, u_int *));
   1647 		break;
   1648 	default:
   1649 		return EINVAL;
   1650 	}
   1651 
   1652 	if (tval > maxval)
   1653 		return EINVAL;
   1654 
   1655 	*val = tval;
   1656 	return 0;
   1657 }
   1658 
   1659 /*
   1660  * Set the IP multicast options in response to user setsockopt().
   1661  */
   1662 int
   1663 ip_setmoptions(int optname, struct ip_moptions **imop, struct mbuf *m)
   1664 {
   1665 	int error = 0;
   1666 	int i;
   1667 	struct in_addr addr;
   1668 	struct ip_mreq *mreq;
   1669 	struct ifnet *ifp;
   1670 	struct ip_moptions *imo = *imop;
   1671 	int ifindex;
   1672 
   1673 	if (imo == NULL) {
   1674 		/*
   1675 		 * No multicast option buffer attached to the pcb;
   1676 		 * allocate one and initialize to default values.
   1677 		 */
   1678 		imo = (struct ip_moptions *)malloc(sizeof(*imo), M_IPMOPTS,
   1679 		    M_WAITOK);
   1680 
   1681 		if (imo == NULL)
   1682 			return (ENOBUFS);
   1683 		*imop = imo;
   1684 		imo->imo_multicast_ifp = NULL;
   1685 		imo->imo_multicast_addr.s_addr = INADDR_ANY;
   1686 		imo->imo_multicast_ttl = IP_DEFAULT_MULTICAST_TTL;
   1687 		imo->imo_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
   1688 		imo->imo_num_memberships = 0;
   1689 	}
   1690 
   1691 	switch (optname) {
   1692 
   1693 	case IP_MULTICAST_IF:
   1694 		/*
   1695 		 * Select the interface for outgoing multicast packets.
   1696 		 */
   1697 		if (m == NULL || m->m_len != sizeof(struct in_addr)) {
   1698 			error = EINVAL;
   1699 			break;
   1700 		}
   1701 		addr = *(mtod(m, struct in_addr *));
   1702 		/*
   1703 		 * INADDR_ANY is used to remove a previous selection.
   1704 		 * When no interface is selected, a default one is
   1705 		 * chosen every time a multicast packet is sent.
   1706 		 */
   1707 		if (in_nullhost(addr)) {
   1708 			imo->imo_multicast_ifp = NULL;
   1709 			break;
   1710 		}
   1711 		/*
   1712 		 * The selected interface is identified by its local
   1713 		 * IP address.  Find the interface and confirm that
   1714 		 * it supports multicasting.
   1715 		 */
   1716 		ifp = ip_multicast_if(&addr, &ifindex);
   1717 		if (ifp == NULL || (ifp->if_flags & IFF_MULTICAST) == 0) {
   1718 			error = EADDRNOTAVAIL;
   1719 			break;
   1720 		}
   1721 		imo->imo_multicast_ifp = ifp;
   1722 		if (ifindex)
   1723 			imo->imo_multicast_addr = addr;
   1724 		else
   1725 			imo->imo_multicast_addr.s_addr = INADDR_ANY;
   1726 		break;
   1727 
   1728 	case IP_MULTICAST_TTL:
   1729 		/*
   1730 		 * Set the IP time-to-live for outgoing multicast packets.
   1731 		 */
   1732 		error = ip_getoptval(m, &imo->imo_multicast_ttl, MAXTTL);
   1733 		break;
   1734 
   1735 	case IP_MULTICAST_LOOP:
   1736 		/*
   1737 		 * Set the loopback flag for outgoing multicast packets.
   1738 		 * Must be zero or one.
   1739 		 */
   1740 		error = ip_getoptval(m, &imo->imo_multicast_loop, 1);
   1741 		break;
   1742 
   1743 	case IP_ADD_MEMBERSHIP:
   1744 		/*
   1745 		 * Add a multicast group membership.
   1746 		 * Group must be a valid IP multicast address.
   1747 		 */
   1748 		if (m == NULL || m->m_len != sizeof(struct ip_mreq)) {
   1749 			error = EINVAL;
   1750 			break;
   1751 		}
   1752 		mreq = mtod(m, struct ip_mreq *);
   1753 		if (!IN_MULTICAST(mreq->imr_multiaddr.s_addr)) {
   1754 			error = EINVAL;
   1755 			break;
   1756 		}
   1757 		/*
   1758 		 * If no interface address was provided, use the interface of
   1759 		 * the route to the given multicast address.
   1760 		 */
   1761 		if (in_nullhost(mreq->imr_interface)) {
   1762 			union {
   1763 				struct sockaddr		dst;
   1764 				struct sockaddr_in	dst4;
   1765 			} u;
   1766 			struct route ro;
   1767 
   1768 			memset(&ro, 0, sizeof(ro));
   1769 
   1770 			sockaddr_in_init(&u.dst4, &mreq->imr_multiaddr, 0);
   1771 			rtcache_setdst(&ro, &u.dst);
   1772 			rtcache_init(&ro);
   1773 			ifp = (ro.ro_rt != NULL) ? ro.ro_rt->rt_ifp : NULL;
   1774 			rtcache_free(&ro);
   1775 		} else {
   1776 			ifp = ip_multicast_if(&mreq->imr_interface, NULL);
   1777 		}
   1778 		/*
   1779 		 * See if we found an interface, and confirm that it
   1780 		 * supports multicast.
   1781 		 */
   1782 		if (ifp == NULL || (ifp->if_flags & IFF_MULTICAST) == 0) {
   1783 			error = EADDRNOTAVAIL;
   1784 			break;
   1785 		}
   1786 		/*
   1787 		 * See if the membership already exists or if all the
   1788 		 * membership slots are full.
   1789 		 */
   1790 		for (i = 0; i < imo->imo_num_memberships; ++i) {
   1791 			if (imo->imo_membership[i]->inm_ifp == ifp &&
   1792 			    in_hosteq(imo->imo_membership[i]->inm_addr,
   1793 				      mreq->imr_multiaddr))
   1794 				break;
   1795 		}
   1796 		if (i < imo->imo_num_memberships) {
   1797 			error = EADDRINUSE;
   1798 			break;
   1799 		}
   1800 		if (i == IP_MAX_MEMBERSHIPS) {
   1801 			error = ETOOMANYREFS;
   1802 			break;
   1803 		}
   1804 		/*
   1805 		 * Everything looks good; add a new record to the multicast
   1806 		 * address list for the given interface.
   1807 		 */
   1808 		if ((imo->imo_membership[i] =
   1809 		    in_addmulti(&mreq->imr_multiaddr, ifp)) == NULL) {
   1810 			error = ENOBUFS;
   1811 			break;
   1812 		}
   1813 		++imo->imo_num_memberships;
   1814 		break;
   1815 
   1816 	case IP_DROP_MEMBERSHIP:
   1817 		/*
   1818 		 * Drop a multicast group membership.
   1819 		 * Group must be a valid IP multicast address.
   1820 		 */
   1821 		if (m == NULL || m->m_len != sizeof(struct ip_mreq)) {
   1822 			error = EINVAL;
   1823 			break;
   1824 		}
   1825 		mreq = mtod(m, struct ip_mreq *);
   1826 		if (!IN_MULTICAST(mreq->imr_multiaddr.s_addr)) {
   1827 			error = EINVAL;
   1828 			break;
   1829 		}
   1830 		/*
   1831 		 * If an interface address was specified, get a pointer
   1832 		 * to its ifnet structure.
   1833 		 */
   1834 		if (in_nullhost(mreq->imr_interface))
   1835 			ifp = NULL;
   1836 		else {
   1837 			ifp = ip_multicast_if(&mreq->imr_interface, NULL);
   1838 			if (ifp == NULL) {
   1839 				error = EADDRNOTAVAIL;
   1840 				break;
   1841 			}
   1842 		}
   1843 		/*
   1844 		 * Find the membership in the membership array.
   1845 		 */
   1846 		for (i = 0; i < imo->imo_num_memberships; ++i) {
   1847 			if ((ifp == NULL ||
   1848 			     imo->imo_membership[i]->inm_ifp == ifp) &&
   1849 			     in_hosteq(imo->imo_membership[i]->inm_addr,
   1850 				       mreq->imr_multiaddr))
   1851 				break;
   1852 		}
   1853 		if (i == imo->imo_num_memberships) {
   1854 			error = EADDRNOTAVAIL;
   1855 			break;
   1856 		}
   1857 		/*
   1858 		 * Give up the multicast address record to which the
   1859 		 * membership points.
   1860 		 */
   1861 		in_delmulti(imo->imo_membership[i]);
   1862 		/*
   1863 		 * Remove the gap in the membership array.
   1864 		 */
   1865 		for (++i; i < imo->imo_num_memberships; ++i)
   1866 			imo->imo_membership[i-1] = imo->imo_membership[i];
   1867 		--imo->imo_num_memberships;
   1868 		break;
   1869 
   1870 	default:
   1871 		error = EOPNOTSUPP;
   1872 		break;
   1873 	}
   1874 
   1875 	/*
   1876 	 * If all options have default values, no need to keep the mbuf.
   1877 	 */
   1878 	if (imo->imo_multicast_ifp == NULL &&
   1879 	    imo->imo_multicast_ttl == IP_DEFAULT_MULTICAST_TTL &&
   1880 	    imo->imo_multicast_loop == IP_DEFAULT_MULTICAST_LOOP &&
   1881 	    imo->imo_num_memberships == 0) {
   1882 		free(*imop, M_IPMOPTS);
   1883 		*imop = NULL;
   1884 	}
   1885 
   1886 	return (error);
   1887 }
   1888 
   1889 /*
   1890  * Return the IP multicast options in response to user getsockopt().
   1891  */
   1892 int
   1893 ip_getmoptions(int optname, struct ip_moptions *imo, struct mbuf **mp)
   1894 {
   1895 	u_char *ttl;
   1896 	u_char *loop;
   1897 	struct in_addr *addr;
   1898 	struct in_ifaddr *ia;
   1899 
   1900 	*mp = m_get(M_WAIT, MT_SOOPTS);
   1901 
   1902 	switch (optname) {
   1903 
   1904 	case IP_MULTICAST_IF:
   1905 		addr = mtod(*mp, struct in_addr *);
   1906 		(*mp)->m_len = sizeof(struct in_addr);
   1907 		if (imo == NULL || imo->imo_multicast_ifp == NULL)
   1908 			*addr = zeroin_addr;
   1909 		else if (imo->imo_multicast_addr.s_addr) {
   1910 			/* return the value user has set */
   1911 			*addr = imo->imo_multicast_addr;
   1912 		} else {
   1913 			IFP_TO_IA(imo->imo_multicast_ifp, ia);
   1914 			*addr = ia ? ia->ia_addr.sin_addr : zeroin_addr;
   1915 		}
   1916 		return (0);
   1917 
   1918 	case IP_MULTICAST_TTL:
   1919 		ttl = mtod(*mp, u_char *);
   1920 		(*mp)->m_len = 1;
   1921 		*ttl = imo ? imo->imo_multicast_ttl
   1922 			   : IP_DEFAULT_MULTICAST_TTL;
   1923 		return (0);
   1924 
   1925 	case IP_MULTICAST_LOOP:
   1926 		loop = mtod(*mp, u_char *);
   1927 		(*mp)->m_len = 1;
   1928 		*loop = imo ? imo->imo_multicast_loop
   1929 			    : IP_DEFAULT_MULTICAST_LOOP;
   1930 		return (0);
   1931 
   1932 	default:
   1933 		return (EOPNOTSUPP);
   1934 	}
   1935 }
   1936 
   1937 /*
   1938  * Discard the IP multicast options.
   1939  */
   1940 void
   1941 ip_freemoptions(struct ip_moptions *imo)
   1942 {
   1943 	int i;
   1944 
   1945 	if (imo != NULL) {
   1946 		for (i = 0; i < imo->imo_num_memberships; ++i)
   1947 			in_delmulti(imo->imo_membership[i]);
   1948 		free(imo, M_IPMOPTS);
   1949 	}
   1950 }
   1951 
   1952 /*
   1953  * Routine called from ip_output() to loop back a copy of an IP multicast
   1954  * packet to the input queue of a specified interface.  Note that this
   1955  * calls the output routine of the loopback "driver", but with an interface
   1956  * pointer that might NOT be lo0ifp -- easier than replicating that code here.
   1957  */
   1958 static void
   1959 ip_mloopback(struct ifnet *ifp, struct mbuf *m, const struct sockaddr_in *dst)
   1960 {
   1961 	struct ip *ip;
   1962 	struct mbuf *copym;
   1963 
   1964 	copym = m_copy(m, 0, M_COPYALL);
   1965 	if (copym != NULL
   1966 	 && (copym->m_flags & M_EXT || copym->m_len < sizeof(struct ip)))
   1967 		copym = m_pullup(copym, sizeof(struct ip));
   1968 	if (copym == NULL)
   1969 		return;
   1970 	/*
   1971 	 * We don't bother to fragment if the IP length is greater
   1972 	 * than the interface's MTU.  Can this possibly matter?
   1973 	 */
   1974 	ip = mtod(copym, struct ip *);
   1975 
   1976 	if (copym->m_pkthdr.csum_flags & (M_CSUM_TCPv4|M_CSUM_UDPv4)) {
   1977 		in_delayed_cksum(copym);
   1978 		copym->m_pkthdr.csum_flags &=
   1979 		    ~(M_CSUM_TCPv4|M_CSUM_UDPv4);
   1980 	}
   1981 
   1982 	ip->ip_sum = 0;
   1983 	ip->ip_sum = in_cksum(copym, ip->ip_hl << 2);
   1984 	(void)looutput(ifp, copym, sintocsa(dst), NULL);
   1985 }
   1986