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