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