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