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