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