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