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