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