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