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