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