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