Home | History | Annotate | Line # | Download | only in netinet6
ip6_output.c revision 1.231.2.1
      1 /*	$NetBSD: ip6_output.c,v 1.231.2.1 2023/03/23 12:03:04 martin Exp $	*/
      2 /*	$KAME: ip6_output.c,v 1.172 2001/03/25 09:55:56 itojun Exp $	*/
      3 
      4 /*
      5  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
      6  * All rights reserved.
      7  *
      8  * Redistribution and use in source and binary forms, with or without
      9  * modification, are permitted provided that the following conditions
     10  * are met:
     11  * 1. Redistributions of source code must retain the above copyright
     12  *    notice, this list of conditions and the following disclaimer.
     13  * 2. Redistributions in binary form must reproduce the above copyright
     14  *    notice, this list of conditions and the following disclaimer in the
     15  *    documentation and/or other materials provided with the distribution.
     16  * 3. Neither the name of the project nor the names of its contributors
     17  *    may be used to endorse or promote products derived from this software
     18  *    without specific prior written permission.
     19  *
     20  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
     21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
     24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     30  * SUCH DAMAGE.
     31  */
     32 
     33 /*
     34  * Copyright (c) 1982, 1986, 1988, 1990, 1993
     35  *	The Regents of the University of California.  All rights reserved.
     36  *
     37  * Redistribution and use in source and binary forms, with or without
     38  * modification, are permitted provided that the following conditions
     39  * are met:
     40  * 1. Redistributions of source code must retain the above copyright
     41  *    notice, this list of conditions and the following disclaimer.
     42  * 2. Redistributions in binary form must reproduce the above copyright
     43  *    notice, this list of conditions and the following disclaimer in the
     44  *    documentation and/or other materials provided with the distribution.
     45  * 3. Neither the name of the University nor the names of its contributors
     46  *    may be used to endorse or promote products derived from this software
     47  *    without specific prior written permission.
     48  *
     49  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     50  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     51  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     52  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     53  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     54  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     55  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     56  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     57  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     58  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     59  * SUCH DAMAGE.
     60  *
     61  *	@(#)ip_output.c	8.3 (Berkeley) 1/21/94
     62  */
     63 
     64 #include <sys/cdefs.h>
     65 __KERNEL_RCSID(0, "$NetBSD: ip6_output.c,v 1.231.2.1 2023/03/23 12:03:04 martin Exp $");
     66 
     67 #ifdef _KERNEL_OPT
     68 #include "opt_inet.h"
     69 #include "opt_inet6.h"
     70 #include "opt_ipsec.h"
     71 #endif
     72 
     73 #include <sys/param.h>
     74 #include <sys/malloc.h>
     75 #include <sys/mbuf.h>
     76 #include <sys/errno.h>
     77 #include <sys/socket.h>
     78 #include <sys/socketvar.h>
     79 #include <sys/syslog.h>
     80 #include <sys/systm.h>
     81 #include <sys/proc.h>
     82 #include <sys/kauth.h>
     83 
     84 #include <net/if.h>
     85 #include <net/route.h>
     86 #include <net/pfil.h>
     87 
     88 #include <netinet/in.h>
     89 #include <netinet/in_var.h>
     90 #include <netinet/ip6.h>
     91 #include <netinet/ip_var.h>
     92 #include <netinet/icmp6.h>
     93 #include <netinet/in_offload.h>
     94 #include <netinet/portalgo.h>
     95 #include <netinet6/in6_offload.h>
     96 #include <netinet6/ip6_var.h>
     97 #include <netinet6/ip6_private.h>
     98 #include <netinet6/in6_pcb.h>
     99 #include <netinet6/nd6.h>
    100 #include <netinet6/ip6protosw.h>
    101 #include <netinet6/scope6_var.h>
    102 
    103 #ifdef IPSEC
    104 #include <netipsec/ipsec.h>
    105 #include <netipsec/ipsec6.h>
    106 #include <netipsec/key.h>
    107 #endif
    108 
    109 extern pfil_head_t *inet6_pfil_hook;	/* XXX */
    110 
    111 struct ip6_exthdrs {
    112 	struct mbuf *ip6e_ip6;
    113 	struct mbuf *ip6e_hbh;
    114 	struct mbuf *ip6e_dest1;
    115 	struct mbuf *ip6e_rthdr;
    116 	struct mbuf *ip6e_dest2;
    117 };
    118 
    119 static int ip6_pcbopt(int, u_char *, int, struct ip6_pktopts **,
    120 	kauth_cred_t, int);
    121 static int ip6_getpcbopt(struct ip6_pktopts *, int, struct sockopt *);
    122 static int ip6_setpktopt(int, u_char *, int, struct ip6_pktopts *, kauth_cred_t,
    123 	int, int, int);
    124 static int ip6_setmoptions(const struct sockopt *, struct inpcb *);
    125 static int ip6_getmoptions(struct sockopt *, struct inpcb *);
    126 static int ip6_copyexthdr(struct mbuf **, void *, int);
    127 static int ip6_insertfraghdr(struct mbuf *, struct mbuf *, int,
    128 	struct ip6_frag **);
    129 static int ip6_insert_jumboopt(struct ip6_exthdrs *, u_int32_t);
    130 static int ip6_splithdr(struct mbuf *, struct ip6_exthdrs *);
    131 static int ip6_getpmtu(struct rtentry *, struct ifnet *, u_long *, int *);
    132 static int copypktopts(struct ip6_pktopts *, struct ip6_pktopts *, int);
    133 static int ip6_ifaddrvalid(const struct in6_addr *, const struct in6_addr *);
    134 static int ip6_handle_rthdr(struct ip6_rthdr *, struct ip6_hdr *);
    135 
    136 #ifdef RFC2292
    137 static int ip6_pcbopts(struct ip6_pktopts **, struct socket *, struct sockopt *);
    138 #endif
    139 
    140 static int
    141 ip6_handle_rthdr(struct ip6_rthdr *rh, struct ip6_hdr *ip6)
    142 {
    143 	int error = 0;
    144 
    145 	switch (rh->ip6r_type) {
    146 	case IPV6_RTHDR_TYPE_0:
    147 		/* Dropped, RFC5095. */
    148 	default:	/* is it possible? */
    149 		error = EINVAL;
    150 	}
    151 
    152 	return error;
    153 }
    154 
    155 /*
    156  * Send an IP packet to a host.
    157  */
    158 int
    159 ip6_if_output(struct ifnet * const ifp, struct ifnet * const origifp,
    160     struct mbuf * const m, const struct sockaddr_in6 * const dst,
    161     const struct rtentry *rt)
    162 {
    163 	int error = 0;
    164 
    165 	if (rt != NULL) {
    166 		error = rt_check_reject_route(rt, ifp);
    167 		if (error != 0) {
    168 			IP6_STATINC(IP6_STAT_RTREJECT);
    169 			m_freem(m);
    170 			return error;
    171 		}
    172 	}
    173 
    174 	if ((ifp->if_flags & IFF_LOOPBACK) != 0)
    175 		error = if_output_lock(ifp, origifp, m, sin6tocsa(dst), rt);
    176 	else
    177 		error = if_output_lock(ifp, ifp, m, sin6tocsa(dst), rt);
    178 	return error;
    179 }
    180 
    181 /*
    182  * IP6 output. The packet in mbuf chain m contains a skeletal IP6
    183  * header (with pri, len, nxt, hlim, src, dst).
    184  *
    185  * This function may modify ver and hlim only. The mbuf chain containing the
    186  * packet will be freed. The mbuf opt, if present, will not be freed.
    187  *
    188  * Type of "mtu": rt_rmx.rmx_mtu is u_long, ifnet.ifr_mtu is int, and
    189  * nd_ifinfo.linkmtu is u_int32_t. So we use u_long to hold largest one,
    190  * which is rt_rmx.rmx_mtu.
    191  */
    192 int
    193 ip6_output(
    194     struct mbuf *m0,
    195     struct ip6_pktopts *opt,
    196     struct route *ro,
    197     int flags,
    198     struct ip6_moptions *im6o,
    199     struct inpcb *inp,
    200     struct ifnet **ifpp		/* XXX: just for statistics */
    201 )
    202 {
    203 	struct ip6_hdr *ip6, *mhip6;
    204 	struct ifnet *ifp = NULL, *origifp = NULL;
    205 	struct mbuf *m = m0;
    206 	int tlen, len, off;
    207 	bool tso;
    208 	struct route ip6route;
    209 	struct rtentry *rt = NULL, *rt_pmtu;
    210 	const struct sockaddr_in6 *dst;
    211 	struct sockaddr_in6 src_sa, dst_sa;
    212 	int error = 0;
    213 	struct in6_ifaddr *ia = NULL;
    214 	u_long mtu;
    215 	int alwaysfrag, dontfrag;
    216 	u_int32_t optlen = 0, plen = 0, unfragpartlen = 0;
    217 	struct ip6_exthdrs exthdrs;
    218 	struct in6_addr finaldst, src0, dst0;
    219 	u_int32_t zone;
    220 	struct route *ro_pmtu = NULL;
    221 	int hdrsplit = 0;
    222 	int needipsec = 0;
    223 #ifdef IPSEC
    224 	struct secpolicy *sp = NULL;
    225 #endif
    226 	struct psref psref, psref_ia;
    227 	int bound = curlwp_bind();
    228 	bool release_psref_ia = false;
    229 
    230 #ifdef DIAGNOSTIC
    231 	if ((m->m_flags & M_PKTHDR) == 0)
    232 		panic("ip6_output: no HDR");
    233 	if ((m->m_pkthdr.csum_flags &
    234 	    (M_CSUM_TCPv4|M_CSUM_UDPv4|M_CSUM_TSOv4)) != 0) {
    235 		panic("ip6_output: IPv4 checksum offload flags: %d",
    236 		    m->m_pkthdr.csum_flags);
    237 	}
    238 	if ((m->m_pkthdr.csum_flags & (M_CSUM_TCPv6|M_CSUM_UDPv6)) ==
    239 	    (M_CSUM_TCPv6|M_CSUM_UDPv6)) {
    240 		panic("ip6_output: conflicting checksum offload flags: %d",
    241 		    m->m_pkthdr.csum_flags);
    242 	}
    243 #endif
    244 
    245 	M_CSUM_DATA_IPv6_SET(m->m_pkthdr.csum_data, sizeof(struct ip6_hdr));
    246 
    247 #define MAKE_EXTHDR(hp, mp)						\
    248     do {								\
    249 	if (hp) {							\
    250 		struct ip6_ext *eh = (struct ip6_ext *)(hp);		\
    251 		error = ip6_copyexthdr((mp), (void *)(hp), 		\
    252 		    ((eh)->ip6e_len + 1) << 3);				\
    253 		if (error)						\
    254 			goto freehdrs;					\
    255 	}								\
    256     } while (/*CONSTCOND*/ 0)
    257 
    258 	memset(&exthdrs, 0, sizeof(exthdrs));
    259 	if (opt) {
    260 		/* Hop-by-Hop options header */
    261 		MAKE_EXTHDR(opt->ip6po_hbh, &exthdrs.ip6e_hbh);
    262 		/* Destination options header (1st part) */
    263 		MAKE_EXTHDR(opt->ip6po_dest1, &exthdrs.ip6e_dest1);
    264 		/* Routing header */
    265 		MAKE_EXTHDR(opt->ip6po_rthdr, &exthdrs.ip6e_rthdr);
    266 		/* Destination options header (2nd part) */
    267 		MAKE_EXTHDR(opt->ip6po_dest2, &exthdrs.ip6e_dest2);
    268 	}
    269 
    270 	/*
    271 	 * Calculate the total length of the extension header chain.
    272 	 * Keep the length of the unfragmentable part for fragmentation.
    273 	 */
    274 	optlen = 0;
    275 	if (exthdrs.ip6e_hbh)
    276 		optlen += exthdrs.ip6e_hbh->m_len;
    277 	if (exthdrs.ip6e_dest1)
    278 		optlen += exthdrs.ip6e_dest1->m_len;
    279 	if (exthdrs.ip6e_rthdr)
    280 		optlen += exthdrs.ip6e_rthdr->m_len;
    281 	unfragpartlen = optlen + sizeof(struct ip6_hdr);
    282 	/* NOTE: we don't add AH/ESP length here. do that later. */
    283 	if (exthdrs.ip6e_dest2)
    284 		optlen += exthdrs.ip6e_dest2->m_len;
    285 
    286 #ifdef IPSEC
    287 	if (ipsec_used) {
    288 		/* Check the security policy (SP) for the packet */
    289 		sp = ipsec6_check_policy(m, inp, flags, &needipsec, &error);
    290 		if (error != 0) {
    291 			/*
    292 			 * Hack: -EINVAL is used to signal that a packet
    293 			 * should be silently discarded.  This is typically
    294 			 * because we asked key management for an SA and
    295 			 * it was delayed (e.g. kicked up to IKE).
    296 			 */
    297 			if (error == -EINVAL)
    298 				error = 0;
    299 			IP6_STATINC(IP6_STAT_IPSECDROP_OUT);
    300 			goto freehdrs;
    301 		}
    302 	}
    303 #endif
    304 
    305 	if (needipsec &&
    306 	    (m->m_pkthdr.csum_flags & (M_CSUM_UDPv6|M_CSUM_TCPv6)) != 0) {
    307 		in6_undefer_cksum_tcpudp(m);
    308 		m->m_pkthdr.csum_flags &= ~(M_CSUM_UDPv6|M_CSUM_TCPv6);
    309 	}
    310 
    311 	/*
    312 	 * If we need IPsec, or there is at least one extension header,
    313 	 * separate IP6 header from the payload.
    314 	 */
    315 	if ((needipsec || optlen) && !hdrsplit) {
    316 		if ((error = ip6_splithdr(m, &exthdrs)) != 0) {
    317 			IP6_STATINC(IP6_STAT_ODROPPED);
    318 			m = NULL;
    319 			goto freehdrs;
    320 		}
    321 		m = exthdrs.ip6e_ip6;
    322 		hdrsplit++;
    323 	}
    324 
    325 	/* adjust pointer */
    326 	ip6 = mtod(m, struct ip6_hdr *);
    327 
    328 	/* adjust mbuf packet header length */
    329 	m->m_pkthdr.len += optlen;
    330 	plen = m->m_pkthdr.len - sizeof(*ip6);
    331 
    332 	/* If this is a jumbo payload, insert a jumbo payload option. */
    333 	if (plen > IPV6_MAXPACKET) {
    334 		if (!hdrsplit) {
    335 			if ((error = ip6_splithdr(m, &exthdrs)) != 0) {
    336 				IP6_STATINC(IP6_STAT_ODROPPED);
    337 				m = NULL;
    338 				goto freehdrs;
    339 			}
    340 			m = exthdrs.ip6e_ip6;
    341 			hdrsplit++;
    342 		}
    343 		/* adjust pointer */
    344 		ip6 = mtod(m, struct ip6_hdr *);
    345 		if ((error = ip6_insert_jumboopt(&exthdrs, plen)) != 0) {
    346 			IP6_STATINC(IP6_STAT_ODROPPED);
    347 			goto freehdrs;
    348 		}
    349 		optlen += 8; /* XXX JUMBOOPTLEN */
    350 		ip6->ip6_plen = 0;
    351 	} else
    352 		ip6->ip6_plen = htons(plen);
    353 
    354 	/*
    355 	 * Concatenate headers and fill in next header fields.
    356 	 * Here we have, on "m"
    357 	 *	IPv6 payload
    358 	 * and we insert headers accordingly.  Finally, we should be getting:
    359 	 *	IPv6 hbh dest1 rthdr ah* [esp* dest2 payload]
    360 	 *
    361 	 * during the header composing process, "m" points to IPv6 header.
    362 	 * "mprev" points to an extension header prior to esp.
    363 	 */
    364 	{
    365 		u_char *nexthdrp = &ip6->ip6_nxt;
    366 		struct mbuf *mprev = m;
    367 
    368 		/*
    369 		 * we treat dest2 specially.  this makes IPsec processing
    370 		 * much easier.  the goal here is to make mprev point the
    371 		 * mbuf prior to dest2.
    372 		 *
    373 		 * result: IPv6 dest2 payload
    374 		 * m and mprev will point to IPv6 header.
    375 		 */
    376 		if (exthdrs.ip6e_dest2) {
    377 			if (!hdrsplit)
    378 				panic("assumption failed: hdr not split");
    379 			exthdrs.ip6e_dest2->m_next = m->m_next;
    380 			m->m_next = exthdrs.ip6e_dest2;
    381 			*mtod(exthdrs.ip6e_dest2, u_char *) = ip6->ip6_nxt;
    382 			ip6->ip6_nxt = IPPROTO_DSTOPTS;
    383 		}
    384 
    385 #define MAKE_CHAIN(m, mp, p, i)\
    386     do {\
    387 	if (m) {\
    388 		if (!hdrsplit) \
    389 			panic("assumption failed: hdr not split"); \
    390 		*mtod((m), u_char *) = *(p);\
    391 		*(p) = (i);\
    392 		p = mtod((m), u_char *);\
    393 		(m)->m_next = (mp)->m_next;\
    394 		(mp)->m_next = (m);\
    395 		(mp) = (m);\
    396 	}\
    397     } while (/*CONSTCOND*/ 0)
    398 		/*
    399 		 * result: IPv6 hbh dest1 rthdr dest2 payload
    400 		 * m will point to IPv6 header.  mprev will point to the
    401 		 * extension header prior to dest2 (rthdr in the above case).
    402 		 */
    403 		MAKE_CHAIN(exthdrs.ip6e_hbh, mprev, nexthdrp, IPPROTO_HOPOPTS);
    404 		MAKE_CHAIN(exthdrs.ip6e_dest1, mprev, nexthdrp,
    405 		    IPPROTO_DSTOPTS);
    406 		MAKE_CHAIN(exthdrs.ip6e_rthdr, mprev, nexthdrp,
    407 		    IPPROTO_ROUTING);
    408 
    409 		M_CSUM_DATA_IPv6_SET(m->m_pkthdr.csum_data,
    410 		    sizeof(struct ip6_hdr) + optlen);
    411 	}
    412 
    413 	/* Need to save for pmtu */
    414 	finaldst = ip6->ip6_dst;
    415 
    416 	/*
    417 	 * If there is a routing header, replace destination address field
    418 	 * with the first hop of the routing header.
    419 	 */
    420 	if (exthdrs.ip6e_rthdr) {
    421 		struct ip6_rthdr *rh;
    422 
    423 		rh = mtod(exthdrs.ip6e_rthdr, struct ip6_rthdr *);
    424 
    425 		error = ip6_handle_rthdr(rh, ip6);
    426 		if (error != 0) {
    427 			IP6_STATINC(IP6_STAT_ODROPPED);
    428 			goto bad;
    429 		}
    430 	}
    431 
    432 	/* Source address validation */
    433 	if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src) &&
    434 	    (flags & IPV6_UNSPECSRC) == 0) {
    435 		error = EOPNOTSUPP;
    436 		IP6_STATINC(IP6_STAT_BADSCOPE);
    437 		goto bad;
    438 	}
    439 	if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_src)) {
    440 		error = EOPNOTSUPP;
    441 		IP6_STATINC(IP6_STAT_BADSCOPE);
    442 		goto bad;
    443 	}
    444 
    445 	IP6_STATINC(IP6_STAT_LOCALOUT);
    446 
    447 	/*
    448 	 * Route packet.
    449 	 */
    450 	/* initialize cached route */
    451 	if (ro == NULL) {
    452 		memset(&ip6route, 0, sizeof(ip6route));
    453 		ro = &ip6route;
    454 	}
    455 	ro_pmtu = ro;
    456 	if (opt && opt->ip6po_rthdr)
    457 		ro = &opt->ip6po_route;
    458 
    459 	/*
    460 	 * if specified, try to fill in the traffic class field.
    461 	 * do not override if a non-zero value is already set.
    462 	 * we check the diffserv field and the ecn field separately.
    463 	 */
    464 	if (opt && opt->ip6po_tclass >= 0) {
    465 		int mask = 0;
    466 
    467 		if ((ip6->ip6_flow & htonl(0xfc << 20)) == 0)
    468 			mask |= 0xfc;
    469 		if ((ip6->ip6_flow & htonl(0x03 << 20)) == 0)
    470 			mask |= 0x03;
    471 		if (mask != 0)
    472 			ip6->ip6_flow |= htonl((opt->ip6po_tclass & mask) << 20);
    473 	}
    474 
    475 	/* fill in or override the hop limit field, if necessary. */
    476 	if (opt && opt->ip6po_hlim != -1)
    477 		ip6->ip6_hlim = opt->ip6po_hlim & 0xff;
    478 	else if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
    479 		if (im6o != NULL)
    480 			ip6->ip6_hlim = im6o->im6o_multicast_hlim;
    481 		else
    482 			ip6->ip6_hlim = ip6_defmcasthlim;
    483 	}
    484 
    485 #ifdef IPSEC
    486 	if (needipsec) {
    487 		int s = splsoftnet();
    488 		error = ipsec6_process_packet(m, sp->req, flags);
    489 		splx(s);
    490 
    491 		/*
    492 		 * Preserve KAME behaviour: ENOENT can be returned
    493 		 * when an SA acquire is in progress.  Don't propagate
    494 		 * this to user-level; it confuses applications.
    495 		 * XXX this will go away when the SADB is redone.
    496 		 */
    497 		if (error == ENOENT)
    498 			error = 0;
    499 
    500 		goto done;
    501 	}
    502 #endif
    503 
    504 	/* adjust pointer */
    505 	ip6 = mtod(m, struct ip6_hdr *);
    506 
    507 	sockaddr_in6_init(&dst_sa, &ip6->ip6_dst, 0, 0, 0);
    508 
    509 	/* We do not need a route for multicast */
    510 	if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
    511 		struct in6_pktinfo *pi = NULL;
    512 
    513 		/*
    514 		 * If the outgoing interface for the address is specified by
    515 		 * the caller, use it.
    516 		 */
    517 		if (opt && (pi = opt->ip6po_pktinfo) != NULL) {
    518 			/* XXX boundary check is assumed to be already done. */
    519 			ifp = if_get_byindex(pi->ipi6_ifindex, &psref);
    520 		} else if (im6o != NULL) {
    521 			ifp = if_get_byindex(im6o->im6o_multicast_if_index,
    522 			    &psref);
    523 		}
    524 	}
    525 
    526 	if (ifp == NULL) {
    527 		error = in6_selectroute(&dst_sa, opt, &ro, &rt, true);
    528 		if (error != 0)
    529 			goto bad;
    530 		ifp = if_get_byindex(rt->rt_ifp->if_index, &psref);
    531 	}
    532 
    533 	if (rt == NULL) {
    534 		/*
    535 		 * If in6_selectroute() does not return a route entry,
    536 		 * dst may not have been updated.
    537 		 */
    538 		error = rtcache_setdst(ro, sin6tosa(&dst_sa));
    539 		if (error) {
    540 			IP6_STATINC(IP6_STAT_ODROPPED);
    541 			goto bad;
    542 		}
    543 	}
    544 
    545 	/*
    546 	 * then rt (for unicast) and ifp must be non-NULL valid values.
    547 	 */
    548 	if ((flags & IPV6_FORWARDING) == 0) {
    549 		/* XXX: the FORWARDING flag can be set for mrouting. */
    550 		in6_ifstat_inc(ifp, ifs6_out_request);
    551 	}
    552 	if (rt != NULL) {
    553 		ia = (struct in6_ifaddr *)(rt->rt_ifa);
    554 		rt->rt_use++;
    555 	}
    556 
    557 	/*
    558 	 * The outgoing interface must be in the zone of source and
    559 	 * destination addresses.  We should use ia_ifp to support the
    560 	 * case of sending packets to an address of our own.
    561 	 */
    562 	if (ia != NULL) {
    563 		origifp = ia->ia_ifp;
    564 		if (if_is_deactivated(origifp)) {
    565 			IP6_STATINC(IP6_STAT_ODROPPED);
    566 			goto bad;
    567 		}
    568 		if_acquire(origifp, &psref_ia);
    569 		release_psref_ia = true;
    570 	} else
    571 		origifp = ifp;
    572 
    573 	src0 = ip6->ip6_src;
    574 	if (in6_setscope(&src0, origifp, &zone))
    575 		goto badscope;
    576 	sockaddr_in6_init(&src_sa, &ip6->ip6_src, 0, 0, 0);
    577 	if (sa6_recoverscope(&src_sa) || zone != src_sa.sin6_scope_id)
    578 		goto badscope;
    579 
    580 	dst0 = ip6->ip6_dst;
    581 	if (in6_setscope(&dst0, origifp, &zone))
    582 		goto badscope;
    583 	/* re-initialize to be sure */
    584 	sockaddr_in6_init(&dst_sa, &ip6->ip6_dst, 0, 0, 0);
    585 	if (sa6_recoverscope(&dst_sa) || zone != dst_sa.sin6_scope_id)
    586 		goto badscope;
    587 
    588 	/* scope check is done. */
    589 
    590 	/* Ensure we only send from a valid address. */
    591 	if ((ifp->if_flags & IFF_LOOPBACK) == 0 &&
    592 	    (flags & IPV6_FORWARDING) == 0 &&
    593 	    (error = ip6_ifaddrvalid(&src0, &dst0)) != 0)
    594 	{
    595 		char ip6buf[INET6_ADDRSTRLEN];
    596 		nd6log(LOG_ERR,
    597 		    "refusing to send from invalid address %s (pid %d)\n",
    598 		    IN6_PRINT(ip6buf, &src0), curproc->p_pid);
    599 		IP6_STATINC(IP6_STAT_ODROPPED);
    600 		in6_ifstat_inc(origifp, ifs6_out_discard);
    601 		if (error == 1)
    602 			/*
    603 			 * Address exists, but is tentative or detached.
    604 			 * We can't send from it because it's invalid,
    605 			 * so we drop the packet.
    606 			 */
    607 			error = 0;
    608 		else
    609 			error = EADDRNOTAVAIL;
    610 		goto bad;
    611 	}
    612 
    613 	if (rt != NULL && (rt->rt_flags & RTF_GATEWAY) &&
    614 	    !IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst))
    615 		dst = satocsin6(rt->rt_gateway);
    616 	else
    617 		dst = satocsin6(rtcache_getdst(ro));
    618 
    619 	/*
    620 	 * XXXXXX: original code follows:
    621 	 */
    622 	if (!IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst))
    623 		m->m_flags &= ~(M_BCAST | M_MCAST);	/* just in case */
    624 	else {
    625 		bool ingroup;
    626 
    627 		m->m_flags = (m->m_flags & ~M_BCAST) | M_MCAST;
    628 
    629 		in6_ifstat_inc(ifp, ifs6_out_mcast);
    630 
    631 		/*
    632 		 * Confirm that the outgoing interface supports multicast.
    633 		 */
    634 		if (!(ifp->if_flags & IFF_MULTICAST)) {
    635 			IP6_STATINC(IP6_STAT_NOROUTE);
    636 			in6_ifstat_inc(ifp, ifs6_out_discard);
    637 			error = ENETUNREACH;
    638 			goto bad;
    639 		}
    640 
    641 		ingroup = in6_multi_group(&ip6->ip6_dst, ifp);
    642 		if (ingroup && (im6o == NULL || im6o->im6o_multicast_loop)) {
    643 			/*
    644 			 * If we belong to the destination multicast group
    645 			 * on the outgoing interface, and the caller did not
    646 			 * forbid loopback, loop back a copy.
    647 			 */
    648 			KASSERT(dst != NULL);
    649 			ip6_mloopback(ifp, m, dst);
    650 		} else {
    651 			/*
    652 			 * If we are acting as a multicast router, perform
    653 			 * multicast forwarding as if the packet had just
    654 			 * arrived on the interface to which we are about
    655 			 * to send.  The multicast forwarding function
    656 			 * recursively calls this function, using the
    657 			 * IPV6_FORWARDING flag to prevent infinite recursion.
    658 			 *
    659 			 * Multicasts that are looped back by ip6_mloopback(),
    660 			 * above, will be forwarded by the ip6_input() routine,
    661 			 * if necessary.
    662 			 */
    663 			if (ip6_mrouter && (flags & IPV6_FORWARDING) == 0) {
    664 				if (ip6_mforward(ip6, ifp, m) != 0) {
    665 					m_freem(m);
    666 					goto done;
    667 				}
    668 			}
    669 		}
    670 		/*
    671 		 * Multicasts with a hoplimit of zero may be looped back,
    672 		 * above, but must not be transmitted on a network.
    673 		 * Also, multicasts addressed to the loopback interface
    674 		 * are not sent -- the above call to ip6_mloopback() will
    675 		 * loop back a copy if this host actually belongs to the
    676 		 * destination group on the loopback interface.
    677 		 */
    678 		if (ip6->ip6_hlim == 0 || (ifp->if_flags & IFF_LOOPBACK) ||
    679 		    IN6_IS_ADDR_MC_INTFACELOCAL(&ip6->ip6_dst)) {
    680 			m_freem(m);
    681 			goto done;
    682 		}
    683 	}
    684 
    685 	/*
    686 	 * Fill the outgoing interface to tell the upper layer
    687 	 * to increment per-interface statistics.
    688 	 */
    689 	if (ifpp)
    690 		*ifpp = ifp;
    691 
    692 	/* Determine path MTU. */
    693 	/*
    694 	 * ro_pmtu represent final destination while
    695 	 * ro might represent immediate destination.
    696 	 * Use ro_pmtu destination since MTU might differ.
    697 	 */
    698 	if (ro_pmtu != ro) {
    699 		union {
    700 			struct sockaddr		dst;
    701 			struct sockaddr_in6	dst6;
    702 		} u;
    703 
    704 		/* ro_pmtu may not have a cache */
    705 		sockaddr_in6_init(&u.dst6, &finaldst, 0, 0, 0);
    706 		rt_pmtu = rtcache_lookup(ro_pmtu, &u.dst);
    707 	} else
    708 		rt_pmtu = rt;
    709 	error = ip6_getpmtu(rt_pmtu, ifp, &mtu, &alwaysfrag);
    710 	if (rt_pmtu != NULL && rt_pmtu != rt)
    711 		rtcache_unref(rt_pmtu, ro_pmtu);
    712 	KASSERT(error == 0); /* ip6_getpmtu never fail if ifp is passed */
    713 
    714 	/*
    715 	 * The caller of this function may specify to use the minimum MTU
    716 	 * in some cases.
    717 	 * An advanced API option (IPV6_USE_MIN_MTU) can also override MTU
    718 	 * setting.  The logic is a bit complicated; by default, unicast
    719 	 * packets will follow path MTU while multicast packets will be sent at
    720 	 * the minimum MTU.  If IP6PO_MINMTU_ALL is specified, all packets
    721 	 * including unicast ones will be sent at the minimum MTU.  Multicast
    722 	 * packets will always be sent at the minimum MTU unless
    723 	 * IP6PO_MINMTU_DISABLE is explicitly specified.
    724 	 * See RFC 3542 for more details.
    725 	 */
    726 	if (mtu > IPV6_MMTU) {
    727 		if ((flags & IPV6_MINMTU))
    728 			mtu = IPV6_MMTU;
    729 		else if (opt && opt->ip6po_minmtu == IP6PO_MINMTU_ALL)
    730 			mtu = IPV6_MMTU;
    731 		else if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) &&
    732 			 (opt == NULL ||
    733 			  opt->ip6po_minmtu != IP6PO_MINMTU_DISABLE)) {
    734 			mtu = IPV6_MMTU;
    735 		}
    736 	}
    737 
    738 	/*
    739 	 * clear embedded scope identifiers if necessary.
    740 	 * in6_clearscope will touch the addresses only when necessary.
    741 	 */
    742 	in6_clearscope(&ip6->ip6_src);
    743 	in6_clearscope(&ip6->ip6_dst);
    744 
    745 	/*
    746 	 * If the outgoing packet contains a hop-by-hop options header,
    747 	 * it must be examined and processed even by the source node.
    748 	 * (RFC 2460, section 4.)
    749 	 *
    750 	 * XXX Is this really necessary?
    751 	 */
    752 	if (ip6->ip6_nxt == IPPROTO_HOPOPTS) {
    753 		u_int32_t dummy1; /* XXX unused */
    754 		u_int32_t dummy2; /* XXX unused */
    755 		int hoff = sizeof(struct ip6_hdr);
    756 
    757 		if (ip6_hopopts_input(&dummy1, &dummy2, &m, &hoff)) {
    758 			/* m was already freed at this point */
    759 			error = EINVAL;
    760 			goto done;
    761 		}
    762 
    763 		ip6 = mtod(m, struct ip6_hdr *);
    764 	}
    765 
    766 	/*
    767 	 * Run through list of hooks for output packets.
    768 	 */
    769 	error = pfil_run_hooks(inet6_pfil_hook, &m, ifp, PFIL_OUT);
    770 	if (error != 0 || m == NULL) {
    771 		IP6_STATINC(IP6_STAT_PFILDROP_OUT);
    772 		goto done;
    773 	}
    774 	ip6 = mtod(m, struct ip6_hdr *);
    775 
    776 	/*
    777 	 * Send the packet to the outgoing interface.
    778 	 * If necessary, do IPv6 fragmentation before sending.
    779 	 *
    780 	 * the logic here is rather complex:
    781 	 * 1: normal case (dontfrag == 0, alwaysfrag == 0)
    782 	 * 1-a:	send as is if tlen <= path mtu
    783 	 * 1-b:	fragment if tlen > path mtu
    784 	 *
    785 	 * 2: if user asks us not to fragment (dontfrag == 1)
    786 	 * 2-a:	send as is if tlen <= interface mtu
    787 	 * 2-b:	error if tlen > interface mtu
    788 	 *
    789 	 * 3: if we always need to attach fragment header (alwaysfrag == 1)
    790 	 *	always fragment
    791 	 *
    792 	 * 4: if dontfrag == 1 && alwaysfrag == 1
    793 	 *	error, as we cannot handle this conflicting request
    794 	 */
    795 	tlen = m->m_pkthdr.len;
    796 	tso = (m->m_pkthdr.csum_flags & M_CSUM_TSOv6) != 0;
    797 	if (opt && (opt->ip6po_flags & IP6PO_DONTFRAG))
    798 		dontfrag = 1;
    799 	else
    800 		dontfrag = 0;
    801 
    802 	if (dontfrag && alwaysfrag) {	/* case 4 */
    803 		/* conflicting request - can't transmit */
    804 		IP6_STATINC(IP6_STAT_CANTFRAG);
    805 		error = EMSGSIZE;
    806 		goto bad;
    807 	}
    808 	if (dontfrag && (!tso && tlen > ifp->if_mtu)) {	/* case 2-b */
    809 		/*
    810 		 * Even if the DONTFRAG option is specified, we cannot send the
    811 		 * packet when the data length is larger than the MTU of the
    812 		 * outgoing interface.
    813 		 * Notify the error by sending IPV6_PATHMTU ancillary data as
    814 		 * well as returning an error code (the latter is not described
    815 		 * in the API spec.)
    816 		 */
    817 		u_int32_t mtu32;
    818 		struct ip6ctlparam ip6cp;
    819 
    820 		mtu32 = (u_int32_t)mtu;
    821 		memset(&ip6cp, 0, sizeof(ip6cp));
    822 		ip6cp.ip6c_cmdarg = (void *)&mtu32;
    823 		pfctlinput2(PRC_MSGSIZE,
    824 		    rtcache_getdst(ro_pmtu), &ip6cp);
    825 
    826 		IP6_STATINC(IP6_STAT_CANTFRAG);
    827 		error = EMSGSIZE;
    828 		goto bad;
    829 	}
    830 
    831 	/*
    832 	 * transmit packet without fragmentation
    833 	 */
    834 	if (dontfrag || (!alwaysfrag && (tlen <= mtu || tso))) {
    835 		/* case 1-a and 2-a */
    836 		struct in6_ifaddr *ia6;
    837 		int sw_csum;
    838 		int s;
    839 
    840 		ip6 = mtod(m, struct ip6_hdr *);
    841 		s = pserialize_read_enter();
    842 		ia6 = in6_ifawithifp(ifp, &ip6->ip6_src);
    843 		if (ia6) {
    844 			/* Record statistics for this interface address. */
    845 			ia6->ia_ifa.ifa_data.ifad_outbytes += m->m_pkthdr.len;
    846 		}
    847 		pserialize_read_exit(s);
    848 
    849 		sw_csum = m->m_pkthdr.csum_flags & ~ifp->if_csum_flags_tx;
    850 		if ((sw_csum & (M_CSUM_UDPv6|M_CSUM_TCPv6)) != 0) {
    851 			if (IN6_NEED_CHECKSUM(ifp,
    852 			    sw_csum & (M_CSUM_UDPv6|M_CSUM_TCPv6))) {
    853 				in6_undefer_cksum_tcpudp(m);
    854 			}
    855 			m->m_pkthdr.csum_flags &= ~(M_CSUM_UDPv6|M_CSUM_TCPv6);
    856 		}
    857 
    858 		KASSERT(dst != NULL);
    859 		if (__predict_false(sw_csum & M_CSUM_TSOv6)) {
    860 			/*
    861 			 * TSO6 is required by a packet, but disabled for
    862 			 * the interface.
    863 			 */
    864 			error = ip6_tso_output(ifp, origifp, m, dst, rt);
    865 		} else
    866 			error = ip6_if_output(ifp, origifp, m, dst, rt);
    867 		goto done;
    868 	}
    869 
    870 	if (tso) {
    871 		IP6_STATINC(IP6_STAT_CANTFRAG); /* XXX */
    872 		error = EINVAL; /* XXX */
    873 		goto bad;
    874 	}
    875 
    876 	/*
    877 	 * try to fragment the packet.  case 1-b and 3
    878 	 */
    879 	if (mtu < IPV6_MMTU) {
    880 		/* path MTU cannot be less than IPV6_MMTU */
    881 		IP6_STATINC(IP6_STAT_CANTFRAG);
    882 		error = EMSGSIZE;
    883 		in6_ifstat_inc(ifp, ifs6_out_fragfail);
    884 		goto bad;
    885 	} else if (ip6->ip6_plen == 0) {
    886 		/* jumbo payload cannot be fragmented */
    887 		IP6_STATINC(IP6_STAT_CANTFRAG);
    888 		error = EMSGSIZE;
    889 		in6_ifstat_inc(ifp, ifs6_out_fragfail);
    890 		goto bad;
    891 	} else {
    892 		const uint32_t id = ip6_randomid();
    893 		struct mbuf **mnext, *m_frgpart;
    894 		const int hlen = unfragpartlen;
    895 		struct ip6_frag *ip6f;
    896 		u_char nextproto;
    897 
    898 		if (mtu > IPV6_MAXPACKET)
    899 			mtu = IPV6_MAXPACKET;
    900 
    901 		/*
    902 		 * Must be able to put at least 8 bytes per fragment.
    903 		 */
    904 		len = (mtu - hlen - sizeof(struct ip6_frag)) & ~7;
    905 		if (len < 8) {
    906 			IP6_STATINC(IP6_STAT_CANTFRAG);
    907 			error = EMSGSIZE;
    908 			in6_ifstat_inc(ifp, ifs6_out_fragfail);
    909 			goto bad;
    910 		}
    911 
    912 		mnext = &m->m_nextpkt;
    913 
    914 		/*
    915 		 * Change the next header field of the last header in the
    916 		 * unfragmentable part.
    917 		 */
    918 		if (exthdrs.ip6e_rthdr) {
    919 			nextproto = *mtod(exthdrs.ip6e_rthdr, u_char *);
    920 			*mtod(exthdrs.ip6e_rthdr, u_char *) = IPPROTO_FRAGMENT;
    921 		} else if (exthdrs.ip6e_dest1) {
    922 			nextproto = *mtod(exthdrs.ip6e_dest1, u_char *);
    923 			*mtod(exthdrs.ip6e_dest1, u_char *) = IPPROTO_FRAGMENT;
    924 		} else if (exthdrs.ip6e_hbh) {
    925 			nextproto = *mtod(exthdrs.ip6e_hbh, u_char *);
    926 			*mtod(exthdrs.ip6e_hbh, u_char *) = IPPROTO_FRAGMENT;
    927 		} else {
    928 			nextproto = ip6->ip6_nxt;
    929 			ip6->ip6_nxt = IPPROTO_FRAGMENT;
    930 		}
    931 
    932 		if ((m->m_pkthdr.csum_flags & (M_CSUM_UDPv6|M_CSUM_TCPv6))
    933 		    != 0) {
    934 			if (IN6_NEED_CHECKSUM(ifp,
    935 			    m->m_pkthdr.csum_flags &
    936 			    (M_CSUM_UDPv6|M_CSUM_TCPv6))) {
    937 				in6_undefer_cksum_tcpudp(m);
    938 			}
    939 			m->m_pkthdr.csum_flags &= ~(M_CSUM_UDPv6|M_CSUM_TCPv6);
    940 		}
    941 
    942 		/*
    943 		 * Loop through length of segment after first fragment,
    944 		 * make new header and copy data of each part and link onto
    945 		 * chain.
    946 		 */
    947 		m0 = m;
    948 		for (off = hlen; off < tlen; off += len) {
    949 			struct mbuf *mlast;
    950 
    951 			MGETHDR(m, M_DONTWAIT, MT_HEADER);
    952 			if (!m) {
    953 				error = ENOBUFS;
    954 				IP6_STATINC(IP6_STAT_ODROPPED);
    955 				goto sendorfree;
    956 			}
    957 			m_reset_rcvif(m);
    958 			m->m_flags = m0->m_flags & M_COPYFLAGS;
    959 			*mnext = m;
    960 			mnext = &m->m_nextpkt;
    961 			m->m_data += max_linkhdr;
    962 			mhip6 = mtod(m, struct ip6_hdr *);
    963 			*mhip6 = *ip6;
    964 			m->m_len = sizeof(*mhip6);
    965 
    966 			ip6f = NULL;
    967 			error = ip6_insertfraghdr(m0, m, hlen, &ip6f);
    968 			if (error) {
    969 				IP6_STATINC(IP6_STAT_ODROPPED);
    970 				goto sendorfree;
    971 			}
    972 
    973 			/* Fill in the Frag6 Header */
    974 			ip6f->ip6f_offlg = htons((u_int16_t)((off - hlen) & ~7));
    975 			if (off + len >= tlen)
    976 				len = tlen - off;
    977 			else
    978 				ip6f->ip6f_offlg |= IP6F_MORE_FRAG;
    979 			ip6f->ip6f_reserved = 0;
    980 			ip6f->ip6f_ident = id;
    981 			ip6f->ip6f_nxt = nextproto;
    982 
    983 			mhip6->ip6_plen = htons((u_int16_t)(len + hlen +
    984 			    sizeof(*ip6f) - sizeof(struct ip6_hdr)));
    985 			if ((m_frgpart = m_copym(m0, off, len, M_DONTWAIT)) == NULL) {
    986 				error = ENOBUFS;
    987 				IP6_STATINC(IP6_STAT_ODROPPED);
    988 				goto sendorfree;
    989 			}
    990 			for (mlast = m; mlast->m_next; mlast = mlast->m_next)
    991 				;
    992 			mlast->m_next = m_frgpart;
    993 
    994 			m->m_pkthdr.len = len + hlen + sizeof(*ip6f);
    995 			m_reset_rcvif(m);
    996 			IP6_STATINC(IP6_STAT_OFRAGMENTS);
    997 			in6_ifstat_inc(ifp, ifs6_out_fragcreat);
    998 		}
    999 
   1000 		in6_ifstat_inc(ifp, ifs6_out_fragok);
   1001 	}
   1002 
   1003 sendorfree:
   1004 	m = m0->m_nextpkt;
   1005 	m0->m_nextpkt = 0;
   1006 	m_freem(m0);
   1007 	for (m0 = m; m; m = m0) {
   1008 		m0 = m->m_nextpkt;
   1009 		m->m_nextpkt = 0;
   1010 		if (error == 0) {
   1011 			struct in6_ifaddr *ia6;
   1012 			int s;
   1013 			ip6 = mtod(m, struct ip6_hdr *);
   1014 			s = pserialize_read_enter();
   1015 			ia6 = in6_ifawithifp(ifp, &ip6->ip6_src);
   1016 			if (ia6) {
   1017 				/*
   1018 				 * Record statistics for this interface
   1019 				 * address.
   1020 				 */
   1021 				ia6->ia_ifa.ifa_data.ifad_outbytes +=
   1022 				    m->m_pkthdr.len;
   1023 			}
   1024 			pserialize_read_exit(s);
   1025 			KASSERT(dst != NULL);
   1026 			error = ip6_if_output(ifp, origifp, m, dst, rt);
   1027 		} else
   1028 			m_freem(m);
   1029 	}
   1030 
   1031 	if (error == 0)
   1032 		IP6_STATINC(IP6_STAT_FRAGMENTED);
   1033 
   1034 done:
   1035 	rtcache_unref(rt, ro);
   1036 	if (ro == &ip6route)
   1037 		rtcache_free(&ip6route);
   1038 #ifdef IPSEC
   1039 	if (sp != NULL)
   1040 		KEY_SP_UNREF(&sp);
   1041 #endif
   1042 	if_put(ifp, &psref);
   1043 	if (release_psref_ia)
   1044 		if_put(origifp, &psref_ia);
   1045 	curlwp_bindx(bound);
   1046 
   1047 	return error;
   1048 
   1049 freehdrs:
   1050 	m_freem(exthdrs.ip6e_hbh);
   1051 	m_freem(exthdrs.ip6e_dest1);
   1052 	m_freem(exthdrs.ip6e_rthdr);
   1053 	m_freem(exthdrs.ip6e_dest2);
   1054 	/* FALLTHROUGH */
   1055 bad:
   1056 	m_freem(m);
   1057 	goto done;
   1058 
   1059 badscope:
   1060 	IP6_STATINC(IP6_STAT_BADSCOPE);
   1061 	in6_ifstat_inc(origifp, ifs6_out_discard);
   1062 	if (error == 0)
   1063 		error = EHOSTUNREACH; /* XXX */
   1064 	goto bad;
   1065 }
   1066 
   1067 static int
   1068 ip6_copyexthdr(struct mbuf **mp, void *hdr, int hlen)
   1069 {
   1070 	struct mbuf *m;
   1071 
   1072 	if (hlen > MCLBYTES)
   1073 		return ENOBUFS; /* XXX */
   1074 
   1075 	MGET(m, M_DONTWAIT, MT_DATA);
   1076 	if (!m)
   1077 		return ENOBUFS;
   1078 
   1079 	if (hlen > MLEN) {
   1080 		MCLGET(m, M_DONTWAIT);
   1081 		if ((m->m_flags & M_EXT) == 0) {
   1082 			m_free(m);
   1083 			return ENOBUFS;
   1084 		}
   1085 	}
   1086 	m->m_len = hlen;
   1087 	if (hdr)
   1088 		memcpy(mtod(m, void *), hdr, hlen);
   1089 
   1090 	*mp = m;
   1091 	return 0;
   1092 }
   1093 
   1094 /*
   1095  * Insert jumbo payload option.
   1096  */
   1097 static int
   1098 ip6_insert_jumboopt(struct ip6_exthdrs *exthdrs, u_int32_t plen)
   1099 {
   1100 	struct mbuf *mopt;
   1101 	u_int8_t *optbuf;
   1102 	u_int32_t v;
   1103 
   1104 #define JUMBOOPTLEN	8	/* length of jumbo payload option and padding */
   1105 
   1106 	/*
   1107 	 * If there is no hop-by-hop options header, allocate new one.
   1108 	 * If there is one but it doesn't have enough space to store the
   1109 	 * jumbo payload option, allocate a cluster to store the whole options.
   1110 	 * Otherwise, use it to store the options.
   1111 	 */
   1112 	if (exthdrs->ip6e_hbh == NULL) {
   1113 		MGET(mopt, M_DONTWAIT, MT_DATA);
   1114 		if (mopt == 0)
   1115 			return (ENOBUFS);
   1116 		mopt->m_len = JUMBOOPTLEN;
   1117 		optbuf = mtod(mopt, u_int8_t *);
   1118 		optbuf[1] = 0;	/* = ((JUMBOOPTLEN) >> 3) - 1 */
   1119 		exthdrs->ip6e_hbh = mopt;
   1120 	} else {
   1121 		struct ip6_hbh *hbh;
   1122 
   1123 		mopt = exthdrs->ip6e_hbh;
   1124 		if (M_TRAILINGSPACE(mopt) < JUMBOOPTLEN) {
   1125 			const int oldoptlen = mopt->m_len;
   1126 			struct mbuf *n;
   1127 
   1128 			/*
   1129 			 * Assumptions:
   1130 			 * - exthdrs->ip6e_hbh is not referenced from places
   1131 			 *   other than exthdrs.
   1132 			 * - exthdrs->ip6e_hbh is not an mbuf chain.
   1133 			 */
   1134 			KASSERT(mopt->m_next == NULL);
   1135 
   1136 			/*
   1137 			 * Give up if the whole (new) hbh header does not fit
   1138 			 * even in an mbuf cluster.
   1139 			 */
   1140 			if (oldoptlen + JUMBOOPTLEN > MCLBYTES)
   1141 				return ENOBUFS;
   1142 
   1143 			/*
   1144 			 * At this point, we must always prepare a cluster.
   1145 			 */
   1146 			MGET(n, M_DONTWAIT, MT_DATA);
   1147 			if (n) {
   1148 				MCLGET(n, M_DONTWAIT);
   1149 				if ((n->m_flags & M_EXT) == 0) {
   1150 					m_freem(n);
   1151 					n = NULL;
   1152 				}
   1153 			}
   1154 			if (!n)
   1155 				return ENOBUFS;
   1156 
   1157 			n->m_len = oldoptlen + JUMBOOPTLEN;
   1158 			bcopy(mtod(mopt, void *), mtod(n, void *),
   1159 			    oldoptlen);
   1160 			optbuf = mtod(n, u_int8_t *) + oldoptlen;
   1161 			m_freem(mopt);
   1162 			mopt = exthdrs->ip6e_hbh = n;
   1163 		} else {
   1164 			optbuf = mtod(mopt, u_int8_t *) + mopt->m_len;
   1165 			mopt->m_len += JUMBOOPTLEN;
   1166 		}
   1167 		optbuf[0] = IP6OPT_PADN;
   1168 		optbuf[1] = 0;
   1169 
   1170 		/*
   1171 		 * Adjust the header length according to the pad and
   1172 		 * the jumbo payload option.
   1173 		 */
   1174 		hbh = mtod(mopt, struct ip6_hbh *);
   1175 		hbh->ip6h_len += (JUMBOOPTLEN >> 3);
   1176 	}
   1177 
   1178 	/* fill in the option. */
   1179 	optbuf[2] = IP6OPT_JUMBO;
   1180 	optbuf[3] = 4;
   1181 	v = (u_int32_t)htonl(plen + JUMBOOPTLEN);
   1182 	memcpy(&optbuf[4], &v, sizeof(u_int32_t));
   1183 
   1184 	/* finally, adjust the packet header length */
   1185 	exthdrs->ip6e_ip6->m_pkthdr.len += JUMBOOPTLEN;
   1186 
   1187 	return 0;
   1188 #undef JUMBOOPTLEN
   1189 }
   1190 
   1191 /*
   1192  * Insert fragment header and copy unfragmentable header portions.
   1193  *
   1194  * *frghdrp will not be read, and it is guaranteed that either an
   1195  * error is returned or that *frghdrp will point to space allocated
   1196  * for the fragment header.
   1197  *
   1198  * On entry, m contains:
   1199  *     IPv6 Header
   1200  * On exit, it contains:
   1201  *     IPv6 Header -> Unfragmentable Part -> Frag6 Header
   1202  */
   1203 static int
   1204 ip6_insertfraghdr(struct mbuf *m0, struct mbuf *m, int hlen,
   1205 	struct ip6_frag **frghdrp)
   1206 {
   1207 	struct mbuf *n, *mlast;
   1208 
   1209 	if (hlen > sizeof(struct ip6_hdr)) {
   1210 		n = m_copym(m0, sizeof(struct ip6_hdr),
   1211 		    hlen - sizeof(struct ip6_hdr), M_DONTWAIT);
   1212 		if (n == NULL)
   1213 			return ENOBUFS;
   1214 		m->m_next = n;
   1215 	} else
   1216 		n = m;
   1217 
   1218 	/* Search for the last mbuf of unfragmentable part. */
   1219 	for (mlast = n; mlast->m_next; mlast = mlast->m_next)
   1220 		;
   1221 
   1222 	if ((mlast->m_flags & M_EXT) == 0 &&
   1223 	    M_TRAILINGSPACE(mlast) >= sizeof(struct ip6_frag)) {
   1224 		/* use the trailing space of the last mbuf for the fragment hdr */
   1225 		*frghdrp = (struct ip6_frag *)(mtod(mlast, char *) +
   1226 		    mlast->m_len);
   1227 		mlast->m_len += sizeof(struct ip6_frag);
   1228 	} else {
   1229 		/* allocate a new mbuf for the fragment header */
   1230 		struct mbuf *mfrg;
   1231 
   1232 		MGET(mfrg, M_DONTWAIT, MT_DATA);
   1233 		if (mfrg == NULL)
   1234 			return ENOBUFS;
   1235 		mfrg->m_len = sizeof(struct ip6_frag);
   1236 		*frghdrp = mtod(mfrg, struct ip6_frag *);
   1237 		mlast->m_next = mfrg;
   1238 	}
   1239 
   1240 	return 0;
   1241 }
   1242 
   1243 static int
   1244 ip6_getpmtu(struct rtentry *rt, struct ifnet *ifp, u_long *mtup,
   1245     int *alwaysfragp)
   1246 {
   1247 	u_int32_t mtu = 0;
   1248 	int alwaysfrag = 0;
   1249 	int error = 0;
   1250 
   1251 	if (rt != NULL) {
   1252 		if (ifp == NULL)
   1253 			ifp = rt->rt_ifp;
   1254 		mtu = rt->rt_rmx.rmx_mtu;
   1255 		if (mtu == 0)
   1256 			mtu = ifp->if_mtu;
   1257 		else if (mtu < IPV6_MMTU) {
   1258 			/*
   1259 			 * RFC2460 section 5, last paragraph:
   1260 			 * if we record ICMPv6 too big message with
   1261 			 * mtu < IPV6_MMTU, transmit packets sized IPV6_MMTU
   1262 			 * or smaller, with fragment header attached.
   1263 			 * (fragment header is needed regardless from the
   1264 			 * packet size, for translators to identify packets)
   1265 			 */
   1266 			alwaysfrag = 1;
   1267 			mtu = IPV6_MMTU;
   1268 		} else if (mtu > ifp->if_mtu) {
   1269 			/*
   1270 			 * The MTU on the route is larger than the MTU on
   1271 			 * the interface!  This shouldn't happen, unless the
   1272 			 * MTU of the interface has been changed after the
   1273 			 * interface was brought up.  Change the MTU in the
   1274 			 * route to match the interface MTU (as long as the
   1275 			 * field isn't locked).
   1276 			 */
   1277 			mtu = ifp->if_mtu;
   1278 			if (!(rt->rt_rmx.rmx_locks & RTV_MTU))
   1279 				rt->rt_rmx.rmx_mtu = mtu;
   1280 		}
   1281 	} else if (ifp) {
   1282 		mtu = ifp->if_mtu;
   1283 	} else
   1284 		error = EHOSTUNREACH; /* XXX */
   1285 
   1286 	*mtup = mtu;
   1287 	if (alwaysfragp)
   1288 		*alwaysfragp = alwaysfrag;
   1289 	return (error);
   1290 }
   1291 
   1292 /*
   1293  * IP6 socket option processing.
   1294  */
   1295 int
   1296 ip6_ctloutput(int op, struct socket *so, struct sockopt *sopt)
   1297 {
   1298 	int optdatalen, uproto;
   1299 	void *optdata;
   1300 	struct inpcb *inp = sotoinpcb(so);
   1301 	struct ip_moptions **mopts;
   1302 	int error, optval;
   1303 	int level, optname;
   1304 
   1305 	KASSERT(solocked(so));
   1306 	KASSERT(sopt != NULL);
   1307 
   1308 	level = sopt->sopt_level;
   1309 	optname = sopt->sopt_name;
   1310 
   1311 	error = optval = 0;
   1312 	uproto = (int)so->so_proto->pr_protocol;
   1313 
   1314 	switch (level) {
   1315 	case IPPROTO_IP:
   1316 		switch (optname) {
   1317 		case IP_ADD_MEMBERSHIP:
   1318 		case IP_DROP_MEMBERSHIP:
   1319 		case IP_MULTICAST_IF:
   1320 		case IP_MULTICAST_LOOP:
   1321 		case IP_MULTICAST_TTL:
   1322 			mopts = &inp->inp_moptions;
   1323 			switch (op) {
   1324 			case PRCO_GETOPT:
   1325 				return ip_getmoptions(*mopts, sopt);
   1326 			case PRCO_SETOPT:
   1327 				return ip_setmoptions(mopts, sopt);
   1328 			default:
   1329 				return EINVAL;
   1330 			}
   1331 		default:
   1332 			return ENOPROTOOPT;
   1333 		}
   1334 	case IPPROTO_IPV6:
   1335 		break;
   1336 	default:
   1337 		return ENOPROTOOPT;
   1338 	}
   1339 	switch (op) {
   1340 	case PRCO_SETOPT:
   1341 		switch (optname) {
   1342 #ifdef RFC2292
   1343 		case IPV6_2292PKTOPTIONS:
   1344 			error = ip6_pcbopts(&in6p_outputopts(inp), so, sopt);
   1345 			break;
   1346 #endif
   1347 
   1348 		/*
   1349 		 * Use of some Hop-by-Hop options or some
   1350 		 * Destination options, might require special
   1351 		 * privilege.  That is, normal applications
   1352 		 * (without special privilege) might be forbidden
   1353 		 * from setting certain options in outgoing packets,
   1354 		 * and might never see certain options in received
   1355 		 * packets. [RFC 2292 Section 6]
   1356 		 * KAME specific note:
   1357 		 *  KAME prevents non-privileged users from sending or
   1358 		 *  receiving ANY hbh/dst options in order to avoid
   1359 		 *  overhead of parsing options in the kernel.
   1360 		 */
   1361 		case IPV6_RECVHOPOPTS:
   1362 		case IPV6_RECVDSTOPTS:
   1363 		case IPV6_RECVRTHDRDSTOPTS:
   1364 			error = kauth_authorize_network(
   1365 			    kauth_cred_get(),
   1366 			    KAUTH_NETWORK_IPV6, KAUTH_REQ_NETWORK_IPV6_HOPBYHOP,
   1367 			    NULL, NULL, NULL);
   1368 			if (error)
   1369 				break;
   1370 			/* FALLTHROUGH */
   1371 		case IPV6_UNICAST_HOPS:
   1372 		case IPV6_HOPLIMIT:
   1373 		case IPV6_FAITH:
   1374 
   1375 		case IPV6_RECVPKTINFO:
   1376 		case IPV6_RECVHOPLIMIT:
   1377 		case IPV6_RECVRTHDR:
   1378 		case IPV6_RECVPATHMTU:
   1379 		case IPV6_RECVTCLASS:
   1380 		case IPV6_V6ONLY:
   1381 		case IPV6_BINDANY:
   1382 			error = sockopt_getint(sopt, &optval);
   1383 			if (error)
   1384 				break;
   1385 			switch (optname) {
   1386 			case IPV6_UNICAST_HOPS:
   1387 				if (optval < -1 || optval >= 256)
   1388 					error = EINVAL;
   1389 				else {
   1390 					/* -1 = kernel default */
   1391 					in6p_hops6(inp) = optval;
   1392 				}
   1393 				break;
   1394 #define OPTSET(bit) \
   1395 do { \
   1396 if (optval) \
   1397 	inp->inp_flags |= (bit); \
   1398 else \
   1399 	inp->inp_flags &= ~(bit); \
   1400 } while (/*CONSTCOND*/ 0)
   1401 
   1402 #ifdef RFC2292
   1403 #define OPTSET2292(bit) 			\
   1404 do { 						\
   1405 inp->inp_flags |= IN6P_RFC2292; 	\
   1406 if (optval) 				\
   1407 	inp->inp_flags |= (bit); 	\
   1408 else 					\
   1409 	inp->inp_flags &= ~(bit); 	\
   1410 } while (/*CONSTCOND*/ 0)
   1411 #endif
   1412 
   1413 #define OPTBIT(bit) (inp->inp_flags & (bit) ? 1 : 0)
   1414 
   1415 			case IPV6_RECVPKTINFO:
   1416 #ifdef RFC2292
   1417 				/* cannot mix with RFC2292 */
   1418 				if (OPTBIT(IN6P_RFC2292)) {
   1419 					error = EINVAL;
   1420 					break;
   1421 				}
   1422 #endif
   1423 				OPTSET(IN6P_PKTINFO);
   1424 				break;
   1425 
   1426 			case IPV6_HOPLIMIT:
   1427 			{
   1428 				struct ip6_pktopts **optp;
   1429 
   1430 #ifdef RFC2292
   1431 				/* cannot mix with RFC2292 */
   1432 				if (OPTBIT(IN6P_RFC2292)) {
   1433 					error = EINVAL;
   1434 					break;
   1435 				}
   1436 #endif
   1437 				optp = &in6p_outputopts(inp);
   1438 				error = ip6_pcbopt(IPV6_HOPLIMIT,
   1439 						   (u_char *)&optval,
   1440 						   sizeof(optval),
   1441 						   optp,
   1442 						   kauth_cred_get(), uproto);
   1443 				break;
   1444 			}
   1445 
   1446 			case IPV6_RECVHOPLIMIT:
   1447 #ifdef RFC2292
   1448 				/* cannot mix with RFC2292 */
   1449 				if (OPTBIT(IN6P_RFC2292)) {
   1450 					error = EINVAL;
   1451 					break;
   1452 				}
   1453 #endif
   1454 				OPTSET(IN6P_HOPLIMIT);
   1455 				break;
   1456 
   1457 			case IPV6_RECVHOPOPTS:
   1458 #ifdef RFC2292
   1459 				/* cannot mix with RFC2292 */
   1460 				if (OPTBIT(IN6P_RFC2292)) {
   1461 					error = EINVAL;
   1462 					break;
   1463 				}
   1464 #endif
   1465 				OPTSET(IN6P_HOPOPTS);
   1466 				break;
   1467 
   1468 			case IPV6_RECVDSTOPTS:
   1469 #ifdef RFC2292
   1470 				/* cannot mix with RFC2292 */
   1471 				if (OPTBIT(IN6P_RFC2292)) {
   1472 					error = EINVAL;
   1473 					break;
   1474 				}
   1475 #endif
   1476 				OPTSET(IN6P_DSTOPTS);
   1477 				break;
   1478 
   1479 			case IPV6_RECVRTHDRDSTOPTS:
   1480 #ifdef RFC2292
   1481 				/* cannot mix with RFC2292 */
   1482 				if (OPTBIT(IN6P_RFC2292)) {
   1483 					error = EINVAL;
   1484 					break;
   1485 				}
   1486 #endif
   1487 				OPTSET(IN6P_RTHDRDSTOPTS);
   1488 				break;
   1489 
   1490 			case IPV6_RECVRTHDR:
   1491 #ifdef RFC2292
   1492 				/* cannot mix with RFC2292 */
   1493 				if (OPTBIT(IN6P_RFC2292)) {
   1494 					error = EINVAL;
   1495 					break;
   1496 				}
   1497 #endif
   1498 				OPTSET(IN6P_RTHDR);
   1499 				break;
   1500 
   1501 			case IPV6_FAITH:
   1502 				OPTSET(IN6P_FAITH);
   1503 				break;
   1504 
   1505 			case IPV6_RECVPATHMTU:
   1506 				/*
   1507 				 * We ignore this option for TCP
   1508 				 * sockets.
   1509 				 * (RFC3542 leaves this case
   1510 				 * unspecified.)
   1511 				 */
   1512 				if (uproto != IPPROTO_TCP)
   1513 					OPTSET(IN6P_MTU);
   1514 				break;
   1515 
   1516 			case IPV6_V6ONLY:
   1517 				/*
   1518 				 * make setsockopt(IPV6_V6ONLY)
   1519 				 * available only prior to bind(2).
   1520 				 * see ipng mailing list, Jun 22 2001.
   1521 				 */
   1522 				if (inp->inp_lport ||
   1523 				    !IN6_IS_ADDR_UNSPECIFIED(&in6p_laddr(inp))) {
   1524 					error = EINVAL;
   1525 					break;
   1526 				}
   1527 #ifdef INET6_BINDV6ONLY
   1528 				if (!optval)
   1529 					error = EINVAL;
   1530 #else
   1531 				OPTSET(IN6P_IPV6_V6ONLY);
   1532 #endif
   1533 				break;
   1534 
   1535 			case IPV6_RECVTCLASS:
   1536 #ifdef RFC2292
   1537 				/* cannot mix with RFC2292 XXX */
   1538 				if (OPTBIT(IN6P_RFC2292)) {
   1539 					error = EINVAL;
   1540 					break;
   1541 				}
   1542 #endif
   1543 				OPTSET(IN6P_TCLASS);
   1544 				break;
   1545 
   1546 			case IPV6_BINDANY:
   1547 				error = kauth_authorize_network(
   1548 				    kauth_cred_get(), KAUTH_NETWORK_BIND,
   1549 				    KAUTH_REQ_NETWORK_BIND_ANYADDR, so, NULL,
   1550 				    NULL);
   1551 				if (error)
   1552 					break;
   1553 				OPTSET(IN6P_BINDANY);
   1554 				break;
   1555 			}
   1556 			break;
   1557 
   1558 		case IPV6_OTCLASS:
   1559 		{
   1560 			struct ip6_pktopts **optp;
   1561 			u_int8_t tclass;
   1562 
   1563 			error = sockopt_get(sopt, &tclass, sizeof(tclass));
   1564 			if (error)
   1565 				break;
   1566 			optp = &in6p_outputopts(inp);
   1567 			error = ip6_pcbopt(optname,
   1568 					   (u_char *)&tclass,
   1569 					   sizeof(tclass),
   1570 					   optp,
   1571 					   kauth_cred_get(), uproto);
   1572 			break;
   1573 		}
   1574 
   1575 		case IPV6_TCLASS:
   1576 		case IPV6_DONTFRAG:
   1577 		case IPV6_USE_MIN_MTU:
   1578 		case IPV6_PREFER_TEMPADDR:
   1579 			error = sockopt_getint(sopt, &optval);
   1580 			if (error)
   1581 				break;
   1582 			{
   1583 				struct ip6_pktopts **optp;
   1584 				optp = &in6p_outputopts(inp);
   1585 				error = ip6_pcbopt(optname,
   1586 						   (u_char *)&optval,
   1587 						   sizeof(optval),
   1588 						   optp,
   1589 						   kauth_cred_get(), uproto);
   1590 				break;
   1591 			}
   1592 
   1593 #ifdef RFC2292
   1594 		case IPV6_2292PKTINFO:
   1595 		case IPV6_2292HOPLIMIT:
   1596 		case IPV6_2292HOPOPTS:
   1597 		case IPV6_2292DSTOPTS:
   1598 		case IPV6_2292RTHDR:
   1599 			/* RFC 2292 */
   1600 			error = sockopt_getint(sopt, &optval);
   1601 			if (error)
   1602 				break;
   1603 
   1604 			switch (optname) {
   1605 			case IPV6_2292PKTINFO:
   1606 				OPTSET2292(IN6P_PKTINFO);
   1607 				break;
   1608 			case IPV6_2292HOPLIMIT:
   1609 				OPTSET2292(IN6P_HOPLIMIT);
   1610 				break;
   1611 			case IPV6_2292HOPOPTS:
   1612 				/*
   1613 				 * Check super-user privilege.
   1614 				 * See comments for IPV6_RECVHOPOPTS.
   1615 				 */
   1616 				error = kauth_authorize_network(
   1617 				    kauth_cred_get(),
   1618 				    KAUTH_NETWORK_IPV6,
   1619 				    KAUTH_REQ_NETWORK_IPV6_HOPBYHOP, NULL,
   1620 				    NULL, NULL);
   1621 				if (error)
   1622 					return (error);
   1623 				OPTSET2292(IN6P_HOPOPTS);
   1624 				break;
   1625 			case IPV6_2292DSTOPTS:
   1626 				error = kauth_authorize_network(
   1627 				    kauth_cred_get(),
   1628 				    KAUTH_NETWORK_IPV6,
   1629 				    KAUTH_REQ_NETWORK_IPV6_HOPBYHOP, NULL,
   1630 				    NULL, NULL);
   1631 				if (error)
   1632 					return (error);
   1633 				OPTSET2292(IN6P_DSTOPTS|IN6P_RTHDRDSTOPTS); /* XXX */
   1634 				break;
   1635 			case IPV6_2292RTHDR:
   1636 				OPTSET2292(IN6P_RTHDR);
   1637 				break;
   1638 			}
   1639 			break;
   1640 #endif
   1641 		case IPV6_PKTINFO:
   1642 		case IPV6_HOPOPTS:
   1643 		case IPV6_RTHDR:
   1644 		case IPV6_DSTOPTS:
   1645 		case IPV6_RTHDRDSTOPTS:
   1646 		case IPV6_NEXTHOP: {
   1647 			/* new advanced API (RFC3542) */
   1648 			void *optbuf;
   1649 			int optbuflen;
   1650 			struct ip6_pktopts **optp;
   1651 
   1652 #ifdef RFC2292
   1653 			/* cannot mix with RFC2292 */
   1654 			if (OPTBIT(IN6P_RFC2292)) {
   1655 				error = EINVAL;
   1656 				break;
   1657 			}
   1658 #endif
   1659 
   1660 			optbuflen = sopt->sopt_size;
   1661 			optbuf = malloc(optbuflen, M_IP6OPT, M_NOWAIT);
   1662 			if (optbuf == NULL) {
   1663 				error = ENOBUFS;
   1664 				break;
   1665 			}
   1666 
   1667 			error = sockopt_get(sopt, optbuf, optbuflen);
   1668 			if (error) {
   1669 				free(optbuf, M_IP6OPT);
   1670 				break;
   1671 			}
   1672 			optp = &in6p_outputopts(inp);
   1673 			error = ip6_pcbopt(optname, optbuf, optbuflen,
   1674 			    optp, kauth_cred_get(), uproto);
   1675 
   1676 			free(optbuf, M_IP6OPT);
   1677 			break;
   1678 			}
   1679 #undef OPTSET
   1680 
   1681 		case IPV6_MULTICAST_IF:
   1682 		case IPV6_MULTICAST_HOPS:
   1683 		case IPV6_MULTICAST_LOOP:
   1684 		case IPV6_JOIN_GROUP:
   1685 		case IPV6_LEAVE_GROUP:
   1686 			error = ip6_setmoptions(sopt, inp);
   1687 			break;
   1688 
   1689 		case IPV6_PORTRANGE:
   1690 			error = sockopt_getint(sopt, &optval);
   1691 			if (error)
   1692 				break;
   1693 
   1694 			switch (optval) {
   1695 			case IPV6_PORTRANGE_DEFAULT:
   1696 				inp->inp_flags &= ~(IN6P_LOWPORT);
   1697 				inp->inp_flags &= ~(IN6P_HIGHPORT);
   1698 				break;
   1699 
   1700 			case IPV6_PORTRANGE_HIGH:
   1701 				inp->inp_flags &= ~(IN6P_LOWPORT);
   1702 				inp->inp_flags |= IN6P_HIGHPORT;
   1703 				break;
   1704 
   1705 			case IPV6_PORTRANGE_LOW:
   1706 				inp->inp_flags &= ~(IN6P_HIGHPORT);
   1707 				inp->inp_flags |= IN6P_LOWPORT;
   1708 				break;
   1709 
   1710 			default:
   1711 				error = EINVAL;
   1712 				break;
   1713 			}
   1714 			break;
   1715 
   1716 		case IPV6_PORTALGO:
   1717 			error = sockopt_getint(sopt, &optval);
   1718 			if (error)
   1719 				break;
   1720 
   1721 			error = portalgo_algo_index_select(inp, optval);
   1722 			break;
   1723 
   1724 #if defined(IPSEC)
   1725 		case IPV6_IPSEC_POLICY:
   1726 			if (ipsec_enabled) {
   1727 				error = ipsec_set_policy(inp,
   1728 				    sopt->sopt_data, sopt->sopt_size,
   1729 				    kauth_cred_get());
   1730 			} else
   1731 				error = ENOPROTOOPT;
   1732 			break;
   1733 #endif /* IPSEC */
   1734 
   1735 		default:
   1736 			error = ENOPROTOOPT;
   1737 			break;
   1738 		}
   1739 		break;
   1740 
   1741 	case PRCO_GETOPT:
   1742 		switch (optname) {
   1743 #ifdef RFC2292
   1744 		case IPV6_2292PKTOPTIONS:
   1745 			/*
   1746 			 * RFC3542 (effectively) deprecated the
   1747 			 * semantics of the 2292-style pktoptions.
   1748 			 * Since it was not reliable in nature (i.e.,
   1749 			 * applications had to expect the lack of some
   1750 			 * information after all), it would make sense
   1751 			 * to simplify this part by always returning
   1752 			 * empty data.
   1753 			 */
   1754 			break;
   1755 #endif
   1756 
   1757 		case IPV6_RECVHOPOPTS:
   1758 		case IPV6_RECVDSTOPTS:
   1759 		case IPV6_RECVRTHDRDSTOPTS:
   1760 		case IPV6_UNICAST_HOPS:
   1761 		case IPV6_RECVPKTINFO:
   1762 		case IPV6_RECVHOPLIMIT:
   1763 		case IPV6_RECVRTHDR:
   1764 		case IPV6_RECVPATHMTU:
   1765 
   1766 		case IPV6_FAITH:
   1767 		case IPV6_V6ONLY:
   1768 		case IPV6_PORTRANGE:
   1769 		case IPV6_RECVTCLASS:
   1770 		case IPV6_BINDANY:
   1771 			switch (optname) {
   1772 
   1773 			case IPV6_RECVHOPOPTS:
   1774 				optval = OPTBIT(IN6P_HOPOPTS);
   1775 				break;
   1776 
   1777 			case IPV6_RECVDSTOPTS:
   1778 				optval = OPTBIT(IN6P_DSTOPTS);
   1779 				break;
   1780 
   1781 			case IPV6_RECVRTHDRDSTOPTS:
   1782 				optval = OPTBIT(IN6P_RTHDRDSTOPTS);
   1783 				break;
   1784 
   1785 			case IPV6_UNICAST_HOPS:
   1786 				optval = in6p_hops6(inp);
   1787 				break;
   1788 
   1789 			case IPV6_RECVPKTINFO:
   1790 				optval = OPTBIT(IN6P_PKTINFO);
   1791 				break;
   1792 
   1793 			case IPV6_RECVHOPLIMIT:
   1794 				optval = OPTBIT(IN6P_HOPLIMIT);
   1795 				break;
   1796 
   1797 			case IPV6_RECVRTHDR:
   1798 				optval = OPTBIT(IN6P_RTHDR);
   1799 				break;
   1800 
   1801 			case IPV6_RECVPATHMTU:
   1802 				optval = OPTBIT(IN6P_MTU);
   1803 				break;
   1804 
   1805 			case IPV6_FAITH:
   1806 				optval = OPTBIT(IN6P_FAITH);
   1807 				break;
   1808 
   1809 			case IPV6_V6ONLY:
   1810 				optval = OPTBIT(IN6P_IPV6_V6ONLY);
   1811 				break;
   1812 
   1813 			case IPV6_PORTRANGE:
   1814 			    {
   1815 				int flags;
   1816 				flags = inp->inp_flags;
   1817 				if (flags & IN6P_HIGHPORT)
   1818 					optval = IPV6_PORTRANGE_HIGH;
   1819 				else if (flags & IN6P_LOWPORT)
   1820 					optval = IPV6_PORTRANGE_LOW;
   1821 				else
   1822 					optval = 0;
   1823 				break;
   1824 			    }
   1825 			case IPV6_RECVTCLASS:
   1826 				optval = OPTBIT(IN6P_TCLASS);
   1827 				break;
   1828 
   1829 			case IPV6_BINDANY:
   1830 				optval = OPTBIT(IN6P_BINDANY);
   1831 				break;
   1832 			}
   1833 
   1834 			if (error)
   1835 				break;
   1836 			error = sockopt_setint(sopt, optval);
   1837 			break;
   1838 
   1839 		case IPV6_PATHMTU:
   1840 		    {
   1841 			u_long pmtu = 0;
   1842 			struct ip6_mtuinfo mtuinfo;
   1843 			struct route *ro = &inp->inp_route;
   1844 			struct rtentry *rt;
   1845 			union {
   1846 				struct sockaddr		dst;
   1847 				struct sockaddr_in6	dst6;
   1848 			} u;
   1849 
   1850 			if (!(so->so_state & SS_ISCONNECTED))
   1851 				return (ENOTCONN);
   1852 			/*
   1853 			 * XXX: we dot not consider the case of source
   1854 			 * routing, or optional information to specify
   1855 			 * the outgoing interface.
   1856 			 */
   1857 			sockaddr_in6_init(&u.dst6, &in6p_faddr(inp), 0, 0, 0);
   1858 			rt = rtcache_lookup(ro, &u.dst);
   1859 			error = ip6_getpmtu(rt, NULL, &pmtu, NULL);
   1860 			rtcache_unref(rt, ro);
   1861 			if (error)
   1862 				break;
   1863 			if (pmtu > IPV6_MAXPACKET)
   1864 				pmtu = IPV6_MAXPACKET;
   1865 
   1866 			memset(&mtuinfo, 0, sizeof(mtuinfo));
   1867 			mtuinfo.ip6m_mtu = (u_int32_t)pmtu;
   1868 			optdata = (void *)&mtuinfo;
   1869 			optdatalen = sizeof(mtuinfo);
   1870 			if (optdatalen > MCLBYTES)
   1871 				return (EMSGSIZE); /* XXX */
   1872 			error = sockopt_set(sopt, optdata, optdatalen);
   1873 			break;
   1874 		    }
   1875 
   1876 #ifdef RFC2292
   1877 		case IPV6_2292PKTINFO:
   1878 		case IPV6_2292HOPLIMIT:
   1879 		case IPV6_2292HOPOPTS:
   1880 		case IPV6_2292RTHDR:
   1881 		case IPV6_2292DSTOPTS:
   1882 			switch (optname) {
   1883 			case IPV6_2292PKTINFO:
   1884 				optval = OPTBIT(IN6P_PKTINFO);
   1885 				break;
   1886 			case IPV6_2292HOPLIMIT:
   1887 				optval = OPTBIT(IN6P_HOPLIMIT);
   1888 				break;
   1889 			case IPV6_2292HOPOPTS:
   1890 				optval = OPTBIT(IN6P_HOPOPTS);
   1891 				break;
   1892 			case IPV6_2292RTHDR:
   1893 				optval = OPTBIT(IN6P_RTHDR);
   1894 				break;
   1895 			case IPV6_2292DSTOPTS:
   1896 				optval = OPTBIT(IN6P_DSTOPTS|IN6P_RTHDRDSTOPTS);
   1897 				break;
   1898 			}
   1899 			error = sockopt_setint(sopt, optval);
   1900 			break;
   1901 #endif
   1902 		case IPV6_PKTINFO:
   1903 		case IPV6_HOPOPTS:
   1904 		case IPV6_RTHDR:
   1905 		case IPV6_DSTOPTS:
   1906 		case IPV6_RTHDRDSTOPTS:
   1907 		case IPV6_NEXTHOP:
   1908 		case IPV6_OTCLASS:
   1909 		case IPV6_TCLASS:
   1910 		case IPV6_DONTFRAG:
   1911 		case IPV6_USE_MIN_MTU:
   1912 		case IPV6_PREFER_TEMPADDR:
   1913 			error = ip6_getpcbopt(in6p_outputopts(inp),
   1914 			    optname, sopt);
   1915 			break;
   1916 
   1917 		case IPV6_MULTICAST_IF:
   1918 		case IPV6_MULTICAST_HOPS:
   1919 		case IPV6_MULTICAST_LOOP:
   1920 		case IPV6_JOIN_GROUP:
   1921 		case IPV6_LEAVE_GROUP:
   1922 			error = ip6_getmoptions(sopt, inp);
   1923 			break;
   1924 
   1925 		case IPV6_PORTALGO:
   1926 			optval = inp->inp_portalgo;
   1927 			error = sockopt_setint(sopt, optval);
   1928 			break;
   1929 
   1930 #if defined(IPSEC)
   1931 		case IPV6_IPSEC_POLICY:
   1932 			if (ipsec_used) {
   1933 				struct mbuf *m = NULL;
   1934 
   1935 				/*
   1936 				 * XXX: this will return EINVAL as sopt is
   1937 				 * empty
   1938 				 */
   1939 				error = ipsec_get_policy(inp, sopt->sopt_data,
   1940 				    sopt->sopt_size, &m);
   1941 				if (!error)
   1942 					error = sockopt_setmbuf(sopt, m);
   1943 			} else
   1944 				error = ENOPROTOOPT;
   1945 			break;
   1946 #endif /* IPSEC */
   1947 
   1948 		default:
   1949 			error = ENOPROTOOPT;
   1950 			break;
   1951 		}
   1952 		break;
   1953 	}
   1954 	return (error);
   1955 }
   1956 
   1957 int
   1958 ip6_raw_ctloutput(int op, struct socket *so, struct sockopt *sopt)
   1959 {
   1960 	int error = 0, optval;
   1961 	const int icmp6off = offsetof(struct icmp6_hdr, icmp6_cksum);
   1962 	struct inpcb *inp = sotoinpcb(so);
   1963 	int level, optname;
   1964 
   1965 	KASSERT(sopt != NULL);
   1966 
   1967 	level = sopt->sopt_level;
   1968 	optname = sopt->sopt_name;
   1969 
   1970 	if (level != IPPROTO_IPV6) {
   1971 		return ENOPROTOOPT;
   1972 	}
   1973 
   1974 	switch (optname) {
   1975 	case IPV6_CHECKSUM:
   1976 		/*
   1977 		 * For ICMPv6 sockets, no modification allowed for checksum
   1978 		 * offset, permit "no change" values to help existing apps.
   1979 		 *
   1980 		 * XXX RFC3542 says: "An attempt to set IPV6_CHECKSUM
   1981 		 * for an ICMPv6 socket will fail."  The current
   1982 		 * behavior does not meet RFC3542.
   1983 		 */
   1984 		switch (op) {
   1985 		case PRCO_SETOPT:
   1986 			error = sockopt_getint(sopt, &optval);
   1987 			if (error)
   1988 				break;
   1989 			if (optval < -1 ||
   1990 			    (optval > 0 && (optval % 2) != 0)) {
   1991 				/*
   1992 				 * The API assumes non-negative even offset
   1993 				 * values or -1 as a special value.
   1994 				 */
   1995 				error = EINVAL;
   1996 			} else if (so->so_proto->pr_protocol ==
   1997 			    IPPROTO_ICMPV6) {
   1998 				if (optval != icmp6off)
   1999 					error = EINVAL;
   2000 			} else
   2001 				in6p_cksum(inp) = optval;
   2002 			break;
   2003 
   2004 		case PRCO_GETOPT:
   2005 			if (so->so_proto->pr_protocol == IPPROTO_ICMPV6)
   2006 				optval = icmp6off;
   2007 			else
   2008 				optval = in6p_cksum(inp);
   2009 
   2010 			error = sockopt_setint(sopt, optval);
   2011 			break;
   2012 
   2013 		default:
   2014 			error = EINVAL;
   2015 			break;
   2016 		}
   2017 		break;
   2018 
   2019 	default:
   2020 		error = ENOPROTOOPT;
   2021 		break;
   2022 	}
   2023 
   2024 	return (error);
   2025 }
   2026 
   2027 #ifdef RFC2292
   2028 /*
   2029  * Set up IP6 options in pcb for insertion in output packets or
   2030  * specifying behavior of outgoing packets.
   2031  */
   2032 static int
   2033 ip6_pcbopts(struct ip6_pktopts **pktopt, struct socket *so,
   2034     struct sockopt *sopt)
   2035 {
   2036 	struct ip6_pktopts *opt = *pktopt;
   2037 	struct mbuf *m;
   2038 	int error = 0;
   2039 
   2040 	KASSERT(solocked(so));
   2041 
   2042 	/* turn off any old options. */
   2043 	if (opt) {
   2044 #ifdef DIAGNOSTIC
   2045 	    if (opt->ip6po_pktinfo || opt->ip6po_nexthop ||
   2046 		opt->ip6po_hbh || opt->ip6po_dest1 || opt->ip6po_dest2 ||
   2047 		opt->ip6po_rhinfo.ip6po_rhi_rthdr)
   2048 		    printf("ip6_pcbopts: all specified options are cleared.\n");
   2049 #endif
   2050 		ip6_clearpktopts(opt, -1);
   2051 	} else {
   2052 		opt = malloc(sizeof(*opt), M_IP6OPT, M_NOWAIT);
   2053 		if (opt == NULL)
   2054 			return (ENOBUFS);
   2055 	}
   2056 	*pktopt = NULL;
   2057 
   2058 	if (sopt == NULL || sopt->sopt_size == 0) {
   2059 		/*
   2060 		 * Only turning off any previous options, regardless of
   2061 		 * whether the opt is just created or given.
   2062 		 */
   2063 		free(opt, M_IP6OPT);
   2064 		return (0);
   2065 	}
   2066 
   2067 	/*  set options specified by user. */
   2068 	m = sockopt_getmbuf(sopt);
   2069 	if (m == NULL) {
   2070 		free(opt, M_IP6OPT);
   2071 		return (ENOBUFS);
   2072 	}
   2073 
   2074 	error = ip6_setpktopts(m, opt, NULL, kauth_cred_get(),
   2075 	    so->so_proto->pr_protocol);
   2076 	m_freem(m);
   2077 	if (error != 0) {
   2078 		ip6_clearpktopts(opt, -1); /* XXX: discard all options */
   2079 		free(opt, M_IP6OPT);
   2080 		return (error);
   2081 	}
   2082 	*pktopt = opt;
   2083 	return (0);
   2084 }
   2085 #endif
   2086 
   2087 /*
   2088  * initialize ip6_pktopts.  beware that there are non-zero default values in
   2089  * the struct.
   2090  */
   2091 void
   2092 ip6_initpktopts(struct ip6_pktopts *opt)
   2093 {
   2094 
   2095 	memset(opt, 0, sizeof(*opt));
   2096 	opt->ip6po_hlim = -1;	/* -1 means default hop limit */
   2097 	opt->ip6po_tclass = -1;	/* -1 means default traffic class */
   2098 	opt->ip6po_minmtu = IP6PO_MINMTU_MCASTONLY;
   2099 	opt->ip6po_prefer_tempaddr = IP6PO_TEMPADDR_SYSTEM;
   2100 }
   2101 
   2102 #define sin6tosa(sin6)	((struct sockaddr *)(sin6)) /* XXX */
   2103 static int
   2104 ip6_pcbopt(int optname, u_char *buf, int len, struct ip6_pktopts **pktopt,
   2105     kauth_cred_t cred, int uproto)
   2106 {
   2107 	struct ip6_pktopts *opt;
   2108 
   2109 	if (*pktopt == NULL) {
   2110 		*pktopt = malloc(sizeof(struct ip6_pktopts), M_IP6OPT,
   2111 		    M_NOWAIT);
   2112 		if (*pktopt == NULL)
   2113 			return (ENOBUFS);
   2114 
   2115 		ip6_initpktopts(*pktopt);
   2116 	}
   2117 	opt = *pktopt;
   2118 
   2119 	return (ip6_setpktopt(optname, buf, len, opt, cred, 1, 0, uproto));
   2120 }
   2121 
   2122 static int
   2123 ip6_getpcbopt(struct ip6_pktopts *pktopt, int optname, struct sockopt *sopt)
   2124 {
   2125 	void *optdata = NULL;
   2126 	int optdatalen = 0;
   2127 	struct ip6_ext *ip6e;
   2128 	int error = 0;
   2129 	struct in6_pktinfo null_pktinfo;
   2130 	int deftclass = 0, on;
   2131 	int defminmtu = IP6PO_MINMTU_MCASTONLY;
   2132 	int defpreftemp = IP6PO_TEMPADDR_SYSTEM;
   2133 
   2134 	switch (optname) {
   2135 	case IPV6_PKTINFO:
   2136 		if (pktopt && pktopt->ip6po_pktinfo)
   2137 			optdata = (void *)pktopt->ip6po_pktinfo;
   2138 		else {
   2139 			/* XXX: we don't have to do this every time... */
   2140 			memset(&null_pktinfo, 0, sizeof(null_pktinfo));
   2141 			optdata = (void *)&null_pktinfo;
   2142 		}
   2143 		optdatalen = sizeof(struct in6_pktinfo);
   2144 		break;
   2145 	case IPV6_OTCLASS:
   2146 		/* XXX */
   2147 		return (EINVAL);
   2148 	case IPV6_TCLASS:
   2149 		if (pktopt && pktopt->ip6po_tclass >= 0)
   2150 			optdata = (void *)&pktopt->ip6po_tclass;
   2151 		else
   2152 			optdata = (void *)&deftclass;
   2153 		optdatalen = sizeof(int);
   2154 		break;
   2155 	case IPV6_HOPOPTS:
   2156 		if (pktopt && pktopt->ip6po_hbh) {
   2157 			optdata = (void *)pktopt->ip6po_hbh;
   2158 			ip6e = (struct ip6_ext *)pktopt->ip6po_hbh;
   2159 			optdatalen = (ip6e->ip6e_len + 1) << 3;
   2160 		}
   2161 		break;
   2162 	case IPV6_RTHDR:
   2163 		if (pktopt && pktopt->ip6po_rthdr) {
   2164 			optdata = (void *)pktopt->ip6po_rthdr;
   2165 			ip6e = (struct ip6_ext *)pktopt->ip6po_rthdr;
   2166 			optdatalen = (ip6e->ip6e_len + 1) << 3;
   2167 		}
   2168 		break;
   2169 	case IPV6_RTHDRDSTOPTS:
   2170 		if (pktopt && pktopt->ip6po_dest1) {
   2171 			optdata = (void *)pktopt->ip6po_dest1;
   2172 			ip6e = (struct ip6_ext *)pktopt->ip6po_dest1;
   2173 			optdatalen = (ip6e->ip6e_len + 1) << 3;
   2174 		}
   2175 		break;
   2176 	case IPV6_DSTOPTS:
   2177 		if (pktopt && pktopt->ip6po_dest2) {
   2178 			optdata = (void *)pktopt->ip6po_dest2;
   2179 			ip6e = (struct ip6_ext *)pktopt->ip6po_dest2;
   2180 			optdatalen = (ip6e->ip6e_len + 1) << 3;
   2181 		}
   2182 		break;
   2183 	case IPV6_NEXTHOP:
   2184 		if (pktopt && pktopt->ip6po_nexthop) {
   2185 			optdata = (void *)pktopt->ip6po_nexthop;
   2186 			optdatalen = pktopt->ip6po_nexthop->sa_len;
   2187 		}
   2188 		break;
   2189 	case IPV6_USE_MIN_MTU:
   2190 		if (pktopt)
   2191 			optdata = (void *)&pktopt->ip6po_minmtu;
   2192 		else
   2193 			optdata = (void *)&defminmtu;
   2194 		optdatalen = sizeof(int);
   2195 		break;
   2196 	case IPV6_DONTFRAG:
   2197 		if (pktopt && ((pktopt->ip6po_flags) & IP6PO_DONTFRAG))
   2198 			on = 1;
   2199 		else
   2200 			on = 0;
   2201 		optdata = (void *)&on;
   2202 		optdatalen = sizeof(on);
   2203 		break;
   2204 	case IPV6_PREFER_TEMPADDR:
   2205 		if (pktopt)
   2206 			optdata = (void *)&pktopt->ip6po_prefer_tempaddr;
   2207 		else
   2208 			optdata = (void *)&defpreftemp;
   2209 		optdatalen = sizeof(int);
   2210 		break;
   2211 	default:		/* should not happen */
   2212 #ifdef DIAGNOSTIC
   2213 		panic("ip6_getpcbopt: unexpected option\n");
   2214 #endif
   2215 		return (ENOPROTOOPT);
   2216 	}
   2217 
   2218 	error = sockopt_set(sopt, optdata, optdatalen);
   2219 
   2220 	return (error);
   2221 }
   2222 
   2223 void
   2224 ip6_clearpktopts(struct ip6_pktopts *pktopt, int optname)
   2225 {
   2226 	if (optname == -1 || optname == IPV6_PKTINFO) {
   2227 		if (pktopt->ip6po_pktinfo)
   2228 			free(pktopt->ip6po_pktinfo, M_IP6OPT);
   2229 		pktopt->ip6po_pktinfo = NULL;
   2230 	}
   2231 	if (optname == -1 || optname == IPV6_HOPLIMIT)
   2232 		pktopt->ip6po_hlim = -1;
   2233 	if (optname == -1 || optname == IPV6_TCLASS)
   2234 		pktopt->ip6po_tclass = -1;
   2235 	if (optname == -1 || optname == IPV6_NEXTHOP) {
   2236 		rtcache_free(&pktopt->ip6po_nextroute);
   2237 		if (pktopt->ip6po_nexthop)
   2238 			free(pktopt->ip6po_nexthop, M_IP6OPT);
   2239 		pktopt->ip6po_nexthop = NULL;
   2240 	}
   2241 	if (optname == -1 || optname == IPV6_HOPOPTS) {
   2242 		if (pktopt->ip6po_hbh)
   2243 			free(pktopt->ip6po_hbh, M_IP6OPT);
   2244 		pktopt->ip6po_hbh = NULL;
   2245 	}
   2246 	if (optname == -1 || optname == IPV6_RTHDRDSTOPTS) {
   2247 		if (pktopt->ip6po_dest1)
   2248 			free(pktopt->ip6po_dest1, M_IP6OPT);
   2249 		pktopt->ip6po_dest1 = NULL;
   2250 	}
   2251 	if (optname == -1 || optname == IPV6_RTHDR) {
   2252 		if (pktopt->ip6po_rhinfo.ip6po_rhi_rthdr)
   2253 			free(pktopt->ip6po_rhinfo.ip6po_rhi_rthdr, M_IP6OPT);
   2254 		pktopt->ip6po_rhinfo.ip6po_rhi_rthdr = NULL;
   2255 		rtcache_free(&pktopt->ip6po_route);
   2256 	}
   2257 	if (optname == -1 || optname == IPV6_DSTOPTS) {
   2258 		if (pktopt->ip6po_dest2)
   2259 			free(pktopt->ip6po_dest2, M_IP6OPT);
   2260 		pktopt->ip6po_dest2 = NULL;
   2261 	}
   2262 }
   2263 
   2264 #define PKTOPT_EXTHDRCPY(type) 					\
   2265 do {								\
   2266 	if (src->type) {					\
   2267 		int hlen = (((struct ip6_ext *)src->type)->ip6e_len + 1) << 3;\
   2268 		dst->type = malloc(hlen, M_IP6OPT, canwait);	\
   2269 		if (dst->type == NULL)				\
   2270 			goto bad;				\
   2271 		memcpy(dst->type, src->type, hlen);		\
   2272 	}							\
   2273 } while (/*CONSTCOND*/ 0)
   2274 
   2275 static int
   2276 copypktopts(struct ip6_pktopts *dst, struct ip6_pktopts *src, int canwait)
   2277 {
   2278 	dst->ip6po_hlim = src->ip6po_hlim;
   2279 	dst->ip6po_tclass = src->ip6po_tclass;
   2280 	dst->ip6po_flags = src->ip6po_flags;
   2281 	dst->ip6po_minmtu = src->ip6po_minmtu;
   2282 	dst->ip6po_prefer_tempaddr = src->ip6po_prefer_tempaddr;
   2283 	if (src->ip6po_pktinfo) {
   2284 		dst->ip6po_pktinfo = malloc(sizeof(*dst->ip6po_pktinfo),
   2285 		    M_IP6OPT, canwait);
   2286 		if (dst->ip6po_pktinfo == NULL)
   2287 			goto bad;
   2288 		*dst->ip6po_pktinfo = *src->ip6po_pktinfo;
   2289 	}
   2290 	if (src->ip6po_nexthop) {
   2291 		dst->ip6po_nexthop = malloc(src->ip6po_nexthop->sa_len,
   2292 		    M_IP6OPT, canwait);
   2293 		if (dst->ip6po_nexthop == NULL)
   2294 			goto bad;
   2295 		memcpy(dst->ip6po_nexthop, src->ip6po_nexthop,
   2296 		    src->ip6po_nexthop->sa_len);
   2297 	}
   2298 	PKTOPT_EXTHDRCPY(ip6po_hbh);
   2299 	PKTOPT_EXTHDRCPY(ip6po_dest1);
   2300 	PKTOPT_EXTHDRCPY(ip6po_dest2);
   2301 	PKTOPT_EXTHDRCPY(ip6po_rthdr); /* not copy the cached route */
   2302 	return (0);
   2303 
   2304   bad:
   2305 	if (dst->ip6po_pktinfo) free(dst->ip6po_pktinfo, M_IP6OPT);
   2306 	if (dst->ip6po_nexthop) free(dst->ip6po_nexthop, M_IP6OPT);
   2307 	if (dst->ip6po_hbh) free(dst->ip6po_hbh, M_IP6OPT);
   2308 	if (dst->ip6po_dest1) free(dst->ip6po_dest1, M_IP6OPT);
   2309 	if (dst->ip6po_dest2) free(dst->ip6po_dest2, M_IP6OPT);
   2310 	if (dst->ip6po_rthdr) free(dst->ip6po_rthdr, M_IP6OPT);
   2311 
   2312 	return (ENOBUFS);
   2313 }
   2314 #undef PKTOPT_EXTHDRCPY
   2315 
   2316 struct ip6_pktopts *
   2317 ip6_copypktopts(struct ip6_pktopts *src, int canwait)
   2318 {
   2319 	int error;
   2320 	struct ip6_pktopts *dst;
   2321 
   2322 	dst = malloc(sizeof(*dst), M_IP6OPT, canwait);
   2323 	if (dst == NULL)
   2324 		return (NULL);
   2325 	ip6_initpktopts(dst);
   2326 
   2327 	if ((error = copypktopts(dst, src, canwait)) != 0) {
   2328 		free(dst, M_IP6OPT);
   2329 		return (NULL);
   2330 	}
   2331 
   2332 	return (dst);
   2333 }
   2334 
   2335 void
   2336 ip6_freepcbopts(struct ip6_pktopts *pktopt)
   2337 {
   2338 	if (pktopt == NULL)
   2339 		return;
   2340 
   2341 	ip6_clearpktopts(pktopt, -1);
   2342 
   2343 	free(pktopt, M_IP6OPT);
   2344 }
   2345 
   2346 int
   2347 ip6_get_membership(const struct sockopt *sopt, struct ifnet **ifp,
   2348     struct psref *psref, void *v, size_t l)
   2349 {
   2350 	struct ipv6_mreq mreq;
   2351 	int error;
   2352 	struct in6_addr *ia = &mreq.ipv6mr_multiaddr;
   2353 	struct in_addr *ia4 = (void *)&ia->s6_addr32[3];
   2354 
   2355 	error = sockopt_get(sopt, &mreq, sizeof(mreq));
   2356 	if (error != 0)
   2357 		return error;
   2358 
   2359 	if (IN6_IS_ADDR_UNSPECIFIED(ia)) {
   2360 		/*
   2361 		 * We use the unspecified address to specify to accept
   2362 		 * all multicast addresses. Only super user is allowed
   2363 		 * to do this.
   2364 		 */
   2365 		if (kauth_authorize_network(kauth_cred_get(),
   2366 		    KAUTH_NETWORK_IPV6,
   2367 		    KAUTH_REQ_NETWORK_IPV6_JOIN_MULTICAST, NULL, NULL, NULL))
   2368 			return EACCES;
   2369 	} else if (IN6_IS_ADDR_V4MAPPED(ia)) {
   2370 		// Don't bother if we are not going to use ifp.
   2371 		if (l == sizeof(*ia)) {
   2372 			memcpy(v, ia, l);
   2373 			return 0;
   2374 		}
   2375 	} else if (!IN6_IS_ADDR_MULTICAST(ia)) {
   2376 		return EINVAL;
   2377 	}
   2378 
   2379 	/*
   2380 	 * If no interface was explicitly specified, choose an
   2381 	 * appropriate one according to the given multicast address.
   2382 	 */
   2383 	if (mreq.ipv6mr_interface == 0) {
   2384 		struct rtentry *rt;
   2385 		union {
   2386 			struct sockaddr		dst;
   2387 			struct sockaddr_in	dst4;
   2388 			struct sockaddr_in6	dst6;
   2389 		} u;
   2390 		struct route ro;
   2391 
   2392 		/*
   2393 		 * Look up the routing table for the
   2394 		 * address, and choose the outgoing interface.
   2395 		 *   XXX: is it a good approach?
   2396 		 */
   2397 		memset(&ro, 0, sizeof(ro));
   2398 		if (IN6_IS_ADDR_V4MAPPED(ia))
   2399 			sockaddr_in_init(&u.dst4, ia4, 0);
   2400 		else
   2401 			sockaddr_in6_init(&u.dst6, ia, 0, 0, 0);
   2402 		error = rtcache_setdst(&ro, &u.dst);
   2403 		if (error != 0)
   2404 			return error;
   2405 		rt = rtcache_init(&ro);
   2406 		*ifp = rt != NULL ?
   2407 		    if_get_byindex(rt->rt_ifp->if_index, psref) : NULL;
   2408 		rtcache_unref(rt, &ro);
   2409 		rtcache_free(&ro);
   2410 	} else {
   2411 		/*
   2412 		 * If the interface is specified, validate it.
   2413 		 */
   2414 		*ifp = if_get_byindex(mreq.ipv6mr_interface, psref);
   2415 		if (*ifp == NULL)
   2416 			return ENXIO;	/* XXX EINVAL? */
   2417 	}
   2418 	if (sizeof(*ia) == l)
   2419 		memcpy(v, ia, l);
   2420 	else
   2421 		memcpy(v, ia4, l);
   2422 	return 0;
   2423 }
   2424 
   2425 /*
   2426  * Set the IP6 multicast options in response to user setsockopt().
   2427  */
   2428 static int
   2429 ip6_setmoptions(const struct sockopt *sopt, struct inpcb *inp)
   2430 {
   2431 	int error = 0;
   2432 	u_int loop, ifindex;
   2433 	struct ipv6_mreq mreq;
   2434 	struct in6_addr ia;
   2435 	struct ifnet *ifp;
   2436 	struct ip6_moptions *im6o = in6p_moptions(inp);
   2437 	struct in6_multi_mship *imm;
   2438 
   2439 	KASSERT(inp_locked(inp));
   2440 
   2441 	if (im6o == NULL) {
   2442 		/*
   2443 		 * No multicast option buffer attached to the pcb;
   2444 		 * allocate one and initialize to default values.
   2445 		 */
   2446 		im6o = malloc(sizeof(*im6o), M_IPMOPTS, M_NOWAIT);
   2447 		if (im6o == NULL)
   2448 			return (ENOBUFS);
   2449 		in6p_moptions(inp) = im6o;
   2450 		im6o->im6o_multicast_if_index = 0;
   2451 		im6o->im6o_multicast_hlim = ip6_defmcasthlim;
   2452 		im6o->im6o_multicast_loop = IPV6_DEFAULT_MULTICAST_LOOP;
   2453 		LIST_INIT(&im6o->im6o_memberships);
   2454 	}
   2455 
   2456 	switch (sopt->sopt_name) {
   2457 
   2458 	case IPV6_MULTICAST_IF: {
   2459 		int s;
   2460 		/*
   2461 		 * Select the interface for outgoing multicast packets.
   2462 		 */
   2463 		error = sockopt_get(sopt, &ifindex, sizeof(ifindex));
   2464 		if (error != 0)
   2465 			break;
   2466 
   2467 		s = pserialize_read_enter();
   2468 		if (ifindex != 0) {
   2469 			if ((ifp = if_byindex(ifindex)) == NULL) {
   2470 				pserialize_read_exit(s);
   2471 				error = ENXIO;	/* XXX EINVAL? */
   2472 				break;
   2473 			}
   2474 			if ((ifp->if_flags & IFF_MULTICAST) == 0) {
   2475 				pserialize_read_exit(s);
   2476 				error = EADDRNOTAVAIL;
   2477 				break;
   2478 			}
   2479 		} else
   2480 			ifp = NULL;
   2481 		im6o->im6o_multicast_if_index = if_get_index(ifp);
   2482 		pserialize_read_exit(s);
   2483 		break;
   2484 	    }
   2485 
   2486 	case IPV6_MULTICAST_HOPS:
   2487 	    {
   2488 		/*
   2489 		 * Set the IP6 hoplimit for outgoing multicast packets.
   2490 		 */
   2491 		int optval;
   2492 
   2493 		error = sockopt_getint(sopt, &optval);
   2494 		if (error != 0)
   2495 			break;
   2496 
   2497 		if (optval < -1 || optval >= 256)
   2498 			error = EINVAL;
   2499 		else if (optval == -1)
   2500 			im6o->im6o_multicast_hlim = ip6_defmcasthlim;
   2501 		else
   2502 			im6o->im6o_multicast_hlim = optval;
   2503 		break;
   2504 	    }
   2505 
   2506 	case IPV6_MULTICAST_LOOP:
   2507 		/*
   2508 		 * Set the loopback flag for outgoing multicast packets.
   2509 		 * Must be zero or one.
   2510 		 */
   2511 		error = sockopt_get(sopt, &loop, sizeof(loop));
   2512 		if (error != 0)
   2513 			break;
   2514 		if (loop > 1) {
   2515 			error = EINVAL;
   2516 			break;
   2517 		}
   2518 		im6o->im6o_multicast_loop = loop;
   2519 		break;
   2520 
   2521 	case IPV6_JOIN_GROUP: {
   2522 		int bound;
   2523 		struct psref psref;
   2524 		/*
   2525 		 * Add a multicast group membership.
   2526 		 * Group must be a valid IP6 multicast address.
   2527 		 */
   2528 		bound = curlwp_bind();
   2529 		ifp = NULL;
   2530 		error = ip6_get_membership(sopt, &ifp, &psref, &ia, sizeof(ia));
   2531 		if (error != 0) {
   2532 			KASSERT(ifp == NULL);
   2533 			curlwp_bindx(bound);
   2534 			return error;
   2535 		}
   2536 
   2537 		if (IN6_IS_ADDR_V4MAPPED(&ia)) {
   2538 			error = ip_setmoptions(&inp->inp_moptions, sopt);
   2539 			goto put_break;
   2540 		}
   2541 		/*
   2542 		 * See if we found an interface, and confirm that it
   2543 		 * supports multicast
   2544 		 */
   2545 		if (ifp == NULL || (ifp->if_flags & IFF_MULTICAST) == 0) {
   2546 			error = EADDRNOTAVAIL;
   2547 			goto put_break;
   2548 		}
   2549 
   2550 		if (in6_setscope(&ia, ifp, NULL)) {
   2551 			error = EADDRNOTAVAIL; /* XXX: should not happen */
   2552 			goto put_break;
   2553 		}
   2554 
   2555 		/*
   2556 		 * See if the membership already exists.
   2557 		 */
   2558 		LIST_FOREACH(imm, &im6o->im6o_memberships, i6mm_chain) {
   2559 			if (imm->i6mm_maddr->in6m_ifp == ifp &&
   2560 			    IN6_ARE_ADDR_EQUAL(&imm->i6mm_maddr->in6m_addr,
   2561 			    &ia))
   2562 				goto put_break;
   2563 		}
   2564 		if (imm != NULL) {
   2565 			error = EADDRINUSE;
   2566 			goto put_break;
   2567 		}
   2568 		/*
   2569 		 * Everything looks good; add a new record to the multicast
   2570 		 * address list for the given interface.
   2571 		 */
   2572 		imm = in6_joingroup(ifp, &ia, &error, 0);
   2573 		if (imm == NULL)
   2574 			goto put_break;
   2575 		LIST_INSERT_HEAD(&im6o->im6o_memberships, imm, i6mm_chain);
   2576 	    put_break:
   2577 		if_put(ifp, &psref);
   2578 		curlwp_bindx(bound);
   2579 		break;
   2580 	    }
   2581 
   2582 	case IPV6_LEAVE_GROUP: {
   2583 		/*
   2584 		 * Drop a multicast group membership.
   2585 		 * Group must be a valid IP6 multicast address.
   2586 		 */
   2587 		error = sockopt_get(sopt, &mreq, sizeof(mreq));
   2588 		if (error != 0)
   2589 			break;
   2590 
   2591 		if (IN6_IS_ADDR_V4MAPPED(&mreq.ipv6mr_multiaddr)) {
   2592 			error = ip_setmoptions(&inp->inp_moptions, sopt);
   2593 			break;
   2594 		}
   2595 		/*
   2596 		 * If an interface address was specified, get a pointer
   2597 		 * to its ifnet structure.
   2598 		 */
   2599 		if (mreq.ipv6mr_interface != 0) {
   2600 			if ((ifp = if_byindex(mreq.ipv6mr_interface)) == NULL) {
   2601 				error = ENXIO;	/* XXX EINVAL? */
   2602 				break;
   2603 			}
   2604 		} else
   2605 			ifp = NULL;
   2606 
   2607 		/* Fill in the scope zone ID */
   2608 		if (ifp) {
   2609 			if (in6_setscope(&mreq.ipv6mr_multiaddr, ifp, NULL)) {
   2610 				/* XXX: should not happen */
   2611 				error = EADDRNOTAVAIL;
   2612 				break;
   2613 			}
   2614 		} else if (mreq.ipv6mr_interface != 0) {
   2615 			/*
   2616 			 * XXX: This case would happens when the (positive)
   2617 			 * index is in the valid range, but the corresponding
   2618 			 * interface has been detached dynamically.  The above
   2619 			 * check probably avoids such case to happen here, but
   2620 			 * we check it explicitly for safety.
   2621 			 */
   2622 			error = EADDRNOTAVAIL;
   2623 			break;
   2624 		} else {	/* ipv6mr_interface == 0 */
   2625 			struct sockaddr_in6 sa6_mc;
   2626 
   2627 			/*
   2628 			 * The API spec says as follows:
   2629 			 *  If the interface index is specified as 0, the
   2630 			 *  system may choose a multicast group membership to
   2631 			 *  drop by matching the multicast address only.
   2632 			 * On the other hand, we cannot disambiguate the scope
   2633 			 * zone unless an interface is provided.  Thus, we
   2634 			 * check if there's ambiguity with the default scope
   2635 			 * zone as the last resort.
   2636 			 */
   2637 			sockaddr_in6_init(&sa6_mc, &mreq.ipv6mr_multiaddr,
   2638 			    0, 0, 0);
   2639 			error = sa6_embedscope(&sa6_mc, ip6_use_defzone);
   2640 			if (error != 0)
   2641 				break;
   2642 			mreq.ipv6mr_multiaddr = sa6_mc.sin6_addr;
   2643 		}
   2644 
   2645 		/*
   2646 		 * Find the membership in the membership list.
   2647 		 */
   2648 		LIST_FOREACH(imm, &im6o->im6o_memberships, i6mm_chain) {
   2649 			if ((ifp == NULL || imm->i6mm_maddr->in6m_ifp == ifp) &&
   2650 			    IN6_ARE_ADDR_EQUAL(&imm->i6mm_maddr->in6m_addr,
   2651 			    &mreq.ipv6mr_multiaddr))
   2652 				break;
   2653 		}
   2654 		if (imm == NULL) {
   2655 			/* Unable to resolve interface */
   2656 			error = EADDRNOTAVAIL;
   2657 			break;
   2658 		}
   2659 		/*
   2660 		 * Give up the multicast address record to which the
   2661 		 * membership points.
   2662 		 */
   2663 		LIST_REMOVE(imm, i6mm_chain);
   2664 		in6_leavegroup(imm);
   2665 		/* in6m_ifp should not leave thanks to inp_lock */
   2666 		break;
   2667 	    }
   2668 
   2669 	default:
   2670 		error = EOPNOTSUPP;
   2671 		break;
   2672 	}
   2673 
   2674 	/*
   2675 	 * If all options have default values, no need to keep the mbuf.
   2676 	 */
   2677 	if (im6o->im6o_multicast_if_index == 0 &&
   2678 	    im6o->im6o_multicast_hlim == ip6_defmcasthlim &&
   2679 	    im6o->im6o_multicast_loop == IPV6_DEFAULT_MULTICAST_LOOP &&
   2680 	    LIST_EMPTY(&im6o->im6o_memberships)) {
   2681 		free(in6p_moptions(inp), M_IPMOPTS);
   2682 		in6p_moptions(inp) = NULL;
   2683 	}
   2684 
   2685 	return (error);
   2686 }
   2687 
   2688 /*
   2689  * Return the IP6 multicast options in response to user getsockopt().
   2690  */
   2691 static int
   2692 ip6_getmoptions(struct sockopt *sopt, struct inpcb *inp)
   2693 {
   2694 	u_int optval;
   2695 	int error;
   2696 	struct ip6_moptions *im6o = in6p_moptions(inp);
   2697 
   2698 	switch (sopt->sopt_name) {
   2699 	case IPV6_MULTICAST_IF:
   2700 		if (im6o == NULL || im6o->im6o_multicast_if_index == 0)
   2701 			optval = 0;
   2702 		else
   2703 			optval = im6o->im6o_multicast_if_index;
   2704 
   2705 		error = sockopt_set(sopt, &optval, sizeof(optval));
   2706 		break;
   2707 
   2708 	case IPV6_MULTICAST_HOPS:
   2709 		if (im6o == NULL)
   2710 			optval = ip6_defmcasthlim;
   2711 		else
   2712 			optval = im6o->im6o_multicast_hlim;
   2713 
   2714 		error = sockopt_set(sopt, &optval, sizeof(optval));
   2715 		break;
   2716 
   2717 	case IPV6_MULTICAST_LOOP:
   2718 		if (im6o == NULL)
   2719 			optval = IPV6_DEFAULT_MULTICAST_LOOP;
   2720 		else
   2721 			optval = im6o->im6o_multicast_loop;
   2722 
   2723 		error = sockopt_set(sopt, &optval, sizeof(optval));
   2724 		break;
   2725 
   2726 	default:
   2727 		error = EOPNOTSUPP;
   2728 	}
   2729 
   2730 	return (error);
   2731 }
   2732 
   2733 /*
   2734  * Discard the IP6 multicast options.
   2735  */
   2736 void
   2737 ip6_freemoptions(struct ip6_moptions *im6o)
   2738 {
   2739 	struct in6_multi_mship *imm, *nimm;
   2740 
   2741 	if (im6o == NULL)
   2742 		return;
   2743 
   2744 	/* The owner of im6o (inp) should be protected by solock */
   2745 	LIST_FOREACH_SAFE(imm, &im6o->im6o_memberships, i6mm_chain, nimm) {
   2746 		LIST_REMOVE(imm, i6mm_chain);
   2747 		in6_leavegroup(imm);
   2748 	}
   2749 	free(im6o, M_IPMOPTS);
   2750 }
   2751 
   2752 /*
   2753  * Set IPv6 outgoing packet options based on advanced API.
   2754  */
   2755 int
   2756 ip6_setpktopts(struct mbuf *control, struct ip6_pktopts *opt,
   2757 	struct ip6_pktopts *stickyopt, kauth_cred_t cred, int uproto)
   2758 {
   2759 	struct cmsghdr *cm = 0;
   2760 
   2761 	if (control == NULL || opt == NULL)
   2762 		return (EINVAL);
   2763 
   2764 	ip6_initpktopts(opt);
   2765 	if (stickyopt) {
   2766 		int error;
   2767 
   2768 		/*
   2769 		 * If stickyopt is provided, make a local copy of the options
   2770 		 * for this particular packet, then override them by ancillary
   2771 		 * objects.
   2772 		 * XXX: copypktopts() does not copy the cached route to a next
   2773 		 * hop (if any).  This is not very good in terms of efficiency,
   2774 		 * but we can allow this since this option should be rarely
   2775 		 * used.
   2776 		 */
   2777 		if ((error = copypktopts(opt, stickyopt, M_NOWAIT)) != 0)
   2778 			return (error);
   2779 	}
   2780 
   2781 	/*
   2782 	 * XXX: Currently, we assume all the optional information is stored
   2783 	 * in a single mbuf.
   2784 	 */
   2785 	if (control->m_next)
   2786 		return (EINVAL);
   2787 
   2788 	/* XXX if cm->cmsg_len is not aligned, control->m_len can become <0 */
   2789 	for (; control->m_len > 0; control->m_data += CMSG_ALIGN(cm->cmsg_len),
   2790 	    control->m_len -= CMSG_ALIGN(cm->cmsg_len)) {
   2791 		int error;
   2792 
   2793 		if (control->m_len < CMSG_LEN(0))
   2794 			return (EINVAL);
   2795 
   2796 		cm = mtod(control, struct cmsghdr *);
   2797 		if (cm->cmsg_len < CMSG_LEN(0) || cm->cmsg_len > control->m_len)
   2798 			return (EINVAL);
   2799 		if (cm->cmsg_level != IPPROTO_IPV6)
   2800 			continue;
   2801 
   2802 		error = ip6_setpktopt(cm->cmsg_type, CMSG_DATA(cm),
   2803 		    cm->cmsg_len - CMSG_LEN(0), opt, cred, 0, 1, uproto);
   2804 		if (error)
   2805 			return (error);
   2806 	}
   2807 
   2808 	return (0);
   2809 }
   2810 
   2811 /*
   2812  * Set a particular packet option, as a sticky option or an ancillary data
   2813  * item.  "len" can be 0 only when it's a sticky option.
   2814  * We have 4 cases of combination of "sticky" and "cmsg":
   2815  * "sticky=0, cmsg=0": impossible
   2816  * "sticky=0, cmsg=1": RFC2292 or RFC3542 ancillary data
   2817  * "sticky=1, cmsg=0": RFC3542 socket option
   2818  * "sticky=1, cmsg=1": RFC2292 socket option
   2819  */
   2820 static int
   2821 ip6_setpktopt(int optname, u_char *buf, int len, struct ip6_pktopts *opt,
   2822     kauth_cred_t cred, int sticky, int cmsg, int uproto)
   2823 {
   2824 	int minmtupolicy;
   2825 	int error;
   2826 
   2827 	if (!sticky && !cmsg) {
   2828 #ifdef DIAGNOSTIC
   2829 		printf("ip6_setpktopt: impossible case\n");
   2830 #endif
   2831 		return (EINVAL);
   2832 	}
   2833 
   2834 	/*
   2835 	 * IPV6_2292xxx is for backward compatibility to RFC2292, and should
   2836 	 * not be specified in the context of RFC3542.  Conversely,
   2837 	 * RFC3542 types should not be specified in the context of RFC2292.
   2838 	 */
   2839 	if (!cmsg) {
   2840 		switch (optname) {
   2841 		case IPV6_2292PKTINFO:
   2842 		case IPV6_2292HOPLIMIT:
   2843 		case IPV6_2292NEXTHOP:
   2844 		case IPV6_2292HOPOPTS:
   2845 		case IPV6_2292DSTOPTS:
   2846 		case IPV6_2292RTHDR:
   2847 		case IPV6_2292PKTOPTIONS:
   2848 			return (ENOPROTOOPT);
   2849 		}
   2850 	}
   2851 	if (sticky && cmsg) {
   2852 		switch (optname) {
   2853 		case IPV6_PKTINFO:
   2854 		case IPV6_HOPLIMIT:
   2855 		case IPV6_NEXTHOP:
   2856 		case IPV6_HOPOPTS:
   2857 		case IPV6_DSTOPTS:
   2858 		case IPV6_RTHDRDSTOPTS:
   2859 		case IPV6_RTHDR:
   2860 		case IPV6_USE_MIN_MTU:
   2861 		case IPV6_DONTFRAG:
   2862 		case IPV6_OTCLASS:
   2863 		case IPV6_TCLASS:
   2864 		case IPV6_PREFER_TEMPADDR: /* XXX not an RFC3542 option */
   2865 			return (ENOPROTOOPT);
   2866 		}
   2867 	}
   2868 
   2869 	switch (optname) {
   2870 #ifdef RFC2292
   2871 	case IPV6_2292PKTINFO:
   2872 #endif
   2873 	case IPV6_PKTINFO:
   2874 	{
   2875 		struct in6_pktinfo *pktinfo;
   2876 
   2877 		if (len != sizeof(struct in6_pktinfo))
   2878 			return (EINVAL);
   2879 
   2880 		pktinfo = (struct in6_pktinfo *)buf;
   2881 
   2882 		/*
   2883 		 * An application can clear any sticky IPV6_PKTINFO option by
   2884 		 * doing a "regular" setsockopt with ipi6_addr being
   2885 		 * in6addr_any and ipi6_ifindex being zero.
   2886 		 * [RFC 3542, Section 6]
   2887 		 */
   2888 		if (optname == IPV6_PKTINFO && opt->ip6po_pktinfo &&
   2889 		    pktinfo->ipi6_ifindex == 0 &&
   2890 		    IN6_IS_ADDR_UNSPECIFIED(&pktinfo->ipi6_addr)) {
   2891 			ip6_clearpktopts(opt, optname);
   2892 			break;
   2893 		}
   2894 
   2895 		if (uproto == IPPROTO_TCP && optname == IPV6_PKTINFO &&
   2896 		    sticky && !IN6_IS_ADDR_UNSPECIFIED(&pktinfo->ipi6_addr)) {
   2897 			return (EINVAL);
   2898 		}
   2899 
   2900 		/* Validate the interface index if specified. */
   2901 		if (pktinfo->ipi6_ifindex) {
   2902 			struct ifnet *ifp;
   2903 			int s = pserialize_read_enter();
   2904 			ifp = if_byindex(pktinfo->ipi6_ifindex);
   2905 			if (ifp == NULL) {
   2906 				pserialize_read_exit(s);
   2907 				return ENXIO;
   2908 			}
   2909 			pserialize_read_exit(s);
   2910 		}
   2911 
   2912 		/*
   2913 		 * We store the address anyway, and let in6_selectsrc()
   2914 		 * validate the specified address.  This is because ipi6_addr
   2915 		 * may not have enough information about its scope zone, and
   2916 		 * we may need additional information (such as outgoing
   2917 		 * interface or the scope zone of a destination address) to
   2918 		 * disambiguate the scope.
   2919 		 * XXX: the delay of the validation may confuse the
   2920 		 * application when it is used as a sticky option.
   2921 		 */
   2922 		if (opt->ip6po_pktinfo == NULL) {
   2923 			opt->ip6po_pktinfo = malloc(sizeof(*pktinfo),
   2924 			    M_IP6OPT, M_NOWAIT);
   2925 			if (opt->ip6po_pktinfo == NULL)
   2926 				return (ENOBUFS);
   2927 		}
   2928 		memcpy(opt->ip6po_pktinfo, pktinfo, sizeof(*pktinfo));
   2929 		break;
   2930 	}
   2931 
   2932 #ifdef RFC2292
   2933 	case IPV6_2292HOPLIMIT:
   2934 #endif
   2935 	case IPV6_HOPLIMIT:
   2936 	{
   2937 		int *hlimp;
   2938 
   2939 		/*
   2940 		 * RFC 3542 deprecated the usage of sticky IPV6_HOPLIMIT
   2941 		 * to simplify the ordering among hoplimit options.
   2942 		 */
   2943 		if (optname == IPV6_HOPLIMIT && sticky)
   2944 			return (ENOPROTOOPT);
   2945 
   2946 		if (len != sizeof(int))
   2947 			return (EINVAL);
   2948 		hlimp = (int *)buf;
   2949 		if (*hlimp < -1 || *hlimp > 255)
   2950 			return (EINVAL);
   2951 
   2952 		opt->ip6po_hlim = *hlimp;
   2953 		break;
   2954 	}
   2955 
   2956 	case IPV6_OTCLASS:
   2957 		if (len != sizeof(u_int8_t))
   2958 			return (EINVAL);
   2959 
   2960 		opt->ip6po_tclass = *(u_int8_t *)buf;
   2961 		break;
   2962 
   2963 	case IPV6_TCLASS:
   2964 	{
   2965 		int tclass;
   2966 
   2967 		if (len != sizeof(int))
   2968 			return (EINVAL);
   2969 		tclass = *(int *)buf;
   2970 		if (tclass < -1 || tclass > 255)
   2971 			return (EINVAL);
   2972 
   2973 		opt->ip6po_tclass = tclass;
   2974 		break;
   2975 	}
   2976 
   2977 #ifdef RFC2292
   2978 	case IPV6_2292NEXTHOP:
   2979 #endif
   2980 	case IPV6_NEXTHOP:
   2981 		error = kauth_authorize_network(cred,
   2982 		    KAUTH_NETWORK_IPV6,
   2983 		    KAUTH_REQ_NETWORK_IPV6_HOPBYHOP, NULL, NULL, NULL);
   2984 		if (error)
   2985 			return (error);
   2986 
   2987 		if (len == 0) {	/* just remove the option */
   2988 			ip6_clearpktopts(opt, IPV6_NEXTHOP);
   2989 			break;
   2990 		}
   2991 
   2992 		/* check if cmsg_len is large enough for sa_len */
   2993 		if (len < sizeof(struct sockaddr) || len < *buf)
   2994 			return (EINVAL);
   2995 
   2996 		switch (((struct sockaddr *)buf)->sa_family) {
   2997 		case AF_INET6:
   2998 		{
   2999 			struct sockaddr_in6 *sa6 = (struct sockaddr_in6 *)buf;
   3000 
   3001 			if (sa6->sin6_len != sizeof(struct sockaddr_in6))
   3002 				return (EINVAL);
   3003 
   3004 			if (IN6_IS_ADDR_UNSPECIFIED(&sa6->sin6_addr) ||
   3005 			    IN6_IS_ADDR_MULTICAST(&sa6->sin6_addr)) {
   3006 				return (EINVAL);
   3007 			}
   3008 			if ((error = sa6_embedscope(sa6, ip6_use_defzone))
   3009 			    != 0) {
   3010 				return (error);
   3011 			}
   3012 			break;
   3013 		}
   3014 		case AF_LINK:	/* eventually be supported? */
   3015 		default:
   3016 			return (EAFNOSUPPORT);
   3017 		}
   3018 
   3019 		/* turn off the previous option, then set the new option. */
   3020 		ip6_clearpktopts(opt, IPV6_NEXTHOP);
   3021 		opt->ip6po_nexthop = malloc(*buf, M_IP6OPT, M_NOWAIT);
   3022 		if (opt->ip6po_nexthop == NULL)
   3023 			return (ENOBUFS);
   3024 		memcpy(opt->ip6po_nexthop, buf, *buf);
   3025 		break;
   3026 
   3027 #ifdef RFC2292
   3028 	case IPV6_2292HOPOPTS:
   3029 #endif
   3030 	case IPV6_HOPOPTS:
   3031 	{
   3032 		struct ip6_hbh *hbh;
   3033 		int hbhlen;
   3034 
   3035 		/*
   3036 		 * XXX: We don't allow a non-privileged user to set ANY HbH
   3037 		 * options, since per-option restriction has too much
   3038 		 * overhead.
   3039 		 */
   3040 		error = kauth_authorize_network(cred,
   3041 		    KAUTH_NETWORK_IPV6,
   3042 		    KAUTH_REQ_NETWORK_IPV6_HOPBYHOP, NULL, NULL, NULL);
   3043 		if (error)
   3044 			return (error);
   3045 
   3046 		if (len == 0) {
   3047 			ip6_clearpktopts(opt, IPV6_HOPOPTS);
   3048 			break;	/* just remove the option */
   3049 		}
   3050 
   3051 		/* message length validation */
   3052 		if (len < sizeof(struct ip6_hbh))
   3053 			return (EINVAL);
   3054 		hbh = (struct ip6_hbh *)buf;
   3055 		hbhlen = (hbh->ip6h_len + 1) << 3;
   3056 		if (len != hbhlen)
   3057 			return (EINVAL);
   3058 
   3059 		/* turn off the previous option, then set the new option. */
   3060 		ip6_clearpktopts(opt, IPV6_HOPOPTS);
   3061 		opt->ip6po_hbh = malloc(hbhlen, M_IP6OPT, M_NOWAIT);
   3062 		if (opt->ip6po_hbh == NULL)
   3063 			return (ENOBUFS);
   3064 		memcpy(opt->ip6po_hbh, hbh, hbhlen);
   3065 
   3066 		break;
   3067 	}
   3068 
   3069 #ifdef RFC2292
   3070 	case IPV6_2292DSTOPTS:
   3071 #endif
   3072 	case IPV6_DSTOPTS:
   3073 	case IPV6_RTHDRDSTOPTS:
   3074 	{
   3075 		struct ip6_dest *dest, **newdest = NULL;
   3076 		int destlen;
   3077 
   3078 		/* XXX: see the comment for IPV6_HOPOPTS */
   3079 		error = kauth_authorize_network(cred,
   3080 		    KAUTH_NETWORK_IPV6,
   3081 		    KAUTH_REQ_NETWORK_IPV6_HOPBYHOP, NULL, NULL, NULL);
   3082 		if (error)
   3083 			return (error);
   3084 
   3085 		if (len == 0) {
   3086 			ip6_clearpktopts(opt, optname);
   3087 			break;	/* just remove the option */
   3088 		}
   3089 
   3090 		/* message length validation */
   3091 		if (len < sizeof(struct ip6_dest))
   3092 			return (EINVAL);
   3093 		dest = (struct ip6_dest *)buf;
   3094 		destlen = (dest->ip6d_len + 1) << 3;
   3095 		if (len != destlen)
   3096 			return (EINVAL);
   3097 		/*
   3098 		 * Determine the position that the destination options header
   3099 		 * should be inserted; before or after the routing header.
   3100 		 */
   3101 		switch (optname) {
   3102 		case IPV6_2292DSTOPTS:
   3103 			/*
   3104 			 * The old advanced API is ambiguous on this point.
   3105 			 * Our approach is to determine the position based
   3106 			 * according to the existence of a routing header.
   3107 			 * Note, however, that this depends on the order of the
   3108 			 * extension headers in the ancillary data; the 1st
   3109 			 * part of the destination options header must appear
   3110 			 * before the routing header in the ancillary data,
   3111 			 * too.
   3112 			 * RFC3542 solved the ambiguity by introducing
   3113 			 * separate ancillary data or option types.
   3114 			 */
   3115 			if (opt->ip6po_rthdr == NULL)
   3116 				newdest = &opt->ip6po_dest1;
   3117 			else
   3118 				newdest = &opt->ip6po_dest2;
   3119 			break;
   3120 		case IPV6_RTHDRDSTOPTS:
   3121 			newdest = &opt->ip6po_dest1;
   3122 			break;
   3123 		case IPV6_DSTOPTS:
   3124 			newdest = &opt->ip6po_dest2;
   3125 			break;
   3126 		}
   3127 
   3128 		/* turn off the previous option, then set the new option. */
   3129 		ip6_clearpktopts(opt, optname);
   3130 		*newdest = malloc(destlen, M_IP6OPT, M_NOWAIT);
   3131 		if (*newdest == NULL)
   3132 			return (ENOBUFS);
   3133 		memcpy(*newdest, dest, destlen);
   3134 
   3135 		break;
   3136 	}
   3137 
   3138 #ifdef RFC2292
   3139 	case IPV6_2292RTHDR:
   3140 #endif
   3141 	case IPV6_RTHDR:
   3142 	{
   3143 		struct ip6_rthdr *rth;
   3144 		int rthlen;
   3145 
   3146 		if (len == 0) {
   3147 			ip6_clearpktopts(opt, IPV6_RTHDR);
   3148 			break;	/* just remove the option */
   3149 		}
   3150 
   3151 		/* message length validation */
   3152 		if (len < sizeof(struct ip6_rthdr))
   3153 			return (EINVAL);
   3154 		rth = (struct ip6_rthdr *)buf;
   3155 		rthlen = (rth->ip6r_len + 1) << 3;
   3156 		if (len != rthlen)
   3157 			return (EINVAL);
   3158 		switch (rth->ip6r_type) {
   3159 		case IPV6_RTHDR_TYPE_0:
   3160 			/* Dropped, RFC5095. */
   3161 		default:
   3162 			return (EINVAL);	/* not supported */
   3163 		}
   3164 		/* turn off the previous option */
   3165 		ip6_clearpktopts(opt, IPV6_RTHDR);
   3166 		opt->ip6po_rthdr = malloc(rthlen, M_IP6OPT, M_NOWAIT);
   3167 		if (opt->ip6po_rthdr == NULL)
   3168 			return (ENOBUFS);
   3169 		memcpy(opt->ip6po_rthdr, rth, rthlen);
   3170 		break;
   3171 	}
   3172 
   3173 	case IPV6_USE_MIN_MTU:
   3174 		if (len != sizeof(int))
   3175 			return (EINVAL);
   3176 		minmtupolicy = *(int *)buf;
   3177 		if (minmtupolicy != IP6PO_MINMTU_MCASTONLY &&
   3178 		    minmtupolicy != IP6PO_MINMTU_DISABLE &&
   3179 		    minmtupolicy != IP6PO_MINMTU_ALL) {
   3180 			return (EINVAL);
   3181 		}
   3182 		opt->ip6po_minmtu = minmtupolicy;
   3183 		break;
   3184 
   3185 	case IPV6_DONTFRAG:
   3186 		if (len != sizeof(int))
   3187 			return (EINVAL);
   3188 
   3189 		if (uproto == IPPROTO_TCP || *(int *)buf == 0) {
   3190 			/*
   3191 			 * we ignore this option for TCP sockets.
   3192 			 * (RFC3542 leaves this case unspecified.)
   3193 			 */
   3194 			opt->ip6po_flags &= ~IP6PO_DONTFRAG;
   3195 		} else
   3196 			opt->ip6po_flags |= IP6PO_DONTFRAG;
   3197 		break;
   3198 
   3199 	case IPV6_PREFER_TEMPADDR:
   3200 	{
   3201 		int preftemp;
   3202 
   3203 		if (len != sizeof(int))
   3204 			return (EINVAL);
   3205 		preftemp = *(int *)buf;
   3206 		switch (preftemp) {
   3207 		case IP6PO_TEMPADDR_SYSTEM:
   3208 		case IP6PO_TEMPADDR_NOTPREFER:
   3209 		case IP6PO_TEMPADDR_PREFER:
   3210 			break;
   3211 		default:
   3212 			return (EINVAL);
   3213 		}
   3214 		opt->ip6po_prefer_tempaddr = preftemp;
   3215 		break;
   3216 	}
   3217 
   3218 	default:
   3219 		return (ENOPROTOOPT);
   3220 	} /* end of switch */
   3221 
   3222 	return (0);
   3223 }
   3224 
   3225 /*
   3226  * Routine called from ip6_output() to loop back a copy of an IP6 multicast
   3227  * packet to the input queue of a specified interface.  Note that this
   3228  * calls the output routine of the loopback "driver", but with an interface
   3229  * pointer that might NOT be lo0ifp -- easier than replicating that code here.
   3230  */
   3231 void
   3232 ip6_mloopback(struct ifnet *ifp, struct mbuf *m,
   3233 	const struct sockaddr_in6 *dst)
   3234 {
   3235 	struct mbuf *copym;
   3236 	struct ip6_hdr *ip6;
   3237 
   3238 	copym = m_copypacket(m, M_DONTWAIT);
   3239 	if (copym == NULL)
   3240 		return;
   3241 
   3242 	/*
   3243 	 * Make sure to deep-copy IPv6 header portion in case the data
   3244 	 * is in an mbuf cluster, so that we can safely override the IPv6
   3245 	 * header portion later.
   3246 	 */
   3247 	if ((copym->m_flags & M_EXT) != 0 ||
   3248 	    copym->m_len < sizeof(struct ip6_hdr)) {
   3249 		copym = m_pullup(copym, sizeof(struct ip6_hdr));
   3250 		if (copym == NULL)
   3251 			return;
   3252 	}
   3253 
   3254 #ifdef DIAGNOSTIC
   3255 	if (copym->m_len < sizeof(*ip6)) {
   3256 		m_freem(copym);
   3257 		return;
   3258 	}
   3259 #endif
   3260 
   3261 	ip6 = mtod(copym, struct ip6_hdr *);
   3262 	/*
   3263 	 * clear embedded scope identifiers if necessary.
   3264 	 * in6_clearscope will touch the addresses only when necessary.
   3265 	 */
   3266 	in6_clearscope(&ip6->ip6_src);
   3267 	in6_clearscope(&ip6->ip6_dst);
   3268 
   3269 	(void)looutput(ifp, copym, (const struct sockaddr *)dst, NULL);
   3270 }
   3271 
   3272 /*
   3273  * Chop IPv6 header off from the payload.
   3274  */
   3275 static int
   3276 ip6_splithdr(struct mbuf *m, struct ip6_exthdrs *exthdrs)
   3277 {
   3278 	struct mbuf *mh;
   3279 	struct ip6_hdr *ip6;
   3280 
   3281 	ip6 = mtod(m, struct ip6_hdr *);
   3282 	if (m->m_len > sizeof(*ip6)) {
   3283 		MGETHDR(mh, M_DONTWAIT, MT_HEADER);
   3284 		if (mh == NULL) {
   3285 			m_freem(m);
   3286 			return ENOBUFS;
   3287 		}
   3288 		m_move_pkthdr(mh, m);
   3289 		m_align(mh, sizeof(*ip6));
   3290 		m->m_len -= sizeof(*ip6);
   3291 		m->m_data += sizeof(*ip6);
   3292 		mh->m_next = m;
   3293 		mh->m_len = sizeof(*ip6);
   3294 		memcpy(mtod(mh, void *), (void *)ip6, sizeof(*ip6));
   3295 		m = mh;
   3296 	}
   3297 	exthdrs->ip6e_ip6 = m;
   3298 	return 0;
   3299 }
   3300 
   3301 /*
   3302  * Compute IPv6 extension header length.
   3303  */
   3304 int
   3305 ip6_optlen(struct inpcb *inp)
   3306 {
   3307 	int len;
   3308 
   3309 	if (!in6p_outputopts(inp))
   3310 		return 0;
   3311 
   3312 	len = 0;
   3313 #define elen(x) \
   3314     (((struct ip6_ext *)(x)) ? (((struct ip6_ext *)(x))->ip6e_len + 1) << 3 : 0)
   3315 
   3316 	len += elen(in6p_outputopts(inp)->ip6po_hbh);
   3317 	len += elen(in6p_outputopts(inp)->ip6po_dest1);
   3318 	len += elen(in6p_outputopts(inp)->ip6po_rthdr);
   3319 	len += elen(in6p_outputopts(inp)->ip6po_dest2);
   3320 	return len;
   3321 #undef elen
   3322 }
   3323 
   3324 /*
   3325  * Ensure sending address is valid.
   3326  * Returns 0 on success, -1 if an error should be sent back or 1
   3327  * if the packet could be dropped without error (protocol dependent).
   3328  */
   3329 static int
   3330 ip6_ifaddrvalid(const struct in6_addr *src, const struct in6_addr *dst)
   3331 {
   3332 	struct sockaddr_in6 sin6;
   3333 	int s, error;
   3334 	struct ifaddr *ifa;
   3335 	struct in6_ifaddr *ia6;
   3336 
   3337 	if (IN6_IS_ADDR_UNSPECIFIED(src))
   3338 		return 0;
   3339 
   3340 	memset(&sin6, 0, sizeof(sin6));
   3341 	sin6.sin6_family = AF_INET6;
   3342 	sin6.sin6_len = sizeof(sin6);
   3343 	sin6.sin6_addr = *src;
   3344 
   3345 	s = pserialize_read_enter();
   3346 	ifa = ifa_ifwithaddr(sin6tosa(&sin6));
   3347 	if ((ia6 = ifatoia6(ifa)) == NULL ||
   3348 	    ia6->ia6_flags & (IN6_IFF_ANYCAST | IN6_IFF_DUPLICATED))
   3349 		error = -1;
   3350 	else if (ia6->ia6_flags & IN6_IFF_TENTATIVE)
   3351 		error = 1;
   3352 	else if (ia6->ia6_flags & IN6_IFF_DETACHED &&
   3353 	    (sin6.sin6_addr = *dst, ifa_ifwithaddr(sin6tosa(&sin6)) == NULL))
   3354 		/* Allow internal traffic to DETACHED addresses */
   3355 		error = 1;
   3356 	else
   3357 		error = 0;
   3358 	pserialize_read_exit(s);
   3359 
   3360 	return error;
   3361 }
   3362