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