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