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