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