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