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