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