Home | History | Annotate | Line # | Download | only in netinet
ip_output.c revision 1.305
      1 /*	$NetBSD: ip_output.c,v 1.305 2018/05/29 17:21:57 maxv 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.305 2018/05/29 17:21:57 maxv Exp $");
     95 
     96 #ifdef _KERNEL_OPT
     97 #include "opt_inet.h"
     98 #include "opt_ipsec.h"
     99 #include "opt_mrouting.h"
    100 #include "opt_net_mpsafe.h"
    101 #include "opt_mpls.h"
    102 #endif
    103 
    104 #include "arp.h"
    105 
    106 #include <sys/param.h>
    107 #include <sys/kmem.h>
    108 #include <sys/mbuf.h>
    109 #include <sys/socket.h>
    110 #include <sys/socketvar.h>
    111 #include <sys/kauth.h>
    112 #include <sys/systm.h>
    113 #include <sys/syslog.h>
    114 
    115 #include <net/if.h>
    116 #include <net/if_types.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 #include <netinet/udp_var.h>
    131 
    132 #ifdef INET6
    133 #include <netinet6/ip6_var.h>
    134 #endif
    135 
    136 #ifdef MROUTING
    137 #include <netinet/ip_mroute.h>
    138 #endif
    139 
    140 #ifdef IPSEC
    141 #include <netipsec/ipsec.h>
    142 #include <netipsec/key.h>
    143 #endif
    144 
    145 #ifdef MPLS
    146 #include <netmpls/mpls.h>
    147 #include <netmpls/mpls_var.h>
    148 #endif
    149 
    150 static int ip_pcbopts(struct inpcb *, const struct sockopt *);
    151 static struct mbuf *ip_insertoptions(struct mbuf *, struct mbuf *, int *);
    152 static struct ifnet *ip_multicast_if(struct in_addr *, int *);
    153 static void ip_mloopback(struct ifnet *, struct mbuf *,
    154     const struct sockaddr_in *);
    155 static int ip_ifaddrvalid(const struct in_ifaddr *);
    156 
    157 extern pfil_head_t *inet_pfil_hook;			/* XXX */
    158 
    159 int ip_do_loopback_cksum = 0;
    160 
    161 static int
    162 ip_mark_mpls(struct ifnet * const ifp, struct mbuf * const m,
    163     const struct rtentry *rt)
    164 {
    165 	int error = 0;
    166 #ifdef MPLS
    167 	union mpls_shim msh;
    168 
    169 	if (rt == NULL || rt_gettag(rt) == NULL ||
    170 	    rt_gettag(rt)->sa_family != AF_MPLS ||
    171 	    (m->m_flags & (M_MCAST | M_BCAST)) != 0 ||
    172 	    ifp->if_type != IFT_ETHER)
    173 		return 0;
    174 
    175 	msh.s_addr = MPLS_GETSADDR(rt);
    176 	if (msh.shim.label != MPLS_LABEL_IMPLNULL) {
    177 		struct m_tag *mtag;
    178 		/*
    179 		 * XXX tentative solution to tell ether_output
    180 		 * it's MPLS. Need some more efficient solution.
    181 		 */
    182 		mtag = m_tag_get(PACKET_TAG_MPLS,
    183 		    sizeof(int) /* dummy */,
    184 		    M_NOWAIT);
    185 		if (mtag == NULL)
    186 			return ENOMEM;
    187 		m_tag_prepend(m, mtag);
    188 	}
    189 #endif
    190 	return error;
    191 }
    192 
    193 /*
    194  * Send an IP packet to a host.
    195  */
    196 int
    197 ip_if_output(struct ifnet * const ifp, struct mbuf * const m,
    198     const struct sockaddr * const dst, const struct rtentry *rt)
    199 {
    200 	int error = 0;
    201 
    202 	if (rt != NULL) {
    203 		error = rt_check_reject_route(rt, ifp);
    204 		if (error != 0) {
    205 			m_freem(m);
    206 			return error;
    207 		}
    208 	}
    209 
    210 	error = ip_mark_mpls(ifp, m, rt);
    211 	if (error != 0) {
    212 		m_freem(m);
    213 		return error;
    214 	}
    215 
    216 	error = if_output_lock(ifp, ifp, m, dst, rt);
    217 
    218 	return error;
    219 }
    220 
    221 /*
    222  * IP output.  The packet in mbuf chain m contains a skeletal IP
    223  * header (with len, off, ttl, proto, tos, src, dst).
    224  * The mbuf chain containing the packet will be freed.
    225  * The mbuf opt, if present, will not be freed.
    226  */
    227 int
    228 ip_output(struct mbuf *m0, struct mbuf *opt, struct route *ro, int flags,
    229     struct ip_moptions *imo, struct inpcb *inp)
    230 {
    231 	struct rtentry *rt;
    232 	struct ip *ip;
    233 	struct ifnet *ifp, *mifp = NULL;
    234 	struct mbuf *m = m0;
    235 	int len, hlen, error = 0;
    236 	struct route iproute;
    237 	const struct sockaddr_in *dst;
    238 	struct in_ifaddr *ia = NULL;
    239 	struct ifaddr *ifa;
    240 	int isbroadcast;
    241 	int sw_csum;
    242 	u_long mtu;
    243 	bool natt_frag = false;
    244 	bool rtmtu_nolock;
    245 	union {
    246 		struct sockaddr		sa;
    247 		struct sockaddr_in	sin;
    248 	} udst, usrc;
    249 	struct sockaddr *rdst = &udst.sa;	/* real IP destination, as
    250 						 * opposed to the nexthop
    251 						 */
    252 	struct psref psref, psref_ia;
    253 	int bound;
    254 	bool bind_need_restore = false;
    255 
    256 	len = 0;
    257 
    258 	MCLAIM(m, &ip_tx_mowner);
    259 
    260 	KASSERT((m->m_flags & M_PKTHDR) != 0);
    261 	KASSERT((m->m_pkthdr.csum_flags & (M_CSUM_TCPv6|M_CSUM_UDPv6)) == 0);
    262 	KASSERT((m->m_pkthdr.csum_flags & (M_CSUM_TCPv4|M_CSUM_UDPv4)) !=
    263 	    (M_CSUM_TCPv4|M_CSUM_UDPv4));
    264 	KASSERT(m->m_len >= sizeof(struct ip));
    265 
    266 	hlen = sizeof(struct ip);
    267 	if (opt) {
    268 		m = ip_insertoptions(m, opt, &len);
    269 		hlen = len;
    270 	}
    271 	ip = mtod(m, struct ip *);
    272 
    273 	/*
    274 	 * Fill in IP header.
    275 	 */
    276 	if ((flags & (IP_FORWARDING|IP_RAWOUTPUT)) == 0) {
    277 		ip->ip_v = IPVERSION;
    278 		ip->ip_off = htons(0);
    279 		/* ip->ip_id filled in after we find out source ia */
    280 		ip->ip_hl = hlen >> 2;
    281 		IP_STATINC(IP_STAT_LOCALOUT);
    282 	} else {
    283 		hlen = ip->ip_hl << 2;
    284 	}
    285 
    286 	/*
    287 	 * Route packet.
    288 	 */
    289 	if (ro == NULL) {
    290 		memset(&iproute, 0, sizeof(iproute));
    291 		ro = &iproute;
    292 	}
    293 	sockaddr_in_init(&udst.sin, &ip->ip_dst, 0);
    294 	dst = satocsin(rtcache_getdst(ro));
    295 
    296 	/*
    297 	 * If there is a cached route, check that it is to the same
    298 	 * destination and is still up.  If not, free it and try again.
    299 	 * The address family should also be checked in case of sharing
    300 	 * the cache with IPv6.
    301 	 */
    302 	if (dst && (dst->sin_family != AF_INET ||
    303 	    !in_hosteq(dst->sin_addr, ip->ip_dst)))
    304 		rtcache_free(ro);
    305 
    306 	/* XXX must be before rtcache operations */
    307 	bound = curlwp_bind();
    308 	bind_need_restore = true;
    309 
    310 	if ((rt = rtcache_validate(ro)) == NULL &&
    311 	    (rt = rtcache_update(ro, 1)) == NULL) {
    312 		dst = &udst.sin;
    313 		error = rtcache_setdst(ro, &udst.sa);
    314 		if (error != 0)
    315 			goto bad;
    316 	}
    317 
    318 	/*
    319 	 * If routing to interface only, short circuit routing lookup.
    320 	 */
    321 	if (flags & IP_ROUTETOIF) {
    322 		ifa = ifa_ifwithladdr_psref(sintocsa(dst), &psref_ia);
    323 		if (ifa == NULL) {
    324 			IP_STATINC(IP_STAT_NOROUTE);
    325 			error = ENETUNREACH;
    326 			goto bad;
    327 		}
    328 		/* ia is already referenced by psref_ia */
    329 		ia = ifatoia(ifa);
    330 
    331 		ifp = ia->ia_ifp;
    332 		mtu = ifp->if_mtu;
    333 		ip->ip_ttl = 1;
    334 		isbroadcast = in_broadcast(dst->sin_addr, ifp);
    335 	} else if (((IN_MULTICAST(ip->ip_dst.s_addr) ||
    336 	    ip->ip_dst.s_addr == INADDR_BROADCAST) ||
    337 	    (flags & IP_ROUTETOIFINDEX)) &&
    338 	    imo != NULL && imo->imo_multicast_if_index != 0) {
    339 		ifp = mifp = if_get_byindex(imo->imo_multicast_if_index, &psref);
    340 		if (ifp == NULL) {
    341 			IP_STATINC(IP_STAT_NOROUTE);
    342 			error = ENETUNREACH;
    343 			goto bad;
    344 		}
    345 		mtu = ifp->if_mtu;
    346 		ia = in_get_ia_from_ifp_psref(ifp, &psref_ia);
    347 		if (ia == NULL) {
    348 			error = EADDRNOTAVAIL;
    349 			goto bad;
    350 		}
    351 		if (IN_MULTICAST(ip->ip_dst.s_addr) ||
    352 		    ip->ip_dst.s_addr == INADDR_BROADCAST) {
    353 			isbroadcast = 0;
    354 		} else {
    355 			/* IP_ROUTETOIFINDEX */
    356 			isbroadcast = in_broadcast(dst->sin_addr, ifp);
    357 			if ((isbroadcast == 0) && ((ifp->if_flags &
    358 			    (IFF_LOOPBACK | IFF_POINTOPOINT)) == 0) &&
    359 			    (in_direct(dst->sin_addr, ifp) == 0)) {
    360 				/* gateway address required */
    361 				if (rt == NULL)
    362 					rt = rtcache_init(ro);
    363 				if (rt == NULL || rt->rt_ifp != ifp) {
    364 					IP_STATINC(IP_STAT_NOROUTE);
    365 					error = EHOSTUNREACH;
    366 					goto bad;
    367 				}
    368 				rt->rt_use++;
    369 				if (rt->rt_flags & RTF_GATEWAY)
    370 					dst = satosin(rt->rt_gateway);
    371 				if (rt->rt_flags & RTF_HOST)
    372 					isbroadcast =
    373 					    rt->rt_flags & RTF_BROADCAST;
    374 			}
    375 		}
    376 	} else {
    377 		if (rt == NULL)
    378 			rt = rtcache_init(ro);
    379 		if (rt == NULL) {
    380 			IP_STATINC(IP_STAT_NOROUTE);
    381 			error = EHOSTUNREACH;
    382 			goto bad;
    383 		}
    384 		if (ifa_is_destroying(rt->rt_ifa)) {
    385 			rtcache_unref(rt, ro);
    386 			rt = NULL;
    387 			IP_STATINC(IP_STAT_NOROUTE);
    388 			error = EHOSTUNREACH;
    389 			goto bad;
    390 		}
    391 		ifa_acquire(rt->rt_ifa, &psref_ia);
    392 		ia = ifatoia(rt->rt_ifa);
    393 		ifp = rt->rt_ifp;
    394 		if ((mtu = rt->rt_rmx.rmx_mtu) == 0)
    395 			mtu = ifp->if_mtu;
    396 		rt->rt_use++;
    397 		if (rt->rt_flags & RTF_GATEWAY)
    398 			dst = satosin(rt->rt_gateway);
    399 		if (rt->rt_flags & RTF_HOST)
    400 			isbroadcast = rt->rt_flags & RTF_BROADCAST;
    401 		else
    402 			isbroadcast = in_broadcast(dst->sin_addr, ifp);
    403 	}
    404 	rtmtu_nolock = rt && (rt->rt_rmx.rmx_locks & RTV_MTU) == 0;
    405 
    406 	if (IN_MULTICAST(ip->ip_dst.s_addr) ||
    407 	    (ip->ip_dst.s_addr == INADDR_BROADCAST)) {
    408 		bool inmgroup;
    409 
    410 		m->m_flags |= (ip->ip_dst.s_addr == INADDR_BROADCAST) ?
    411 		    M_BCAST : M_MCAST;
    412 		/*
    413 		 * See if the caller provided any multicast options
    414 		 */
    415 		if (imo != NULL)
    416 			ip->ip_ttl = imo->imo_multicast_ttl;
    417 		else
    418 			ip->ip_ttl = IP_DEFAULT_MULTICAST_TTL;
    419 
    420 		/*
    421 		 * if we don't know the outgoing ifp yet, we can't generate
    422 		 * output
    423 		 */
    424 		if (!ifp) {
    425 			IP_STATINC(IP_STAT_NOROUTE);
    426 			error = ENETUNREACH;
    427 			goto bad;
    428 		}
    429 
    430 		/*
    431 		 * If the packet is multicast or broadcast, confirm that
    432 		 * the outgoing interface can transmit it.
    433 		 */
    434 		if (((m->m_flags & M_MCAST) &&
    435 		     (ifp->if_flags & IFF_MULTICAST) == 0) ||
    436 		    ((m->m_flags & M_BCAST) &&
    437 		     (ifp->if_flags & (IFF_BROADCAST|IFF_POINTOPOINT)) == 0))  {
    438 			IP_STATINC(IP_STAT_NOROUTE);
    439 			error = ENETUNREACH;
    440 			goto bad;
    441 		}
    442 		/*
    443 		 * If source address not specified yet, use an address
    444 		 * of outgoing interface.
    445 		 */
    446 		if (in_nullhost(ip->ip_src)) {
    447 			struct in_ifaddr *xia;
    448 			struct ifaddr *xifa;
    449 			struct psref _psref;
    450 
    451 			xia = in_get_ia_from_ifp_psref(ifp, &_psref);
    452 			if (!xia) {
    453 				error = EADDRNOTAVAIL;
    454 				goto bad;
    455 			}
    456 			xifa = &xia->ia_ifa;
    457 			if (xifa->ifa_getifa != NULL) {
    458 				ia4_release(xia, &_psref);
    459 				/* FIXME ifa_getifa is NOMPSAFE */
    460 				xia = ifatoia((*xifa->ifa_getifa)(xifa, rdst));
    461 				if (xia == NULL) {
    462 					error = EADDRNOTAVAIL;
    463 					goto bad;
    464 				}
    465 				ia4_acquire(xia, &_psref);
    466 			}
    467 			ip->ip_src = xia->ia_addr.sin_addr;
    468 			ia4_release(xia, &_psref);
    469 		}
    470 
    471 		inmgroup = in_multi_group(ip->ip_dst, ifp, flags);
    472 		if (inmgroup && (imo == NULL || imo->imo_multicast_loop)) {
    473 			/*
    474 			 * If we belong to the destination multicast group
    475 			 * on the outgoing interface, and the caller did not
    476 			 * forbid loopback, loop back a copy.
    477 			 */
    478 			ip_mloopback(ifp, m, &udst.sin);
    479 		}
    480 #ifdef MROUTING
    481 		else {
    482 			/*
    483 			 * If we are acting as a multicast router, perform
    484 			 * multicast forwarding as if the packet had just
    485 			 * arrived on the interface to which we are about
    486 			 * to send.  The multicast forwarding function
    487 			 * recursively calls this function, using the
    488 			 * IP_FORWARDING flag to prevent infinite recursion.
    489 			 *
    490 			 * Multicasts that are looped back by ip_mloopback(),
    491 			 * above, will be forwarded by the ip_input() routine,
    492 			 * if necessary.
    493 			 */
    494 			extern struct socket *ip_mrouter;
    495 
    496 			if (ip_mrouter && (flags & IP_FORWARDING) == 0) {
    497 				if (ip_mforward(m, ifp) != 0) {
    498 					m_freem(m);
    499 					goto done;
    500 				}
    501 			}
    502 		}
    503 #endif
    504 		/*
    505 		 * Multicasts with a time-to-live of zero may be looped-
    506 		 * back, above, but must not be transmitted on a network.
    507 		 * Also, multicasts addressed to the loopback interface
    508 		 * are not sent -- the above call to ip_mloopback() will
    509 		 * loop back a copy if this host actually belongs to the
    510 		 * destination group on the loopback interface.
    511 		 */
    512 		if (ip->ip_ttl == 0 || (ifp->if_flags & IFF_LOOPBACK) != 0) {
    513 			m_freem(m);
    514 			goto done;
    515 		}
    516 		goto sendit;
    517 	}
    518 
    519 	/*
    520 	 * If source address not specified yet, use address
    521 	 * of outgoing interface.
    522 	 */
    523 	if (in_nullhost(ip->ip_src)) {
    524 		struct ifaddr *xifa;
    525 
    526 		xifa = &ia->ia_ifa;
    527 		if (xifa->ifa_getifa != NULL) {
    528 			ia4_release(ia, &psref_ia);
    529 			/* FIXME ifa_getifa is NOMPSAFE */
    530 			ia = ifatoia((*xifa->ifa_getifa)(xifa, rdst));
    531 			if (ia == NULL) {
    532 				error = EADDRNOTAVAIL;
    533 				goto bad;
    534 			}
    535 			ia4_acquire(ia, &psref_ia);
    536 		}
    537 		ip->ip_src = ia->ia_addr.sin_addr;
    538 	}
    539 
    540 	/*
    541 	 * Packets with Class-D address as source are not valid per
    542 	 * RFC1112.
    543 	 */
    544 	if (IN_MULTICAST(ip->ip_src.s_addr)) {
    545 		IP_STATINC(IP_STAT_ODROPPED);
    546 		error = EADDRNOTAVAIL;
    547 		goto bad;
    548 	}
    549 
    550 	/*
    551 	 * Look for broadcast address and verify user is allowed to
    552 	 * send such a packet.
    553 	 */
    554 	if (isbroadcast) {
    555 		if ((ifp->if_flags & IFF_BROADCAST) == 0) {
    556 			error = EADDRNOTAVAIL;
    557 			goto bad;
    558 		}
    559 		if ((flags & IP_ALLOWBROADCAST) == 0) {
    560 			error = EACCES;
    561 			goto bad;
    562 		}
    563 		/* don't allow broadcast messages to be fragmented */
    564 		if (ntohs(ip->ip_len) > ifp->if_mtu) {
    565 			error = EMSGSIZE;
    566 			goto bad;
    567 		}
    568 		m->m_flags |= M_BCAST;
    569 	} else
    570 		m->m_flags &= ~M_BCAST;
    571 
    572 sendit:
    573 	if ((flags & (IP_FORWARDING|IP_NOIPNEWID)) == 0) {
    574 		if (m->m_pkthdr.len < IP_MINFRAGSIZE) {
    575 			ip->ip_id = 0;
    576 		} else if ((m->m_pkthdr.csum_flags & M_CSUM_TSOv4) == 0) {
    577 			ip->ip_id = ip_newid(ia);
    578 		} else {
    579 			/*
    580 			 * TSO capable interfaces (typically?) increment
    581 			 * ip_id for each segment.
    582 			 * "allocate" enough ids here to increase the chance
    583 			 * for them to be unique.
    584 			 *
    585 			 * note that the following calculation is not
    586 			 * needed to be precise.  wasting some ip_id is fine.
    587 			 */
    588 
    589 			unsigned int segsz = m->m_pkthdr.segsz;
    590 			unsigned int datasz = ntohs(ip->ip_len) - hlen;
    591 			unsigned int num = howmany(datasz, segsz);
    592 
    593 			ip->ip_id = ip_newid_range(ia, num);
    594 		}
    595 	}
    596 	if (ia != NULL) {
    597 		ia4_release(ia, &psref_ia);
    598 		ia = NULL;
    599 	}
    600 
    601 	/*
    602 	 * If we're doing Path MTU Discovery, we need to set DF unless
    603 	 * the route's MTU is locked.
    604 	 */
    605 	if ((flags & IP_MTUDISC) != 0 && rtmtu_nolock) {
    606 		ip->ip_off |= htons(IP_DF);
    607 	}
    608 
    609 #ifdef IPSEC
    610 	if (ipsec_used) {
    611 		bool ipsec_done = false;
    612 
    613 		/* Perform IPsec processing, if any. */
    614 		error = ipsec4_output(m, inp, flags, &mtu, &natt_frag,
    615 		    &ipsec_done);
    616 		if (error || ipsec_done)
    617 			goto done;
    618 	}
    619 #endif
    620 
    621 	/*
    622 	 * Run through list of hooks for output packets.
    623 	 */
    624 	error = pfil_run_hooks(inet_pfil_hook, &m, ifp, PFIL_OUT);
    625 	if (error)
    626 		goto done;
    627 	if (m == NULL)
    628 		goto done;
    629 
    630 	ip = mtod(m, struct ip *);
    631 	hlen = ip->ip_hl << 2;
    632 
    633 	m->m_pkthdr.csum_data |= hlen << 16;
    634 
    635 	/*
    636 	 * search for the source address structure to
    637 	 * maintain output statistics, and verify address
    638 	 * validity
    639 	 */
    640 	KASSERT(ia == NULL);
    641 	sockaddr_in_init(&usrc.sin, &ip->ip_src, 0);
    642 	ifa = ifaof_ifpforaddr_psref(&usrc.sa, ifp, &psref_ia);
    643 	if (ifa != NULL)
    644 		ia = ifatoia(ifa);
    645 
    646 	/*
    647 	 * Ensure we only send from a valid address.
    648 	 * A NULL address is valid because the packet could be
    649 	 * generated from a packet filter.
    650 	 */
    651 	if (ia != NULL && (flags & IP_FORWARDING) == 0 &&
    652 	    (error = ip_ifaddrvalid(ia)) != 0)
    653 	{
    654 		ARPLOG(LOG_ERR,
    655 		    "refusing to send from invalid address %s (pid %d)\n",
    656 		    ARPLOGADDR(&ip->ip_src), curproc->p_pid);
    657 		IP_STATINC(IP_STAT_ODROPPED);
    658 		if (error == 1)
    659 			/*
    660 			 * Address exists, but is tentative or detached.
    661 			 * We can't send from it because it's invalid,
    662 			 * so we drop the packet.
    663 			 */
    664 			error = 0;
    665 		else
    666 			error = EADDRNOTAVAIL;
    667 		goto bad;
    668 	}
    669 
    670 	/* Maybe skip checksums on loopback interfaces. */
    671 	if (IN_NEED_CHECKSUM(ifp, M_CSUM_IPv4)) {
    672 		m->m_pkthdr.csum_flags |= M_CSUM_IPv4;
    673 	}
    674 	sw_csum = m->m_pkthdr.csum_flags & ~ifp->if_csum_flags_tx;
    675 
    676 	/*
    677 	 * If small enough for mtu of path, or if using TCP segmentation
    678 	 * offload, can just send directly.
    679 	 */
    680 	if (ntohs(ip->ip_len) <= mtu ||
    681 	    (m->m_pkthdr.csum_flags & M_CSUM_TSOv4) != 0) {
    682 		const struct sockaddr *sa;
    683 
    684 #if IFA_STATS
    685 		if (ia)
    686 			ia->ia_ifa.ifa_data.ifad_outbytes += ntohs(ip->ip_len);
    687 #endif
    688 		/*
    689 		 * Always initialize the sum to 0!  Some HW assisted
    690 		 * checksumming requires this.
    691 		 */
    692 		ip->ip_sum = 0;
    693 
    694 		if ((m->m_pkthdr.csum_flags & M_CSUM_TSOv4) == 0) {
    695 			/*
    696 			 * Perform any checksums that the hardware can't do
    697 			 * for us.
    698 			 *
    699 			 * XXX Does any hardware require the {th,uh}_sum
    700 			 * XXX fields to be 0?
    701 			 */
    702 			if (sw_csum & M_CSUM_IPv4) {
    703 				KASSERT(IN_NEED_CHECKSUM(ifp, M_CSUM_IPv4));
    704 				ip->ip_sum = in_cksum(m, hlen);
    705 				m->m_pkthdr.csum_flags &= ~M_CSUM_IPv4;
    706 			}
    707 			if (sw_csum & (M_CSUM_TCPv4|M_CSUM_UDPv4)) {
    708 				if (IN_NEED_CHECKSUM(ifp,
    709 				    sw_csum & (M_CSUM_TCPv4|M_CSUM_UDPv4))) {
    710 					in_delayed_cksum(m);
    711 				}
    712 				m->m_pkthdr.csum_flags &=
    713 				    ~(M_CSUM_TCPv4|M_CSUM_UDPv4);
    714 			}
    715 		}
    716 
    717 		sa = (m->m_flags & M_MCAST) ? sintocsa(rdst) : sintocsa(dst);
    718 		if (__predict_true(
    719 		    (m->m_pkthdr.csum_flags & M_CSUM_TSOv4) == 0 ||
    720 		    (ifp->if_capenable & IFCAP_TSOv4) != 0)) {
    721 			error = ip_if_output(ifp, m, sa, rt);
    722 		} else {
    723 			error = ip_tso_output(ifp, m, sa, rt);
    724 		}
    725 		goto done;
    726 	}
    727 
    728 	/*
    729 	 * We can't use HW checksumming if we're about to fragment the packet.
    730 	 *
    731 	 * XXX Some hardware can do this.
    732 	 */
    733 	if (m->m_pkthdr.csum_flags & (M_CSUM_TCPv4|M_CSUM_UDPv4)) {
    734 		if (IN_NEED_CHECKSUM(ifp,
    735 		    m->m_pkthdr.csum_flags & (M_CSUM_TCPv4|M_CSUM_UDPv4))) {
    736 			in_delayed_cksum(m);
    737 		}
    738 		m->m_pkthdr.csum_flags &= ~(M_CSUM_TCPv4|M_CSUM_UDPv4);
    739 	}
    740 
    741 	/*
    742 	 * Too large for interface; fragment if possible.
    743 	 * Must be able to put at least 8 bytes per fragment.
    744 	 */
    745 	if (ntohs(ip->ip_off) & IP_DF) {
    746 		if (flags & IP_RETURNMTU) {
    747 			KASSERT(inp != NULL);
    748 			inp->inp_errormtu = mtu;
    749 		}
    750 		error = EMSGSIZE;
    751 		IP_STATINC(IP_STAT_CANTFRAG);
    752 		goto bad;
    753 	}
    754 
    755 	error = ip_fragment(m, ifp, mtu);
    756 	if (error) {
    757 		m = NULL;
    758 		goto bad;
    759 	}
    760 
    761 	for (; m; m = m0) {
    762 		m0 = m->m_nextpkt;
    763 		m->m_nextpkt = NULL;
    764 		if (error) {
    765 			m_freem(m);
    766 			continue;
    767 		}
    768 #if IFA_STATS
    769 		if (ia)
    770 			ia->ia_ifa.ifa_data.ifad_outbytes += ntohs(ip->ip_len);
    771 #endif
    772 		/*
    773 		 * If we get there, the packet has not been handled by
    774 		 * IPsec whereas it should have. Now that it has been
    775 		 * fragmented, re-inject it in ip_output so that IPsec
    776 		 * processing can occur.
    777 		 */
    778 		if (natt_frag) {
    779 			error = ip_output(m, opt, ro,
    780 			    flags | IP_RAWOUTPUT | IP_NOIPNEWID,
    781 			    imo, inp);
    782 		} else {
    783 			KASSERT((m->m_pkthdr.csum_flags &
    784 			    (M_CSUM_UDPv4 | M_CSUM_TCPv4)) == 0);
    785 			error = ip_if_output(ifp, m,
    786 			    (m->m_flags & M_MCAST) ?
    787 			    sintocsa(rdst) : sintocsa(dst), rt);
    788 		}
    789 	}
    790 	if (error == 0) {
    791 		IP_STATINC(IP_STAT_FRAGMENTED);
    792 	}
    793 
    794 done:
    795 	ia4_release(ia, &psref_ia);
    796 	rtcache_unref(rt, ro);
    797 	if (ro == &iproute) {
    798 		rtcache_free(&iproute);
    799 	}
    800 	if (mifp != NULL) {
    801 		if_put(mifp, &psref);
    802 	}
    803 	if (bind_need_restore)
    804 		curlwp_bindx(bound);
    805 	return error;
    806 
    807 bad:
    808 	m_freem(m);
    809 	goto done;
    810 }
    811 
    812 int
    813 ip_fragment(struct mbuf *m, struct ifnet *ifp, u_long mtu)
    814 {
    815 	struct ip *ip, *mhip;
    816 	struct mbuf *m0;
    817 	int len, hlen, off;
    818 	int mhlen, firstlen;
    819 	struct mbuf **mnext;
    820 	int sw_csum = m->m_pkthdr.csum_flags;
    821 	int fragments = 0;
    822 	int error = 0;
    823 	int ipoff, ipflg;
    824 
    825 	ip = mtod(m, struct ip *);
    826 	hlen = ip->ip_hl << 2;
    827 
    828 	/* Preserve the offset and flags. */
    829 	ipoff = ntohs(ip->ip_off) & IP_OFFMASK;
    830 	ipflg = ntohs(ip->ip_off) & (IP_RF|IP_DF|IP_MF);
    831 
    832 	if (ifp != NULL)
    833 		sw_csum &= ~ifp->if_csum_flags_tx;
    834 
    835 	len = (mtu - hlen) &~ 7;
    836 	if (len < 8) {
    837 		m_freem(m);
    838 		return EMSGSIZE;
    839 	}
    840 
    841 	firstlen = len;
    842 	mnext = &m->m_nextpkt;
    843 
    844 	/*
    845 	 * Loop through length of segment after first fragment,
    846 	 * make new header and copy data of each part and link onto chain.
    847 	 */
    848 	m0 = m;
    849 	mhlen = sizeof(struct ip);
    850 	for (off = hlen + len; off < ntohs(ip->ip_len); off += len) {
    851 		MGETHDR(m, M_DONTWAIT, MT_HEADER);
    852 		if (m == NULL) {
    853 			error = ENOBUFS;
    854 			IP_STATINC(IP_STAT_ODROPPED);
    855 			goto sendorfree;
    856 		}
    857 		MCLAIM(m, m0->m_owner);
    858 
    859 		*mnext = m;
    860 		mnext = &m->m_nextpkt;
    861 
    862 		m->m_data += max_linkhdr;
    863 		mhip = mtod(m, struct ip *);
    864 		*mhip = *ip;
    865 
    866 		/* we must inherit MCAST and BCAST flags */
    867 		m->m_flags |= m0->m_flags & (M_MCAST|M_BCAST);
    868 
    869 		if (hlen > sizeof(struct ip)) {
    870 			mhlen = ip_optcopy(ip, mhip) + sizeof(struct ip);
    871 			mhip->ip_hl = mhlen >> 2;
    872 		}
    873 		m->m_len = mhlen;
    874 
    875 		mhip->ip_off = ((off - hlen) >> 3) + ipoff;
    876 		mhip->ip_off |= ipflg;
    877 		if (off + len >= ntohs(ip->ip_len))
    878 			len = ntohs(ip->ip_len) - off;
    879 		else
    880 			mhip->ip_off |= IP_MF;
    881 		HTONS(mhip->ip_off);
    882 
    883 		mhip->ip_len = htons((u_int16_t)(len + mhlen));
    884 		m->m_next = m_copym(m0, off, len, M_DONTWAIT);
    885 		if (m->m_next == NULL) {
    886 			error = ENOBUFS;
    887 			IP_STATINC(IP_STAT_ODROPPED);
    888 			goto sendorfree;
    889 		}
    890 
    891 		m->m_pkthdr.len = mhlen + len;
    892 		m_reset_rcvif(m);
    893 
    894 		mhip->ip_sum = 0;
    895 		KASSERT((m->m_pkthdr.csum_flags & M_CSUM_IPv4) == 0);
    896 		if (sw_csum & M_CSUM_IPv4) {
    897 			mhip->ip_sum = in_cksum(m, mhlen);
    898 		} else {
    899 			/*
    900 			 * checksum is hw-offloaded or not necessary.
    901 			 */
    902 			m->m_pkthdr.csum_flags |=
    903 			    m0->m_pkthdr.csum_flags & M_CSUM_IPv4;
    904 			m->m_pkthdr.csum_data |= mhlen << 16;
    905 			KASSERT(!(ifp != NULL &&
    906 			    IN_NEED_CHECKSUM(ifp, M_CSUM_IPv4)) ||
    907 			    (m->m_pkthdr.csum_flags & M_CSUM_IPv4) != 0);
    908 		}
    909 		IP_STATINC(IP_STAT_OFRAGMENTS);
    910 		fragments++;
    911 	}
    912 
    913 	/*
    914 	 * Update first fragment by trimming what's been copied out
    915 	 * and updating header, then send each fragment (in order).
    916 	 */
    917 	m = m0;
    918 	m_adj(m, hlen + firstlen - ntohs(ip->ip_len));
    919 	m->m_pkthdr.len = hlen + firstlen;
    920 	ip->ip_len = htons((u_int16_t)m->m_pkthdr.len);
    921 	ip->ip_off |= htons(IP_MF);
    922 	ip->ip_sum = 0;
    923 	if (sw_csum & M_CSUM_IPv4) {
    924 		ip->ip_sum = in_cksum(m, hlen);
    925 		m->m_pkthdr.csum_flags &= ~M_CSUM_IPv4;
    926 	} else {
    927 		/*
    928 		 * checksum is hw-offloaded or not necessary.
    929 		 */
    930 		KASSERT(!(ifp != NULL && IN_NEED_CHECKSUM(ifp, M_CSUM_IPv4)) ||
    931 		    (m->m_pkthdr.csum_flags & M_CSUM_IPv4) != 0);
    932 		KASSERT(M_CSUM_DATA_IPv4_IPHL(m->m_pkthdr.csum_data) >=
    933 		    sizeof(struct ip));
    934 	}
    935 
    936 sendorfree:
    937 	/*
    938 	 * If there is no room for all the fragments, don't queue
    939 	 * any of them.
    940 	 */
    941 	if (ifp != NULL) {
    942 		IFQ_LOCK(&ifp->if_snd);
    943 		if (ifp->if_snd.ifq_maxlen - ifp->if_snd.ifq_len < fragments &&
    944 		    error == 0) {
    945 			error = ENOBUFS;
    946 			IP_STATINC(IP_STAT_ODROPPED);
    947 			IFQ_INC_DROPS(&ifp->if_snd);
    948 		}
    949 		IFQ_UNLOCK(&ifp->if_snd);
    950 	}
    951 	if (error) {
    952 		for (m = m0; m; m = m0) {
    953 			m0 = m->m_nextpkt;
    954 			m->m_nextpkt = NULL;
    955 			m_freem(m);
    956 		}
    957 	}
    958 
    959 	return error;
    960 }
    961 
    962 /*
    963  * Process a delayed payload checksum calculation.
    964  */
    965 void
    966 in_delayed_cksum(struct mbuf *m)
    967 {
    968 	struct ip *ip;
    969 	u_int16_t csum, offset;
    970 
    971 	ip = mtod(m, struct ip *);
    972 	offset = ip->ip_hl << 2;
    973 	csum = in4_cksum(m, 0, offset, ntohs(ip->ip_len) - offset);
    974 	if (csum == 0 && (m->m_pkthdr.csum_flags & M_CSUM_UDPv4) != 0)
    975 		csum = 0xffff;
    976 
    977 	offset += M_CSUM_DATA_IPv4_OFFSET(m->m_pkthdr.csum_data);
    978 
    979 	if ((offset + sizeof(u_int16_t)) > m->m_len) {
    980 		/* This happens when ip options were inserted */
    981 		m_copyback(m, offset, sizeof(csum), (void *)&csum);
    982 	} else {
    983 		*(u_int16_t *)(mtod(m, char *) + offset) = csum;
    984 	}
    985 }
    986 
    987 /*
    988  * Determine the maximum length of the options to be inserted;
    989  * we would far rather allocate too much space rather than too little.
    990  */
    991 u_int
    992 ip_optlen(struct inpcb *inp)
    993 {
    994 	struct mbuf *m = inp->inp_options;
    995 
    996 	if (m && m->m_len > offsetof(struct ipoption, ipopt_dst)) {
    997 		return (m->m_len - offsetof(struct ipoption, ipopt_dst));
    998 	}
    999 	return 0;
   1000 }
   1001 
   1002 /*
   1003  * Insert IP options into preformed packet.
   1004  * Adjust IP destination as required for IP source routing,
   1005  * as indicated by a non-zero in_addr at the start of the options.
   1006  */
   1007 static struct mbuf *
   1008 ip_insertoptions(struct mbuf *m, struct mbuf *opt, int *phlen)
   1009 {
   1010 	struct ipoption *p = mtod(opt, struct ipoption *);
   1011 	struct mbuf *n;
   1012 	struct ip *ip = mtod(m, struct ip *);
   1013 	unsigned optlen;
   1014 
   1015 	optlen = opt->m_len - sizeof(p->ipopt_dst);
   1016 	KASSERT(optlen % 4 == 0);
   1017 	if (optlen + ntohs(ip->ip_len) > IP_MAXPACKET)
   1018 		return m;		/* XXX should fail */
   1019 	if (!in_nullhost(p->ipopt_dst))
   1020 		ip->ip_dst = p->ipopt_dst;
   1021 	if (M_READONLY(m) || M_LEADINGSPACE(m) < optlen) {
   1022 		MGETHDR(n, M_DONTWAIT, MT_HEADER);
   1023 		if (n == NULL)
   1024 			return m;
   1025 		MCLAIM(n, m->m_owner);
   1026 		M_MOVE_PKTHDR(n, m);
   1027 		m->m_len -= sizeof(struct ip);
   1028 		m->m_data += sizeof(struct ip);
   1029 		n->m_next = m;
   1030 		n->m_len = optlen + sizeof(struct ip);
   1031 		n->m_data += max_linkhdr;
   1032 		memcpy(mtod(n, void *), ip, sizeof(struct ip));
   1033 		m = n;
   1034 	} else {
   1035 		m->m_data -= optlen;
   1036 		m->m_len += optlen;
   1037 		memmove(mtod(m, void *), ip, sizeof(struct ip));
   1038 	}
   1039 	m->m_pkthdr.len += optlen;
   1040 	ip = mtod(m, struct ip *);
   1041 	memcpy(ip + 1, p->ipopt_list, optlen);
   1042 	*phlen = sizeof(struct ip) + optlen;
   1043 	ip->ip_len = htons(ntohs(ip->ip_len) + optlen);
   1044 	return m;
   1045 }
   1046 
   1047 /*
   1048  * Copy options from ipsrc to ipdst, omitting those not copied during
   1049  * fragmentation.
   1050  */
   1051 int
   1052 ip_optcopy(struct ip *ipsrc, struct ip *ipdst)
   1053 {
   1054 	u_char *cp, *dp;
   1055 	int opt, optlen, cnt;
   1056 
   1057 	cp = (u_char *)(ipsrc + 1);
   1058 	dp = (u_char *)(ipdst + 1);
   1059 	cnt = (ipsrc->ip_hl << 2) - sizeof(struct ip);
   1060 	for (; cnt > 0; cnt -= optlen, cp += optlen) {
   1061 		opt = cp[0];
   1062 		if (opt == IPOPT_EOL)
   1063 			break;
   1064 		if (opt == IPOPT_NOP) {
   1065 			/* Preserve for IP mcast tunnel's LSRR alignment. */
   1066 			*dp++ = IPOPT_NOP;
   1067 			optlen = 1;
   1068 			continue;
   1069 		}
   1070 
   1071 		KASSERT(cnt >= IPOPT_OLEN + sizeof(*cp));
   1072 		optlen = cp[IPOPT_OLEN];
   1073 		KASSERT(optlen >= IPOPT_OLEN + sizeof(*cp) && optlen < cnt);
   1074 
   1075 		/* Invalid lengths should have been caught by ip_dooptions. */
   1076 		if (optlen > cnt)
   1077 			optlen = cnt;
   1078 		if (IPOPT_COPIED(opt)) {
   1079 			bcopy((void *)cp, (void *)dp, (unsigned)optlen);
   1080 			dp += optlen;
   1081 		}
   1082 	}
   1083 
   1084 	for (optlen = dp - (u_char *)(ipdst+1); optlen & 0x3; optlen++) {
   1085 		*dp++ = IPOPT_EOL;
   1086 	}
   1087 
   1088 	return optlen;
   1089 }
   1090 
   1091 /*
   1092  * IP socket option processing.
   1093  */
   1094 int
   1095 ip_ctloutput(int op, struct socket *so, struct sockopt *sopt)
   1096 {
   1097 	struct inpcb *inp = sotoinpcb(so);
   1098 	struct ip *ip = &inp->inp_ip;
   1099 	int inpflags = inp->inp_flags;
   1100 	int optval = 0, error = 0;
   1101 	struct in_pktinfo pktinfo;
   1102 
   1103 	KASSERT(solocked(so));
   1104 
   1105 	if (sopt->sopt_level != IPPROTO_IP) {
   1106 		if (sopt->sopt_level == SOL_SOCKET && sopt->sopt_name == SO_NOHEADER)
   1107 			return 0;
   1108 		return ENOPROTOOPT;
   1109 	}
   1110 
   1111 	switch (op) {
   1112 	case PRCO_SETOPT:
   1113 		switch (sopt->sopt_name) {
   1114 		case IP_OPTIONS:
   1115 #ifdef notyet
   1116 		case IP_RETOPTS:
   1117 #endif
   1118 			error = ip_pcbopts(inp, sopt);
   1119 			break;
   1120 
   1121 		case IP_TOS:
   1122 		case IP_TTL:
   1123 		case IP_MINTTL:
   1124 		case IP_RECVOPTS:
   1125 		case IP_RECVRETOPTS:
   1126 		case IP_RECVDSTADDR:
   1127 		case IP_RECVIF:
   1128 		case IP_RECVPKTINFO:
   1129 		case IP_RECVTTL:
   1130 			error = sockopt_getint(sopt, &optval);
   1131 			if (error)
   1132 				break;
   1133 
   1134 			switch (sopt->sopt_name) {
   1135 			case IP_TOS:
   1136 				ip->ip_tos = optval;
   1137 				break;
   1138 
   1139 			case IP_TTL:
   1140 				ip->ip_ttl = optval;
   1141 				break;
   1142 
   1143 			case IP_MINTTL:
   1144 				if (optval > 0 && optval <= MAXTTL)
   1145 					inp->inp_ip_minttl = optval;
   1146 				else
   1147 					error = EINVAL;
   1148 				break;
   1149 #define	OPTSET(bit) \
   1150 	if (optval) \
   1151 		inpflags |= bit; \
   1152 	else \
   1153 		inpflags &= ~bit;
   1154 
   1155 			case IP_RECVOPTS:
   1156 				OPTSET(INP_RECVOPTS);
   1157 				break;
   1158 
   1159 			case IP_RECVPKTINFO:
   1160 				OPTSET(INP_RECVPKTINFO);
   1161 				break;
   1162 
   1163 			case IP_RECVRETOPTS:
   1164 				OPTSET(INP_RECVRETOPTS);
   1165 				break;
   1166 
   1167 			case IP_RECVDSTADDR:
   1168 				OPTSET(INP_RECVDSTADDR);
   1169 				break;
   1170 
   1171 			case IP_RECVIF:
   1172 				OPTSET(INP_RECVIF);
   1173 				break;
   1174 
   1175 			case IP_RECVTTL:
   1176 				OPTSET(INP_RECVTTL);
   1177 				break;
   1178 			}
   1179 			break;
   1180 		case IP_PKTINFO:
   1181 			error = sockopt_getint(sopt, &optval);
   1182 			if (!error) {
   1183 				/* Linux compatibility */
   1184 				OPTSET(INP_RECVPKTINFO);
   1185 				break;
   1186 			}
   1187 			error = sockopt_get(sopt, &pktinfo, sizeof(pktinfo));
   1188 			if (error)
   1189 				break;
   1190 
   1191 			if (pktinfo.ipi_ifindex == 0) {
   1192 				inp->inp_prefsrcip = pktinfo.ipi_addr;
   1193 				break;
   1194 			}
   1195 
   1196 			/* Solaris compatibility */
   1197 			struct ifnet *ifp;
   1198 			struct in_ifaddr *ia;
   1199 			int s;
   1200 
   1201 			/* pick up primary address */
   1202 			s = pserialize_read_enter();
   1203 			ifp = if_byindex(pktinfo.ipi_ifindex);
   1204 			if (ifp == NULL) {
   1205 				pserialize_read_exit(s);
   1206 				error = EADDRNOTAVAIL;
   1207 				break;
   1208 			}
   1209 			ia = in_get_ia_from_ifp(ifp);
   1210 			if (ia == NULL) {
   1211 				pserialize_read_exit(s);
   1212 				error = EADDRNOTAVAIL;
   1213 				break;
   1214 			}
   1215 			inp->inp_prefsrcip = IA_SIN(ia)->sin_addr;
   1216 			pserialize_read_exit(s);
   1217 			break;
   1218 		break;
   1219 #undef OPTSET
   1220 
   1221 		case IP_MULTICAST_IF:
   1222 		case IP_MULTICAST_TTL:
   1223 		case IP_MULTICAST_LOOP:
   1224 		case IP_ADD_MEMBERSHIP:
   1225 		case IP_DROP_MEMBERSHIP:
   1226 			error = ip_setmoptions(&inp->inp_moptions, sopt);
   1227 			break;
   1228 
   1229 		case IP_PORTRANGE:
   1230 			error = sockopt_getint(sopt, &optval);
   1231 			if (error)
   1232 				break;
   1233 
   1234 			switch (optval) {
   1235 			case IP_PORTRANGE_DEFAULT:
   1236 			case IP_PORTRANGE_HIGH:
   1237 				inpflags &= ~(INP_LOWPORT);
   1238 				break;
   1239 
   1240 			case IP_PORTRANGE_LOW:
   1241 				inpflags |= INP_LOWPORT;
   1242 				break;
   1243 
   1244 			default:
   1245 				error = EINVAL;
   1246 				break;
   1247 			}
   1248 			break;
   1249 
   1250 		case IP_PORTALGO:
   1251 			error = sockopt_getint(sopt, &optval);
   1252 			if (error)
   1253 				break;
   1254 
   1255 			error = portalgo_algo_index_select(
   1256 			    (struct inpcb_hdr *)inp, optval);
   1257 			break;
   1258 
   1259 #if defined(IPSEC)
   1260 		case IP_IPSEC_POLICY:
   1261 			if (ipsec_enabled) {
   1262 				error = ipsec_set_policy(inp,
   1263 				    sopt->sopt_data, sopt->sopt_size,
   1264 				    curlwp->l_cred);
   1265 				break;
   1266 			}
   1267 			/*FALLTHROUGH*/
   1268 #endif /* IPSEC */
   1269 
   1270 		default:
   1271 			error = ENOPROTOOPT;
   1272 			break;
   1273 		}
   1274 		break;
   1275 
   1276 	case PRCO_GETOPT:
   1277 		switch (sopt->sopt_name) {
   1278 		case IP_OPTIONS:
   1279 		case IP_RETOPTS: {
   1280 			struct mbuf *mopts = inp->inp_options;
   1281 
   1282 			if (mopts) {
   1283 				struct mbuf *m;
   1284 
   1285 				m = m_copym(mopts, 0, M_COPYALL, M_DONTWAIT);
   1286 				if (m == NULL) {
   1287 					error = ENOBUFS;
   1288 					break;
   1289 				}
   1290 				error = sockopt_setmbuf(sopt, m);
   1291 			}
   1292 			break;
   1293 		}
   1294 		case IP_TOS:
   1295 		case IP_TTL:
   1296 		case IP_MINTTL:
   1297 		case IP_RECVOPTS:
   1298 		case IP_RECVRETOPTS:
   1299 		case IP_RECVDSTADDR:
   1300 		case IP_RECVIF:
   1301 		case IP_RECVPKTINFO:
   1302 		case IP_RECVTTL:
   1303 		case IP_ERRORMTU:
   1304 			switch (sopt->sopt_name) {
   1305 			case IP_TOS:
   1306 				optval = ip->ip_tos;
   1307 				break;
   1308 
   1309 			case IP_TTL:
   1310 				optval = ip->ip_ttl;
   1311 				break;
   1312 
   1313 			case IP_MINTTL:
   1314 				optval = inp->inp_ip_minttl;
   1315 				break;
   1316 
   1317 			case IP_ERRORMTU:
   1318 				optval = inp->inp_errormtu;
   1319 				break;
   1320 
   1321 #define	OPTBIT(bit)	(inpflags & bit ? 1 : 0)
   1322 
   1323 			case IP_RECVOPTS:
   1324 				optval = OPTBIT(INP_RECVOPTS);
   1325 				break;
   1326 
   1327 			case IP_RECVPKTINFO:
   1328 				optval = OPTBIT(INP_RECVPKTINFO);
   1329 				break;
   1330 
   1331 			case IP_RECVRETOPTS:
   1332 				optval = OPTBIT(INP_RECVRETOPTS);
   1333 				break;
   1334 
   1335 			case IP_RECVDSTADDR:
   1336 				optval = OPTBIT(INP_RECVDSTADDR);
   1337 				break;
   1338 
   1339 			case IP_RECVIF:
   1340 				optval = OPTBIT(INP_RECVIF);
   1341 				break;
   1342 
   1343 			case IP_RECVTTL:
   1344 				optval = OPTBIT(INP_RECVTTL);
   1345 				break;
   1346 			}
   1347 			error = sockopt_setint(sopt, optval);
   1348 			break;
   1349 
   1350 		case IP_PKTINFO:
   1351 			switch (sopt->sopt_size) {
   1352 			case sizeof(int):
   1353 				/* Linux compatibility */
   1354 				optval = OPTBIT(INP_RECVPKTINFO);
   1355 				error = sockopt_setint(sopt, optval);
   1356 				break;
   1357 			case sizeof(struct in_pktinfo):
   1358 				/* Solaris compatibility */
   1359 				pktinfo.ipi_ifindex = 0;
   1360 				pktinfo.ipi_addr = inp->inp_prefsrcip;
   1361 				error = sockopt_set(sopt, &pktinfo,
   1362 				    sizeof(pktinfo));
   1363 				break;
   1364 			default:
   1365 				/*
   1366 				 * While size is stuck at 0, and, later, if
   1367 				 * the caller doesn't use an exactly sized
   1368 				 * recipient for the data, default to Linux
   1369 				 * compatibility
   1370 				 */
   1371 				optval = OPTBIT(INP_RECVPKTINFO);
   1372 				error = sockopt_setint(sopt, optval);
   1373 				break;
   1374 			}
   1375 			break;
   1376 
   1377 #if 0	/* defined(IPSEC) */
   1378 		case IP_IPSEC_POLICY:
   1379 		{
   1380 			struct mbuf *m = NULL;
   1381 
   1382 			/* XXX this will return EINVAL as sopt is empty */
   1383 			error = ipsec_get_policy(inp, sopt->sopt_data,
   1384 			    sopt->sopt_size, &m);
   1385 			if (error == 0)
   1386 				error = sockopt_setmbuf(sopt, m);
   1387 			break;
   1388 		}
   1389 #endif /*IPSEC*/
   1390 
   1391 		case IP_MULTICAST_IF:
   1392 		case IP_MULTICAST_TTL:
   1393 		case IP_MULTICAST_LOOP:
   1394 		case IP_ADD_MEMBERSHIP:
   1395 		case IP_DROP_MEMBERSHIP:
   1396 			error = ip_getmoptions(inp->inp_moptions, sopt);
   1397 			break;
   1398 
   1399 		case IP_PORTRANGE:
   1400 			if (inpflags & INP_LOWPORT)
   1401 				optval = IP_PORTRANGE_LOW;
   1402 			else
   1403 				optval = IP_PORTRANGE_DEFAULT;
   1404 			error = sockopt_setint(sopt, optval);
   1405 			break;
   1406 
   1407 		case IP_PORTALGO:
   1408 			optval = inp->inp_portalgo;
   1409 			error = sockopt_setint(sopt, optval);
   1410 			break;
   1411 
   1412 		default:
   1413 			error = ENOPROTOOPT;
   1414 			break;
   1415 		}
   1416 		break;
   1417 	}
   1418 
   1419 	if (!error) {
   1420 		inp->inp_flags = inpflags;
   1421 	}
   1422 	return error;
   1423 }
   1424 
   1425 static int
   1426 ip_pktinfo_prepare(const struct in_pktinfo *pktinfo, struct ip_pktopts *pktopts,
   1427     int *flags, kauth_cred_t cred)
   1428 {
   1429 	struct ip_moptions *imo;
   1430 	int error = 0;
   1431 	bool addrset = false;
   1432 
   1433 	if (!in_nullhost(pktinfo->ipi_addr)) {
   1434 		pktopts->ippo_laddr.sin_addr = pktinfo->ipi_addr;
   1435 		/* EADDRNOTAVAIL? */
   1436 		error = in_pcbbindableaddr(&pktopts->ippo_laddr, cred);
   1437 		if (error != 0)
   1438 			return error;
   1439 		addrset = true;
   1440 	}
   1441 
   1442 	if (pktinfo->ipi_ifindex != 0) {
   1443 		if (!addrset) {
   1444 			struct ifnet *ifp;
   1445 			struct in_ifaddr *ia;
   1446 			int s;
   1447 
   1448 			/* pick up primary address */
   1449 			s = pserialize_read_enter();
   1450 			ifp = if_byindex(pktinfo->ipi_ifindex);
   1451 			if (ifp == NULL) {
   1452 				pserialize_read_exit(s);
   1453 				return EADDRNOTAVAIL;
   1454 			}
   1455 			ia = in_get_ia_from_ifp(ifp);
   1456 			if (ia == NULL) {
   1457 				pserialize_read_exit(s);
   1458 				return EADDRNOTAVAIL;
   1459 			}
   1460 			pktopts->ippo_laddr.sin_addr = IA_SIN(ia)->sin_addr;
   1461 			pserialize_read_exit(s);
   1462 		}
   1463 
   1464 		/*
   1465 		 * If specified ipi_ifindex,
   1466 		 * use copied or locally initialized ip_moptions.
   1467 		 * Original ip_moptions must not be modified.
   1468 		 */
   1469 		imo = &pktopts->ippo_imobuf;	/* local buf in pktopts */
   1470 		if (pktopts->ippo_imo != NULL) {
   1471 			memcpy(imo, pktopts->ippo_imo, sizeof(*imo));
   1472 		} else {
   1473 			memset(imo, 0, sizeof(*imo));
   1474 			imo->imo_multicast_ttl = IP_DEFAULT_MULTICAST_TTL;
   1475 			imo->imo_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
   1476 		}
   1477 		imo->imo_multicast_if_index = pktinfo->ipi_ifindex;
   1478 		pktopts->ippo_imo = imo;
   1479 		*flags |= IP_ROUTETOIFINDEX;
   1480 	}
   1481 	return error;
   1482 }
   1483 
   1484 /*
   1485  * Set up IP outgoing packet options. Even if control is NULL,
   1486  * pktopts->ippo_laddr and pktopts->ippo_imo are set and used.
   1487  */
   1488 int
   1489 ip_setpktopts(struct mbuf *control, struct ip_pktopts *pktopts, int *flags,
   1490     struct inpcb *inp, kauth_cred_t cred)
   1491 {
   1492 	struct cmsghdr *cm;
   1493 	struct in_pktinfo pktinfo;
   1494 	int error;
   1495 
   1496 	pktopts->ippo_imo = inp->inp_moptions;
   1497 
   1498 	struct in_addr *ia = in_nullhost(inp->inp_prefsrcip) ? &inp->inp_laddr :
   1499 	    &inp->inp_prefsrcip;
   1500 	sockaddr_in_init(&pktopts->ippo_laddr, ia, 0);
   1501 
   1502 	if (control == NULL)
   1503 		return 0;
   1504 
   1505 	/*
   1506 	 * XXX: Currently, we assume all the optional information is
   1507 	 * stored in a single mbuf.
   1508 	 */
   1509 	if (control->m_next)
   1510 		return EINVAL;
   1511 
   1512 	for (; control->m_len > 0;
   1513 	    control->m_data += CMSG_ALIGN(cm->cmsg_len),
   1514 	    control->m_len -= CMSG_ALIGN(cm->cmsg_len)) {
   1515 		cm = mtod(control, struct cmsghdr *);
   1516 		if ((control->m_len < sizeof(*cm)) ||
   1517 		    (cm->cmsg_len == 0) ||
   1518 		    (cm->cmsg_len > control->m_len)) {
   1519 			return EINVAL;
   1520 		}
   1521 		if (cm->cmsg_level != IPPROTO_IP)
   1522 			continue;
   1523 
   1524 		switch (cm->cmsg_type) {
   1525 		case IP_PKTINFO:
   1526 			if (cm->cmsg_len != CMSG_LEN(sizeof(pktinfo)))
   1527 				return EINVAL;
   1528 			memcpy(&pktinfo, CMSG_DATA(cm), sizeof(pktinfo));
   1529 			error = ip_pktinfo_prepare(&pktinfo, pktopts, flags,
   1530 			    cred);
   1531 			if (error)
   1532 				return error;
   1533 			break;
   1534 		case IP_SENDSRCADDR: /* FreeBSD compatibility */
   1535 			if (cm->cmsg_len != CMSG_LEN(sizeof(struct in_addr)))
   1536 				return EINVAL;
   1537 			pktinfo.ipi_ifindex = 0;
   1538 			pktinfo.ipi_addr =
   1539 			    ((struct in_pktinfo *)CMSG_DATA(cm))->ipi_addr;
   1540 			error = ip_pktinfo_prepare(&pktinfo, pktopts, flags,
   1541 			    cred);
   1542 			if (error)
   1543 				return error;
   1544 			break;
   1545 		default:
   1546 			return ENOPROTOOPT;
   1547 		}
   1548 	}
   1549 	return 0;
   1550 }
   1551 
   1552 /*
   1553  * Set up IP options in pcb for insertion in output packets.
   1554  * Store in mbuf with pointer in pcbopt, adding pseudo-option
   1555  * with destination address if source routed.
   1556  */
   1557 static int
   1558 ip_pcbopts(struct inpcb *inp, const struct sockopt *sopt)
   1559 {
   1560 	struct mbuf *m;
   1561 	const u_char *cp;
   1562 	u_char *dp;
   1563 	int cnt;
   1564 
   1565 	KASSERT(inp_locked(inp));
   1566 
   1567 	/* Turn off any old options. */
   1568 	if (inp->inp_options) {
   1569 		m_free(inp->inp_options);
   1570 	}
   1571 	inp->inp_options = NULL;
   1572 	if ((cnt = sopt->sopt_size) == 0) {
   1573 		/* Only turning off any previous options. */
   1574 		return 0;
   1575 	}
   1576 	cp = sopt->sopt_data;
   1577 
   1578 	if (cnt % 4) {
   1579 		/* Must be 4-byte aligned, because there's no padding. */
   1580 		return EINVAL;
   1581 	}
   1582 
   1583 	m = m_get(M_DONTWAIT, MT_SOOPTS);
   1584 	if (m == NULL)
   1585 		return ENOBUFS;
   1586 
   1587 	dp = mtod(m, u_char *);
   1588 	memset(dp, 0, sizeof(struct in_addr));
   1589 	dp += sizeof(struct in_addr);
   1590 	m->m_len = sizeof(struct in_addr);
   1591 
   1592 	/*
   1593 	 * IP option list according to RFC791. Each option is of the form
   1594 	 *
   1595 	 *	[optval] [olen] [(olen - 2) data bytes]
   1596 	 *
   1597 	 * We validate the list and copy options to an mbuf for prepending
   1598 	 * to data packets. The IP first-hop destination address will be
   1599 	 * stored before actual options and is zero if unset.
   1600 	 */
   1601 	while (cnt > 0) {
   1602 		uint8_t optval, olen, offset;
   1603 
   1604 		optval = cp[IPOPT_OPTVAL];
   1605 
   1606 		if (optval == IPOPT_EOL || optval == IPOPT_NOP) {
   1607 			olen = 1;
   1608 		} else {
   1609 			if (cnt < IPOPT_OLEN + 1)
   1610 				goto bad;
   1611 
   1612 			olen = cp[IPOPT_OLEN];
   1613 			if (olen < IPOPT_OLEN + 1 || olen > cnt)
   1614 				goto bad;
   1615 		}
   1616 
   1617 		if (optval == IPOPT_LSRR || optval == IPOPT_SSRR) {
   1618 			/*
   1619 			 * user process specifies route as:
   1620 			 *	->A->B->C->D
   1621 			 * D must be our final destination (but we can't
   1622 			 * check that since we may not have connected yet).
   1623 			 * A is first hop destination, which doesn't appear in
   1624 			 * actual IP option, but is stored before the options.
   1625 			 */
   1626 			if (olen < IPOPT_OFFSET + 1 + sizeof(struct in_addr))
   1627 				goto bad;
   1628 
   1629 			offset = cp[IPOPT_OFFSET];
   1630 			memcpy(mtod(m, u_char *), cp + IPOPT_OFFSET + 1,
   1631 			    sizeof(struct in_addr));
   1632 
   1633 			cp += sizeof(struct in_addr);
   1634 			cnt -= sizeof(struct in_addr);
   1635 			olen -= sizeof(struct in_addr);
   1636 
   1637 			if (m->m_len + olen > MAX_IPOPTLEN + sizeof(struct in_addr))
   1638 				goto bad;
   1639 
   1640 			memcpy(dp, cp, olen);
   1641 			dp[IPOPT_OPTVAL] = optval;
   1642 			dp[IPOPT_OLEN] = olen;
   1643 			dp[IPOPT_OFFSET] = offset;
   1644 			break;
   1645 		} else {
   1646 			if (m->m_len + olen > MAX_IPOPTLEN + sizeof(struct in_addr))
   1647 				goto bad;
   1648 
   1649 			memcpy(dp, cp, olen);
   1650 			break;
   1651 		}
   1652 
   1653 		dp += olen;
   1654 		m->m_len += olen;
   1655 
   1656 		if (optval == IPOPT_EOL)
   1657 			break;
   1658 
   1659 		cp += olen;
   1660 		cnt -= olen;
   1661 	}
   1662 
   1663 	inp->inp_options = m;
   1664 	return 0;
   1665 
   1666 bad:
   1667 	(void)m_free(m);
   1668 	return EINVAL;
   1669 }
   1670 
   1671 /*
   1672  * following RFC1724 section 3.3, 0.0.0.0/8 is interpreted as interface index.
   1673  * Must be called in a pserialize critical section.
   1674  */
   1675 static struct ifnet *
   1676 ip_multicast_if(struct in_addr *a, int *ifindexp)
   1677 {
   1678 	int ifindex;
   1679 	struct ifnet *ifp = NULL;
   1680 	struct in_ifaddr *ia;
   1681 
   1682 	if (ifindexp)
   1683 		*ifindexp = 0;
   1684 	if (ntohl(a->s_addr) >> 24 == 0) {
   1685 		ifindex = ntohl(a->s_addr) & 0xffffff;
   1686 		ifp = if_byindex(ifindex);
   1687 		if (!ifp)
   1688 			return NULL;
   1689 		if (ifindexp)
   1690 			*ifindexp = ifindex;
   1691 	} else {
   1692 		IN_ADDRHASH_READER_FOREACH(ia, a->s_addr) {
   1693 			if (in_hosteq(ia->ia_addr.sin_addr, *a) &&
   1694 			    (ia->ia_ifp->if_flags & IFF_MULTICAST) != 0) {
   1695 				ifp = ia->ia_ifp;
   1696 				if (if_is_deactivated(ifp))
   1697 					ifp = NULL;
   1698 				break;
   1699 			}
   1700 		}
   1701 	}
   1702 	return ifp;
   1703 }
   1704 
   1705 static int
   1706 ip_getoptval(const struct sockopt *sopt, u_int8_t *val, u_int maxval)
   1707 {
   1708 	u_int tval;
   1709 	u_char cval;
   1710 	int error;
   1711 
   1712 	if (sopt == NULL)
   1713 		return EINVAL;
   1714 
   1715 	switch (sopt->sopt_size) {
   1716 	case sizeof(u_char):
   1717 		error = sockopt_get(sopt, &cval, sizeof(u_char));
   1718 		tval = cval;
   1719 		break;
   1720 
   1721 	case sizeof(u_int):
   1722 		error = sockopt_get(sopt, &tval, sizeof(u_int));
   1723 		break;
   1724 
   1725 	default:
   1726 		error = EINVAL;
   1727 	}
   1728 
   1729 	if (error)
   1730 		return error;
   1731 
   1732 	if (tval > maxval)
   1733 		return EINVAL;
   1734 
   1735 	*val = tval;
   1736 	return 0;
   1737 }
   1738 
   1739 static int
   1740 ip_get_membership(const struct sockopt *sopt, struct ifnet **ifp,
   1741     struct psref *psref, struct in_addr *ia, bool add)
   1742 {
   1743 	int error;
   1744 	struct ip_mreq mreq;
   1745 
   1746 	error = sockopt_get(sopt, &mreq, sizeof(mreq));
   1747 	if (error)
   1748 		return error;
   1749 
   1750 	if (!IN_MULTICAST(mreq.imr_multiaddr.s_addr))
   1751 		return EINVAL;
   1752 
   1753 	memcpy(ia, &mreq.imr_multiaddr, sizeof(*ia));
   1754 
   1755 	if (in_nullhost(mreq.imr_interface)) {
   1756 		union {
   1757 			struct sockaddr		dst;
   1758 			struct sockaddr_in	dst4;
   1759 		} u;
   1760 		struct route ro;
   1761 
   1762 		if (!add) {
   1763 			*ifp = NULL;
   1764 			return 0;
   1765 		}
   1766 		/*
   1767 		 * If no interface address was provided, use the interface of
   1768 		 * the route to the given multicast address.
   1769 		 */
   1770 		struct rtentry *rt;
   1771 		memset(&ro, 0, sizeof(ro));
   1772 
   1773 		sockaddr_in_init(&u.dst4, ia, 0);
   1774 		error = rtcache_setdst(&ro, &u.dst);
   1775 		if (error != 0)
   1776 			return error;
   1777 		*ifp = (rt = rtcache_init(&ro)) != NULL ? rt->rt_ifp : NULL;
   1778 		if (*ifp != NULL) {
   1779 			if (if_is_deactivated(*ifp))
   1780 				*ifp = NULL;
   1781 			else
   1782 				if_acquire(*ifp, psref);
   1783 		}
   1784 		rtcache_unref(rt, &ro);
   1785 		rtcache_free(&ro);
   1786 	} else {
   1787 		int s = pserialize_read_enter();
   1788 		*ifp = ip_multicast_if(&mreq.imr_interface, NULL);
   1789 		if (!add && *ifp == NULL) {
   1790 			pserialize_read_exit(s);
   1791 			return EADDRNOTAVAIL;
   1792 		}
   1793 		if (*ifp != NULL) {
   1794 			if (if_is_deactivated(*ifp))
   1795 				*ifp = NULL;
   1796 			else
   1797 				if_acquire(*ifp, psref);
   1798 		}
   1799 		pserialize_read_exit(s);
   1800 	}
   1801 	return 0;
   1802 }
   1803 
   1804 /*
   1805  * Add a multicast group membership.
   1806  * Group must be a valid IP multicast address.
   1807  */
   1808 static int
   1809 ip_add_membership(struct ip_moptions *imo, const struct sockopt *sopt)
   1810 {
   1811 	struct ifnet *ifp = NULL;	// XXX: gcc [ppc]
   1812 	struct in_addr ia;
   1813 	int i, error, bound;
   1814 	struct psref psref;
   1815 
   1816 	/* imo is protected by solock or referenced only by the caller */
   1817 
   1818 	bound = curlwp_bind();
   1819 	if (sopt->sopt_size == sizeof(struct ip_mreq))
   1820 		error = ip_get_membership(sopt, &ifp, &psref, &ia, true);
   1821 	else {
   1822 #ifdef INET6
   1823 		error = ip6_get_membership(sopt, &ifp, &psref, &ia, sizeof(ia));
   1824 #else
   1825 		error = EINVAL;
   1826 #endif
   1827 	}
   1828 
   1829 	if (error)
   1830 		goto out;
   1831 
   1832 	/*
   1833 	 * See if we found an interface, and confirm that it
   1834 	 * supports multicast.
   1835 	 */
   1836 	if (ifp == NULL || (ifp->if_flags & IFF_MULTICAST) == 0) {
   1837 		error = EADDRNOTAVAIL;
   1838 		goto out;
   1839 	}
   1840 
   1841 	/*
   1842 	 * See if the membership already exists or if all the
   1843 	 * membership slots are full.
   1844 	 */
   1845 	for (i = 0; i < imo->imo_num_memberships; ++i) {
   1846 		if (imo->imo_membership[i]->inm_ifp == ifp &&
   1847 		    in_hosteq(imo->imo_membership[i]->inm_addr, ia))
   1848 			break;
   1849 	}
   1850 	if (i < imo->imo_num_memberships) {
   1851 		error = EADDRINUSE;
   1852 		goto out;
   1853 	}
   1854 
   1855 	if (i == IP_MAX_MEMBERSHIPS) {
   1856 		error = ETOOMANYREFS;
   1857 		goto out;
   1858 	}
   1859 
   1860 	/*
   1861 	 * Everything looks good; add a new record to the multicast
   1862 	 * address list for the given interface.
   1863 	 */
   1864 	IFNET_LOCK(ifp);
   1865 	imo->imo_membership[i] = in_addmulti(&ia, ifp);
   1866 	IFNET_UNLOCK(ifp);
   1867 	if (imo->imo_membership[i] == NULL) {
   1868 		error = ENOBUFS;
   1869 		goto out;
   1870 	}
   1871 
   1872 	++imo->imo_num_memberships;
   1873 	error = 0;
   1874 out:
   1875 	if_put(ifp, &psref);
   1876 	curlwp_bindx(bound);
   1877 	return error;
   1878 }
   1879 
   1880 /*
   1881  * Drop a multicast group membership.
   1882  * Group must be a valid IP multicast address.
   1883  */
   1884 static int
   1885 ip_drop_membership(struct ip_moptions *imo, const struct sockopt *sopt)
   1886 {
   1887 	struct in_addr ia = { .s_addr = 0 };	// XXX: gcc [ppc]
   1888 	struct ifnet *ifp = NULL;		// XXX: gcc [ppc]
   1889 	int i, error, bound;
   1890 	struct psref psref;
   1891 
   1892 	/* imo is protected by solock or referenced only by the caller */
   1893 
   1894 	bound = curlwp_bind();
   1895 	if (sopt->sopt_size == sizeof(struct ip_mreq))
   1896 		error = ip_get_membership(sopt, &ifp, &psref, &ia, false);
   1897 	else {
   1898 #ifdef INET6
   1899 		error = ip6_get_membership(sopt, &ifp, &psref, &ia, sizeof(ia));
   1900 #else
   1901 		error = EINVAL;
   1902 #endif
   1903 	}
   1904 
   1905 	if (error)
   1906 		goto out;
   1907 
   1908 	/*
   1909 	 * Find the membership in the membership array.
   1910 	 */
   1911 	for (i = 0; i < imo->imo_num_memberships; ++i) {
   1912 		if ((ifp == NULL ||
   1913 		     imo->imo_membership[i]->inm_ifp == ifp) &&
   1914 		    in_hosteq(imo->imo_membership[i]->inm_addr, ia))
   1915 			break;
   1916 	}
   1917 	if (i == imo->imo_num_memberships) {
   1918 		error = EADDRNOTAVAIL;
   1919 		goto out;
   1920 	}
   1921 
   1922 	/*
   1923 	 * Give up the multicast address record to which the
   1924 	 * membership points.
   1925 	 */
   1926 	struct ifnet *inm_ifp = imo->imo_membership[i]->inm_ifp;
   1927 	IFNET_LOCK(inm_ifp);
   1928 	in_delmulti(imo->imo_membership[i]);
   1929 	IFNET_UNLOCK(inm_ifp);
   1930 
   1931 	/*
   1932 	 * Remove the gap in the membership array.
   1933 	 */
   1934 	for (++i; i < imo->imo_num_memberships; ++i)
   1935 		imo->imo_membership[i-1] = imo->imo_membership[i];
   1936 	--imo->imo_num_memberships;
   1937 	error = 0;
   1938 out:
   1939 	if_put(ifp, &psref);
   1940 	curlwp_bindx(bound);
   1941 	return error;
   1942 }
   1943 
   1944 /*
   1945  * Set the IP multicast options in response to user setsockopt().
   1946  */
   1947 int
   1948 ip_setmoptions(struct ip_moptions **pimo, const struct sockopt *sopt)
   1949 {
   1950 	struct ip_moptions *imo = *pimo;
   1951 	struct in_addr addr;
   1952 	struct ifnet *ifp;
   1953 	int ifindex, error = 0;
   1954 
   1955 	/* The passed imo isn't NULL, it should be protected by solock */
   1956 
   1957 	if (!imo) {
   1958 		/*
   1959 		 * No multicast option buffer attached to the pcb;
   1960 		 * allocate one and initialize to default values.
   1961 		 */
   1962 		imo = kmem_intr_alloc(sizeof(*imo), KM_NOSLEEP);
   1963 		if (imo == NULL)
   1964 			return ENOBUFS;
   1965 
   1966 		imo->imo_multicast_if_index = 0;
   1967 		imo->imo_multicast_addr.s_addr = INADDR_ANY;
   1968 		imo->imo_multicast_ttl = IP_DEFAULT_MULTICAST_TTL;
   1969 		imo->imo_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
   1970 		imo->imo_num_memberships = 0;
   1971 		*pimo = imo;
   1972 	}
   1973 
   1974 	switch (sopt->sopt_name) {
   1975 	case IP_MULTICAST_IF: {
   1976 		int s;
   1977 		/*
   1978 		 * Select the interface for outgoing multicast packets.
   1979 		 */
   1980 		error = sockopt_get(sopt, &addr, sizeof(addr));
   1981 		if (error)
   1982 			break;
   1983 
   1984 		/*
   1985 		 * INADDR_ANY is used to remove a previous selection.
   1986 		 * When no interface is selected, a default one is
   1987 		 * chosen every time a multicast packet is sent.
   1988 		 */
   1989 		if (in_nullhost(addr)) {
   1990 			imo->imo_multicast_if_index = 0;
   1991 			break;
   1992 		}
   1993 		/*
   1994 		 * The selected interface is identified by its local
   1995 		 * IP address.  Find the interface and confirm that
   1996 		 * it supports multicasting.
   1997 		 */
   1998 		s = pserialize_read_enter();
   1999 		ifp = ip_multicast_if(&addr, &ifindex);
   2000 		if (ifp == NULL || (ifp->if_flags & IFF_MULTICAST) == 0) {
   2001 			pserialize_read_exit(s);
   2002 			error = EADDRNOTAVAIL;
   2003 			break;
   2004 		}
   2005 		imo->imo_multicast_if_index = ifp->if_index;
   2006 		pserialize_read_exit(s);
   2007 		if (ifindex)
   2008 			imo->imo_multicast_addr = addr;
   2009 		else
   2010 			imo->imo_multicast_addr.s_addr = INADDR_ANY;
   2011 		break;
   2012 	    }
   2013 
   2014 	case IP_MULTICAST_TTL:
   2015 		/*
   2016 		 * Set the IP time-to-live for outgoing multicast packets.
   2017 		 */
   2018 		error = ip_getoptval(sopt, &imo->imo_multicast_ttl, MAXTTL);
   2019 		break;
   2020 
   2021 	case IP_MULTICAST_LOOP:
   2022 		/*
   2023 		 * Set the loopback flag for outgoing multicast packets.
   2024 		 * Must be zero or one.
   2025 		 */
   2026 		error = ip_getoptval(sopt, &imo->imo_multicast_loop, 1);
   2027 		break;
   2028 
   2029 	case IP_ADD_MEMBERSHIP: /* IPV6_JOIN_GROUP */
   2030 		error = ip_add_membership(imo, sopt);
   2031 		break;
   2032 
   2033 	case IP_DROP_MEMBERSHIP: /* IPV6_LEAVE_GROUP */
   2034 		error = ip_drop_membership(imo, sopt);
   2035 		break;
   2036 
   2037 	default:
   2038 		error = EOPNOTSUPP;
   2039 		break;
   2040 	}
   2041 
   2042 	/*
   2043 	 * If all options have default values, no need to keep the mbuf.
   2044 	 */
   2045 	if (imo->imo_multicast_if_index == 0 &&
   2046 	    imo->imo_multicast_ttl == IP_DEFAULT_MULTICAST_TTL &&
   2047 	    imo->imo_multicast_loop == IP_DEFAULT_MULTICAST_LOOP &&
   2048 	    imo->imo_num_memberships == 0) {
   2049 		kmem_intr_free(imo, sizeof(*imo));
   2050 		*pimo = NULL;
   2051 	}
   2052 
   2053 	return error;
   2054 }
   2055 
   2056 /*
   2057  * Return the IP multicast options in response to user getsockopt().
   2058  */
   2059 int
   2060 ip_getmoptions(struct ip_moptions *imo, struct sockopt *sopt)
   2061 {
   2062 	struct in_addr addr;
   2063 	uint8_t optval;
   2064 	int error = 0;
   2065 
   2066 	/* imo is protected by solock or refereced only by the caller */
   2067 
   2068 	switch (sopt->sopt_name) {
   2069 	case IP_MULTICAST_IF:
   2070 		if (imo == NULL || imo->imo_multicast_if_index == 0)
   2071 			addr = zeroin_addr;
   2072 		else if (imo->imo_multicast_addr.s_addr) {
   2073 			/* return the value user has set */
   2074 			addr = imo->imo_multicast_addr;
   2075 		} else {
   2076 			struct ifnet *ifp;
   2077 			struct in_ifaddr *ia = NULL;
   2078 			int s = pserialize_read_enter();
   2079 
   2080 			ifp = if_byindex(imo->imo_multicast_if_index);
   2081 			if (ifp != NULL) {
   2082 				ia = in_get_ia_from_ifp(ifp);
   2083 			}
   2084 			addr = ia ? ia->ia_addr.sin_addr : zeroin_addr;
   2085 			pserialize_read_exit(s);
   2086 		}
   2087 		error = sockopt_set(sopt, &addr, sizeof(addr));
   2088 		break;
   2089 
   2090 	case IP_MULTICAST_TTL:
   2091 		optval = imo ? imo->imo_multicast_ttl
   2092 		    : IP_DEFAULT_MULTICAST_TTL;
   2093 
   2094 		error = sockopt_set(sopt, &optval, sizeof(optval));
   2095 		break;
   2096 
   2097 	case IP_MULTICAST_LOOP:
   2098 		optval = imo ? imo->imo_multicast_loop
   2099 		    : IP_DEFAULT_MULTICAST_LOOP;
   2100 
   2101 		error = sockopt_set(sopt, &optval, sizeof(optval));
   2102 		break;
   2103 
   2104 	default:
   2105 		error = EOPNOTSUPP;
   2106 	}
   2107 
   2108 	return error;
   2109 }
   2110 
   2111 /*
   2112  * Discard the IP multicast options.
   2113  */
   2114 void
   2115 ip_freemoptions(struct ip_moptions *imo)
   2116 {
   2117 	int i;
   2118 
   2119 	/* The owner of imo (inp) should be protected by solock */
   2120 
   2121 	if (imo != NULL) {
   2122 		for (i = 0; i < imo->imo_num_memberships; ++i) {
   2123 			struct in_multi *inm = imo->imo_membership[i];
   2124 			struct ifnet *ifp = inm->inm_ifp;
   2125 			IFNET_LOCK(ifp);
   2126 			in_delmulti(inm);
   2127 			/* ifp should not leave thanks to solock */
   2128 			IFNET_UNLOCK(ifp);
   2129 		}
   2130 
   2131 		kmem_intr_free(imo, sizeof(*imo));
   2132 	}
   2133 }
   2134 
   2135 /*
   2136  * Routine called from ip_output() to loop back a copy of an IP multicast
   2137  * packet to the input queue of a specified interface.  Note that this
   2138  * calls the output routine of the loopback "driver", but with an interface
   2139  * pointer that might NOT be lo0ifp -- easier than replicating that code here.
   2140  */
   2141 static void
   2142 ip_mloopback(struct ifnet *ifp, struct mbuf *m, const struct sockaddr_in *dst)
   2143 {
   2144 	struct ip *ip;
   2145 	struct mbuf *copym;
   2146 
   2147 	copym = m_copypacket(m, M_DONTWAIT);
   2148 	if (copym != NULL &&
   2149 	    (copym->m_flags & M_EXT || copym->m_len < sizeof(struct ip)))
   2150 		copym = m_pullup(copym, sizeof(struct ip));
   2151 	if (copym == NULL)
   2152 		return;
   2153 	/*
   2154 	 * We don't bother to fragment if the IP length is greater
   2155 	 * than the interface's MTU.  Can this possibly matter?
   2156 	 */
   2157 	ip = mtod(copym, struct ip *);
   2158 
   2159 	if (copym->m_pkthdr.csum_flags & (M_CSUM_TCPv4|M_CSUM_UDPv4)) {
   2160 		in_delayed_cksum(copym);
   2161 		copym->m_pkthdr.csum_flags &=
   2162 		    ~(M_CSUM_TCPv4|M_CSUM_UDPv4);
   2163 	}
   2164 
   2165 	ip->ip_sum = 0;
   2166 	ip->ip_sum = in_cksum(copym, ip->ip_hl << 2);
   2167 	KERNEL_LOCK_UNLESS_NET_MPSAFE();
   2168 	(void)looutput(ifp, copym, sintocsa(dst), NULL);
   2169 	KERNEL_UNLOCK_UNLESS_NET_MPSAFE();
   2170 }
   2171 
   2172 /*
   2173  * Ensure sending address is valid.
   2174  * Returns 0 on success, -1 if an error should be sent back or 1
   2175  * if the packet could be dropped without error (protocol dependent).
   2176  */
   2177 static int
   2178 ip_ifaddrvalid(const struct in_ifaddr *ia)
   2179 {
   2180 
   2181 	if (ia->ia_addr.sin_addr.s_addr == INADDR_ANY)
   2182 		return 0;
   2183 
   2184 	if (ia->ia4_flags & IN_IFF_DUPLICATED)
   2185 		return -1;
   2186 	else if (ia->ia4_flags & (IN_IFF_TENTATIVE | IN_IFF_DETACHED))
   2187 		return 1;
   2188 
   2189 	return 0;
   2190 }
   2191