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