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