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