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