Home | History | Annotate | Line # | Download | only in netinet6
ip6_output.c revision 1.44
      1 /*	$NetBSD: ip6_output.c,v 1.44 2002/03/28 01:33:50 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. 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 2002/03/28 01:33:50 itojun 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 > ifmtu || mtu == 0) {
    738 			/*
    739 			 * The MTU on the route is larger than the MTU on
    740 			 * the interface!  This shouldn't happen, unless the
    741 			 * MTU of the interface has been changed after the
    742 			 * interface was brought up.  Change the MTU in the
    743 			 * route to match the interface MTU (as long as the
    744 			 * field isn't locked).
    745 			 *
    746 			 * if MTU on the route is 0, we need to fix the MTU.
    747 			 * this case happens with path MTU discovery timeouts.
    748 			 */
    749 			 mtu = ifmtu;
    750 			 if ((ro_pmtu->ro_rt->rt_rmx.rmx_locks & RTV_MTU) == 0)
    751 				 ro_pmtu->ro_rt->rt_rmx.rmx_mtu = mtu; /* XXX */
    752 		}
    753 	} else {
    754 		mtu = nd_ifinfo[ifp->if_index].linkmtu;
    755 	}
    756 
    757 	if (mtu > IPV6_MMTU &&
    758 	    (flags & IPV6_MINMTU)) {
    759 		mtu = IPV6_MMTU;
    760 	}
    761 
    762 	/* Fake scoped addresses */
    763 	if ((ifp->if_flags & IFF_LOOPBACK) != 0) {
    764 		/*
    765 		 * If source or destination address is a scoped address, and
    766 		 * the packet is going to be sent to a loopback interface,
    767 		 * we should keep the original interface.
    768 		 */
    769 
    770 		/*
    771 		 * XXX: this is a very experimental and temporary solution.
    772 		 * We eventually have sockaddr_in6 and use the sin6_scope_id
    773 		 * field of the structure here.
    774 		 * We rely on the consistency between two scope zone ids
    775 		 * of source add destination, which should already be assured
    776 		 * Larger scopes than link will be supported in the near
    777 		 * future.
    778 		 */
    779 		origifp = NULL;
    780 		if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_src))
    781 			origifp = ifindex2ifnet[ntohs(ip6->ip6_src.s6_addr16[1])];
    782 		else if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_dst))
    783 			origifp = ifindex2ifnet[ntohs(ip6->ip6_dst.s6_addr16[1])];
    784 		/*
    785 		 * XXX: origifp can be NULL even in those two cases above.
    786 		 * For example, if we remove the (only) link-local address
    787 		 * from the loopback interface, and try to send a link-local
    788 		 * address without link-id information.  Then the source
    789 		 * address is ::1, and the destination address is the
    790 		 * link-local address with its s6_addr16[1] being zero.
    791 		 * What is worse, if the packet goes to the loopback interface
    792 		 * by a default rejected route, the null pointer would be
    793 		 * passed to looutput, and the kernel would hang.
    794 		 * The following last resort would prevent such disaster.
    795 		 */
    796 		if (origifp == NULL)
    797 			origifp = ifp;
    798 	}
    799 	else
    800 		origifp = ifp;
    801 	if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_src))
    802 		ip6->ip6_src.s6_addr16[1] = 0;
    803 	if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_dst))
    804 		ip6->ip6_dst.s6_addr16[1] = 0;
    805 
    806 	/*
    807 	 * If the outgoing packet contains a hop-by-hop options header,
    808 	 * it must be examined and processed even by the source node.
    809 	 * (RFC 2460, section 4.)
    810 	 */
    811 	if (exthdrs.ip6e_hbh) {
    812 		struct ip6_hbh *hbh = mtod(exthdrs.ip6e_hbh, struct ip6_hbh *);
    813 		u_int32_t dummy1; /* XXX unused */
    814 		u_int32_t dummy2; /* XXX unused */
    815 
    816 		/*
    817 		 *  XXX: if we have to send an ICMPv6 error to the sender,
    818 		 *       we need the M_LOOP flag since icmp6_error() expects
    819 		 *       the IPv6 and the hop-by-hop options header are
    820 		 *       continuous unless the flag is set.
    821 		 */
    822 		m->m_flags |= M_LOOP;
    823 		m->m_pkthdr.rcvif = ifp;
    824 		if (ip6_process_hopopts(m,
    825 					(u_int8_t *)(hbh + 1),
    826 					((hbh->ip6h_len + 1) << 3) -
    827 					sizeof(struct ip6_hbh),
    828 					&dummy1, &dummy2) < 0) {
    829 			/* m was already freed at this point */
    830 			error = EINVAL;/* better error? */
    831 			goto done;
    832 		}
    833 		m->m_flags &= ~M_LOOP; /* XXX */
    834 		m->m_pkthdr.rcvif = NULL;
    835 	}
    836 
    837 #ifdef PFIL_HOOKS
    838 	/*
    839 	 * Run through list of hooks for output packets.
    840 	 */
    841 	if ((error = pfil_run_hooks(&inet6_pfil_hook, &m, ifp,
    842 				    PFIL_OUT)) != 0)
    843 		goto done;
    844 	if (m == NULL)
    845 		goto done;
    846 	ip6 = mtod(m, struct ip6_hdr *);
    847 #endif /* PFIL_HOOKS */
    848 	/*
    849 	 * Send the packet to the outgoing interface.
    850 	 * If necessary, do IPv6 fragmentation before sending.
    851 	 */
    852 	tlen = m->m_pkthdr.len;
    853 	if (tlen <= mtu
    854 #ifdef notyet
    855 	    /*
    856 	     * On any link that cannot convey a 1280-octet packet in one piece,
    857 	     * link-specific fragmentation and reassembly must be provided at
    858 	     * a layer below IPv6. [RFC 2460, sec.5]
    859 	     * Thus if the interface has ability of link-level fragmentation,
    860 	     * we can just send the packet even if the packet size is
    861 	     * larger than the link's MTU.
    862 	     * XXX: IFF_FRAGMENTABLE (or such) flag has not been defined yet...
    863 	     */
    864 
    865 	    || ifp->if_flags & IFF_FRAGMENTABLE
    866 #endif
    867 	    )
    868 	{
    869 #ifdef IFA_STATS
    870 		struct in6_ifaddr *ia6;
    871 		ip6 = mtod(m, struct ip6_hdr *);
    872 		ia6 = in6_ifawithifp(ifp, &ip6->ip6_src);
    873 		if (ia6) {
    874 			/* Record statistics for this interface address. */
    875 			ia6->ia_ifa.ifa_data.ifad_outbytes +=
    876 				m->m_pkthdr.len;
    877 		}
    878 #endif
    879 #ifdef IPSEC
    880 		/* clean ipsec history once it goes out of the node */
    881 		ipsec_delaux(m);
    882 #endif
    883 		error = nd6_output(ifp, origifp, m, dst, ro->ro_rt);
    884 		goto done;
    885 	} else if (mtu < IPV6_MMTU) {
    886 		/*
    887 		 * note that path MTU is never less than IPV6_MMTU
    888 		 * (see icmp6_input).
    889 		 */
    890 		error = EMSGSIZE;
    891 		in6_ifstat_inc(ifp, ifs6_out_fragfail);
    892 		goto bad;
    893 	} else if (ip6->ip6_plen == 0) { /* jumbo payload cannot be fragmented */
    894 		error = EMSGSIZE;
    895 		in6_ifstat_inc(ifp, ifs6_out_fragfail);
    896 		goto bad;
    897 	} else {
    898 		struct mbuf **mnext, *m_frgpart;
    899 		struct ip6_frag *ip6f;
    900 		u_int32_t id = htonl(ip6_id++);
    901 		u_char nextproto;
    902 
    903 		/*
    904 		 * Too large for the destination or interface;
    905 		 * fragment if possible.
    906 		 * Must be able to put at least 8 bytes per fragment.
    907 		 */
    908 		hlen = unfragpartlen;
    909 		if (mtu > IPV6_MAXPACKET)
    910 			mtu = IPV6_MAXPACKET;
    911 		len = (mtu - hlen - sizeof(struct ip6_frag)) & ~7;
    912 		if (len < 8) {
    913 			error = EMSGSIZE;
    914 			in6_ifstat_inc(ifp, ifs6_out_fragfail);
    915 			goto bad;
    916 		}
    917 
    918 		mnext = &m->m_nextpkt;
    919 
    920 		/*
    921 		 * Change the next header field of the last header in the
    922 		 * unfragmentable part.
    923 		 */
    924 		if (exthdrs.ip6e_rthdr) {
    925 			nextproto = *mtod(exthdrs.ip6e_rthdr, u_char *);
    926 			*mtod(exthdrs.ip6e_rthdr, u_char *) = IPPROTO_FRAGMENT;
    927 		} else if (exthdrs.ip6e_dest1) {
    928 			nextproto = *mtod(exthdrs.ip6e_dest1, u_char *);
    929 			*mtod(exthdrs.ip6e_dest1, u_char *) = IPPROTO_FRAGMENT;
    930 		} else if (exthdrs.ip6e_hbh) {
    931 			nextproto = *mtod(exthdrs.ip6e_hbh, u_char *);
    932 			*mtod(exthdrs.ip6e_hbh, u_char *) = IPPROTO_FRAGMENT;
    933 		} else {
    934 			nextproto = ip6->ip6_nxt;
    935 			ip6->ip6_nxt = IPPROTO_FRAGMENT;
    936 		}
    937 
    938 		/*
    939 		 * Loop through length of segment after first fragment,
    940 		 * make new header and copy data of each part and link onto
    941 		 * chain.
    942 		 */
    943 		m0 = m;
    944 		for (off = hlen; off < tlen; off += len) {
    945 			MGETHDR(m, M_DONTWAIT, MT_HEADER);
    946 			if (!m) {
    947 				error = ENOBUFS;
    948 				ip6stat.ip6s_odropped++;
    949 				goto sendorfree;
    950 			}
    951 			m->m_flags = m0->m_flags & M_COPYFLAGS;
    952 			*mnext = m;
    953 			mnext = &m->m_nextpkt;
    954 			m->m_data += max_linkhdr;
    955 			mhip6 = mtod(m, struct ip6_hdr *);
    956 			*mhip6 = *ip6;
    957 			m->m_len = sizeof(*mhip6);
    958 			error = ip6_insertfraghdr(m0, m, hlen, &ip6f);
    959 			if (error) {
    960 				ip6stat.ip6s_odropped++;
    961 				goto sendorfree;
    962 			}
    963 			ip6f->ip6f_offlg = htons((u_short)((off - hlen) & ~7));
    964 			if (off + len >= tlen)
    965 				len = tlen - off;
    966 			else
    967 				ip6f->ip6f_offlg |= IP6F_MORE_FRAG;
    968 			mhip6->ip6_plen = htons((u_short)(len + hlen +
    969 							  sizeof(*ip6f) -
    970 							  sizeof(struct ip6_hdr)));
    971 			if ((m_frgpart = m_copy(m0, off, len)) == 0) {
    972 				error = ENOBUFS;
    973 				ip6stat.ip6s_odropped++;
    974 				goto sendorfree;
    975 			}
    976 			m_cat(m, m_frgpart);
    977 			m->m_pkthdr.len = len + hlen + sizeof(*ip6f);
    978 			m->m_pkthdr.rcvif = (struct ifnet *)0;
    979 			ip6f->ip6f_reserved = 0;
    980 			ip6f->ip6f_ident = id;
    981 			ip6f->ip6f_nxt = nextproto;
    982 			ip6stat.ip6s_ofragments++;
    983 			in6_ifstat_inc(ifp, ifs6_out_fragcreat);
    984 		}
    985 
    986 		in6_ifstat_inc(ifp, ifs6_out_fragok);
    987 	}
    988 
    989 	/*
    990 	 * Remove leading garbages.
    991 	 */
    992 sendorfree:
    993 	m = m0->m_nextpkt;
    994 	m0->m_nextpkt = 0;
    995 	m_freem(m0);
    996 	for (m0 = m; m; m = m0) {
    997 		m0 = m->m_nextpkt;
    998 		m->m_nextpkt = 0;
    999 		if (error == 0) {
   1000 #ifdef IFA_STATS
   1001 			struct in6_ifaddr *ia6;
   1002 			ip6 = mtod(m, struct ip6_hdr *);
   1003 			ia6 = in6_ifawithifp(ifp, &ip6->ip6_src);
   1004 			if (ia6) {
   1005 				/*
   1006 				 * Record statistics for this interface
   1007 				 * address.
   1008 				 */
   1009 				ia6->ia_ifa.ifa_data.ifad_outbytes +=
   1010 					m->m_pkthdr.len;
   1011 			}
   1012 #endif
   1013 #ifdef IPSEC
   1014 			/* clean ipsec history once it goes out of the node */
   1015 			ipsec_delaux(m);
   1016 #endif
   1017 			error = nd6_output(ifp, origifp, m, dst, ro->ro_rt);
   1018 		} else
   1019 			m_freem(m);
   1020 	}
   1021 
   1022 	if (error == 0)
   1023 		ip6stat.ip6s_fragmented++;
   1024 
   1025 done:
   1026 	if (ro == &ip6route && ro->ro_rt) { /* brace necessary for RTFREE */
   1027 		RTFREE(ro->ro_rt);
   1028 	} else if (ro_pmtu == &ip6route && ro_pmtu->ro_rt) {
   1029 		RTFREE(ro_pmtu->ro_rt);
   1030 	}
   1031 
   1032 #ifdef IPSEC
   1033 	if (sp != NULL)
   1034 		key_freesp(sp);
   1035 #endif /* IPSEC */
   1036 
   1037 	return(error);
   1038 
   1039 freehdrs:
   1040 	m_freem(exthdrs.ip6e_hbh);	/* m_freem will check if mbuf is 0 */
   1041 	m_freem(exthdrs.ip6e_dest1);
   1042 	m_freem(exthdrs.ip6e_rthdr);
   1043 	m_freem(exthdrs.ip6e_dest2);
   1044 	/* fall through */
   1045 bad:
   1046 	m_freem(m);
   1047 	goto done;
   1048 }
   1049 
   1050 static int
   1051 ip6_copyexthdr(mp, hdr, hlen)
   1052 	struct mbuf **mp;
   1053 	caddr_t hdr;
   1054 	int hlen;
   1055 {
   1056 	struct mbuf *m;
   1057 
   1058 	if (hlen > MCLBYTES)
   1059 		return(ENOBUFS); /* XXX */
   1060 
   1061 	MGET(m, M_DONTWAIT, MT_DATA);
   1062 	if (!m)
   1063 		return(ENOBUFS);
   1064 
   1065 	if (hlen > MLEN) {
   1066 		MCLGET(m, M_DONTWAIT);
   1067 		if ((m->m_flags & M_EXT) == 0) {
   1068 			m_free(m);
   1069 			return(ENOBUFS);
   1070 		}
   1071 	}
   1072 	m->m_len = hlen;
   1073 	if (hdr)
   1074 		bcopy(hdr, mtod(m, caddr_t), hlen);
   1075 
   1076 	*mp = m;
   1077 	return(0);
   1078 }
   1079 
   1080 /*
   1081  * Insert jumbo payload option.
   1082  */
   1083 static int
   1084 ip6_insert_jumboopt(exthdrs, plen)
   1085 	struct ip6_exthdrs *exthdrs;
   1086 	u_int32_t plen;
   1087 {
   1088 	struct mbuf *mopt;
   1089 	u_char *optbuf;
   1090 	u_int32_t v;
   1091 
   1092 #define JUMBOOPTLEN	8	/* length of jumbo payload option and padding */
   1093 
   1094 	/*
   1095 	 * If there is no hop-by-hop options header, allocate new one.
   1096 	 * If there is one but it doesn't have enough space to store the
   1097 	 * jumbo payload option, allocate a cluster to store the whole options.
   1098 	 * Otherwise, use it to store the options.
   1099 	 */
   1100 	if (exthdrs->ip6e_hbh == 0) {
   1101 		MGET(mopt, M_DONTWAIT, MT_DATA);
   1102 		if (mopt == 0)
   1103 			return(ENOBUFS);
   1104 		mopt->m_len = JUMBOOPTLEN;
   1105 		optbuf = mtod(mopt, u_char *);
   1106 		optbuf[1] = 0;	/* = ((JUMBOOPTLEN) >> 3) - 1 */
   1107 		exthdrs->ip6e_hbh = mopt;
   1108 	} else {
   1109 		struct ip6_hbh *hbh;
   1110 
   1111 		mopt = exthdrs->ip6e_hbh;
   1112 		if (M_TRAILINGSPACE(mopt) < JUMBOOPTLEN) {
   1113 			/*
   1114 			 * XXX assumption:
   1115 			 * - exthdrs->ip6e_hbh is not referenced from places
   1116 			 *   other than exthdrs.
   1117 			 * - exthdrs->ip6e_hbh is not an mbuf chain.
   1118 			 */
   1119 			int oldoptlen = mopt->m_len;
   1120 			struct mbuf *n;
   1121 
   1122 			/*
   1123 			 * XXX: give up if the whole (new) hbh header does
   1124 			 * not fit even in an mbuf cluster.
   1125 			 */
   1126 			if (oldoptlen + JUMBOOPTLEN > MCLBYTES)
   1127 				return(ENOBUFS);
   1128 
   1129 			/*
   1130 			 * As a consequence, we must always prepare a cluster
   1131 			 * at this point.
   1132 			 */
   1133 			MGET(n, M_DONTWAIT, MT_DATA);
   1134 			if (n) {
   1135 				MCLGET(n, M_DONTWAIT);
   1136 				if ((n->m_flags & M_EXT) == 0) {
   1137 					m_freem(n);
   1138 					n = NULL;
   1139 				}
   1140 			}
   1141 			if (!n)
   1142 				return(ENOBUFS);
   1143 			n->m_len = oldoptlen + JUMBOOPTLEN;
   1144 			bcopy(mtod(mopt, caddr_t), mtod(n, caddr_t),
   1145 			      oldoptlen);
   1146 			optbuf = mtod(n, caddr_t) + oldoptlen;
   1147 			m_freem(mopt);
   1148 			mopt = exthdrs->ip6e_hbh = n;
   1149 		} else {
   1150 			optbuf = mtod(mopt, u_char *) + mopt->m_len;
   1151 			mopt->m_len += JUMBOOPTLEN;
   1152 		}
   1153 		optbuf[0] = IP6OPT_PADN;
   1154 		optbuf[1] = 1;
   1155 
   1156 		/*
   1157 		 * Adjust the header length according to the pad and
   1158 		 * the jumbo payload option.
   1159 		 */
   1160 		hbh = mtod(mopt, struct ip6_hbh *);
   1161 		hbh->ip6h_len += (JUMBOOPTLEN >> 3);
   1162 	}
   1163 
   1164 	/* fill in the option. */
   1165 	optbuf[2] = IP6OPT_JUMBO;
   1166 	optbuf[3] = 4;
   1167 	v = (u_int32_t)htonl(plen + JUMBOOPTLEN);
   1168 	bcopy(&v, &optbuf[4], sizeof(u_int32_t));
   1169 
   1170 	/* finally, adjust the packet header length */
   1171 	exthdrs->ip6e_ip6->m_pkthdr.len += JUMBOOPTLEN;
   1172 
   1173 	return(0);
   1174 #undef JUMBOOPTLEN
   1175 }
   1176 
   1177 /*
   1178  * Insert fragment header and copy unfragmentable header portions.
   1179  */
   1180 static int
   1181 ip6_insertfraghdr(m0, m, hlen, frghdrp)
   1182 	struct mbuf *m0, *m;
   1183 	int hlen;
   1184 	struct ip6_frag **frghdrp;
   1185 {
   1186 	struct mbuf *n, *mlast;
   1187 
   1188 	if (hlen > sizeof(struct ip6_hdr)) {
   1189 		n = m_copym(m0, sizeof(struct ip6_hdr),
   1190 			    hlen - sizeof(struct ip6_hdr), M_DONTWAIT);
   1191 		if (n == 0)
   1192 			return(ENOBUFS);
   1193 		m->m_next = n;
   1194 	} else
   1195 		n = m;
   1196 
   1197 	/* Search for the last mbuf of unfragmentable part. */
   1198 	for (mlast = n; mlast->m_next; mlast = mlast->m_next)
   1199 		;
   1200 
   1201 	if ((mlast->m_flags & M_EXT) == 0 &&
   1202 	    M_TRAILINGSPACE(mlast) >= sizeof(struct ip6_frag)) {
   1203 		/* use the trailing space of the last mbuf for the fragment hdr */
   1204 		*frghdrp =
   1205 			(struct ip6_frag *)(mtod(mlast, caddr_t) + mlast->m_len);
   1206 		mlast->m_len += sizeof(struct ip6_frag);
   1207 		m->m_pkthdr.len += sizeof(struct ip6_frag);
   1208 	} else {
   1209 		/* allocate a new mbuf for the fragment header */
   1210 		struct mbuf *mfrg;
   1211 
   1212 		MGET(mfrg, M_DONTWAIT, MT_DATA);
   1213 		if (mfrg == 0)
   1214 			return(ENOBUFS);
   1215 		mfrg->m_len = sizeof(struct ip6_frag);
   1216 		*frghdrp = mtod(mfrg, struct ip6_frag *);
   1217 		mlast->m_next = mfrg;
   1218 	}
   1219 
   1220 	return(0);
   1221 }
   1222 
   1223 /*
   1224  * IP6 socket option processing.
   1225  */
   1226 int
   1227 ip6_ctloutput(op, so, level, optname, mp)
   1228 	int op;
   1229 	struct socket *so;
   1230 	int level, optname;
   1231 	struct mbuf **mp;
   1232 {
   1233 	struct in6pcb *in6p = sotoin6pcb(so);
   1234 	struct mbuf *m = *mp;
   1235 	int optval = 0;
   1236 	int error = 0;
   1237 	struct proc *p = curproc;	/* XXX */
   1238 
   1239 	if (level == IPPROTO_IPV6) {
   1240 		switch (op) {
   1241 
   1242 		case PRCO_SETOPT:
   1243 			switch (optname) {
   1244 			case IPV6_PKTOPTIONS:
   1245 				/* m is freed in ip6_pcbopts */
   1246 				return(ip6_pcbopts(&in6p->in6p_outputopts,
   1247 						   m, so));
   1248 			case IPV6_HOPOPTS:
   1249 			case IPV6_DSTOPTS:
   1250 				if (p == 0 || suser(p->p_ucred, &p->p_acflag)) {
   1251 					error = EPERM;
   1252 					break;
   1253 				}
   1254 				/* fall through */
   1255 			case IPV6_UNICAST_HOPS:
   1256 			case IPV6_RECVOPTS:
   1257 			case IPV6_RECVRETOPTS:
   1258 			case IPV6_RECVDSTADDR:
   1259 			case IPV6_PKTINFO:
   1260 			case IPV6_HOPLIMIT:
   1261 			case IPV6_RTHDR:
   1262 			case IPV6_FAITH:
   1263 			case IPV6_V6ONLY:
   1264 				if (!m || m->m_len != sizeof(int)) {
   1265 					error = EINVAL;
   1266 					break;
   1267 				}
   1268 				optval = *mtod(m, int *);
   1269 				switch (optname) {
   1270 
   1271 				case IPV6_UNICAST_HOPS:
   1272 					if (optval < -1 || optval >= 256)
   1273 						error = EINVAL;
   1274 					else {
   1275 						/* -1 = kernel default */
   1276 						in6p->in6p_hops = optval;
   1277 					}
   1278 					break;
   1279 #define OPTSET(bit) \
   1280 if (optval) \
   1281 	in6p->in6p_flags |= bit; \
   1282 else \
   1283 	in6p->in6p_flags &= ~bit;
   1284 
   1285 				case IPV6_RECVOPTS:
   1286 					OPTSET(IN6P_RECVOPTS);
   1287 					break;
   1288 
   1289 				case IPV6_RECVRETOPTS:
   1290 					OPTSET(IN6P_RECVRETOPTS);
   1291 					break;
   1292 
   1293 				case IPV6_RECVDSTADDR:
   1294 					OPTSET(IN6P_RECVDSTADDR);
   1295 					break;
   1296 
   1297 				case IPV6_PKTINFO:
   1298 					OPTSET(IN6P_PKTINFO);
   1299 					break;
   1300 
   1301 				case IPV6_HOPLIMIT:
   1302 					OPTSET(IN6P_HOPLIMIT);
   1303 					break;
   1304 
   1305 				case IPV6_HOPOPTS:
   1306 					OPTSET(IN6P_HOPOPTS);
   1307 					break;
   1308 
   1309 				case IPV6_DSTOPTS:
   1310 					OPTSET(IN6P_DSTOPTS);
   1311 					break;
   1312 
   1313 				case IPV6_RTHDR:
   1314 					OPTSET(IN6P_RTHDR);
   1315 					break;
   1316 
   1317 				case IPV6_FAITH:
   1318 					OPTSET(IN6P_FAITH);
   1319 					break;
   1320 
   1321 				case IPV6_V6ONLY:
   1322 					/*
   1323 					 * make setsockopt(IPV6_V6ONLY)
   1324 					 * available only prior to bind(2).
   1325 					 * see ipng mailing list, Jun 22 2001.
   1326 					 */
   1327 					if (in6p->in6p_lport ||
   1328 					    !IN6_IS_ADDR_UNSPECIFIED(&in6p->in6p_laddr))
   1329 					{
   1330 						error = EINVAL;
   1331 						break;
   1332 					}
   1333 #ifdef INET6_BINDV6ONLY
   1334 					if (!optval)
   1335 						error = EINVAL;
   1336 #else
   1337 					OPTSET(IN6P_IPV6_V6ONLY);
   1338 #endif
   1339 					break;
   1340 				}
   1341 				break;
   1342 #undef OPTSET
   1343 
   1344 			case IPV6_MULTICAST_IF:
   1345 			case IPV6_MULTICAST_HOPS:
   1346 			case IPV6_MULTICAST_LOOP:
   1347 			case IPV6_JOIN_GROUP:
   1348 			case IPV6_LEAVE_GROUP:
   1349 				error =	ip6_setmoptions(optname, &in6p->in6p_moptions, m);
   1350 				break;
   1351 
   1352 			case IPV6_PORTRANGE:
   1353 				optval = *mtod(m, int *);
   1354 
   1355 				switch (optval) {
   1356 				case IPV6_PORTRANGE_DEFAULT:
   1357 					in6p->in6p_flags &= ~(IN6P_LOWPORT);
   1358 					in6p->in6p_flags &= ~(IN6P_HIGHPORT);
   1359 					break;
   1360 
   1361 				case IPV6_PORTRANGE_HIGH:
   1362 					in6p->in6p_flags &= ~(IN6P_LOWPORT);
   1363 					in6p->in6p_flags |= IN6P_HIGHPORT;
   1364 					break;
   1365 
   1366 				case IPV6_PORTRANGE_LOW:
   1367 					in6p->in6p_flags &= ~(IN6P_HIGHPORT);
   1368 					in6p->in6p_flags |= IN6P_LOWPORT;
   1369 					break;
   1370 
   1371 				default:
   1372 					error = EINVAL;
   1373 					break;
   1374 				}
   1375 				break;
   1376 
   1377 #ifdef IPSEC
   1378 			case IPV6_IPSEC_POLICY:
   1379 			    {
   1380 				caddr_t req = NULL;
   1381 				size_t len = 0;
   1382 
   1383 				int priv = 0;
   1384 				if (p == 0 || suser(p->p_ucred, &p->p_acflag))
   1385 					priv = 0;
   1386 				else
   1387 					priv = 1;
   1388 				if (m) {
   1389 					req = mtod(m, caddr_t);
   1390 					len = m->m_len;
   1391 				}
   1392 				error = ipsec6_set_policy(in6p,
   1393 				                   optname, req, len, priv);
   1394 			    }
   1395 				break;
   1396 #endif /* IPSEC */
   1397 
   1398 			default:
   1399 				error = ENOPROTOOPT;
   1400 				break;
   1401 			}
   1402 			if (m)
   1403 				(void)m_free(m);
   1404 			break;
   1405 
   1406 		case PRCO_GETOPT:
   1407 			switch (optname) {
   1408 
   1409 			case IPV6_OPTIONS:
   1410 			case IPV6_RETOPTS:
   1411 #if 0
   1412 				*mp = m = m_get(M_WAIT, MT_SOOPTS);
   1413 				if (in6p->in6p_options) {
   1414 					m->m_len = in6p->in6p_options->m_len;
   1415 					bcopy(mtod(in6p->in6p_options, caddr_t),
   1416 					      mtod(m, caddr_t),
   1417 					      (unsigned)m->m_len);
   1418 				} else
   1419 					m->m_len = 0;
   1420 				break;
   1421 #else
   1422 				error = ENOPROTOOPT;
   1423 				break;
   1424 #endif
   1425 
   1426 			case IPV6_PKTOPTIONS:
   1427 				if (in6p->in6p_options) {
   1428 					*mp = m_copym(in6p->in6p_options, 0,
   1429 						      M_COPYALL, M_WAIT);
   1430 				} else {
   1431 					*mp = m_get(M_WAIT, MT_SOOPTS);
   1432 					(*mp)->m_len = 0;
   1433 				}
   1434 				break;
   1435 
   1436 			case IPV6_HOPOPTS:
   1437 			case IPV6_DSTOPTS:
   1438 				if (p == 0 || suser(p->p_ucred, &p->p_acflag)) {
   1439 					error = EPERM;
   1440 					break;
   1441 				}
   1442 				/* fall through */
   1443 			case IPV6_UNICAST_HOPS:
   1444 			case IPV6_RECVOPTS:
   1445 			case IPV6_RECVRETOPTS:
   1446 			case IPV6_RECVDSTADDR:
   1447 			case IPV6_PORTRANGE:
   1448 			case IPV6_PKTINFO:
   1449 			case IPV6_HOPLIMIT:
   1450 			case IPV6_RTHDR:
   1451 			case IPV6_FAITH:
   1452 			case IPV6_V6ONLY:
   1453 				*mp = m = m_get(M_WAIT, MT_SOOPTS);
   1454 				m->m_len = sizeof(int);
   1455 				switch (optname) {
   1456 
   1457 				case IPV6_UNICAST_HOPS:
   1458 					optval = in6p->in6p_hops;
   1459 					break;
   1460 
   1461 #define OPTBIT(bit) (in6p->in6p_flags & bit ? 1 : 0)
   1462 
   1463 				case IPV6_RECVOPTS:
   1464 					optval = OPTBIT(IN6P_RECVOPTS);
   1465 					break;
   1466 
   1467 				case IPV6_RECVRETOPTS:
   1468 					optval = OPTBIT(IN6P_RECVRETOPTS);
   1469 					break;
   1470 
   1471 				case IPV6_RECVDSTADDR:
   1472 					optval = OPTBIT(IN6P_RECVDSTADDR);
   1473 					break;
   1474 
   1475 				case IPV6_PORTRANGE:
   1476 				    {
   1477 					int flags;
   1478 					flags = in6p->in6p_flags;
   1479 					if (flags & IN6P_HIGHPORT)
   1480 						optval = IPV6_PORTRANGE_HIGH;
   1481 					else if (flags & IN6P_LOWPORT)
   1482 						optval = IPV6_PORTRANGE_LOW;
   1483 					else
   1484 						optval = 0;
   1485 					break;
   1486 				    }
   1487 
   1488 				case IPV6_PKTINFO:
   1489 					optval = OPTBIT(IN6P_PKTINFO);
   1490 					break;
   1491 
   1492 				case IPV6_HOPLIMIT:
   1493 					optval = OPTBIT(IN6P_HOPLIMIT);
   1494 					break;
   1495 
   1496 				case IPV6_HOPOPTS:
   1497 					optval = OPTBIT(IN6P_HOPOPTS);
   1498 					break;
   1499 
   1500 				case IPV6_DSTOPTS:
   1501 					optval = OPTBIT(IN6P_DSTOPTS);
   1502 					break;
   1503 
   1504 				case IPV6_RTHDR:
   1505 					optval = OPTBIT(IN6P_RTHDR);
   1506 					break;
   1507 
   1508 				case IPV6_FAITH:
   1509 					optval = OPTBIT(IN6P_FAITH);
   1510 					break;
   1511 
   1512 				case IPV6_V6ONLY:
   1513 					optval = OPTBIT(IN6P_IPV6_V6ONLY);
   1514 					break;
   1515 				}
   1516 				*mtod(m, int *) = optval;
   1517 				break;
   1518 
   1519 			case IPV6_MULTICAST_IF:
   1520 			case IPV6_MULTICAST_HOPS:
   1521 			case IPV6_MULTICAST_LOOP:
   1522 			case IPV6_JOIN_GROUP:
   1523 			case IPV6_LEAVE_GROUP:
   1524 				error = ip6_getmoptions(optname, in6p->in6p_moptions, mp);
   1525 				break;
   1526 
   1527 #ifdef IPSEC
   1528 			case IPV6_IPSEC_POLICY:
   1529 			{
   1530 				caddr_t req = NULL;
   1531 				size_t len = 0;
   1532 
   1533 				if (m) {
   1534 					req = mtod(m, caddr_t);
   1535 					len = m->m_len;
   1536 				}
   1537 				error = ipsec6_get_policy(in6p, req, len, mp);
   1538 				break;
   1539 			}
   1540 #endif /* IPSEC */
   1541 
   1542 			default:
   1543 				error = ENOPROTOOPT;
   1544 				break;
   1545 			}
   1546 			break;
   1547 		}
   1548 	} else {
   1549 		error = EINVAL;
   1550 		if (op == PRCO_SETOPT && *mp)
   1551 			(void)m_free(*mp);
   1552 	}
   1553 	return(error);
   1554 }
   1555 
   1556 /*
   1557  * Set up IP6 options in pcb for insertion in output packets.
   1558  * Store in mbuf with pointer in pcbopt, adding pseudo-option
   1559  * with destination address if source routed.
   1560  */
   1561 static int
   1562 ip6_pcbopts(pktopt, m, so)
   1563 	struct ip6_pktopts **pktopt;
   1564 	struct mbuf *m;
   1565 	struct socket *so;
   1566 {
   1567 	struct ip6_pktopts *opt = *pktopt;
   1568 	int error = 0;
   1569 	struct proc *p = curproc;	/* XXX */
   1570 	int priv = 0;
   1571 
   1572 	/* turn off any old options. */
   1573 	if (opt) {
   1574 		if (opt->ip6po_m)
   1575 			(void)m_free(opt->ip6po_m);
   1576 	} else
   1577 		opt = malloc(sizeof(*opt), M_IP6OPT, M_WAITOK);
   1578 	*pktopt = 0;
   1579 
   1580 	if (!m || m->m_len == 0) {
   1581 		/*
   1582 		 * Only turning off any previous options.
   1583 		 */
   1584 		if (opt)
   1585 			free(opt, M_IP6OPT);
   1586 		if (m)
   1587 			(void)m_free(m);
   1588 		return(0);
   1589 	}
   1590 
   1591 	/*  set options specified by user. */
   1592 	if (p && !suser(p->p_ucred, &p->p_acflag))
   1593 		priv = 1;
   1594 	if ((error = ip6_setpktoptions(m, opt, priv)) != 0) {
   1595 		(void)m_free(m);
   1596 		return(error);
   1597 	}
   1598 	*pktopt = opt;
   1599 	return(0);
   1600 }
   1601 
   1602 /*
   1603  * Set the IP6 multicast options in response to user setsockopt().
   1604  */
   1605 static int
   1606 ip6_setmoptions(optname, im6op, m)
   1607 	int optname;
   1608 	struct ip6_moptions **im6op;
   1609 	struct mbuf *m;
   1610 {
   1611 	int error = 0;
   1612 	u_int loop, ifindex;
   1613 	struct ipv6_mreq *mreq;
   1614 	struct ifnet *ifp;
   1615 	struct ip6_moptions *im6o = *im6op;
   1616 	struct route_in6 ro;
   1617 	struct sockaddr_in6 *dst;
   1618 	struct in6_multi_mship *imm;
   1619 	struct proc *p = curproc;	/* XXX */
   1620 
   1621 	if (im6o == NULL) {
   1622 		/*
   1623 		 * No multicast option buffer attached to the pcb;
   1624 		 * allocate one and initialize to default values.
   1625 		 */
   1626 		im6o = (struct ip6_moptions *)
   1627 			malloc(sizeof(*im6o), M_IPMOPTS, M_WAITOK);
   1628 
   1629 		if (im6o == NULL)
   1630 			return(ENOBUFS);
   1631 		*im6op = im6o;
   1632 		im6o->im6o_multicast_ifp = NULL;
   1633 		im6o->im6o_multicast_hlim = ip6_defmcasthlim;
   1634 		im6o->im6o_multicast_loop = IPV6_DEFAULT_MULTICAST_LOOP;
   1635 		LIST_INIT(&im6o->im6o_memberships);
   1636 	}
   1637 
   1638 	switch (optname) {
   1639 
   1640 	case IPV6_MULTICAST_IF:
   1641 		/*
   1642 		 * Select the interface for outgoing multicast packets.
   1643 		 */
   1644 		if (m == NULL || m->m_len != sizeof(u_int)) {
   1645 			error = EINVAL;
   1646 			break;
   1647 		}
   1648 		bcopy(mtod(m, u_int *), &ifindex, sizeof(ifindex));
   1649 		if (ifindex < 0 || if_index < ifindex) {
   1650 			error = ENXIO;	/* XXX EINVAL? */
   1651 			break;
   1652 		}
   1653 		ifp = ifindex2ifnet[ifindex];
   1654 		if (ifp == NULL || (ifp->if_flags & IFF_MULTICAST) == 0) {
   1655 			error = EADDRNOTAVAIL;
   1656 			break;
   1657 		}
   1658 		im6o->im6o_multicast_ifp = ifp;
   1659 		break;
   1660 
   1661 	case IPV6_MULTICAST_HOPS:
   1662 	    {
   1663 		/*
   1664 		 * Set the IP6 hoplimit for outgoing multicast packets.
   1665 		 */
   1666 		int optval;
   1667 		if (m == NULL || m->m_len != sizeof(int)) {
   1668 			error = EINVAL;
   1669 			break;
   1670 		}
   1671 		bcopy(mtod(m, u_int *), &optval, sizeof(optval));
   1672 		if (optval < -1 || optval >= 256)
   1673 			error = EINVAL;
   1674 		else if (optval == -1)
   1675 			im6o->im6o_multicast_hlim = ip6_defmcasthlim;
   1676 		else
   1677 			im6o->im6o_multicast_hlim = optval;
   1678 		break;
   1679 	    }
   1680 
   1681 	case IPV6_MULTICAST_LOOP:
   1682 		/*
   1683 		 * Set the loopback flag for outgoing multicast packets.
   1684 		 * Must be zero or one.
   1685 		 */
   1686 		if (m == NULL || m->m_len != sizeof(u_int)) {
   1687 			error = EINVAL;
   1688 			break;
   1689 		}
   1690 		bcopy(mtod(m, u_int *), &loop, sizeof(loop));
   1691 		if (loop > 1) {
   1692 			error = EINVAL;
   1693 			break;
   1694 		}
   1695 		im6o->im6o_multicast_loop = loop;
   1696 		break;
   1697 
   1698 	case IPV6_JOIN_GROUP:
   1699 		/*
   1700 		 * Add a multicast group membership.
   1701 		 * Group must be a valid IP6 multicast address.
   1702 		 */
   1703 		if (m == NULL || m->m_len != sizeof(struct ipv6_mreq)) {
   1704 			error = EINVAL;
   1705 			break;
   1706 		}
   1707 		mreq = mtod(m, struct ipv6_mreq *);
   1708 		if (IN6_IS_ADDR_UNSPECIFIED(&mreq->ipv6mr_multiaddr)) {
   1709 			/*
   1710 			 * We use the unspecified address to specify to accept
   1711 			 * all multicast addresses. Only super user is allowed
   1712 			 * to do this.
   1713 			 */
   1714 			if (suser(p->p_ucred, &p->p_acflag))
   1715 			{
   1716 				error = EACCES;
   1717 				break;
   1718 			}
   1719 		} else if (!IN6_IS_ADDR_MULTICAST(&mreq->ipv6mr_multiaddr)) {
   1720 			error = EINVAL;
   1721 			break;
   1722 		}
   1723 
   1724 		/*
   1725 		 * If the interface is specified, validate it.
   1726 		 */
   1727 		if (mreq->ipv6mr_interface < 0
   1728 		 || if_index < mreq->ipv6mr_interface) {
   1729 			error = ENXIO;	/* XXX EINVAL? */
   1730 			break;
   1731 		}
   1732 		/*
   1733 		 * If no interface was explicitly specified, choose an
   1734 		 * appropriate one according to the given multicast address.
   1735 		 */
   1736 		if (mreq->ipv6mr_interface == 0) {
   1737 			/*
   1738 			 * If the multicast address is in node-local scope,
   1739 			 * the interface should be a loopback interface.
   1740 			 * Otherwise, look up the routing table for the
   1741 			 * address, and choose the outgoing interface.
   1742 			 *   XXX: is it a good approach?
   1743 			 */
   1744 			if (IN6_IS_ADDR_MC_NODELOCAL(&mreq->ipv6mr_multiaddr)) {
   1745 				ifp = &loif[0];
   1746 			} else {
   1747 				ro.ro_rt = NULL;
   1748 				dst = (struct sockaddr_in6 *)&ro.ro_dst;
   1749 				bzero(dst, sizeof(*dst));
   1750 				dst->sin6_len = sizeof(struct sockaddr_in6);
   1751 				dst->sin6_family = AF_INET6;
   1752 				dst->sin6_addr = mreq->ipv6mr_multiaddr;
   1753 				rtalloc((struct route *)&ro);
   1754 				if (ro.ro_rt == NULL) {
   1755 					error = EADDRNOTAVAIL;
   1756 					break;
   1757 				}
   1758 				ifp = ro.ro_rt->rt_ifp;
   1759 				rtfree(ro.ro_rt);
   1760 			}
   1761 		} else
   1762 			ifp = ifindex2ifnet[mreq->ipv6mr_interface];
   1763 
   1764 		/*
   1765 		 * See if we found an interface, and confirm that it
   1766 		 * supports multicast
   1767 		 */
   1768 		if (ifp == NULL || (ifp->if_flags & IFF_MULTICAST) == 0) {
   1769 			error = EADDRNOTAVAIL;
   1770 			break;
   1771 		}
   1772 		/*
   1773 		 * Put interface index into the multicast address,
   1774 		 * if the address has link-local scope.
   1775 		 */
   1776 		if (IN6_IS_ADDR_MC_LINKLOCAL(&mreq->ipv6mr_multiaddr)) {
   1777 			mreq->ipv6mr_multiaddr.s6_addr16[1]
   1778 				= htons(mreq->ipv6mr_interface);
   1779 		}
   1780 		/*
   1781 		 * See if the membership already exists.
   1782 		 */
   1783 		for (imm = im6o->im6o_memberships.lh_first;
   1784 		     imm != NULL; imm = imm->i6mm_chain.le_next)
   1785 			if (imm->i6mm_maddr->in6m_ifp == ifp &&
   1786 			    IN6_ARE_ADDR_EQUAL(&imm->i6mm_maddr->in6m_addr,
   1787 					       &mreq->ipv6mr_multiaddr))
   1788 				break;
   1789 		if (imm != NULL) {
   1790 			error = EADDRINUSE;
   1791 			break;
   1792 		}
   1793 		/*
   1794 		 * Everything looks good; add a new record to the multicast
   1795 		 * address list for the given interface.
   1796 		 */
   1797 		imm = in6_joingroup(ifp, &mreq->ipv6mr_multiaddr, &error);
   1798 		if (!imm)
   1799 			break;
   1800 		LIST_INSERT_HEAD(&im6o->im6o_memberships, imm, i6mm_chain);
   1801 		break;
   1802 
   1803 	case IPV6_LEAVE_GROUP:
   1804 		/*
   1805 		 * Drop a multicast group membership.
   1806 		 * Group must be a valid IP6 multicast address.
   1807 		 */
   1808 		if (m == NULL || m->m_len != sizeof(struct ipv6_mreq)) {
   1809 			error = EINVAL;
   1810 			break;
   1811 		}
   1812 		mreq = mtod(m, struct ipv6_mreq *);
   1813 		if (IN6_IS_ADDR_UNSPECIFIED(&mreq->ipv6mr_multiaddr)) {
   1814 			if (suser(p->p_ucred, &p->p_acflag))
   1815 			{
   1816 				error = EACCES;
   1817 				break;
   1818 			}
   1819 		} else if (!IN6_IS_ADDR_MULTICAST(&mreq->ipv6mr_multiaddr)) {
   1820 			error = EINVAL;
   1821 			break;
   1822 		}
   1823 		/*
   1824 		 * If an interface address was specified, get a pointer
   1825 		 * to its ifnet structure.
   1826 		 */
   1827 		if (mreq->ipv6mr_interface < 0
   1828 		 || if_index < mreq->ipv6mr_interface) {
   1829 			error = ENXIO;	/* XXX EINVAL? */
   1830 			break;
   1831 		}
   1832 		ifp = ifindex2ifnet[mreq->ipv6mr_interface];
   1833 		/*
   1834 		 * Put interface index into the multicast address,
   1835 		 * if the address has link-local scope.
   1836 		 */
   1837 		if (IN6_IS_ADDR_MC_LINKLOCAL(&mreq->ipv6mr_multiaddr)) {
   1838 			mreq->ipv6mr_multiaddr.s6_addr16[1]
   1839 				= htons(mreq->ipv6mr_interface);
   1840 		}
   1841 		/*
   1842 		 * Find the membership in the membership list.
   1843 		 */
   1844 		for (imm = im6o->im6o_memberships.lh_first;
   1845 		     imm != NULL; imm = imm->i6mm_chain.le_next) {
   1846 			if ((ifp == NULL ||
   1847 			     imm->i6mm_maddr->in6m_ifp == ifp) &&
   1848 			    IN6_ARE_ADDR_EQUAL(&imm->i6mm_maddr->in6m_addr,
   1849 					       &mreq->ipv6mr_multiaddr))
   1850 				break;
   1851 		}
   1852 		if (imm == NULL) {
   1853 			/* Unable to resolve interface */
   1854 			error = EADDRNOTAVAIL;
   1855 			break;
   1856 		}
   1857 		/*
   1858 		 * Give up the multicast address record to which the
   1859 		 * membership points.
   1860 		 */
   1861 		LIST_REMOVE(imm, i6mm_chain);
   1862 		in6_leavegroup(imm);
   1863 		break;
   1864 
   1865 	default:
   1866 		error = EOPNOTSUPP;
   1867 		break;
   1868 	}
   1869 
   1870 	/*
   1871 	 * If all options have default values, no need to keep the mbuf.
   1872 	 */
   1873 	if (im6o->im6o_multicast_ifp == NULL &&
   1874 	    im6o->im6o_multicast_hlim == ip6_defmcasthlim &&
   1875 	    im6o->im6o_multicast_loop == IPV6_DEFAULT_MULTICAST_LOOP &&
   1876 	    im6o->im6o_memberships.lh_first == NULL) {
   1877 		free(*im6op, M_IPMOPTS);
   1878 		*im6op = NULL;
   1879 	}
   1880 
   1881 	return(error);
   1882 }
   1883 
   1884 /*
   1885  * Return the IP6 multicast options in response to user getsockopt().
   1886  */
   1887 static int
   1888 ip6_getmoptions(optname, im6o, mp)
   1889 	int optname;
   1890 	struct ip6_moptions *im6o;
   1891 	struct mbuf **mp;
   1892 {
   1893 	u_int *hlim, *loop, *ifindex;
   1894 
   1895 	*mp = m_get(M_WAIT, MT_SOOPTS);
   1896 
   1897 	switch (optname) {
   1898 
   1899 	case IPV6_MULTICAST_IF:
   1900 		ifindex = mtod(*mp, u_int *);
   1901 		(*mp)->m_len = sizeof(u_int);
   1902 		if (im6o == NULL || im6o->im6o_multicast_ifp == NULL)
   1903 			*ifindex = 0;
   1904 		else
   1905 			*ifindex = im6o->im6o_multicast_ifp->if_index;
   1906 		return(0);
   1907 
   1908 	case IPV6_MULTICAST_HOPS:
   1909 		hlim = mtod(*mp, u_int *);
   1910 		(*mp)->m_len = sizeof(u_int);
   1911 		if (im6o == NULL)
   1912 			*hlim = ip6_defmcasthlim;
   1913 		else
   1914 			*hlim = im6o->im6o_multicast_hlim;
   1915 		return(0);
   1916 
   1917 	case IPV6_MULTICAST_LOOP:
   1918 		loop = mtod(*mp, u_int *);
   1919 		(*mp)->m_len = sizeof(u_int);
   1920 		if (im6o == NULL)
   1921 			*loop = ip6_defmcasthlim;
   1922 		else
   1923 			*loop = im6o->im6o_multicast_loop;
   1924 		return(0);
   1925 
   1926 	default:
   1927 		return(EOPNOTSUPP);
   1928 	}
   1929 }
   1930 
   1931 /*
   1932  * Discard the IP6 multicast options.
   1933  */
   1934 void
   1935 ip6_freemoptions(im6o)
   1936 	struct ip6_moptions *im6o;
   1937 {
   1938 	struct in6_multi_mship *imm;
   1939 
   1940 	if (im6o == NULL)
   1941 		return;
   1942 
   1943 	while ((imm = im6o->im6o_memberships.lh_first) != NULL) {
   1944 		LIST_REMOVE(imm, i6mm_chain);
   1945 		in6_leavegroup(imm);
   1946 	}
   1947 	free(im6o, M_IPMOPTS);
   1948 }
   1949 
   1950 /*
   1951  * Set IPv6 outgoing packet options based on advanced API.
   1952  */
   1953 int
   1954 ip6_setpktoptions(control, opt, priv)
   1955 	struct mbuf *control;
   1956 	struct ip6_pktopts *opt;
   1957 	int priv;
   1958 {
   1959 	struct cmsghdr *cm = 0;
   1960 
   1961 	if (control == 0 || opt == 0)
   1962 		return(EINVAL);
   1963 
   1964 	bzero(opt, sizeof(*opt));
   1965 	opt->ip6po_hlim = -1; /* -1 means to use default hop limit */
   1966 
   1967 	/*
   1968 	 * XXX: Currently, we assume all the optional information is stored
   1969 	 * in a single mbuf.
   1970 	 */
   1971 	if (control->m_next)
   1972 		return(EINVAL);
   1973 
   1974 	opt->ip6po_m = control;
   1975 
   1976 	for (; control->m_len; control->m_data += CMSG_ALIGN(cm->cmsg_len),
   1977 		     control->m_len -= CMSG_ALIGN(cm->cmsg_len)) {
   1978 		cm = mtod(control, struct cmsghdr *);
   1979 		if (cm->cmsg_len == 0 || cm->cmsg_len > control->m_len)
   1980 			return(EINVAL);
   1981 		if (cm->cmsg_level != IPPROTO_IPV6)
   1982 			continue;
   1983 
   1984 		switch (cm->cmsg_type) {
   1985 		case IPV6_PKTINFO:
   1986 			if (cm->cmsg_len != CMSG_LEN(sizeof(struct in6_pktinfo)))
   1987 				return(EINVAL);
   1988 			opt->ip6po_pktinfo = (struct in6_pktinfo *)CMSG_DATA(cm);
   1989 			if (opt->ip6po_pktinfo->ipi6_ifindex &&
   1990 			    IN6_IS_ADDR_LINKLOCAL(&opt->ip6po_pktinfo->ipi6_addr))
   1991 				opt->ip6po_pktinfo->ipi6_addr.s6_addr16[1] =
   1992 					htons(opt->ip6po_pktinfo->ipi6_ifindex);
   1993 
   1994 			if (opt->ip6po_pktinfo->ipi6_ifindex > if_index
   1995 			 || opt->ip6po_pktinfo->ipi6_ifindex < 0) {
   1996 				return(ENXIO);
   1997 			}
   1998 
   1999 			/*
   2000 			 * Check if the requested source address is indeed a
   2001 			 * unicast address assigned to the node, and can be
   2002 			 * used as the packet's source address.
   2003 			 */
   2004 			if (!IN6_IS_ADDR_UNSPECIFIED(&opt->ip6po_pktinfo->ipi6_addr)) {
   2005 				struct ifaddr *ia;
   2006 				struct in6_ifaddr *ia6;
   2007 				struct sockaddr_in6 sin6;
   2008 
   2009 				bzero(&sin6, sizeof(sin6));
   2010 				sin6.sin6_len = sizeof(sin6);
   2011 				sin6.sin6_family = AF_INET6;
   2012 				sin6.sin6_addr =
   2013 					opt->ip6po_pktinfo->ipi6_addr;
   2014 				ia = ifa_ifwithaddr(sin6tosa(&sin6));
   2015 				if (ia == NULL ||
   2016 				    (opt->ip6po_pktinfo->ipi6_ifindex &&
   2017 				     (ia->ifa_ifp->if_index !=
   2018 				      opt->ip6po_pktinfo->ipi6_ifindex))) {
   2019 					return(EADDRNOTAVAIL);
   2020 				}
   2021 				ia6 = (struct in6_ifaddr *)ia;
   2022 				if ((ia6->ia6_flags & (IN6_IFF_ANYCAST|IN6_IFF_NOTREADY)) != 0) {
   2023 					return(EADDRNOTAVAIL);
   2024 				}
   2025 
   2026 				/*
   2027 				 * Check if the requested source address is
   2028 				 * indeed a unicast address assigned to the
   2029 				 * node.
   2030 				 */
   2031 				if (IN6_IS_ADDR_MULTICAST(&opt->ip6po_pktinfo->ipi6_addr))
   2032 					return(EADDRNOTAVAIL);
   2033 			}
   2034 			break;
   2035 
   2036 		case IPV6_HOPLIMIT:
   2037 			if (cm->cmsg_len != CMSG_LEN(sizeof(int)))
   2038 				return(EINVAL);
   2039 
   2040 			bcopy(CMSG_DATA(cm), &opt->ip6po_hlim,
   2041 			    sizeof(opt->ip6po_hlim));
   2042 			if (opt->ip6po_hlim < -1 || opt->ip6po_hlim > 255)
   2043 				return(EINVAL);
   2044 			break;
   2045 
   2046 		case IPV6_NEXTHOP:
   2047 			if (!priv)
   2048 				return(EPERM);
   2049 
   2050 			if (cm->cmsg_len < sizeof(u_char) ||
   2051 			    /* check if cmsg_len is large enough for sa_len */
   2052 			    cm->cmsg_len < CMSG_LEN(*CMSG_DATA(cm)))
   2053 				return(EINVAL);
   2054 
   2055 			opt->ip6po_nexthop = (struct sockaddr *)CMSG_DATA(cm);
   2056 
   2057 			break;
   2058 
   2059 		case IPV6_HOPOPTS:
   2060 			if (cm->cmsg_len < CMSG_LEN(sizeof(struct ip6_hbh)))
   2061 				return(EINVAL);
   2062 			opt->ip6po_hbh = (struct ip6_hbh *)CMSG_DATA(cm);
   2063 			if (cm->cmsg_len !=
   2064 			    CMSG_LEN((opt->ip6po_hbh->ip6h_len + 1) << 3))
   2065 				return(EINVAL);
   2066 			break;
   2067 
   2068 		case IPV6_DSTOPTS:
   2069 			if (cm->cmsg_len < CMSG_LEN(sizeof(struct ip6_dest)))
   2070 				return(EINVAL);
   2071 
   2072 			/*
   2073 			 * If there is no routing header yet, the destination
   2074 			 * options header should be put on the 1st part.
   2075 			 * Otherwise, the header should be on the 2nd part.
   2076 			 * (See RFC 2460, section 4.1)
   2077 			 */
   2078 			if (opt->ip6po_rthdr == NULL) {
   2079 				opt->ip6po_dest1 =
   2080 					(struct ip6_dest *)CMSG_DATA(cm);
   2081 				if (cm->cmsg_len !=
   2082 				    CMSG_LEN((opt->ip6po_dest1->ip6d_len + 1)
   2083 					     << 3))
   2084 					return(EINVAL);
   2085 			}
   2086 			else {
   2087 				opt->ip6po_dest2 =
   2088 					(struct ip6_dest *)CMSG_DATA(cm);
   2089 				if (cm->cmsg_len !=
   2090 				    CMSG_LEN((opt->ip6po_dest2->ip6d_len + 1)
   2091 					     << 3))
   2092 					return(EINVAL);
   2093 			}
   2094 			break;
   2095 
   2096 		case IPV6_RTHDR:
   2097 			if (cm->cmsg_len < CMSG_LEN(sizeof(struct ip6_rthdr)))
   2098 				return(EINVAL);
   2099 			opt->ip6po_rthdr = (struct ip6_rthdr *)CMSG_DATA(cm);
   2100 			if (cm->cmsg_len !=
   2101 			    CMSG_LEN((opt->ip6po_rthdr->ip6r_len + 1) << 3))
   2102 				return(EINVAL);
   2103 			switch (opt->ip6po_rthdr->ip6r_type) {
   2104 			case IPV6_RTHDR_TYPE_0:
   2105 				if (opt->ip6po_rthdr->ip6r_segleft == 0)
   2106 					return(EINVAL);
   2107 				break;
   2108 			default:
   2109 				return(EINVAL);
   2110 			}
   2111 			break;
   2112 
   2113 		default:
   2114 			return(ENOPROTOOPT);
   2115 		}
   2116 	}
   2117 
   2118 	return(0);
   2119 }
   2120 
   2121 /*
   2122  * Routine called from ip6_output() to loop back a copy of an IP6 multicast
   2123  * packet to the input queue of a specified interface.  Note that this
   2124  * calls the output routine of the loopback "driver", but with an interface
   2125  * pointer that might NOT be &loif -- easier than replicating that code here.
   2126  */
   2127 void
   2128 ip6_mloopback(ifp, m, dst)
   2129 	struct ifnet *ifp;
   2130 	struct mbuf *m;
   2131 	struct sockaddr_in6 *dst;
   2132 {
   2133 	struct mbuf *copym;
   2134 	struct ip6_hdr *ip6;
   2135 
   2136 	copym = m_copy(m, 0, M_COPYALL);
   2137 	if (copym == NULL)
   2138 		return;
   2139 
   2140 	/*
   2141 	 * Make sure to deep-copy IPv6 header portion in case the data
   2142 	 * is in an mbuf cluster, so that we can safely override the IPv6
   2143 	 * header portion later.
   2144 	 */
   2145 	if ((copym->m_flags & M_EXT) != 0 ||
   2146 	    copym->m_len < sizeof(struct ip6_hdr)) {
   2147 		copym = m_pullup(copym, sizeof(struct ip6_hdr));
   2148 		if (copym == NULL)
   2149 			return;
   2150 	}
   2151 
   2152 #ifdef DIAGNOSTIC
   2153 	if (copym->m_len < sizeof(*ip6)) {
   2154 		m_freem(copym);
   2155 		return;
   2156 	}
   2157 #endif
   2158 
   2159 	ip6 = mtod(copym, struct ip6_hdr *);
   2160 	if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_src))
   2161 		ip6->ip6_src.s6_addr16[1] = 0;
   2162 	if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_dst))
   2163 		ip6->ip6_dst.s6_addr16[1] = 0;
   2164 
   2165 	(void)looutput(ifp, copym, (struct sockaddr *)dst, NULL);
   2166 }
   2167 
   2168 /*
   2169  * Chop IPv6 header off from the payload.
   2170  */
   2171 static int
   2172 ip6_splithdr(m, exthdrs)
   2173 	struct mbuf *m;
   2174 	struct ip6_exthdrs *exthdrs;
   2175 {
   2176 	struct mbuf *mh;
   2177 	struct ip6_hdr *ip6;
   2178 
   2179 	ip6 = mtod(m, struct ip6_hdr *);
   2180 	if (m->m_len > sizeof(*ip6)) {
   2181 		MGETHDR(mh, M_DONTWAIT, MT_HEADER);
   2182 		if (mh == 0) {
   2183 			m_freem(m);
   2184 			return ENOBUFS;
   2185 		}
   2186 		M_COPY_PKTHDR(mh, m);
   2187 		MH_ALIGN(mh, sizeof(*ip6));
   2188 		m->m_flags &= ~M_PKTHDR;
   2189 		m->m_len -= sizeof(*ip6);
   2190 		m->m_data += sizeof(*ip6);
   2191 		mh->m_next = m;
   2192 		m = mh;
   2193 		m->m_len = sizeof(*ip6);
   2194 		bcopy((caddr_t)ip6, mtod(m, caddr_t), sizeof(*ip6));
   2195 	}
   2196 	exthdrs->ip6e_ip6 = m;
   2197 	return 0;
   2198 }
   2199 
   2200 /*
   2201  * Compute IPv6 extension header length.
   2202  */
   2203 int
   2204 ip6_optlen(in6p)
   2205 	struct in6pcb *in6p;
   2206 {
   2207 	int len;
   2208 
   2209 	if (!in6p->in6p_outputopts)
   2210 		return 0;
   2211 
   2212 	len = 0;
   2213 #define elen(x) \
   2214     (((struct ip6_ext *)(x)) ? (((struct ip6_ext *)(x))->ip6e_len + 1) << 3 : 0)
   2215 
   2216 	len += elen(in6p->in6p_outputopts->ip6po_hbh);
   2217 	len += elen(in6p->in6p_outputopts->ip6po_dest1);
   2218 	len += elen(in6p->in6p_outputopts->ip6po_rthdr);
   2219 	len += elen(in6p->in6p_outputopts->ip6po_dest2);
   2220 	return len;
   2221 #undef elen
   2222 }
   2223