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