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