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