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