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