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