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