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