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