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