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