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