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