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