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