Home | History | Annotate | Line # | Download | only in netinet6
ip6_output.c revision 1.95.2.4
      1 /*	$NetBSD: ip6_output.c,v 1.95.2.4 2006/05/06 23:32:11 christos 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.95.2.4 2006/05/06 23:32:11 christos Exp $");
     66 
     67 #include "opt_inet.h"
     68 #include "opt_ipsec.h"
     69 #include "opt_pfil_hooks.h"
     70 
     71 #include <sys/param.h>
     72 #include <sys/malloc.h>
     73 #include <sys/mbuf.h>
     74 #include <sys/errno.h>
     75 #include <sys/protosw.h>
     76 #include <sys/socket.h>
     77 #include <sys/socketvar.h>
     78 #include <sys/systm.h>
     79 #include <sys/proc.h>
     80 #include <sys/kauth.h>
     81 
     82 #include <net/if.h>
     83 #include <net/route.h>
     84 #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_pcbopts __P((struct ip6_pktopts **, struct mbuf *,
    119 	struct socket *));
    120 static int ip6_setmoptions __P((int, struct ip6_moptions **, struct mbuf *));
    121 static int ip6_getmoptions __P((int, struct ip6_moptions *, struct mbuf **));
    122 static int ip6_copyexthdr __P((struct mbuf **, caddr_t, int));
    123 static int ip6_insertfraghdr __P((struct mbuf *, struct mbuf *, int,
    124 	struct ip6_frag **));
    125 static int ip6_insert_jumboopt __P((struct ip6_exthdrs *, u_int32_t));
    126 static int ip6_splithdr __P((struct mbuf *, struct ip6_exthdrs *));
    127 static int ip6_getpmtu __P((struct route_in6 *, struct route_in6 *,
    128 	struct ifnet *, struct in6_addr *, u_long *, int *));
    129 
    130 #define	IN6_NEED_CHECKSUM(ifp, csum_flags) \
    131 	(__predict_true(((ifp)->if_flags & IFF_LOOPBACK) == 0 || \
    132 	(((csum_flags) & M_CSUM_UDPv6) != 0 && udp_do_loopback_cksum) || \
    133 	(((csum_flags) & M_CSUM_TCPv6) != 0 && tcp_do_loopback_cksum)))
    134 
    135 /*
    136  * IP6 output. The packet in mbuf chain m contains a skeletal IP6
    137  * header (with pri, len, nxt, hlim, src, dst).
    138  * This function may modify ver and hlim only.
    139  * The mbuf chain containing the packet will be freed.
    140  * The mbuf opt, if present, will not be freed.
    141  *
    142  * type of "mtu": rt_rmx.rmx_mtu is u_long, ifnet.ifr_mtu is int, and
    143  * nd_ifinfo.linkmtu is u_int32_t.  so we use u_long to hold largest one,
    144  * which is rt_rmx.rmx_mtu.
    145  */
    146 int
    147 ip6_output(m0, opt, ro, flags, im6o, so, ifpp)
    148 	struct mbuf *m0;
    149 	struct ip6_pktopts *opt;
    150 	struct route_in6 *ro;
    151 	int flags;
    152 	struct ip6_moptions *im6o;
    153 	struct socket *so;
    154 	struct ifnet **ifpp;		/* XXX: just for statistics */
    155 {
    156 	struct ip6_hdr *ip6, *mhip6;
    157 	struct ifnet *ifp, *origifp;
    158 	struct mbuf *m = m0;
    159 	int hlen, tlen, len, off;
    160 	struct route_in6 ip6route;
    161 	struct rtentry *rt = NULL;
    162 	struct sockaddr_in6 *dst, src_sa, dst_sa;
    163 	int error = 0;
    164 	struct in6_ifaddr *ia = NULL;
    165 	u_long mtu;
    166 	int alwaysfrag, dontfrag;
    167 	u_int32_t optlen = 0, plen = 0, unfragpartlen = 0;
    168 	struct ip6_exthdrs exthdrs;
    169 	struct in6_addr finaldst, src0, dst0;
    170 	u_int32_t zone;
    171 	struct route_in6 *ro_pmtu = NULL;
    172 	int hdrsplit = 0;
    173 	int needipsec = 0;
    174 #ifdef IPSEC
    175 	int needipsectun = 0;
    176 	struct secpolicy *sp = NULL;
    177 
    178 	ip6 = mtod(m, struct ip6_hdr *);
    179 #endif /* IPSEC */
    180 
    181 	M_CSUM_DATA_IPv6_HL_SET(m->m_pkthdr.csum_data, sizeof(struct ip6_hdr));
    182 
    183 #define MAKE_EXTHDR(hp, mp)						\
    184     do {								\
    185 	if (hp) {							\
    186 		struct ip6_ext *eh = (struct ip6_ext *)(hp);		\
    187 		error = ip6_copyexthdr((mp), (caddr_t)(hp), 		\
    188 		    ((eh)->ip6e_len + 1) << 3);				\
    189 		if (error)						\
    190 			goto freehdrs;					\
    191 	}								\
    192     } while (/*CONSTCOND*/ 0)
    193 
    194 	bzero(&exthdrs, sizeof(exthdrs));
    195 	if (opt) {
    196 		/* Hop-by-Hop options header */
    197 		MAKE_EXTHDR(opt->ip6po_hbh, &exthdrs.ip6e_hbh);
    198 		/* Destination options header(1st part) */
    199 		MAKE_EXTHDR(opt->ip6po_dest1, &exthdrs.ip6e_dest1);
    200 		/* Routing header */
    201 		MAKE_EXTHDR(opt->ip6po_rthdr, &exthdrs.ip6e_rthdr);
    202 		/* Destination options header(2nd part) */
    203 		MAKE_EXTHDR(opt->ip6po_dest2, &exthdrs.ip6e_dest2);
    204 	}
    205 
    206 #ifdef IPSEC
    207 	if ((flags & IPV6_FORWARDING) != 0) {
    208 		needipsec = 0;
    209 		goto skippolicycheck;
    210 	}
    211 
    212 	/* get a security policy for this packet */
    213 	if (so == NULL)
    214 		sp = ipsec6_getpolicybyaddr(m, IPSEC_DIR_OUTBOUND, 0, &error);
    215 	else {
    216 		if (IPSEC_PCB_SKIP_IPSEC(sotoinpcb_hdr(so)->inph_sp,
    217 					 IPSEC_DIR_OUTBOUND)) {
    218 			needipsec = 0;
    219 			goto skippolicycheck;
    220 		}
    221 		sp = ipsec6_getpolicybysock(m, IPSEC_DIR_OUTBOUND, so, &error);
    222 	}
    223 
    224 	if (sp == NULL) {
    225 		ipsec6stat.out_inval++;
    226 		goto freehdrs;
    227 	}
    228 
    229 	error = 0;
    230 
    231 	/* check policy */
    232 	switch (sp->policy) {
    233 	case IPSEC_POLICY_DISCARD:
    234 		/*
    235 		 * This packet is just discarded.
    236 		 */
    237 		ipsec6stat.out_polvio++;
    238 		goto freehdrs;
    239 
    240 	case IPSEC_POLICY_BYPASS:
    241 	case IPSEC_POLICY_NONE:
    242 		/* no need to do IPsec. */
    243 		needipsec = 0;
    244 		break;
    245 
    246 	case IPSEC_POLICY_IPSEC:
    247 		if (sp->req == NULL) {
    248 			/* XXX should be panic ? */
    249 			printf("ip6_output: No IPsec request specified.\n");
    250 			error = EINVAL;
    251 			goto freehdrs;
    252 		}
    253 		needipsec = 1;
    254 		break;
    255 
    256 	case IPSEC_POLICY_ENTRUST:
    257 	default:
    258 		printf("ip6_output: Invalid policy found. %d\n", sp->policy);
    259 	}
    260 
    261   skippolicycheck:;
    262 #endif /* IPSEC */
    263 
    264 	if (needipsec &&
    265 	    (m->m_pkthdr.csum_flags & (M_CSUM_UDPv6|M_CSUM_TCPv6)) != 0) {
    266 		in6_delayed_cksum(m);
    267 		m->m_pkthdr.csum_flags &= ~(M_CSUM_UDPv6|M_CSUM_TCPv6);
    268 	}
    269 
    270 	/*
    271 	 * Calculate the total length of the extension header chain.
    272 	 * Keep the length of the unfragmentable part for fragmentation.
    273 	 */
    274 	optlen = 0;
    275 	if (exthdrs.ip6e_hbh) optlen += exthdrs.ip6e_hbh->m_len;
    276 	if (exthdrs.ip6e_dest1) optlen += exthdrs.ip6e_dest1->m_len;
    277 	if (exthdrs.ip6e_rthdr) optlen += exthdrs.ip6e_rthdr->m_len;
    278 	unfragpartlen = optlen + sizeof(struct ip6_hdr);
    279 	/* NOTE: we don't add AH/ESP length here. do that later. */
    280 	if (exthdrs.ip6e_dest2) optlen += exthdrs.ip6e_dest2->m_len;
    281 
    282 	/*
    283 	 * If we need IPsec, or there is at least one extension header,
    284 	 * separate IP6 header from the payload.
    285 	 */
    286 	if ((needipsec || optlen) && !hdrsplit) {
    287 		if ((error = ip6_splithdr(m, &exthdrs)) != 0) {
    288 			m = NULL;
    289 			goto freehdrs;
    290 		}
    291 		m = exthdrs.ip6e_ip6;
    292 		hdrsplit++;
    293 	}
    294 
    295 	/* adjust pointer */
    296 	ip6 = mtod(m, struct ip6_hdr *);
    297 
    298 	/* adjust mbuf packet header length */
    299 	m->m_pkthdr.len += optlen;
    300 	plen = m->m_pkthdr.len - sizeof(*ip6);
    301 
    302 	/* If this is a jumbo payload, insert a jumbo payload option. */
    303 	if (plen > IPV6_MAXPACKET) {
    304 		if (!hdrsplit) {
    305 			if ((error = ip6_splithdr(m, &exthdrs)) != 0) {
    306 				m = NULL;
    307 				goto freehdrs;
    308 			}
    309 			m = exthdrs.ip6e_ip6;
    310 			hdrsplit++;
    311 		}
    312 		/* adjust pointer */
    313 		ip6 = mtod(m, struct ip6_hdr *);
    314 		if ((error = ip6_insert_jumboopt(&exthdrs, plen)) != 0)
    315 			goto freehdrs;
    316 		optlen += 8; /* XXX JUMBOOPTLEN */
    317 		ip6->ip6_plen = 0;
    318 	} else
    319 		ip6->ip6_plen = htons(plen);
    320 
    321 	/*
    322 	 * Concatenate headers and fill in next header fields.
    323 	 * Here we have, on "m"
    324 	 *	IPv6 payload
    325 	 * and we insert headers accordingly.  Finally, we should be getting:
    326 	 *	IPv6 hbh dest1 rthdr ah* [esp* dest2 payload]
    327 	 *
    328 	 * during the header composing process, "m" points to IPv6 header.
    329 	 * "mprev" points to an extension header prior to esp.
    330 	 */
    331 	{
    332 		u_char *nexthdrp = &ip6->ip6_nxt;
    333 		struct mbuf *mprev = m;
    334 
    335 		/*
    336 		 * we treat dest2 specially.  this makes IPsec processing
    337 		 * much easier.  the goal here is to make mprev point the
    338 		 * mbuf prior to dest2.
    339 		 *
    340 		 * result: IPv6 dest2 payload
    341 		 * m and mprev will point to IPv6 header.
    342 		 */
    343 		if (exthdrs.ip6e_dest2) {
    344 			if (!hdrsplit)
    345 				panic("assumption failed: hdr not split");
    346 			exthdrs.ip6e_dest2->m_next = m->m_next;
    347 			m->m_next = exthdrs.ip6e_dest2;
    348 			*mtod(exthdrs.ip6e_dest2, u_char *) = ip6->ip6_nxt;
    349 			ip6->ip6_nxt = IPPROTO_DSTOPTS;
    350 		}
    351 
    352 #define MAKE_CHAIN(m, mp, p, i)\
    353     do {\
    354 	if (m) {\
    355 		if (!hdrsplit) \
    356 			panic("assumption failed: hdr not split"); \
    357 		*mtod((m), u_char *) = *(p);\
    358 		*(p) = (i);\
    359 		p = mtod((m), u_char *);\
    360 		(m)->m_next = (mp)->m_next;\
    361 		(mp)->m_next = (m);\
    362 		(mp) = (m);\
    363 	}\
    364     } while (/*CONSTCOND*/ 0)
    365 		/*
    366 		 * result: IPv6 hbh dest1 rthdr dest2 payload
    367 		 * m will point to IPv6 header.  mprev will point to the
    368 		 * extension header prior to dest2 (rthdr in the above case).
    369 		 */
    370 		MAKE_CHAIN(exthdrs.ip6e_hbh, mprev, nexthdrp, IPPROTO_HOPOPTS);
    371 		MAKE_CHAIN(exthdrs.ip6e_dest1, mprev, nexthdrp,
    372 		    IPPROTO_DSTOPTS);
    373 		MAKE_CHAIN(exthdrs.ip6e_rthdr, mprev, nexthdrp,
    374 		    IPPROTO_ROUTING);
    375 
    376 		M_CSUM_DATA_IPv6_HL_SET(m->m_pkthdr.csum_data,
    377 		    sizeof(struct ip6_hdr) + optlen);
    378 
    379 #ifdef IPSEC
    380 		if (!needipsec)
    381 			goto skip_ipsec2;
    382 
    383 		/*
    384 		 * pointers after IPsec headers are not valid any more.
    385 		 * other pointers need a great care too.
    386 		 * (IPsec routines should not mangle mbufs prior to AH/ESP)
    387 		 */
    388 		exthdrs.ip6e_dest2 = NULL;
    389 
    390 	    {
    391 		struct ip6_rthdr *rh = NULL;
    392 		int segleft_org = 0;
    393 		struct ipsec_output_state state;
    394 
    395 		if (exthdrs.ip6e_rthdr) {
    396 			rh = mtod(exthdrs.ip6e_rthdr, struct ip6_rthdr *);
    397 			segleft_org = rh->ip6r_segleft;
    398 			rh->ip6r_segleft = 0;
    399 		}
    400 
    401 		bzero(&state, sizeof(state));
    402 		state.m = m;
    403 		error = ipsec6_output_trans(&state, nexthdrp, mprev, sp, flags,
    404 		    &needipsectun);
    405 		m = state.m;
    406 		if (error) {
    407 			/* mbuf is already reclaimed in ipsec6_output_trans. */
    408 			m = NULL;
    409 			switch (error) {
    410 			case EHOSTUNREACH:
    411 			case ENETUNREACH:
    412 			case EMSGSIZE:
    413 			case ENOBUFS:
    414 			case ENOMEM:
    415 				break;
    416 			default:
    417 				printf("ip6_output (ipsec): error code %d\n", error);
    418 				/* FALLTHROUGH */
    419 			case ENOENT:
    420 				/* don't show these error codes to the user */
    421 				error = 0;
    422 				break;
    423 			}
    424 			goto bad;
    425 		}
    426 		if (exthdrs.ip6e_rthdr) {
    427 			/* ah6_output doesn't modify mbuf chain */
    428 			rh->ip6r_segleft = segleft_org;
    429 		}
    430 	    }
    431 skip_ipsec2:;
    432 #endif
    433 	}
    434 
    435 	/*
    436 	 * If there is a routing header, replace destination address field
    437 	 * with the first hop of the routing header.
    438 	 */
    439 	if (exthdrs.ip6e_rthdr) {
    440 		struct ip6_rthdr *rh;
    441 		struct ip6_rthdr0 *rh0;
    442 		struct in6_addr *addr;
    443 		struct sockaddr_in6 sa;
    444 
    445 		rh = (struct ip6_rthdr *)(mtod(exthdrs.ip6e_rthdr,
    446 		    struct ip6_rthdr *));
    447 		finaldst = ip6->ip6_dst;
    448 		switch (rh->ip6r_type) {
    449 		case IPV6_RTHDR_TYPE_0:
    450 			 rh0 = (struct ip6_rthdr0 *)rh;
    451 			 addr = (struct in6_addr *)(rh0 + 1);
    452 
    453 			 /*
    454 			  * construct a sockaddr_in6 form of
    455 			  * the first hop.
    456 			  *
    457 			  * XXX: we may not have enough
    458 			  * information about its scope zone;
    459 			  * there is no standard API to pass
    460 			  * the information from the
    461 			  * application.
    462 			  */
    463 			 bzero(&sa, sizeof(sa));
    464 			 sa.sin6_family = AF_INET6;
    465 			 sa.sin6_len = sizeof(sa);
    466 			 sa.sin6_addr = addr[0];
    467 			 if ((error = sa6_embedscope(&sa,
    468 			     ip6_use_defzone)) != 0) {
    469 				 goto bad;
    470 			 }
    471 			 ip6->ip6_dst = sa.sin6_addr;
    472 			 (void)memmove(&addr[0], &addr[1],
    473 			     sizeof(struct in6_addr) *
    474 			     (rh0->ip6r0_segleft - 1));
    475 			 addr[rh0->ip6r0_segleft - 1] = finaldst;
    476 			 /* XXX */
    477 			 in6_clearscope(addr + rh0->ip6r0_segleft - 1);
    478 			 break;
    479 		default:	/* is it possible? */
    480 			 error = EINVAL;
    481 			 goto bad;
    482 		}
    483 	}
    484 
    485 	/* Source address validation */
    486 	if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src) &&
    487 	    (flags & IPV6_UNSPECSRC) == 0) {
    488 		error = EOPNOTSUPP;
    489 		ip6stat.ip6s_badscope++;
    490 		goto bad;
    491 	}
    492 	if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_src)) {
    493 		error = EOPNOTSUPP;
    494 		ip6stat.ip6s_badscope++;
    495 		goto bad;
    496 	}
    497 
    498 	ip6stat.ip6s_localout++;
    499 
    500 	/*
    501 	 * Route packet.
    502 	 */
    503 	/* initialize cached route */
    504 	if (ro == 0) {
    505 		ro = &ip6route;
    506 		bzero((caddr_t)ro, sizeof(*ro));
    507 	}
    508 	ro_pmtu = ro;
    509 	if (opt && opt->ip6po_rthdr)
    510 		ro = &opt->ip6po_route;
    511 	dst = (struct sockaddr_in6 *)&ro->ro_dst;
    512 
    513 #ifdef notyet	     /* this will be available with the RFC3542 support */
    514  	/*
    515 	 * if specified, try to fill in the traffic class field.
    516 	 * do not override if a non-zero value is already set.
    517 	 * we check the diffserv field and the ecn field separately.
    518 	 */
    519 	if (opt && opt->ip6po_tclass >= 0) {
    520 		int mask = 0;
    521 
    522 		if ((ip6->ip6_flow & htonl(0xfc << 20)) == 0)
    523 			mask |= 0xfc;
    524 		if ((ip6->ip6_flow & htonl(0x03 << 20)) == 0)
    525 			mask |= 0x03;
    526 		if (mask != 0)
    527 			ip6->ip6_flow |= htonl((opt->ip6po_tclass & mask) << 20);
    528 	}
    529 #endif
    530 
    531 	/* fill in or override the hop limit field, if necessary. */
    532 	if (opt && opt->ip6po_hlim != -1)
    533 		ip6->ip6_hlim = opt->ip6po_hlim & 0xff;
    534 	else if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
    535 		if (im6o != NULL)
    536 			ip6->ip6_hlim = im6o->im6o_multicast_hlim;
    537 		else
    538 			ip6->ip6_hlim = ip6_defmcasthlim;
    539 	}
    540 
    541 #ifdef IPSEC
    542 	if (needipsec && needipsectun) {
    543 		struct ipsec_output_state state;
    544 
    545 		/*
    546 		 * All the extension headers will become inaccessible
    547 		 * (since they can be encrypted).
    548 		 * Don't panic, we need no more updates to extension headers
    549 		 * on inner IPv6 packet (since they are now encapsulated).
    550 		 *
    551 		 * IPv6 [ESP|AH] IPv6 [extension headers] payload
    552 		 */
    553 		bzero(&exthdrs, sizeof(exthdrs));
    554 		exthdrs.ip6e_ip6 = m;
    555 
    556 		bzero(&state, sizeof(state));
    557 		state.m = m;
    558 		state.ro = (struct route *)ro;
    559 		state.dst = (struct sockaddr *)dst;
    560 
    561 		error = ipsec6_output_tunnel(&state, sp, flags);
    562 
    563 		m = state.m;
    564 		ro_pmtu = ro = (struct route_in6 *)state.ro;
    565 		dst = (struct sockaddr_in6 *)state.dst;
    566 		if (error) {
    567 			/* mbuf is already reclaimed in ipsec6_output_tunnel. */
    568 			m0 = m = NULL;
    569 			m = NULL;
    570 			switch (error) {
    571 			case EHOSTUNREACH:
    572 			case ENETUNREACH:
    573 			case EMSGSIZE:
    574 			case ENOBUFS:
    575 			case ENOMEM:
    576 				break;
    577 			default:
    578 				printf("ip6_output (ipsec): error code %d\n", error);
    579 				/* FALLTHROUGH */
    580 			case ENOENT:
    581 				/* don't show these error codes to the user */
    582 				error = 0;
    583 				break;
    584 			}
    585 			goto bad;
    586 		}
    587 
    588 		exthdrs.ip6e_ip6 = m;
    589 	}
    590 #endif /* IPSEC */
    591 
    592 	/* adjust pointer */
    593 	ip6 = mtod(m, struct ip6_hdr *);
    594 
    595 	bzero(&dst_sa, sizeof(dst_sa));
    596 	dst_sa.sin6_family = AF_INET6;
    597 	dst_sa.sin6_len = sizeof(dst_sa);
    598 	dst_sa.sin6_addr = ip6->ip6_dst;
    599 	if ((error = in6_selectroute(&dst_sa, opt, im6o, ro, &ifp, &rt, 0))
    600 	    != 0) {
    601 		switch (error) {
    602 		case EHOSTUNREACH:
    603 			ip6stat.ip6s_noroute++;
    604 			break;
    605 		case EADDRNOTAVAIL:
    606 		default:
    607 			break; /* XXX statistics? */
    608 		}
    609 		if (ifp != NULL)
    610 			in6_ifstat_inc(ifp, ifs6_out_discard);
    611 		goto bad;
    612 	}
    613 	if (rt == NULL) {
    614 		/*
    615 		 * If in6_selectroute() does not return a route entry,
    616 		 * dst may not have been updated.
    617 		 */
    618 		*dst = dst_sa;	/* XXX */
    619 	}
    620 
    621 	/*
    622 	 * then rt (for unicast) and ifp must be non-NULL valid values.
    623 	 */
    624 	if ((flags & IPV6_FORWARDING) == 0) {
    625 		/* XXX: the FORWARDING flag can be set for mrouting. */
    626 		in6_ifstat_inc(ifp, ifs6_out_request);
    627 	}
    628 	if (rt != NULL) {
    629 		ia = (struct in6_ifaddr *)(rt->rt_ifa);
    630 		rt->rt_use++;
    631 	}
    632 
    633 	/*
    634 	 * The outgoing interface must be in the zone of source and
    635 	 * destination addresses.  We should use ia_ifp to support the
    636 	 * case of sending packets to an address of our own.
    637 	 */
    638 	if (ia != NULL && ia->ia_ifp)
    639 		origifp = ia->ia_ifp;
    640 	else
    641 		origifp = ifp;
    642 
    643 	src0 = ip6->ip6_src;
    644 	if (in6_setscope(&src0, origifp, &zone))
    645 		goto badscope;
    646 	bzero(&src_sa, sizeof(src_sa));
    647 	src_sa.sin6_family = AF_INET6;
    648 	src_sa.sin6_len = sizeof(src_sa);
    649 	src_sa.sin6_addr = ip6->ip6_src;
    650 	if (sa6_recoverscope(&src_sa) || zone != src_sa.sin6_scope_id)
    651 		goto badscope;
    652 
    653 	dst0 = ip6->ip6_dst;
    654 	if (in6_setscope(&dst0, origifp, &zone))
    655 		goto badscope;
    656 	/* re-initialize to be sure */
    657 	bzero(&dst_sa, sizeof(dst_sa));
    658 	dst_sa.sin6_family = AF_INET6;
    659 	dst_sa.sin6_len = sizeof(dst_sa);
    660 	dst_sa.sin6_addr = ip6->ip6_dst;
    661 	if (sa6_recoverscope(&dst_sa) || zone != dst_sa.sin6_scope_id)
    662 		goto badscope;
    663 
    664 	/* scope check is done. */
    665 	goto routefound;
    666 
    667   badscope:
    668 	ip6stat.ip6s_badscope++;
    669 	in6_ifstat_inc(origifp, ifs6_out_discard);
    670 	if (error == 0)
    671 		error = EHOSTUNREACH; /* XXX */
    672 	goto bad;
    673 
    674   routefound:
    675 	if (rt && !IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
    676 #ifdef notyet	     /* this will be available with the RFC3542 support */
    677 		if (opt && opt->ip6po_nextroute.ro_rt) {
    678 			/*
    679 			 * The nexthop is explicitly specified by the
    680 			 * application.  We assume the next hop is an IPv6
    681 			 * address.
    682 			 */
    683 			dst = (struct sockaddr_in6 *)opt->ip6po_nexthop;
    684 		} else
    685 #endif
    686 			if ((rt->rt_flags & RTF_GATEWAY))
    687 				dst = (struct sockaddr_in6 *)rt->rt_gateway;
    688 	}
    689 
    690 	/*
    691 	 * XXXXXX: original code follows:
    692 	 */
    693 	if (!IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst))
    694 		m->m_flags &= ~(M_BCAST | M_MCAST);	/* just in case */
    695 	else {
    696 		struct	in6_multi *in6m;
    697 
    698 		m->m_flags = (m->m_flags & ~M_BCAST) | M_MCAST;
    699 
    700 		in6_ifstat_inc(ifp, ifs6_out_mcast);
    701 
    702 		/*
    703 		 * Confirm that the outgoing interface supports multicast.
    704 		 */
    705 		if (!(ifp->if_flags & IFF_MULTICAST)) {
    706 			ip6stat.ip6s_noroute++;
    707 			in6_ifstat_inc(ifp, ifs6_out_discard);
    708 			error = ENETUNREACH;
    709 			goto bad;
    710 		}
    711 
    712 		IN6_LOOKUP_MULTI(ip6->ip6_dst, ifp, in6m);
    713 		if (in6m != NULL &&
    714 		   (im6o == NULL || im6o->im6o_multicast_loop)) {
    715 			/*
    716 			 * If we belong to the destination multicast group
    717 			 * on the outgoing interface, and the caller did not
    718 			 * forbid loopback, loop back a copy.
    719 			 */
    720 			ip6_mloopback(ifp, m, dst);
    721 		} else {
    722 			/*
    723 			 * If we are acting as a multicast router, perform
    724 			 * multicast forwarding as if the packet had just
    725 			 * arrived on the interface to which we are about
    726 			 * to send.  The multicast forwarding function
    727 			 * recursively calls this function, using the
    728 			 * IPV6_FORWARDING flag to prevent infinite recursion.
    729 			 *
    730 			 * Multicasts that are looped back by ip6_mloopback(),
    731 			 * above, will be forwarded by the ip6_input() routine,
    732 			 * if necessary.
    733 			 */
    734 			if (ip6_mrouter && (flags & IPV6_FORWARDING) == 0) {
    735 				if (ip6_mforward(ip6, ifp, m) != 0) {
    736 					m_freem(m);
    737 					goto done;
    738 				}
    739 			}
    740 		}
    741 		/*
    742 		 * Multicasts with a hoplimit of zero may be looped back,
    743 		 * above, but must not be transmitted on a network.
    744 		 * Also, multicasts addressed to the loopback interface
    745 		 * are not sent -- the above call to ip6_mloopback() will
    746 		 * loop back a copy if this host actually belongs to the
    747 		 * destination group on the loopback interface.
    748 		 */
    749 		if (ip6->ip6_hlim == 0 || (ifp->if_flags & IFF_LOOPBACK) ||
    750 		    IN6_IS_ADDR_MC_INTFACELOCAL(&ip6->ip6_dst)) {
    751 			m_freem(m);
    752 			goto done;
    753 		}
    754 	}
    755 
    756 	/*
    757 	 * Fill the outgoing inteface to tell the upper layer
    758 	 * to increment per-interface statistics.
    759 	 */
    760 	if (ifpp)
    761 		*ifpp = ifp;
    762 
    763 	/* Determine path MTU. */
    764 	if ((error = ip6_getpmtu(ro_pmtu, ro, ifp, &finaldst, &mtu,
    765 	    &alwaysfrag)) != 0)
    766 		goto bad;
    767 #ifdef IPSEC
    768 	if (needipsectun)
    769 		mtu = IPV6_MMTU;
    770 #endif
    771 
    772 	/*
    773 	 * The caller of this function may specify to use the minimum MTU
    774 	 * in some cases.
    775 	 */
    776 	if (mtu > IPV6_MMTU) {
    777 		if ((flags & IPV6_MINMTU))
    778 			mtu = IPV6_MMTU;
    779 	}
    780 
    781 	/*
    782 	 * clear embedded scope identifiers if necessary.
    783 	 * in6_clearscope will touch the addresses only when necessary.
    784 	 */
    785 	in6_clearscope(&ip6->ip6_src);
    786 	in6_clearscope(&ip6->ip6_dst);
    787 
    788 	/*
    789 	 * If the outgoing packet contains a hop-by-hop options header,
    790 	 * it must be examined and processed even by the source node.
    791 	 * (RFC 2460, section 4.)
    792 	 */
    793 	if (exthdrs.ip6e_hbh) {
    794 		struct ip6_hbh *hbh = mtod(exthdrs.ip6e_hbh, struct ip6_hbh *);
    795 		u_int32_t dummy1; /* XXX unused */
    796 		u_int32_t dummy2; /* XXX unused */
    797 
    798 		/*
    799 		 *  XXX: if we have to send an ICMPv6 error to the sender,
    800 		 *       we need the M_LOOP flag since icmp6_error() expects
    801 		 *       the IPv6 and the hop-by-hop options header are
    802 		 *       continuous unless the flag is set.
    803 		 */
    804 		m->m_flags |= M_LOOP;
    805 		m->m_pkthdr.rcvif = ifp;
    806 		if (ip6_process_hopopts(m, (u_int8_t *)(hbh + 1),
    807 		    ((hbh->ip6h_len + 1) << 3) - sizeof(struct ip6_hbh),
    808 		    &dummy1, &dummy2) < 0) {
    809 			/* m was already freed at this point */
    810 			error = EINVAL;/* better error? */
    811 			goto done;
    812 		}
    813 		m->m_flags &= ~M_LOOP; /* XXX */
    814 		m->m_pkthdr.rcvif = NULL;
    815 	}
    816 
    817 #ifdef PFIL_HOOKS
    818 	/*
    819 	 * Run through list of hooks for output packets.
    820 	 */
    821 	if ((error = pfil_run_hooks(&inet6_pfil_hook, &m, ifp, PFIL_OUT)) != 0)
    822 		goto done;
    823 	if (m == NULL)
    824 		goto done;
    825 	ip6 = mtod(m, struct ip6_hdr *);
    826 #endif /* PFIL_HOOKS */
    827 	/*
    828 	 * Send the packet to the outgoing interface.
    829 	 * If necessary, do IPv6 fragmentation before sending.
    830 	 *
    831 	 * the logic here is rather complex:
    832 	 * 1: normal case (dontfrag == 0, alwaysfrag == 0)
    833 	 * 1-a:	send as is if tlen <= path mtu
    834 	 * 1-b:	fragment if tlen > path mtu
    835 	 *
    836 	 * 2: if user asks us not to fragment (dontfrag == 1)
    837 	 * 2-a:	send as is if tlen <= interface mtu
    838 	 * 2-b:	error if tlen > interface mtu
    839 	 *
    840 	 * 3: if we always need to attach fragment header (alwaysfrag == 1)
    841 	 *	always fragment
    842 	 *
    843 	 * 4: if dontfrag == 1 && alwaysfrag == 1
    844 	 *	error, as we cannot handle this conflicting request
    845 	 */
    846 	tlen = m->m_pkthdr.len;
    847 
    848 	dontfrag = 0;
    849 #ifdef notdef
    850 	if (dontfrag && alwaysfrag) {	/* case 4 */
    851 		/* conflicting request - can't transmit */
    852 		error = EMSGSIZE;
    853 		goto bad;
    854 	}
    855 	if (dontfrag && tlen > IN6_LINKMTU(ifp)) {	/* case 2-b */
    856 		/*
    857 		 * Even if the DONTFRAG option is specified, we cannot send the
    858 		 * packet when the data length is larger than the MTU of the
    859 		 * outgoing interface.
    860 		 * Notify the error by sending IPV6_PATHMTU ancillary data as
    861 		 * well as returning an error code (the latter is not described
    862 		 * in the API spec.)
    863 		 */
    864 		u_int32_t mtu32;
    865 		struct ip6ctlparam ip6cp;
    866 
    867 		mtu32 = (u_int32_t)mtu;
    868 		bzero(&ip6cp, sizeof(ip6cp));
    869 		ip6cp.ip6c_cmdarg = (void *)&mtu32;
    870 		pfctlinput2(PRC_MSGSIZE, (struct sockaddr *)&ro_pmtu->ro_dst,
    871 		    (void *)&ip6cp);
    872 
    873 		error = EMSGSIZE;
    874 		goto bad;
    875 	}
    876 #endif
    877 	/*
    878 	 * transmit packet without fragmentation
    879 	 */
    880 	if (dontfrag || (!alwaysfrag && tlen <= mtu)) {	/* case 1-a and 2-a */
    881 		struct in6_ifaddr *ia6;
    882 		int sw_csum;
    883 
    884 		ip6 = mtod(m, struct ip6_hdr *);
    885 		ia6 = in6_ifawithifp(ifp, &ip6->ip6_src);
    886 		if (ia6) {
    887 			/* Record statistics for this interface address. */
    888 			ia6->ia_ifa.ifa_data.ifad_outbytes += m->m_pkthdr.len;
    889 		}
    890 #ifdef IPSEC
    891 		/* clean ipsec history once it goes out of the node */
    892 		ipsec_delaux(m);
    893 #endif
    894 
    895 		sw_csum = m->m_pkthdr.csum_flags & ~ifp->if_csum_flags_tx;
    896 		if ((sw_csum & (M_CSUM_UDPv6|M_CSUM_TCPv6)) != 0) {
    897 			if (IN6_NEED_CHECKSUM(ifp,
    898 			    sw_csum & (M_CSUM_UDPv6|M_CSUM_TCPv6))) {
    899 				in6_delayed_cksum(m);
    900 			}
    901 			m->m_pkthdr.csum_flags &= ~(M_CSUM_UDPv6|M_CSUM_TCPv6);
    902 		}
    903 
    904 		error = nd6_output(ifp, origifp, m, dst, ro->ro_rt);
    905 		goto done;
    906 	}
    907 
    908 	/*
    909 	 * try to fragment the packet.  case 1-b and 3
    910 	 */
    911 	if (mtu < IPV6_MMTU) {
    912 		/* path MTU cannot be less than IPV6_MMTU */
    913 		error = EMSGSIZE;
    914 		in6_ifstat_inc(ifp, ifs6_out_fragfail);
    915 		goto bad;
    916 	} else if (ip6->ip6_plen == 0) {
    917 		/* jumbo payload cannot be fragmented */
    918 		error = EMSGSIZE;
    919 		in6_ifstat_inc(ifp, ifs6_out_fragfail);
    920 		goto bad;
    921 	} else {
    922 		struct mbuf **mnext, *m_frgpart;
    923 		struct ip6_frag *ip6f;
    924 		u_int32_t id = htonl(ip6_randomid());
    925 		u_char nextproto;
    926 		struct ip6ctlparam ip6cp;
    927 		u_int32_t mtu32;
    928 
    929 		/*
    930 		 * Too large for the destination or interface;
    931 		 * fragment if possible.
    932 		 * Must be able to put at least 8 bytes per fragment.
    933 		 */
    934 		hlen = unfragpartlen;
    935 		if (mtu > IPV6_MAXPACKET)
    936 			mtu = IPV6_MAXPACKET;
    937 
    938 		/* Notify a proper path MTU to applications. */
    939 		mtu32 = (u_int32_t)mtu;
    940 		bzero(&ip6cp, sizeof(ip6cp));
    941 		ip6cp.ip6c_cmdarg = (void *)&mtu32;
    942 		pfctlinput2(PRC_MSGSIZE, (struct sockaddr *)&ro_pmtu->ro_dst,
    943 		    (void *)&ip6cp);
    944 
    945 		len = (mtu - hlen - sizeof(struct ip6_frag)) & ~7;
    946 		if (len < 8) {
    947 			error = EMSGSIZE;
    948 			in6_ifstat_inc(ifp, ifs6_out_fragfail);
    949 			goto bad;
    950 		}
    951 
    952 		mnext = &m->m_nextpkt;
    953 
    954 		/*
    955 		 * Change the next header field of the last header in the
    956 		 * unfragmentable part.
    957 		 */
    958 		if (exthdrs.ip6e_rthdr) {
    959 			nextproto = *mtod(exthdrs.ip6e_rthdr, u_char *);
    960 			*mtod(exthdrs.ip6e_rthdr, u_char *) = IPPROTO_FRAGMENT;
    961 		} else if (exthdrs.ip6e_dest1) {
    962 			nextproto = *mtod(exthdrs.ip6e_dest1, u_char *);
    963 			*mtod(exthdrs.ip6e_dest1, u_char *) = IPPROTO_FRAGMENT;
    964 		} else if (exthdrs.ip6e_hbh) {
    965 			nextproto = *mtod(exthdrs.ip6e_hbh, u_char *);
    966 			*mtod(exthdrs.ip6e_hbh, u_char *) = IPPROTO_FRAGMENT;
    967 		} else {
    968 			nextproto = ip6->ip6_nxt;
    969 			ip6->ip6_nxt = IPPROTO_FRAGMENT;
    970 		}
    971 
    972 		if ((m->m_pkthdr.csum_flags & (M_CSUM_UDPv6|M_CSUM_TCPv6))
    973 		    != 0) {
    974 			if (IN6_NEED_CHECKSUM(ifp,
    975 			    m->m_pkthdr.csum_flags &
    976 			    (M_CSUM_UDPv6|M_CSUM_TCPv6))) {
    977 				in6_delayed_cksum(m);
    978 			}
    979 			m->m_pkthdr.csum_flags &= ~(M_CSUM_UDPv6|M_CSUM_TCPv6);
    980 		}
    981 
    982 		/*
    983 		 * Loop through length of segment after first fragment,
    984 		 * make new header and copy data of each part and link onto
    985 		 * chain.
    986 		 */
    987 		m0 = m;
    988 		for (off = hlen; off < tlen; off += len) {
    989 			struct mbuf *mlast;
    990 
    991 			MGETHDR(m, M_DONTWAIT, MT_HEADER);
    992 			if (!m) {
    993 				error = ENOBUFS;
    994 				ip6stat.ip6s_odropped++;
    995 				goto sendorfree;
    996 			}
    997 			m->m_pkthdr.rcvif = NULL;
    998 			m->m_flags = m0->m_flags & M_COPYFLAGS;
    999 			*mnext = m;
   1000 			mnext = &m->m_nextpkt;
   1001 			m->m_data += max_linkhdr;
   1002 			mhip6 = mtod(m, struct ip6_hdr *);
   1003 			*mhip6 = *ip6;
   1004 			m->m_len = sizeof(*mhip6);
   1005 			error = ip6_insertfraghdr(m0, m, hlen, &ip6f);
   1006 			if (error) {
   1007 				ip6stat.ip6s_odropped++;
   1008 				goto sendorfree;
   1009 			}
   1010 			ip6f->ip6f_offlg = htons((u_int16_t)((off - hlen) & ~7));
   1011 			if (off + len >= tlen)
   1012 				len = tlen - off;
   1013 			else
   1014 				ip6f->ip6f_offlg |= IP6F_MORE_FRAG;
   1015 			mhip6->ip6_plen = htons((u_int16_t)(len + hlen +
   1016 			    sizeof(*ip6f) - sizeof(struct ip6_hdr)));
   1017 			if ((m_frgpart = m_copy(m0, off, len)) == 0) {
   1018 				error = ENOBUFS;
   1019 				ip6stat.ip6s_odropped++;
   1020 				goto sendorfree;
   1021 			}
   1022 			for (mlast = m; mlast->m_next; mlast = mlast->m_next)
   1023 				;
   1024 			mlast->m_next = m_frgpart;
   1025 			m->m_pkthdr.len = len + hlen + sizeof(*ip6f);
   1026 			m->m_pkthdr.rcvif = (struct ifnet *)0;
   1027 			ip6f->ip6f_reserved = 0;
   1028 			ip6f->ip6f_ident = id;
   1029 			ip6f->ip6f_nxt = nextproto;
   1030 			ip6stat.ip6s_ofragments++;
   1031 			in6_ifstat_inc(ifp, ifs6_out_fragcreat);
   1032 		}
   1033 
   1034 		in6_ifstat_inc(ifp, ifs6_out_fragok);
   1035 	}
   1036 
   1037 	/*
   1038 	 * Remove leading garbages.
   1039 	 */
   1040 sendorfree:
   1041 	m = m0->m_nextpkt;
   1042 	m0->m_nextpkt = 0;
   1043 	m_freem(m0);
   1044 	for (m0 = m; m; m = m0) {
   1045 		m0 = m->m_nextpkt;
   1046 		m->m_nextpkt = 0;
   1047 		if (error == 0) {
   1048 			struct in6_ifaddr *ia6;
   1049 			ip6 = mtod(m, struct ip6_hdr *);
   1050 			ia6 = in6_ifawithifp(ifp, &ip6->ip6_src);
   1051 			if (ia6) {
   1052 				/*
   1053 				 * Record statistics for this interface
   1054 				 * address.
   1055 				 */
   1056 				ia6->ia_ifa.ifa_data.ifad_outbytes +=
   1057 				    m->m_pkthdr.len;
   1058 			}
   1059 #ifdef IPSEC
   1060 			/* clean ipsec history once it goes out of the node */
   1061 			ipsec_delaux(m);
   1062 #endif
   1063 			error = nd6_output(ifp, origifp, m, dst, ro->ro_rt);
   1064 		} else
   1065 			m_freem(m);
   1066 	}
   1067 
   1068 	if (error == 0)
   1069 		ip6stat.ip6s_fragmented++;
   1070 
   1071 done:
   1072 	if (ro == &ip6route && ro->ro_rt) { /* brace necessary for RTFREE */
   1073 		RTFREE(ro->ro_rt);
   1074 	} else if (ro_pmtu == &ip6route && ro_pmtu->ro_rt) {
   1075 		RTFREE(ro_pmtu->ro_rt);
   1076 	}
   1077 
   1078 #ifdef IPSEC
   1079 	if (sp != NULL)
   1080 		key_freesp(sp);
   1081 #endif /* IPSEC */
   1082 
   1083 	return (error);
   1084 
   1085 freehdrs:
   1086 	m_freem(exthdrs.ip6e_hbh);	/* m_freem will check if mbuf is 0 */
   1087 	m_freem(exthdrs.ip6e_dest1);
   1088 	m_freem(exthdrs.ip6e_rthdr);
   1089 	m_freem(exthdrs.ip6e_dest2);
   1090 	/* FALLTHROUGH */
   1091 bad:
   1092 	m_freem(m);
   1093 	goto done;
   1094 }
   1095 
   1096 static int
   1097 ip6_copyexthdr(mp, hdr, hlen)
   1098 	struct mbuf **mp;
   1099 	caddr_t hdr;
   1100 	int hlen;
   1101 {
   1102 	struct mbuf *m;
   1103 
   1104 	if (hlen > MCLBYTES)
   1105 		return (ENOBUFS); /* XXX */
   1106 
   1107 	MGET(m, M_DONTWAIT, MT_DATA);
   1108 	if (!m)
   1109 		return (ENOBUFS);
   1110 
   1111 	if (hlen > MLEN) {
   1112 		MCLGET(m, M_DONTWAIT);
   1113 		if ((m->m_flags & M_EXT) == 0) {
   1114 			m_free(m);
   1115 			return (ENOBUFS);
   1116 		}
   1117 	}
   1118 	m->m_len = hlen;
   1119 	if (hdr)
   1120 		bcopy(hdr, mtod(m, caddr_t), hlen);
   1121 
   1122 	*mp = m;
   1123 	return (0);
   1124 }
   1125 
   1126 /*
   1127  * Process a delayed payload checksum calculation.
   1128  */
   1129 void
   1130 in6_delayed_cksum(struct mbuf *m)
   1131 {
   1132 	uint16_t csum, offset;
   1133 
   1134 	KASSERT((m->m_pkthdr.csum_flags & (M_CSUM_UDPv6|M_CSUM_TCPv6)) != 0);
   1135 	KASSERT((~m->m_pkthdr.csum_flags & (M_CSUM_UDPv6|M_CSUM_TCPv6)) != 0);
   1136 	KASSERT((m->m_pkthdr.csum_flags
   1137 	    & (M_CSUM_UDPv4|M_CSUM_TCPv4|M_CSUM_TSOv4)) == 0);
   1138 
   1139 	offset = M_CSUM_DATA_IPv6_HL(m->m_pkthdr.csum_data);
   1140 	csum = in6_cksum(m, 0, offset, m->m_pkthdr.len - offset);
   1141 	if (csum == 0 && (m->m_pkthdr.csum_flags & M_CSUM_UDPv6) != 0) {
   1142 		csum = 0xffff;
   1143 	}
   1144 
   1145 	offset += M_CSUM_DATA_IPv6_OFFSET(m->m_pkthdr.csum_data);
   1146 	if ((offset + sizeof(csum)) > m->m_len) {
   1147 		m_copyback(m, offset, sizeof(csum), &csum);
   1148 	} else {
   1149 		*(uint16_t *)(mtod(m, caddr_t) + offset) = csum;
   1150 	}
   1151 }
   1152 
   1153 /*
   1154  * Insert jumbo payload option.
   1155  */
   1156 static int
   1157 ip6_insert_jumboopt(exthdrs, plen)
   1158 	struct ip6_exthdrs *exthdrs;
   1159 	u_int32_t plen;
   1160 {
   1161 	struct mbuf *mopt;
   1162 	u_int8_t *optbuf;
   1163 	u_int32_t v;
   1164 
   1165 #define JUMBOOPTLEN	8	/* length of jumbo payload option and padding */
   1166 
   1167 	/*
   1168 	 * If there is no hop-by-hop options header, allocate new one.
   1169 	 * If there is one but it doesn't have enough space to store the
   1170 	 * jumbo payload option, allocate a cluster to store the whole options.
   1171 	 * Otherwise, use it to store the options.
   1172 	 */
   1173 	if (exthdrs->ip6e_hbh == 0) {
   1174 		MGET(mopt, M_DONTWAIT, MT_DATA);
   1175 		if (mopt == 0)
   1176 			return (ENOBUFS);
   1177 		mopt->m_len = JUMBOOPTLEN;
   1178 		optbuf = mtod(mopt, u_int8_t *);
   1179 		optbuf[1] = 0;	/* = ((JUMBOOPTLEN) >> 3) - 1 */
   1180 		exthdrs->ip6e_hbh = mopt;
   1181 	} else {
   1182 		struct ip6_hbh *hbh;
   1183 
   1184 		mopt = exthdrs->ip6e_hbh;
   1185 		if (M_TRAILINGSPACE(mopt) < JUMBOOPTLEN) {
   1186 			/*
   1187 			 * XXX assumption:
   1188 			 * - exthdrs->ip6e_hbh is not referenced from places
   1189 			 *   other than exthdrs.
   1190 			 * - exthdrs->ip6e_hbh is not an mbuf chain.
   1191 			 */
   1192 			int oldoptlen = mopt->m_len;
   1193 			struct mbuf *n;
   1194 
   1195 			/*
   1196 			 * XXX: give up if the whole (new) hbh header does
   1197 			 * not fit even in an mbuf cluster.
   1198 			 */
   1199 			if (oldoptlen + JUMBOOPTLEN > MCLBYTES)
   1200 				return (ENOBUFS);
   1201 
   1202 			/*
   1203 			 * As a consequence, we must always prepare a cluster
   1204 			 * at this point.
   1205 			 */
   1206 			MGET(n, M_DONTWAIT, MT_DATA);
   1207 			if (n) {
   1208 				MCLGET(n, M_DONTWAIT);
   1209 				if ((n->m_flags & M_EXT) == 0) {
   1210 					m_freem(n);
   1211 					n = NULL;
   1212 				}
   1213 			}
   1214 			if (!n)
   1215 				return (ENOBUFS);
   1216 			n->m_len = oldoptlen + JUMBOOPTLEN;
   1217 			bcopy(mtod(mopt, caddr_t), mtod(n, caddr_t),
   1218 			    oldoptlen);
   1219 			optbuf = mtod(n, u_int8_t *) + oldoptlen;
   1220 			m_freem(mopt);
   1221 			mopt = exthdrs->ip6e_hbh = n;
   1222 		} else {
   1223 			optbuf = mtod(mopt, u_int8_t *) + mopt->m_len;
   1224 			mopt->m_len += JUMBOOPTLEN;
   1225 		}
   1226 		optbuf[0] = IP6OPT_PADN;
   1227 		optbuf[1] = 0;
   1228 
   1229 		/*
   1230 		 * Adjust the header length according to the pad and
   1231 		 * the jumbo payload option.
   1232 		 */
   1233 		hbh = mtod(mopt, struct ip6_hbh *);
   1234 		hbh->ip6h_len += (JUMBOOPTLEN >> 3);
   1235 	}
   1236 
   1237 	/* fill in the option. */
   1238 	optbuf[2] = IP6OPT_JUMBO;
   1239 	optbuf[3] = 4;
   1240 	v = (u_int32_t)htonl(plen + JUMBOOPTLEN);
   1241 	bcopy(&v, &optbuf[4], sizeof(u_int32_t));
   1242 
   1243 	/* finally, adjust the packet header length */
   1244 	exthdrs->ip6e_ip6->m_pkthdr.len += JUMBOOPTLEN;
   1245 
   1246 	return (0);
   1247 #undef JUMBOOPTLEN
   1248 }
   1249 
   1250 /*
   1251  * Insert fragment header and copy unfragmentable header portions.
   1252  */
   1253 static int
   1254 ip6_insertfraghdr(m0, m, hlen, frghdrp)
   1255 	struct mbuf *m0, *m;
   1256 	int hlen;
   1257 	struct ip6_frag **frghdrp;
   1258 {
   1259 	struct mbuf *n, *mlast;
   1260 
   1261 	if (hlen > sizeof(struct ip6_hdr)) {
   1262 		n = m_copym(m0, sizeof(struct ip6_hdr),
   1263 		    hlen - sizeof(struct ip6_hdr), M_DONTWAIT);
   1264 		if (n == 0)
   1265 			return (ENOBUFS);
   1266 		m->m_next = n;
   1267 	} else
   1268 		n = m;
   1269 
   1270 	/* Search for the last mbuf of unfragmentable part. */
   1271 	for (mlast = n; mlast->m_next; mlast = mlast->m_next)
   1272 		;
   1273 
   1274 	if ((mlast->m_flags & M_EXT) == 0 &&
   1275 	    M_TRAILINGSPACE(mlast) >= sizeof(struct ip6_frag)) {
   1276 		/* use the trailing space of the last mbuf for the fragment hdr */
   1277 		*frghdrp = (struct ip6_frag *)(mtod(mlast, caddr_t) +
   1278 		    mlast->m_len);
   1279 		mlast->m_len += sizeof(struct ip6_frag);
   1280 		m->m_pkthdr.len += sizeof(struct ip6_frag);
   1281 	} else {
   1282 		/* allocate a new mbuf for the fragment header */
   1283 		struct mbuf *mfrg;
   1284 
   1285 		MGET(mfrg, M_DONTWAIT, MT_DATA);
   1286 		if (mfrg == 0)
   1287 			return (ENOBUFS);
   1288 		mfrg->m_len = sizeof(struct ip6_frag);
   1289 		*frghdrp = mtod(mfrg, struct ip6_frag *);
   1290 		mlast->m_next = mfrg;
   1291 	}
   1292 
   1293 	return (0);
   1294 }
   1295 
   1296 static int
   1297 ip6_getpmtu(ro_pmtu, ro, ifp, dst, mtup, alwaysfragp)
   1298 	struct route_in6 *ro_pmtu, *ro;
   1299 	struct ifnet *ifp;
   1300 	struct in6_addr *dst;
   1301 	u_long *mtup;
   1302 	int *alwaysfragp;
   1303 {
   1304 	u_int32_t mtu = 0;
   1305 	int alwaysfrag = 0;
   1306 	int error = 0;
   1307 
   1308 	if (ro_pmtu != ro) {
   1309 		/* The first hop and the final destination may differ. */
   1310 		struct sockaddr_in6 *sa6_dst =
   1311 		    (struct sockaddr_in6 *)&ro_pmtu->ro_dst;
   1312 		if (ro_pmtu->ro_rt &&
   1313 		    ((ro_pmtu->ro_rt->rt_flags & RTF_UP) == 0 ||
   1314 		      !IN6_ARE_ADDR_EQUAL(&sa6_dst->sin6_addr, dst))) {
   1315 			RTFREE(ro_pmtu->ro_rt);
   1316 			ro_pmtu->ro_rt = (struct rtentry *)NULL;
   1317 		}
   1318 		if (ro_pmtu->ro_rt == NULL) {
   1319 			bzero(sa6_dst, sizeof(*sa6_dst)); /* for safety */
   1320 			sa6_dst->sin6_family = AF_INET6;
   1321 			sa6_dst->sin6_len = sizeof(struct sockaddr_in6);
   1322 			sa6_dst->sin6_addr = *dst;
   1323 
   1324 			rtalloc((struct route *)ro_pmtu);
   1325 		}
   1326 	}
   1327 	if (ro_pmtu->ro_rt) {
   1328 		u_int32_t ifmtu;
   1329 
   1330 		if (ifp == NULL)
   1331 			ifp = ro_pmtu->ro_rt->rt_ifp;
   1332 		ifmtu = IN6_LINKMTU(ifp);
   1333 		mtu = ro_pmtu->ro_rt->rt_rmx.rmx_mtu;
   1334 		if (mtu == 0)
   1335 			mtu = ifmtu;
   1336 		else if (mtu < IPV6_MMTU) {
   1337 			/*
   1338 			 * RFC2460 section 5, last paragraph:
   1339 			 * if we record ICMPv6 too big message with
   1340 			 * mtu < IPV6_MMTU, transmit packets sized IPV6_MMTU
   1341 			 * or smaller, with fragment header attached.
   1342 			 * (fragment header is needed regardless from the
   1343 			 * packet size, for translators to identify packets)
   1344 			 */
   1345 			alwaysfrag = 1;
   1346 			mtu = IPV6_MMTU;
   1347 		} else if (mtu > ifmtu) {
   1348 			/*
   1349 			 * The MTU on the route is larger than the MTU on
   1350 			 * the interface!  This shouldn't happen, unless the
   1351 			 * MTU of the interface has been changed after the
   1352 			 * interface was brought up.  Change the MTU in the
   1353 			 * route to match the interface MTU (as long as the
   1354 			 * field isn't locked).
   1355 			 */
   1356 			mtu = ifmtu;
   1357 			if (!(ro_pmtu->ro_rt->rt_rmx.rmx_locks & RTV_MTU))
   1358 				ro_pmtu->ro_rt->rt_rmx.rmx_mtu = mtu;
   1359 		}
   1360 	} else if (ifp) {
   1361 		mtu = IN6_LINKMTU(ifp);
   1362 	} else
   1363 		error = EHOSTUNREACH; /* XXX */
   1364 
   1365 	*mtup = mtu;
   1366 	if (alwaysfragp)
   1367 		*alwaysfragp = alwaysfrag;
   1368 	return (error);
   1369 }
   1370 
   1371 /*
   1372  * IP6 socket option processing.
   1373  */
   1374 int
   1375 ip6_ctloutput(op, so, level, optname, mp)
   1376 	int op;
   1377 	struct socket *so;
   1378 	int level, optname;
   1379 	struct mbuf **mp;
   1380 {
   1381 	struct in6pcb *in6p = sotoin6pcb(so);
   1382 	struct mbuf *m = *mp;
   1383 	int optval = 0;
   1384 	int error = 0;
   1385 	struct proc *p = curproc;	/* XXX */
   1386 
   1387 	if (level == IPPROTO_IPV6) {
   1388 		switch (op) {
   1389 		case PRCO_SETOPT:
   1390 			switch (optname) {
   1391 			case IPV6_PKTOPTIONS:
   1392 				/* m is freed in ip6_pcbopts */
   1393 				return (ip6_pcbopts(&in6p->in6p_outputopts,
   1394 				    m, so));
   1395 			case IPV6_HOPOPTS:
   1396 			case IPV6_DSTOPTS:
   1397 				if (p == 0 || kauth_authorize_generic(p->p_cred,
   1398 						KAUTH_GENERIC_ISSUSER, &p->p_acflag)) {
   1399 					error = EPERM;
   1400 					break;
   1401 				}
   1402 				/* FALLTHROUGH */
   1403 			case IPV6_UNICAST_HOPS:
   1404 			case IPV6_RECVOPTS:
   1405 			case IPV6_RECVRETOPTS:
   1406 			case IPV6_RECVDSTADDR:
   1407 			case IPV6_PKTINFO:
   1408 			case IPV6_HOPLIMIT:
   1409 			case IPV6_RTHDR:
   1410 			case IPV6_FAITH:
   1411 			case IPV6_V6ONLY:
   1412 			case IPV6_USE_MIN_MTU:
   1413 				if (!m || m->m_len != sizeof(int)) {
   1414 					error = EINVAL;
   1415 					break;
   1416 				}
   1417 				optval = *mtod(m, int *);
   1418 				switch (optname) {
   1419 
   1420 				case IPV6_UNICAST_HOPS:
   1421 					if (optval < -1 || optval >= 256)
   1422 						error = EINVAL;
   1423 					else {
   1424 						/* -1 = kernel default */
   1425 						in6p->in6p_hops = optval;
   1426 					}
   1427 					break;
   1428 #define OPTSET(bit) \
   1429 do { \
   1430 	if (optval) \
   1431 		in6p->in6p_flags |= (bit); \
   1432 	else \
   1433 		in6p->in6p_flags &= ~(bit); \
   1434 } while (/*CONSTCOND*/ 0)
   1435 
   1436 				case IPV6_RECVOPTS:
   1437 					OPTSET(IN6P_RECVOPTS);
   1438 					break;
   1439 
   1440 				case IPV6_RECVRETOPTS:
   1441 					OPTSET(IN6P_RECVRETOPTS);
   1442 					break;
   1443 
   1444 				case IPV6_RECVDSTADDR:
   1445 					OPTSET(IN6P_RECVDSTADDR);
   1446 					break;
   1447 
   1448 				case IPV6_PKTINFO:
   1449 					OPTSET(IN6P_PKTINFO);
   1450 					break;
   1451 
   1452 				case IPV6_HOPLIMIT:
   1453 					OPTSET(IN6P_HOPLIMIT);
   1454 					break;
   1455 
   1456 				case IPV6_HOPOPTS:
   1457 					OPTSET(IN6P_HOPOPTS);
   1458 					break;
   1459 
   1460 				case IPV6_DSTOPTS:
   1461 					OPTSET(IN6P_DSTOPTS);
   1462 					break;
   1463 
   1464 				case IPV6_RTHDR:
   1465 					OPTSET(IN6P_RTHDR);
   1466 					break;
   1467 
   1468 				case IPV6_FAITH:
   1469 					OPTSET(IN6P_FAITH);
   1470 					break;
   1471 
   1472 				case IPV6_USE_MIN_MTU:
   1473 					OPTSET(IN6P_MINMTU);
   1474 					break;
   1475 
   1476 				case IPV6_V6ONLY:
   1477 					/*
   1478 					 * make setsockopt(IPV6_V6ONLY)
   1479 					 * available only prior to bind(2).
   1480 					 * see ipng mailing list, Jun 22 2001.
   1481 					 */
   1482 					if (in6p->in6p_lport ||
   1483 					    !IN6_IS_ADDR_UNSPECIFIED(&in6p->in6p_laddr)) {
   1484 						error = EINVAL;
   1485 						break;
   1486 					}
   1487 #ifdef INET6_BINDV6ONLY
   1488 					if (!optval)
   1489 						error = EINVAL;
   1490 #else
   1491 					OPTSET(IN6P_IPV6_V6ONLY);
   1492 #endif
   1493 					break;
   1494 				}
   1495 				break;
   1496 #undef OPTSET
   1497 
   1498 			case IPV6_MULTICAST_IF:
   1499 			case IPV6_MULTICAST_HOPS:
   1500 			case IPV6_MULTICAST_LOOP:
   1501 			case IPV6_JOIN_GROUP:
   1502 			case IPV6_LEAVE_GROUP:
   1503 				error =	ip6_setmoptions(optname,
   1504 				    &in6p->in6p_moptions, m);
   1505 				break;
   1506 
   1507 			case IPV6_PORTRANGE:
   1508 				optval = *mtod(m, int *);
   1509 
   1510 				switch (optval) {
   1511 				case IPV6_PORTRANGE_DEFAULT:
   1512 					in6p->in6p_flags &= ~(IN6P_LOWPORT);
   1513 					in6p->in6p_flags &= ~(IN6P_HIGHPORT);
   1514 					break;
   1515 
   1516 				case IPV6_PORTRANGE_HIGH:
   1517 					in6p->in6p_flags &= ~(IN6P_LOWPORT);
   1518 					in6p->in6p_flags |= IN6P_HIGHPORT;
   1519 					break;
   1520 
   1521 				case IPV6_PORTRANGE_LOW:
   1522 					in6p->in6p_flags &= ~(IN6P_HIGHPORT);
   1523 					in6p->in6p_flags |= IN6P_LOWPORT;
   1524 					break;
   1525 
   1526 				default:
   1527 					error = EINVAL;
   1528 					break;
   1529 				}
   1530 				break;
   1531 
   1532 #ifdef IPSEC
   1533 			case IPV6_IPSEC_POLICY:
   1534 			    {
   1535 				caddr_t req = NULL;
   1536 				size_t len = 0;
   1537 
   1538 				int priv = 0;
   1539 				if (p == 0 || kauth_authorize_generic(p->p_cred,
   1540 						KAUTH_GENERIC_ISSUSER, &p->p_acflag))
   1541 					priv = 0;
   1542 				else
   1543 					priv = 1;
   1544 				if (m) {
   1545 					req = mtod(m, caddr_t);
   1546 					len = m->m_len;
   1547 				}
   1548 				error = ipsec6_set_policy(in6p,
   1549 				                   optname, req, len, priv);
   1550 			    }
   1551 				break;
   1552 #endif /* IPSEC */
   1553 
   1554 			default:
   1555 				error = ENOPROTOOPT;
   1556 				break;
   1557 			}
   1558 			if (m)
   1559 				(void)m_free(m);
   1560 			break;
   1561 
   1562 		case PRCO_GETOPT:
   1563 			switch (optname) {
   1564 
   1565 			case IPV6_OPTIONS:
   1566 			case IPV6_RETOPTS:
   1567 				error = ENOPROTOOPT;
   1568 				break;
   1569 
   1570 			case IPV6_PKTOPTIONS:
   1571 				if (in6p->in6p_options) {
   1572 					*mp = m_copym(in6p->in6p_options, 0,
   1573 					    M_COPYALL, M_WAIT);
   1574 				} else {
   1575 					*mp = m_get(M_WAIT, MT_SOOPTS);
   1576 					(*mp)->m_len = 0;
   1577 				}
   1578 				break;
   1579 
   1580 			case IPV6_HOPOPTS:
   1581 			case IPV6_DSTOPTS:
   1582 				if (p == 0 || kauth_authorize_generic(p->p_cred,
   1583 						KAUTH_GENERIC_ISSUSER, &p->p_acflag)) {
   1584 					error = EPERM;
   1585 					break;
   1586 				}
   1587 				/* FALLTHROUGH */
   1588 			case IPV6_UNICAST_HOPS:
   1589 			case IPV6_RECVOPTS:
   1590 			case IPV6_RECVRETOPTS:
   1591 			case IPV6_RECVDSTADDR:
   1592 			case IPV6_PORTRANGE:
   1593 			case IPV6_PKTINFO:
   1594 			case IPV6_HOPLIMIT:
   1595 			case IPV6_RTHDR:
   1596 			case IPV6_FAITH:
   1597 			case IPV6_V6ONLY:
   1598 			case IPV6_USE_MIN_MTU:
   1599 				*mp = m = m_get(M_WAIT, MT_SOOPTS);
   1600 				m->m_len = sizeof(int);
   1601 				switch (optname) {
   1602 
   1603 				case IPV6_UNICAST_HOPS:
   1604 					optval = in6p->in6p_hops;
   1605 					break;
   1606 
   1607 #define OPTBIT(bit) (in6p->in6p_flags & bit ? 1 : 0)
   1608 
   1609 				case IPV6_RECVOPTS:
   1610 					optval = OPTBIT(IN6P_RECVOPTS);
   1611 					break;
   1612 
   1613 				case IPV6_RECVRETOPTS:
   1614 					optval = OPTBIT(IN6P_RECVRETOPTS);
   1615 					break;
   1616 
   1617 				case IPV6_RECVDSTADDR:
   1618 					optval = OPTBIT(IN6P_RECVDSTADDR);
   1619 					break;
   1620 
   1621 				case IPV6_PORTRANGE:
   1622 				    {
   1623 					int flags;
   1624 					flags = in6p->in6p_flags;
   1625 					if (flags & IN6P_HIGHPORT)
   1626 						optval = IPV6_PORTRANGE_HIGH;
   1627 					else if (flags & IN6P_LOWPORT)
   1628 						optval = IPV6_PORTRANGE_LOW;
   1629 					else
   1630 						optval = 0;
   1631 					break;
   1632 				    }
   1633 
   1634 				case IPV6_PKTINFO:
   1635 					optval = OPTBIT(IN6P_PKTINFO);
   1636 					break;
   1637 
   1638 				case IPV6_HOPLIMIT:
   1639 					optval = OPTBIT(IN6P_HOPLIMIT);
   1640 					break;
   1641 
   1642 				case IPV6_HOPOPTS:
   1643 					optval = OPTBIT(IN6P_HOPOPTS);
   1644 					break;
   1645 
   1646 				case IPV6_DSTOPTS:
   1647 					optval = OPTBIT(IN6P_DSTOPTS);
   1648 					break;
   1649 
   1650 				case IPV6_RTHDR:
   1651 					optval = OPTBIT(IN6P_RTHDR);
   1652 					break;
   1653 
   1654 				case IPV6_FAITH:
   1655 					optval = OPTBIT(IN6P_FAITH);
   1656 					break;
   1657 
   1658 				case IPV6_V6ONLY:
   1659 					optval = OPTBIT(IN6P_IPV6_V6ONLY);
   1660 					break;
   1661 
   1662 				case IPV6_USE_MIN_MTU:
   1663 					optval = OPTBIT(IN6P_MINMTU);
   1664 					break;
   1665 				}
   1666 				*mtod(m, int *) = optval;
   1667 				break;
   1668 
   1669 			case IPV6_MULTICAST_IF:
   1670 			case IPV6_MULTICAST_HOPS:
   1671 			case IPV6_MULTICAST_LOOP:
   1672 			case IPV6_JOIN_GROUP:
   1673 			case IPV6_LEAVE_GROUP:
   1674 				error = ip6_getmoptions(optname, in6p->in6p_moptions, mp);
   1675 				break;
   1676 
   1677 #if 0	/* defined(IPSEC) */
   1678 			/* XXX: code broken */
   1679 			case IPV6_IPSEC_POLICY:
   1680 			{
   1681 				caddr_t req = NULL;
   1682 				size_t len = 0;
   1683 
   1684 				if (m) {
   1685 					req = mtod(m, caddr_t);
   1686 					len = m->m_len;
   1687 				}
   1688 				error = ipsec6_get_policy(in6p, req, len, mp);
   1689 				break;
   1690 			}
   1691 #endif /* IPSEC */
   1692 
   1693 			default:
   1694 				error = ENOPROTOOPT;
   1695 				break;
   1696 			}
   1697 			break;
   1698 		}
   1699 	} else {
   1700 		error = EINVAL;
   1701 		if (op == PRCO_SETOPT && *mp)
   1702 			(void)m_free(*mp);
   1703 	}
   1704 	return (error);
   1705 }
   1706 
   1707 int
   1708 ip6_raw_ctloutput(op, so, level, optname, mp)
   1709 	int op;
   1710 	struct socket *so;
   1711 	int level, optname;
   1712 	struct mbuf **mp;
   1713 {
   1714 	int error = 0, optval, optlen;
   1715 	const int icmp6off = offsetof(struct icmp6_hdr, icmp6_cksum);
   1716 	struct in6pcb *in6p = sotoin6pcb(so);
   1717 	struct mbuf *m = *mp;
   1718 
   1719 	optlen = m ? m->m_len : 0;
   1720 
   1721 	if (level != IPPROTO_IPV6) {
   1722 		if (op == PRCO_SETOPT && *mp)
   1723 			(void)m_free(*mp);
   1724 		return (EINVAL);
   1725 	}
   1726 
   1727 	switch (optname) {
   1728 	case IPV6_CHECKSUM:
   1729 		/*
   1730 		 * For ICMPv6 sockets, no modification allowed for checksum
   1731 		 * offset, permit "no change" values to help existing apps.
   1732 		 *
   1733 		 * XXX 2292bis says: "An attempt to set IPV6_CHECKSUM
   1734 		 * for an ICMPv6 socket will fail."
   1735 		 * The current behavior does not meet 2292bis.
   1736 		 */
   1737 		switch (op) {
   1738 		case PRCO_SETOPT:
   1739 			if (optlen != sizeof(int)) {
   1740 				error = EINVAL;
   1741 				break;
   1742 			}
   1743 			optval = *mtod(m, int *);
   1744 			if ((optval % 2) != 0) {
   1745 				/* the API assumes even offset values */
   1746 				error = EINVAL;
   1747 			} else if (so->so_proto->pr_protocol ==
   1748 			    IPPROTO_ICMPV6) {
   1749 				if (optval != icmp6off)
   1750 					error = EINVAL;
   1751 			} else
   1752 				in6p->in6p_cksum = optval;
   1753 			break;
   1754 
   1755 		case PRCO_GETOPT:
   1756 			if (so->so_proto->pr_protocol == IPPROTO_ICMPV6)
   1757 				optval = icmp6off;
   1758 			else
   1759 				optval = in6p->in6p_cksum;
   1760 
   1761 			*mp = m = m_get(M_WAIT, MT_SOOPTS);
   1762 			m->m_len = sizeof(int);
   1763 			*mtod(m, int *) = optval;
   1764 			break;
   1765 
   1766 		default:
   1767 			error = EINVAL;
   1768 			break;
   1769 		}
   1770 		break;
   1771 
   1772 	default:
   1773 		error = ENOPROTOOPT;
   1774 		break;
   1775 	}
   1776 
   1777 	if (op == PRCO_SETOPT && m)
   1778 		(void)m_free(m);
   1779 
   1780 	return (error);
   1781 }
   1782 
   1783 /*
   1784  * Set up IP6 options in pcb for insertion in output packets.
   1785  * Store in mbuf with pointer in pcbopt, adding pseudo-option
   1786  * with destination address if source routed.
   1787  */
   1788 static int
   1789 ip6_pcbopts(pktopt, m, so)
   1790 	struct ip6_pktopts **pktopt;
   1791 	struct mbuf *m;
   1792 	struct socket *so;
   1793 {
   1794 	struct ip6_pktopts *opt = *pktopt;
   1795 	int error = 0;
   1796 	struct proc *p = curproc;	/* XXX */
   1797 	int priv = 0;
   1798 
   1799 	/* turn off any old options. */
   1800 	if (opt) {
   1801 		if (opt->ip6po_m)
   1802 			(void)m_free(opt->ip6po_m);
   1803 	} else
   1804 		opt = malloc(sizeof(*opt), M_IP6OPT, M_WAITOK);
   1805 	*pktopt = 0;
   1806 
   1807 	if (!m || m->m_len == 0) {
   1808 		/*
   1809 		 * Only turning off any previous options.
   1810 		 */
   1811 		free(opt, M_IP6OPT);
   1812 		if (m)
   1813 			(void)m_free(m);
   1814 		return (0);
   1815 	}
   1816 
   1817 	/*  set options specified by user. */
   1818 	if (p && !kauth_authorize_generic(p->p_cred, KAUTH_GENERIC_ISSUSER, &p->p_acflag))
   1819 		priv = 1;
   1820 	if ((error = ip6_setpktoptions(m, opt, priv)) != 0) {
   1821 		(void)m_free(m);
   1822 		free(opt, M_IP6OPT);
   1823 		return (error);
   1824 	}
   1825 	*pktopt = opt;
   1826 	return (0);
   1827 }
   1828 
   1829 /*
   1830  * Set the IP6 multicast options in response to user setsockopt().
   1831  */
   1832 static int
   1833 ip6_setmoptions(optname, im6op, m)
   1834 	int optname;
   1835 	struct ip6_moptions **im6op;
   1836 	struct mbuf *m;
   1837 {
   1838 	int error = 0;
   1839 	u_int loop, ifindex;
   1840 	struct ipv6_mreq *mreq;
   1841 	struct ifnet *ifp;
   1842 	struct ip6_moptions *im6o = *im6op;
   1843 	struct route_in6 ro;
   1844 	struct in6_multi_mship *imm;
   1845 	struct proc *p = curproc;	/* XXX */
   1846 
   1847 	if (im6o == NULL) {
   1848 		/*
   1849 		 * No multicast option buffer attached to the pcb;
   1850 		 * allocate one and initialize to default values.
   1851 		 */
   1852 		im6o = (struct ip6_moptions *)
   1853 			malloc(sizeof(*im6o), M_IPMOPTS, M_WAITOK);
   1854 
   1855 		if (im6o == NULL)
   1856 			return (ENOBUFS);
   1857 		*im6op = im6o;
   1858 		im6o->im6o_multicast_ifp = NULL;
   1859 		im6o->im6o_multicast_hlim = ip6_defmcasthlim;
   1860 		im6o->im6o_multicast_loop = IPV6_DEFAULT_MULTICAST_LOOP;
   1861 		LIST_INIT(&im6o->im6o_memberships);
   1862 	}
   1863 
   1864 	switch (optname) {
   1865 
   1866 	case IPV6_MULTICAST_IF:
   1867 		/*
   1868 		 * Select the interface for outgoing multicast packets.
   1869 		 */
   1870 		if (m == NULL || m->m_len != sizeof(u_int)) {
   1871 			error = EINVAL;
   1872 			break;
   1873 		}
   1874 		bcopy(mtod(m, u_int *), &ifindex, sizeof(ifindex));
   1875 		if (ifindex != 0) {
   1876 			if (ifindex < 0 || if_indexlim <= ifindex ||
   1877 			    !ifindex2ifnet[ifindex]) {
   1878 				error = ENXIO;	/* XXX EINVAL? */
   1879 				break;
   1880 			}
   1881 			ifp = ifindex2ifnet[ifindex];
   1882 			if ((ifp->if_flags & IFF_MULTICAST) == 0) {
   1883 				error = EADDRNOTAVAIL;
   1884 				break;
   1885 			}
   1886 		} else
   1887 			ifp = NULL;
   1888 		im6o->im6o_multicast_ifp = ifp;
   1889 		break;
   1890 
   1891 	case IPV6_MULTICAST_HOPS:
   1892 	    {
   1893 		/*
   1894 		 * Set the IP6 hoplimit for outgoing multicast packets.
   1895 		 */
   1896 		int optval;
   1897 		if (m == NULL || m->m_len != sizeof(int)) {
   1898 			error = EINVAL;
   1899 			break;
   1900 		}
   1901 		bcopy(mtod(m, u_int *), &optval, sizeof(optval));
   1902 		if (optval < -1 || optval >= 256)
   1903 			error = EINVAL;
   1904 		else if (optval == -1)
   1905 			im6o->im6o_multicast_hlim = ip6_defmcasthlim;
   1906 		else
   1907 			im6o->im6o_multicast_hlim = optval;
   1908 		break;
   1909 	    }
   1910 
   1911 	case IPV6_MULTICAST_LOOP:
   1912 		/*
   1913 		 * Set the loopback flag for outgoing multicast packets.
   1914 		 * Must be zero or one.
   1915 		 */
   1916 		if (m == NULL || m->m_len != sizeof(u_int)) {
   1917 			error = EINVAL;
   1918 			break;
   1919 		}
   1920 		bcopy(mtod(m, u_int *), &loop, sizeof(loop));
   1921 		if (loop > 1) {
   1922 			error = EINVAL;
   1923 			break;
   1924 		}
   1925 		im6o->im6o_multicast_loop = loop;
   1926 		break;
   1927 
   1928 	case IPV6_JOIN_GROUP:
   1929 		/*
   1930 		 * Add a multicast group membership.
   1931 		 * Group must be a valid IP6 multicast address.
   1932 		 */
   1933 		if (m == NULL || m->m_len != sizeof(struct ipv6_mreq)) {
   1934 			error = EINVAL;
   1935 			break;
   1936 		}
   1937 		mreq = mtod(m, struct ipv6_mreq *);
   1938 		if (IN6_IS_ADDR_UNSPECIFIED(&mreq->ipv6mr_multiaddr)) {
   1939 			/*
   1940 			 * We use the unspecified address to specify to accept
   1941 			 * all multicast addresses. Only super user is allowed
   1942 			 * to do this.
   1943 			 */
   1944 			if (kauth_authorize_generic(p->p_cred, KAUTH_GENERIC_ISSUSER, &p->p_acflag))
   1945 			{
   1946 				error = EACCES;
   1947 				break;
   1948 			}
   1949 		} else if (!IN6_IS_ADDR_MULTICAST(&mreq->ipv6mr_multiaddr)) {
   1950 			error = EINVAL;
   1951 			break;
   1952 		}
   1953 
   1954 		/*
   1955 		 * If no interface was explicitly specified, choose an
   1956 		 * appropriate one according to the given multicast address.
   1957 		 */
   1958 		if (mreq->ipv6mr_interface == 0) {
   1959 			struct sockaddr_in6 *dst;
   1960 
   1961 			/*
   1962 			 * Look up the routing table for the
   1963 			 * address, and choose the outgoing interface.
   1964 			 *   XXX: is it a good approach?
   1965 			 */
   1966 			ro.ro_rt = NULL;
   1967 			dst = (struct sockaddr_in6 *)&ro.ro_dst;
   1968 			bzero(dst, sizeof(*dst));
   1969 			dst->sin6_family = AF_INET6;
   1970 			dst->sin6_len = sizeof(*dst);
   1971 			dst->sin6_addr = mreq->ipv6mr_multiaddr;
   1972 			rtalloc((struct route *)&ro);
   1973 			if (ro.ro_rt == NULL) {
   1974 				error = EADDRNOTAVAIL;
   1975 				break;
   1976 			}
   1977 			ifp = ro.ro_rt->rt_ifp;
   1978 			rtfree(ro.ro_rt);
   1979 		} else {
   1980 			/*
   1981 			 * If the interface is specified, validate it.
   1982 			 */
   1983 			if (mreq->ipv6mr_interface < 0 ||
   1984 			    if_indexlim <= mreq->ipv6mr_interface ||
   1985 			    !ifindex2ifnet[mreq->ipv6mr_interface]) {
   1986 				error = ENXIO;	/* XXX EINVAL? */
   1987 				break;
   1988 			}
   1989 			ifp = ifindex2ifnet[mreq->ipv6mr_interface];
   1990 		}
   1991 
   1992 		/*
   1993 		 * See if we found an interface, and confirm that it
   1994 		 * supports multicast
   1995 		 */
   1996 		if (ifp == NULL || (ifp->if_flags & IFF_MULTICAST) == 0) {
   1997 			error = EADDRNOTAVAIL;
   1998 			break;
   1999 		}
   2000 
   2001 		if (in6_setscope(&mreq->ipv6mr_multiaddr, ifp, NULL)) {
   2002 			error = EADDRNOTAVAIL; /* XXX: should not happen */
   2003 			break;
   2004 		}
   2005 
   2006 		/*
   2007 		 * See if the membership already exists.
   2008 		 */
   2009 		for (imm = im6o->im6o_memberships.lh_first;
   2010 		     imm != NULL; imm = imm->i6mm_chain.le_next)
   2011 			if (imm->i6mm_maddr->in6m_ifp == ifp &&
   2012 			    IN6_ARE_ADDR_EQUAL(&imm->i6mm_maddr->in6m_addr,
   2013 			    &mreq->ipv6mr_multiaddr))
   2014 				break;
   2015 		if (imm != NULL) {
   2016 			error = EADDRINUSE;
   2017 			break;
   2018 		}
   2019 		/*
   2020 		 * Everything looks good; add a new record to the multicast
   2021 		 * address list for the given interface.
   2022 		 */
   2023 		imm = in6_joingroup(ifp, &mreq->ipv6mr_multiaddr, &error, 0);
   2024 		if (imm == NULL)
   2025 			break;
   2026 		LIST_INSERT_HEAD(&im6o->im6o_memberships, imm, i6mm_chain);
   2027 		break;
   2028 
   2029 	case IPV6_LEAVE_GROUP:
   2030 		/*
   2031 		 * Drop a multicast group membership.
   2032 		 * Group must be a valid IP6 multicast address.
   2033 		 */
   2034 		if (m == NULL || m->m_len != sizeof(struct ipv6_mreq)) {
   2035 			error = EINVAL;
   2036 			break;
   2037 		}
   2038 		mreq = mtod(m, struct ipv6_mreq *);
   2039 
   2040 		/*
   2041 		 * If an interface address was specified, get a pointer
   2042 		 * to its ifnet structure.
   2043 		 */
   2044 		if (mreq->ipv6mr_interface != 0) {
   2045 			if (mreq->ipv6mr_interface < 0 ||
   2046 			    if_indexlim <= mreq->ipv6mr_interface ||
   2047 			    !ifindex2ifnet[mreq->ipv6mr_interface]) {
   2048 				error = ENXIO;	/* XXX EINVAL? */
   2049 				break;
   2050 			}
   2051 			ifp = ifindex2ifnet[mreq->ipv6mr_interface];
   2052 		} else
   2053 			ifp = NULL;
   2054 
   2055 		/* Fill in the scope zone ID */
   2056 		if (ifp) {
   2057 			if (in6_setscope(&mreq->ipv6mr_multiaddr, ifp, NULL)) {
   2058 				/* XXX: should not happen */
   2059 				error = EADDRNOTAVAIL;
   2060 				break;
   2061 			}
   2062 		} else if (mreq->ipv6mr_interface != 0) {
   2063 			/*
   2064 			 * XXX: This case would happens when the (positive)
   2065 			 * index is in the valid range, but the corresponding
   2066 			 * interface has been detached dynamically.  The above
   2067 			 * check probably avoids such case to happen here, but
   2068 			 * we check it explicitly for safety.
   2069 			 */
   2070 			error = EADDRNOTAVAIL;
   2071 			break;
   2072 		} else {	/* ipv6mr_interface == 0 */
   2073 			struct sockaddr_in6 sa6_mc;
   2074 
   2075 			/*
   2076 			 * The API spec says as follows:
   2077 			 *  If the interface index is specified as 0, the
   2078 			 *  system may choose a multicast group membership to
   2079 			 *  drop by matching the multicast address only.
   2080 			 * On the other hand, we cannot disambiguate the scope
   2081 			 * zone unless an interface is provided.  Thus, we
   2082 			 * check if there's ambiguity with the default scope
   2083 			 * zone as the last resort.
   2084 			 */
   2085 			bzero(&sa6_mc, sizeof(sa6_mc));
   2086 			sa6_mc.sin6_family = AF_INET6;
   2087 			sa6_mc.sin6_len = sizeof(sa6_mc);
   2088 			sa6_mc.sin6_addr = mreq->ipv6mr_multiaddr;
   2089 			error = sa6_embedscope(&sa6_mc, ip6_use_defzone);
   2090 			if (error != 0)
   2091 				break;
   2092 			mreq->ipv6mr_multiaddr = sa6_mc.sin6_addr;
   2093 		}
   2094 
   2095 		/*
   2096 		 * Find the membership in the membership list.
   2097 		 */
   2098 		for (imm = im6o->im6o_memberships.lh_first;
   2099 		     imm != NULL; imm = imm->i6mm_chain.le_next) {
   2100 			if ((ifp == NULL || imm->i6mm_maddr->in6m_ifp == ifp) &&
   2101 			    IN6_ARE_ADDR_EQUAL(&imm->i6mm_maddr->in6m_addr,
   2102 			    &mreq->ipv6mr_multiaddr))
   2103 				break;
   2104 		}
   2105 		if (imm == NULL) {
   2106 			/* Unable to resolve interface */
   2107 			error = EADDRNOTAVAIL;
   2108 			break;
   2109 		}
   2110 		/*
   2111 		 * Give up the multicast address record to which the
   2112 		 * membership points.
   2113 		 */
   2114 		LIST_REMOVE(imm, i6mm_chain);
   2115 		in6_leavegroup(imm);
   2116 		break;
   2117 
   2118 	default:
   2119 		error = EOPNOTSUPP;
   2120 		break;
   2121 	}
   2122 
   2123 	/*
   2124 	 * If all options have default values, no need to keep the mbuf.
   2125 	 */
   2126 	if (im6o->im6o_multicast_ifp == NULL &&
   2127 	    im6o->im6o_multicast_hlim == ip6_defmcasthlim &&
   2128 	    im6o->im6o_multicast_loop == IPV6_DEFAULT_MULTICAST_LOOP &&
   2129 	    im6o->im6o_memberships.lh_first == NULL) {
   2130 		free(*im6op, M_IPMOPTS);
   2131 		*im6op = NULL;
   2132 	}
   2133 
   2134 	return (error);
   2135 }
   2136 
   2137 /*
   2138  * Return the IP6 multicast options in response to user getsockopt().
   2139  */
   2140 static int
   2141 ip6_getmoptions(optname, im6o, mp)
   2142 	int optname;
   2143 	struct ip6_moptions *im6o;
   2144 	struct mbuf **mp;
   2145 {
   2146 	u_int *hlim, *loop, *ifindex;
   2147 
   2148 	*mp = m_get(M_WAIT, MT_SOOPTS);
   2149 
   2150 	switch (optname) {
   2151 
   2152 	case IPV6_MULTICAST_IF:
   2153 		ifindex = mtod(*mp, u_int *);
   2154 		(*mp)->m_len = sizeof(u_int);
   2155 		if (im6o == NULL || im6o->im6o_multicast_ifp == NULL)
   2156 			*ifindex = 0;
   2157 		else
   2158 			*ifindex = im6o->im6o_multicast_ifp->if_index;
   2159 		return (0);
   2160 
   2161 	case IPV6_MULTICAST_HOPS:
   2162 		hlim = mtod(*mp, u_int *);
   2163 		(*mp)->m_len = sizeof(u_int);
   2164 		if (im6o == NULL)
   2165 			*hlim = ip6_defmcasthlim;
   2166 		else
   2167 			*hlim = im6o->im6o_multicast_hlim;
   2168 		return (0);
   2169 
   2170 	case IPV6_MULTICAST_LOOP:
   2171 		loop = mtod(*mp, u_int *);
   2172 		(*mp)->m_len = sizeof(u_int);
   2173 		if (im6o == NULL)
   2174 			*loop = ip6_defmcasthlim;
   2175 		else
   2176 			*loop = im6o->im6o_multicast_loop;
   2177 		return (0);
   2178 
   2179 	default:
   2180 		return (EOPNOTSUPP);
   2181 	}
   2182 }
   2183 
   2184 /*
   2185  * Discard the IP6 multicast options.
   2186  */
   2187 void
   2188 ip6_freemoptions(im6o)
   2189 	struct ip6_moptions *im6o;
   2190 {
   2191 	struct in6_multi_mship *imm;
   2192 
   2193 	if (im6o == NULL)
   2194 		return;
   2195 
   2196 	while ((imm = im6o->im6o_memberships.lh_first) != NULL) {
   2197 		LIST_REMOVE(imm, i6mm_chain);
   2198 		in6_leavegroup(imm);
   2199 	}
   2200 	free(im6o, M_IPMOPTS);
   2201 }
   2202 
   2203 /*
   2204  * Set IPv6 outgoing packet options based on advanced API.
   2205  */
   2206 int
   2207 ip6_setpktoptions(control, opt, priv)
   2208 	struct mbuf *control;
   2209 	struct ip6_pktopts *opt;
   2210 	int priv;
   2211 {
   2212 	struct cmsghdr *cm = 0;
   2213 
   2214 	if (control == 0 || opt == 0)
   2215 		return (EINVAL);
   2216 
   2217 	bzero(opt, sizeof(*opt));
   2218 	opt->ip6po_hlim = -1; /* -1 means to use default hop limit */
   2219 
   2220 	/*
   2221 	 * XXX: Currently, we assume all the optional information is stored
   2222 	 * in a single mbuf.
   2223 	 */
   2224 	if (control->m_next)
   2225 		return (EINVAL);
   2226 
   2227 	opt->ip6po_m = control;
   2228 
   2229 	for (; control->m_len; control->m_data += CMSG_ALIGN(cm->cmsg_len),
   2230 	    control->m_len -= CMSG_ALIGN(cm->cmsg_len)) {
   2231 		cm = mtod(control, struct cmsghdr *);
   2232 		if (cm->cmsg_len == 0 || cm->cmsg_len > control->m_len)
   2233 			return (EINVAL);
   2234 		if (cm->cmsg_level != IPPROTO_IPV6)
   2235 			continue;
   2236 
   2237 		switch (cm->cmsg_type) {
   2238 		case IPV6_PKTINFO:
   2239 			if (cm->cmsg_len != CMSG_LEN(sizeof(struct in6_pktinfo)))
   2240 				return (EINVAL);
   2241 			opt->ip6po_pktinfo = (struct in6_pktinfo *)CMSG_DATA(cm);
   2242 			if (opt->ip6po_pktinfo->ipi6_ifindex >= if_indexlim ||
   2243 			    opt->ip6po_pktinfo->ipi6_ifindex < 0)
   2244 				return (ENXIO);
   2245 			if (opt->ip6po_pktinfo->ipi6_ifindex > 0 &&
   2246 			    !ifindex2ifnet[opt->ip6po_pktinfo->ipi6_ifindex])
   2247 				return (ENXIO);
   2248 
   2249 			if (opt->ip6po_pktinfo->ipi6_ifindex) {
   2250 				struct ifnet *ifp;
   2251 				int error;
   2252 
   2253 				/* ipi6_ifindex must be valid here */
   2254 				ifp = ifindex2ifnet[opt->ip6po_pktinfo->ipi6_ifindex];
   2255 				error = in6_setscope(&opt->ip6po_pktinfo->ipi6_addr,
   2256 				    ifp, NULL);
   2257 				if (error != 0)
   2258 					return (error);
   2259 			}
   2260 
   2261 			/*
   2262 			 * Check if the requested source address is indeed a
   2263 			 * unicast address assigned to the node, and can be
   2264 			 * used as the packet's source address.
   2265 			 */
   2266 			if (!IN6_IS_ADDR_UNSPECIFIED(&opt->ip6po_pktinfo->ipi6_addr)) {
   2267 				struct ifaddr *ia;
   2268 				struct in6_ifaddr *ia6;
   2269 				struct sockaddr_in6 sin6;
   2270 
   2271 				bzero(&sin6, sizeof(sin6));
   2272 				sin6.sin6_len = sizeof(sin6);
   2273 				sin6.sin6_family = AF_INET6;
   2274 				sin6.sin6_addr =
   2275 					opt->ip6po_pktinfo->ipi6_addr;
   2276 				ia = ifa_ifwithaddr(sin6tosa(&sin6));
   2277 				if (ia == NULL ||
   2278 				    (opt->ip6po_pktinfo->ipi6_ifindex &&
   2279 				     (ia->ifa_ifp->if_index !=
   2280 				      opt->ip6po_pktinfo->ipi6_ifindex))) {
   2281 					return (EADDRNOTAVAIL);
   2282 				}
   2283 				ia6 = (struct in6_ifaddr *)ia;
   2284 				if ((ia6->ia6_flags & (IN6_IFF_ANYCAST|IN6_IFF_NOTREADY)) != 0) {
   2285 					return (EADDRNOTAVAIL);
   2286 				}
   2287 
   2288 				/*
   2289 				 * Check if the requested source address is
   2290 				 * indeed a unicast address assigned to the
   2291 				 * node.
   2292 				 */
   2293 				if (IN6_IS_ADDR_MULTICAST(&opt->ip6po_pktinfo->ipi6_addr))
   2294 					return (EADDRNOTAVAIL);
   2295 			}
   2296 			break;
   2297 
   2298 		case IPV6_HOPLIMIT:
   2299 			if (cm->cmsg_len != CMSG_LEN(sizeof(int)))
   2300 				return (EINVAL);
   2301 			else {
   2302 				int t;
   2303 
   2304 				bcopy(CMSG_DATA(cm), &t, sizeof(t));
   2305 				if (t < -1 || t > 255)
   2306 					return (EINVAL);
   2307 				opt->ip6po_hlim = t;
   2308 			}
   2309 			break;
   2310 
   2311 		case IPV6_NEXTHOP:
   2312 			if (!priv)
   2313 				return (EPERM);
   2314 
   2315 			/* check if cmsg_len is large enough for sa_len */
   2316 			if (cm->cmsg_len < sizeof(u_char) ||
   2317 			    cm->cmsg_len < CMSG_LEN(*CMSG_DATA(cm)))
   2318 				return (EINVAL);
   2319 
   2320 			opt->ip6po_nexthop = (struct sockaddr *)CMSG_DATA(cm);
   2321 
   2322 			break;
   2323 
   2324 		case IPV6_HOPOPTS:
   2325 			if (cm->cmsg_len < CMSG_LEN(sizeof(struct ip6_hbh)))
   2326 				return (EINVAL);
   2327 			else {
   2328 				struct  ip6_hbh *t;
   2329 
   2330 				t = (struct ip6_hbh *)CMSG_DATA(cm);
   2331 				if (cm->cmsg_len !=
   2332 				    CMSG_LEN((t->ip6h_len + 1) << 3))
   2333 					return (EINVAL);
   2334 				opt->ip6po_hbh = t;
   2335 			}
   2336 			break;
   2337 
   2338 		case IPV6_DSTOPTS:
   2339 			if (cm->cmsg_len < CMSG_LEN(sizeof(struct ip6_dest)))
   2340 				return (EINVAL);
   2341 
   2342 			/*
   2343 			 * If there is no routing header yet, the destination
   2344 			 * options header should be put on the 1st part.
   2345 			 * Otherwise, the header should be on the 2nd part.
   2346 			 * (See RFC 2460, section 4.1)
   2347 			 */
   2348 			if (opt->ip6po_rthdr == NULL) {
   2349 				struct ip6_dest *t;
   2350 
   2351 				t = (struct ip6_dest *)CMSG_DATA(cm);
   2352 				if (cm->cmsg_len !=
   2353 				    CMSG_LEN((t->ip6d_len + 1) << 3));
   2354 					return (EINVAL);
   2355 				opt->ip6po_dest1 = t;
   2356 			}
   2357 			else {
   2358 				struct ip6_dest *t;
   2359 
   2360 				t = (struct ip6_dest *)CMSG_DATA(cm);
   2361 				if (cm->cmsg_len !=
   2362 				    CMSG_LEN((opt->ip6po_dest2->ip6d_len + 1) << 3))
   2363 					return (EINVAL);
   2364 				opt->ip6po_dest2 = t;
   2365 			}
   2366 			break;
   2367 
   2368 		case IPV6_RTHDR:
   2369 			if (cm->cmsg_len < CMSG_LEN(sizeof(struct ip6_rthdr)))
   2370 				return (EINVAL);
   2371 			else {
   2372 				struct ip6_rthdr *t;
   2373 
   2374 				t = (struct ip6_rthdr *)CMSG_DATA(cm);
   2375 				if (cm->cmsg_len !=
   2376 				    CMSG_LEN((t->ip6r_len + 1) << 3))
   2377 					return (EINVAL);
   2378 				switch (t->ip6r_type) {
   2379 				case IPV6_RTHDR_TYPE_0:
   2380 					if (t->ip6r_segleft == 0)
   2381 						return (EINVAL);
   2382 					break;
   2383 				default:
   2384 					return (EINVAL);
   2385 				}
   2386 				opt->ip6po_rthdr = t;
   2387 			}
   2388 			break;
   2389 
   2390 		default:
   2391 			return (ENOPROTOOPT);
   2392 		}
   2393 	}
   2394 
   2395 	return (0);
   2396 }
   2397 
   2398 /*
   2399  * Routine called from ip6_output() to loop back a copy of an IP6 multicast
   2400  * packet to the input queue of a specified interface.  Note that this
   2401  * calls the output routine of the loopback "driver", but with an interface
   2402  * pointer that might NOT be lo0ifp -- easier than replicating that code here.
   2403  */
   2404 void
   2405 ip6_mloopback(ifp, m, dst)
   2406 	struct ifnet *ifp;
   2407 	struct mbuf *m;
   2408 	struct sockaddr_in6 *dst;
   2409 {
   2410 	struct mbuf *copym;
   2411 	struct ip6_hdr *ip6;
   2412 
   2413 	copym = m_copy(m, 0, M_COPYALL);
   2414 	if (copym == NULL)
   2415 		return;
   2416 
   2417 	/*
   2418 	 * Make sure to deep-copy IPv6 header portion in case the data
   2419 	 * is in an mbuf cluster, so that we can safely override the IPv6
   2420 	 * header portion later.
   2421 	 */
   2422 	if ((copym->m_flags & M_EXT) != 0 ||
   2423 	    copym->m_len < sizeof(struct ip6_hdr)) {
   2424 		copym = m_pullup(copym, sizeof(struct ip6_hdr));
   2425 		if (copym == NULL)
   2426 			return;
   2427 	}
   2428 
   2429 #ifdef DIAGNOSTIC
   2430 	if (copym->m_len < sizeof(*ip6)) {
   2431 		m_freem(copym);
   2432 		return;
   2433 	}
   2434 #endif
   2435 
   2436 	ip6 = mtod(copym, struct ip6_hdr *);
   2437 	/*
   2438 	 * clear embedded scope identifiers if necessary.
   2439 	 * in6_clearscope will touch the addresses only when necessary.
   2440 	 */
   2441 	in6_clearscope(&ip6->ip6_src);
   2442 	in6_clearscope(&ip6->ip6_dst);
   2443 
   2444 	(void)looutput(ifp, copym, (struct sockaddr *)dst, NULL);
   2445 }
   2446 
   2447 /*
   2448  * Chop IPv6 header off from the payload.
   2449  */
   2450 static int
   2451 ip6_splithdr(m, exthdrs)
   2452 	struct mbuf *m;
   2453 	struct ip6_exthdrs *exthdrs;
   2454 {
   2455 	struct mbuf *mh;
   2456 	struct ip6_hdr *ip6;
   2457 
   2458 	ip6 = mtod(m, struct ip6_hdr *);
   2459 	if (m->m_len > sizeof(*ip6)) {
   2460 		MGETHDR(mh, M_DONTWAIT, MT_HEADER);
   2461 		if (mh == 0) {
   2462 			m_freem(m);
   2463 			return ENOBUFS;
   2464 		}
   2465 		M_MOVE_PKTHDR(mh, m);
   2466 		MH_ALIGN(mh, sizeof(*ip6));
   2467 		m->m_len -= sizeof(*ip6);
   2468 		m->m_data += sizeof(*ip6);
   2469 		mh->m_next = m;
   2470 		m = mh;
   2471 		m->m_len = sizeof(*ip6);
   2472 		bcopy((caddr_t)ip6, mtod(m, caddr_t), sizeof(*ip6));
   2473 	}
   2474 	exthdrs->ip6e_ip6 = m;
   2475 	return 0;
   2476 }
   2477 
   2478 /*
   2479  * Compute IPv6 extension header length.
   2480  */
   2481 int
   2482 ip6_optlen(in6p)
   2483 	struct in6pcb *in6p;
   2484 {
   2485 	int len;
   2486 
   2487 	if (!in6p->in6p_outputopts)
   2488 		return 0;
   2489 
   2490 	len = 0;
   2491 #define elen(x) \
   2492     (((struct ip6_ext *)(x)) ? (((struct ip6_ext *)(x))->ip6e_len + 1) << 3 : 0)
   2493 
   2494 	len += elen(in6p->in6p_outputopts->ip6po_hbh);
   2495 	len += elen(in6p->in6p_outputopts->ip6po_dest1);
   2496 	len += elen(in6p->in6p_outputopts->ip6po_rthdr);
   2497 	len += elen(in6p->in6p_outputopts->ip6po_dest2);
   2498 	return len;
   2499 #undef elen
   2500 }
   2501