xref: /dragonfly/sys/netinet6/ip6_output.c (revision 99dd49c5)
1 /*	$FreeBSD: src/sys/netinet6/ip6_output.c,v 1.13.2.18 2003/01/24 05:11:35 sam Exp $	*/
2 /*	$DragonFly: src/sys/netinet6/ip6_output.c,v 1.37 2008/09/04 09:08:22 hasso Exp $	*/
3 /*	$KAME: ip6_output.c,v 1.279 2002/01/26 06:12:30 jinmei Exp $	*/
4 
5 /*
6  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. Neither the name of the project nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33 
34 /*
35  * Copyright (c) 1982, 1986, 1988, 1990, 1993
36  *	The Regents of the University of California.  All rights reserved.
37  *
38  * Redistribution and use in source and binary forms, with or without
39  * modification, are permitted provided that the following conditions
40  * are met:
41  * 1. Redistributions of source code must retain the above copyright
42  *    notice, this list of conditions and the following disclaimer.
43  * 2. Redistributions in binary form must reproduce the above copyright
44  *    notice, this list of conditions and the following disclaimer in the
45  *    documentation and/or other materials provided with the distribution.
46  * 3. All advertising materials mentioning features or use of this software
47  *    must display the following acknowledgement:
48  *	This product includes software developed by the University of
49  *	California, Berkeley and its contributors.
50  * 4. Neither the name of the University nor the names of its contributors
51  *    may be used to endorse or promote products derived from this software
52  *    without specific prior written permission.
53  *
54  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
55  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
56  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
57  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
58  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
59  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
60  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
61  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
62  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
63  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
64  * SUCH DAMAGE.
65  *
66  *	@(#)ip_output.c	8.3 (Berkeley) 1/21/94
67  */
68 
69 #include "opt_ip6fw.h"
70 #include "opt_inet.h"
71 #include "opt_inet6.h"
72 #include "opt_ipsec.h"
73 
74 #include <sys/param.h>
75 #include <sys/malloc.h>
76 #include <sys/mbuf.h>
77 #include <sys/errno.h>
78 #include <sys/protosw.h>
79 #include <sys/socket.h>
80 #include <sys/socketvar.h>
81 #include <sys/systm.h>
82 #include <sys/kernel.h>
83 #include <sys/proc.h>
84 #include <sys/priv.h>
85 
86 #include <net/if.h>
87 #include <net/route.h>
88 #include <net/pfil.h>
89 
90 #include <netinet/in.h>
91 #include <netinet/in_var.h>
92 #include <netinet6/in6_var.h>
93 #include <netinet/ip6.h>
94 #include <netinet/icmp6.h>
95 #include <netinet6/ip6_var.h>
96 #include <netinet/in_pcb.h>
97 #include <netinet6/nd6.h>
98 #include <netinet6/ip6protosw.h>
99 
100 #ifdef IPSEC
101 #include <netinet6/ipsec.h>
102 #ifdef INET6
103 #include <netinet6/ipsec6.h>
104 #endif
105 #include <netproto/key/key.h>
106 #endif /* IPSEC */
107 
108 #ifdef FAST_IPSEC
109 #include <netproto/ipsec/ipsec.h>
110 #include <netproto/ipsec/ipsec6.h>
111 #include <netproto/ipsec/key.h>
112 #endif
113 
114 #include <net/ip6fw/ip6_fw.h>
115 
116 #include <net/net_osdep.h>
117 
118 static MALLOC_DEFINE(M_IPMOPTS, "ip6_moptions", "internet multicast options");
119 
120 struct ip6_exthdrs {
121 	struct mbuf *ip6e_ip6;
122 	struct mbuf *ip6e_hbh;
123 	struct mbuf *ip6e_dest1;
124 	struct mbuf *ip6e_rthdr;
125 	struct mbuf *ip6e_dest2;
126 };
127 
128 static int ip6_pcbopt (int, u_char *, int, struct ip6_pktopts **, int);
129 static int ip6_setpktoption (int, u_char *, int, struct ip6_pktopts *,
130 	 int, int, int, int);
131 static int ip6_pcbopts (struct ip6_pktopts **, struct mbuf *,
132 			    struct socket *, struct sockopt *);
133 static int ip6_getpcbopt(struct ip6_pktopts *, int, struct sockopt *);
134 static int ip6_setmoptions (int, struct ip6_moptions **, struct mbuf *);
135 static int ip6_getmoptions (int, struct ip6_moptions *, struct mbuf **);
136 static int ip6_getpmtu(struct route_in6 *, struct route_in6 *,
137 	struct ifnet *, struct in6_addr *, u_long *, int *);
138 static int copyexthdr (void *, struct mbuf **);
139 static int ip6_insertfraghdr (struct mbuf *, struct mbuf *, int,
140 				  struct ip6_frag **);
141 static int ip6_insert_jumboopt (struct ip6_exthdrs *, u_int32_t);
142 static struct mbuf *ip6_splithdr (struct mbuf *);
143 static int copypktopts(struct ip6_pktopts *, struct ip6_pktopts *, int);
144 
145 /*
146  * IP6 output. The packet in mbuf chain m contains a skeletal IP6
147  * header (with pri, len, nxt, hlim, src, dst).
148  * This function may modify ver and hlim only.
149  * The mbuf chain containing the packet will be freed.
150  * The mbuf opt, if present, will not be freed.
151  *
152  * type of "mtu": rt_rmx.rmx_mtu is u_long, ifnet.ifr_mtu is int, and
153  * nd_ifinfo.linkmtu is u_int32_t.  so we use u_long to hold largest one,
154  * which is rt_rmx.rmx_mtu.
155  */
156 int
157 ip6_output(struct mbuf *m0, struct ip6_pktopts *opt, struct route_in6 *ro,
158 	   int flags, struct ip6_moptions *im6o,
159 	   struct ifnet **ifpp,		/* XXX: just for statistics */
160 	   struct inpcb *inp)
161 {
162 	struct ip6_hdr *ip6, *mhip6;
163 	struct ifnet *ifp, *origifp;
164 	struct mbuf *m = m0;
165 	struct mbuf *mprev;
166 	u_char *nexthdrp;
167 	int hlen, tlen, len, off;
168 	struct route_in6 ip6route;
169 	struct sockaddr_in6 *dst;
170 	int error = 0;
171 	struct in6_ifaddr *ia = NULL;
172 	u_long mtu;
173 	int alwaysfrag, dontfrag;
174 	u_int32_t optlen, plen = 0, unfragpartlen;
175 	struct ip6_exthdrs exthdrs;
176 	struct in6_addr finaldst;
177 	struct route_in6 *ro_pmtu = NULL;
178 	boolean_t hdrsplit = FALSE;
179 	boolean_t needipsec = FALSE;
180 #ifdef IPSEC
181 	boolean_t needipsectun = FALSE;
182 	struct secpolicy *sp = NULL;
183 	struct socket *so = inp ? inp->inp_socket : NULL;
184 
185 	ip6 = mtod(m, struct ip6_hdr *);
186 #endif
187 #ifdef FAST_IPSEC
188 	boolean_t needipsectun = FALSE;
189 	struct secpolicy *sp = NULL;
190 
191 	ip6 = mtod(m, struct ip6_hdr *);
192 #endif
193 
194 	bzero(&exthdrs, sizeof exthdrs);
195 
196 	if (opt) {
197 		if ((error = copyexthdr(opt->ip6po_hbh, &exthdrs.ip6e_hbh)))
198 			goto freehdrs;
199 		if ((error = copyexthdr(opt->ip6po_dest1, &exthdrs.ip6e_dest1)))
200 			goto freehdrs;
201 		if ((error = copyexthdr(opt->ip6po_rthdr, &exthdrs.ip6e_rthdr)))
202 			goto freehdrs;
203 		if ((error = copyexthdr(opt->ip6po_dest2, &exthdrs.ip6e_dest2)))
204 			goto freehdrs;
205 	}
206 
207 #ifdef IPSEC
208 	/* get a security policy for this packet */
209 	if (so == NULL)
210 		sp = ipsec6_getpolicybyaddr(m, IPSEC_DIR_OUTBOUND, 0, &error);
211 	else
212 		sp = ipsec6_getpolicybysock(m, IPSEC_DIR_OUTBOUND, so, &error);
213 
214 	if (sp == NULL) {
215 		ipsec6stat.out_inval++;
216 		goto freehdrs;
217 	}
218 
219 	error = 0;
220 
221 	/* check policy */
222 	switch (sp->policy) {
223 	case IPSEC_POLICY_DISCARD:
224 		/*
225 		 * This packet is just discarded.
226 		 */
227 		ipsec6stat.out_polvio++;
228 		goto freehdrs;
229 
230 	case IPSEC_POLICY_BYPASS:
231 	case IPSEC_POLICY_NONE:
232 		/* no need to do IPsec. */
233 		needipsec = FALSE;
234 		break;
235 
236 	case IPSEC_POLICY_IPSEC:
237 		if (sp->req == NULL) {
238 			error = key_spdacquire(sp);	/* acquire a policy */
239 			goto freehdrs;
240 		}
241 		needipsec = TRUE;
242 		break;
243 
244 	case IPSEC_POLICY_ENTRUST:
245 	default:
246 		kprintf("ip6_output: Invalid policy found. %d\n", sp->policy);
247 	}
248 #endif /* IPSEC */
249 #ifdef FAST_IPSEC
250 	/* get a security policy for this packet */
251 	if (inp == NULL)
252 		sp = ipsec_getpolicybyaddr(m, IPSEC_DIR_OUTBOUND, 0, &error);
253 	else
254 		sp = ipsec_getpolicybysock(m, IPSEC_DIR_OUTBOUND, inp, &error);
255 
256 	if (sp == NULL) {
257 		newipsecstat.ips_out_inval++;
258 		goto freehdrs;
259 	}
260 
261 	error = 0;
262 
263 	/* check policy */
264 	switch (sp->policy) {
265 	case IPSEC_POLICY_DISCARD:
266 		/*
267 		 * This packet is just discarded.
268 		 */
269 		newipsecstat.ips_out_polvio++;
270 		goto freehdrs;
271 
272 	case IPSEC_POLICY_BYPASS:
273 	case IPSEC_POLICY_NONE:
274 		/* no need to do IPsec. */
275 		needipsec = FALSE;
276 		break;
277 
278 	case IPSEC_POLICY_IPSEC:
279 		if (sp->req == NULL) {
280 			error = key_spdacquire(sp);	/* acquire a policy */
281 			goto freehdrs;
282 		}
283 		needipsec = TRUE;
284 		break;
285 
286 	case IPSEC_POLICY_ENTRUST:
287 	default:
288 		kprintf("ip6_output: Invalid policy found. %d\n", sp->policy);
289 	}
290 #endif /* FAST_IPSEC */
291 
292 	/*
293 	 * Calculate the total length of the extension header chain.
294 	 * Keep the length of the unfragmentable part for fragmentation.
295 	 */
296 	optlen = m_lengthm(exthdrs.ip6e_hbh, NULL) +
297 	    m_lengthm(exthdrs.ip6e_dest1, NULL) +
298 	    m_lengthm(exthdrs.ip6e_rthdr, NULL);
299 
300 	unfragpartlen = optlen + sizeof(struct ip6_hdr);
301 
302 	/* NOTE: we don't add AH/ESP length here. do that later. */
303 	optlen += m_lengthm(exthdrs.ip6e_dest2, NULL);
304 
305 	/*
306 	 * If we need IPsec, or there is at least one extension header,
307 	 * separate IP6 header from the payload.
308 	 */
309 	if ((needipsec || optlen) && !hdrsplit) {
310 		exthdrs.ip6e_ip6 = ip6_splithdr(m);
311 		if (exthdrs.ip6e_ip6 == NULL) {
312 			error = ENOBUFS;
313 			goto freehdrs;
314 		}
315 		m = exthdrs.ip6e_ip6;
316 		hdrsplit = TRUE;
317 	}
318 
319 	/* adjust pointer */
320 	ip6 = mtod(m, struct ip6_hdr *);
321 
322 	/* adjust mbuf packet header length */
323 	m->m_pkthdr.len += optlen;
324 	plen = m->m_pkthdr.len - sizeof(*ip6);
325 
326 	/* If this is a jumbo payload, insert a jumbo payload option. */
327 	if (plen > IPV6_MAXPACKET) {
328 		if (!hdrsplit) {
329 			exthdrs.ip6e_ip6 = ip6_splithdr(m);
330 			if (exthdrs.ip6e_ip6 == NULL) {
331 				error = ENOBUFS;
332 				goto freehdrs;
333 			}
334 			m = exthdrs.ip6e_ip6;
335 			hdrsplit = TRUE;
336 		}
337 		/* adjust pointer */
338 		ip6 = mtod(m, struct ip6_hdr *);
339 		if ((error = ip6_insert_jumboopt(&exthdrs, plen)) != 0)
340 			goto freehdrs;
341 		ip6->ip6_plen = 0;
342 	} else
343 		ip6->ip6_plen = htons(plen);
344 
345 	/*
346 	 * Concatenate headers and fill in next header fields.
347 	 * Here we have, on "m"
348 	 *	IPv6 payload
349 	 * and we insert headers accordingly.  Finally, we should be getting:
350 	 *	IPv6 hbh dest1 rthdr ah* [esp* dest2 payload]
351 	 *
352 	 * during the header composing process, "m" points to IPv6 header.
353 	 * "mprev" points to an extension header prior to esp.
354 	 */
355 
356 	nexthdrp = &ip6->ip6_nxt;
357 	mprev = m;
358 
359 	/*
360 	 * we treat dest2 specially.  this makes IPsec processing
361 	 * much easier.  the goal here is to make mprev point the
362 	 * mbuf prior to dest2.
363 	 *
364 	 * result: IPv6 dest2 payload
365 	 * m and mprev will point to IPv6 header.
366 	 */
367 	if (exthdrs.ip6e_dest2) {
368 		if (!hdrsplit)
369 			panic("assumption failed: hdr not split");
370 		exthdrs.ip6e_dest2->m_next = m->m_next;
371 		m->m_next = exthdrs.ip6e_dest2;
372 		*mtod(exthdrs.ip6e_dest2, u_char *) = ip6->ip6_nxt;
373 		ip6->ip6_nxt = IPPROTO_DSTOPTS;
374 	}
375 
376 /*
377  * Place m1 after mprev.
378  */
379 #define MAKE_CHAIN(m1, mprev, nexthdrp, i)\
380     do {\
381 	if (m1) {\
382 		if (!hdrsplit)\
383 			panic("assumption failed: hdr not split");\
384 		*mtod(m1, u_char *) = *nexthdrp;\
385 		*nexthdrp = (i);\
386 		nexthdrp = mtod(m1, u_char *);\
387 		m1->m_next = mprev->m_next;\
388 		mprev->m_next = m1;\
389 		mprev = m1;\
390 	}\
391     } while (0)
392 
393 	/*
394 	 * result: IPv6 hbh dest1 rthdr dest2 payload
395 	 * m will point to IPv6 header.  mprev will point to the
396 	 * extension header prior to dest2 (rthdr in the above case).
397 	 */
398 	MAKE_CHAIN(exthdrs.ip6e_hbh, mprev, nexthdrp, IPPROTO_HOPOPTS);
399 	MAKE_CHAIN(exthdrs.ip6e_dest1, mprev, nexthdrp, IPPROTO_DSTOPTS);
400 	MAKE_CHAIN(exthdrs.ip6e_rthdr, mprev, nexthdrp, IPPROTO_ROUTING);
401 
402 #if defined(IPSEC) || defined(FAST_IPSEC)
403 	if (needipsec) {
404 		struct ipsec_output_state state;
405 		int segleft_org = 0;
406 		struct ip6_rthdr *rh = NULL;
407 
408 		/*
409 		 * pointers after IPsec headers are not valid any more.
410 		 * other pointers need a great care too.
411 		 * (IPsec routines should not mangle mbufs prior to AH/ESP)
412 		 */
413 		exthdrs.ip6e_dest2 = NULL;
414 
415 		if (exthdrs.ip6e_rthdr) {
416 			rh = mtod(exthdrs.ip6e_rthdr, struct ip6_rthdr *);
417 			segleft_org = rh->ip6r_segleft;
418 			rh->ip6r_segleft = 0;
419 		}
420 
421 		bzero(&state, sizeof state);
422 		state.m = m;
423 		error = ipsec6_output_trans(&state, nexthdrp, mprev, sp, flags,
424 					    &needipsectun);
425 		m = state.m;
426 		if (error) {
427 			/* mbuf is already reclaimed in ipsec6_output_trans. */
428 			m = NULL;
429 			switch (error) {
430 			case EHOSTUNREACH:
431 			case ENETUNREACH:
432 			case EMSGSIZE:
433 			case ENOBUFS:
434 			case ENOMEM:
435 				break;
436 			default:
437 				kprintf("ip6_output (ipsec): error code %d\n",
438 				       error);
439 				/* fall through */
440 			case ENOENT:
441 				/* don't show these error codes to the user */
442 				error = 0;
443 				break;
444 			}
445 			goto bad;
446 		}
447 		if (exthdrs.ip6e_rthdr) {
448 			/* ah6_output doesn't modify mbuf chain */
449 			rh->ip6r_segleft = segleft_org;
450 		}
451 	}
452 #endif
453 
454 	/*
455 	 * If there is a routing header, replace destination address field
456 	 * with the first hop of the routing header.
457 	 */
458 	if (exthdrs.ip6e_rthdr) {
459 		struct ip6_rthdr *rh;
460 
461 		finaldst = ip6->ip6_dst;
462 		rh = mtod(exthdrs.ip6e_rthdr, struct ip6_rthdr *);
463 		switch (rh->ip6r_type) {
464 		default:	/* is it possible? */
465 			 error = EINVAL;
466 			 goto bad;
467 		}
468 	}
469 
470 	/* Source address validation */
471 	if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src) &&
472 	    !(flags & IPV6_DADOUTPUT)) {
473 		error = EOPNOTSUPP;
474 		ip6stat.ip6s_badscope++;
475 		goto bad;
476 	}
477 	if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_src)) {
478 		error = EOPNOTSUPP;
479 		ip6stat.ip6s_badscope++;
480 		goto bad;
481 	}
482 
483 	ip6stat.ip6s_localout++;
484 
485 	/*
486 	 * Route packet.
487 	 */
488 	if (ro == NULL) {
489 		ro = &ip6route;
490 		bzero(ro, sizeof(*ro));
491 	}
492 	ro_pmtu = ro;
493 	if (opt && opt->ip6po_rthdr)
494 		ro = &opt->ip6po_route;
495 	dst = (struct sockaddr_in6 *)&ro->ro_dst;
496 	/*
497 	 * If there is a cached route,
498 	 * check that it is to the same destination
499 	 * and is still up. If not, free it and try again.
500 	 */
501 	if (ro->ro_rt != NULL &&
502 	    (!(ro->ro_rt->rt_flags & RTF_UP) || dst->sin6_family != AF_INET6 ||
503 	     !IN6_ARE_ADDR_EQUAL(&dst->sin6_addr, &ip6->ip6_dst))) {
504 		RTFREE(ro->ro_rt);
505 		ro->ro_rt = NULL;
506 	}
507 	if (ro->ro_rt == NULL) {
508 		bzero(dst, sizeof(*dst));
509 		dst->sin6_family = AF_INET6;
510 		dst->sin6_len = sizeof(struct sockaddr_in6);
511 		dst->sin6_addr = ip6->ip6_dst;
512 	}
513 #if defined(IPSEC) || defined(FAST_IPSEC)
514 	if (needipsec && needipsectun) {
515 		struct ipsec_output_state state;
516 
517 		/*
518 		 * All the extension headers will become inaccessible
519 		 * (since they can be encrypted).
520 		 * Don't panic, we need no more updates to extension headers
521 		 * on inner IPv6 packet (since they are now encapsulated).
522 		 *
523 		 * IPv6 [ESP|AH] IPv6 [extension headers] payload
524 		 */
525 		bzero(&exthdrs, sizeof(exthdrs));
526 		exthdrs.ip6e_ip6 = m;
527 
528 		bzero(&state, sizeof(state));
529 		state.m = m;
530 		state.ro = (struct route *)ro;
531 		state.dst = (struct sockaddr *)dst;
532 
533 		error = ipsec6_output_tunnel(&state, sp, flags);
534 
535 		m = state.m;
536 		ro = (struct route_in6 *)state.ro;
537 		dst = (struct sockaddr_in6 *)state.dst;
538 		if (error) {
539 			/* mbuf is already reclaimed in ipsec6_output_tunnel. */
540 			m0 = m = NULL;
541 			m = NULL;
542 			switch (error) {
543 			case EHOSTUNREACH:
544 			case ENETUNREACH:
545 			case EMSGSIZE:
546 			case ENOBUFS:
547 			case ENOMEM:
548 				break;
549 			default:
550 				kprintf("ip6_output (ipsec): error code %d\n", error);
551 				/* fall through */
552 			case ENOENT:
553 				/* don't show these error codes to the user */
554 				error = 0;
555 				break;
556 			}
557 			goto bad;
558 		}
559 
560 		exthdrs.ip6e_ip6 = m;
561 	}
562 #endif
563 
564 	if (!IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
565 		/* Unicast */
566 
567 #define ifatoia6(ifa)	((struct in6_ifaddr *)(ifa))
568 #define sin6tosa(sin6)	((struct sockaddr *)(sin6))
569 		/* xxx
570 		 * interface selection comes here
571 		 * if an interface is specified from an upper layer,
572 		 * ifp must point it.
573 		 */
574 		if (ro->ro_rt == NULL) {
575 			/*
576 			 * non-bsdi always clone routes, if parent is
577 			 * PRF_CLONING.
578 			 */
579 			rtalloc((struct route *)ro);
580 		}
581 		if (ro->ro_rt == NULL) {
582 			ip6stat.ip6s_noroute++;
583 			error = EHOSTUNREACH;
584 			/* XXX in6_ifstat_inc(ifp, ifs6_out_discard); */
585 			goto bad;
586 		}
587 		ia = ifatoia6(ro->ro_rt->rt_ifa);
588 		ifp = ro->ro_rt->rt_ifp;
589 		ro->ro_rt->rt_use++;
590 		if (ro->ro_rt->rt_flags & RTF_GATEWAY)
591 			dst = (struct sockaddr_in6 *)ro->ro_rt->rt_gateway;
592 		m->m_flags &= ~(M_BCAST | M_MCAST);	/* just in case */
593 
594 		in6_ifstat_inc(ifp, ifs6_out_request);
595 
596 		/*
597 		 * Check if the outgoing interface conflicts with
598 		 * the interface specified by ifi6_ifindex (if specified).
599 		 * Note that loopback interface is always okay.
600 		 * (this may happen when we are sending a packet to one of
601 		 *  our own addresses.)
602 		 */
603 		if (opt && opt->ip6po_pktinfo
604 		 && opt->ip6po_pktinfo->ipi6_ifindex) {
605 			if (!(ifp->if_flags & IFF_LOOPBACK)
606 			 && ifp->if_index != opt->ip6po_pktinfo->ipi6_ifindex) {
607 				ip6stat.ip6s_noroute++;
608 				in6_ifstat_inc(ifp, ifs6_out_discard);
609 				error = EHOSTUNREACH;
610 				goto bad;
611 			}
612 		}
613 
614 		if (opt && opt->ip6po_hlim != -1)
615 			ip6->ip6_hlim = opt->ip6po_hlim & 0xff;
616 	} else {
617 		/* Multicast */
618 		struct	in6_multi *in6m;
619 
620 		m->m_flags = (m->m_flags & ~M_BCAST) | M_MCAST;
621 
622 		/*
623 		 * See if the caller provided any multicast options
624 		 */
625 		ifp = NULL;
626 		if (im6o != NULL) {
627 			ip6->ip6_hlim = im6o->im6o_multicast_hlim;
628 			if (im6o->im6o_multicast_ifp != NULL)
629 				ifp = im6o->im6o_multicast_ifp;
630 		} else
631 			ip6->ip6_hlim = ip6_defmcasthlim;
632 
633 		/*
634 		 * See if the caller provided the outgoing interface
635 		 * as an ancillary data.
636 		 * Boundary check for ifindex is assumed to be already done.
637 		 */
638 		if (opt && opt->ip6po_pktinfo && opt->ip6po_pktinfo->ipi6_ifindex)
639 			ifp = ifindex2ifnet[opt->ip6po_pktinfo->ipi6_ifindex];
640 
641 		/*
642 		 * If the destination is a node-local scope multicast,
643 		 * the packet should be loop-backed only.
644 		 */
645 		if (IN6_IS_ADDR_MC_NODELOCAL(&ip6->ip6_dst)) {
646 			/*
647 			 * If the outgoing interface is already specified,
648 			 * it should be a loopback interface.
649 			 */
650 			if (ifp && !(ifp->if_flags & IFF_LOOPBACK)) {
651 				ip6stat.ip6s_badscope++;
652 				error = ENETUNREACH; /* XXX: better error? */
653 				/* XXX correct ifp? */
654 				in6_ifstat_inc(ifp, ifs6_out_discard);
655 				goto bad;
656 			} else {
657 				ifp = &loif[0];
658 			}
659 		}
660 
661 		if (opt && opt->ip6po_hlim != -1)
662 			ip6->ip6_hlim = opt->ip6po_hlim & 0xff;
663 
664 		/*
665 		 * If caller did not provide an interface lookup a
666 		 * default in the routing table.  This is either a
667 		 * default for the speicfied group (i.e. a host
668 		 * route), or a multicast default (a route for the
669 		 * ``net'' ff00::/8).
670 		 */
671 		if (ifp == NULL) {
672 			if (ro->ro_rt == NULL) {
673 				ro->ro_rt =
674 				  rtpurelookup((struct sockaddr *)&ro->ro_dst);
675 			}
676 			if (ro->ro_rt == NULL) {
677 				ip6stat.ip6s_noroute++;
678 				error = EHOSTUNREACH;
679 				/* XXX in6_ifstat_inc(ifp, ifs6_out_discard) */
680 				goto bad;
681 			}
682 			ia = ifatoia6(ro->ro_rt->rt_ifa);
683 			ifp = ro->ro_rt->rt_ifp;
684 			ro->ro_rt->rt_use++;
685 		}
686 
687 		if (!(flags & IPV6_FORWARDING))
688 			in6_ifstat_inc(ifp, ifs6_out_request);
689 		in6_ifstat_inc(ifp, ifs6_out_mcast);
690 
691 		/*
692 		 * Confirm that the outgoing interface supports multicast.
693 		 */
694 		if (!(ifp->if_flags & IFF_MULTICAST)) {
695 			ip6stat.ip6s_noroute++;
696 			in6_ifstat_inc(ifp, ifs6_out_discard);
697 			error = ENETUNREACH;
698 			goto bad;
699 		}
700 		IN6_LOOKUP_MULTI(ip6->ip6_dst, ifp, in6m);
701 		if (in6m != NULL &&
702 		   (im6o == NULL || im6o->im6o_multicast_loop)) {
703 			/*
704 			 * If we belong to the destination multicast group
705 			 * on the outgoing interface, and the caller did not
706 			 * forbid loopback, loop back a copy.
707 			 */
708 			ip6_mloopback(ifp, m, dst);
709 		} else {
710 			/*
711 			 * If we are acting as a multicast router, perform
712 			 * multicast forwarding as if the packet had just
713 			 * arrived on the interface to which we are about
714 			 * to send.  The multicast forwarding function
715 			 * recursively calls this function, using the
716 			 * IPV6_FORWARDING flag to prevent infinite recursion.
717 			 *
718 			 * Multicasts that are looped back by ip6_mloopback(),
719 			 * above, will be forwarded by the ip6_input() routine,
720 			 * if necessary.
721 			 */
722 			if (ip6_mrouter && !(flags & IPV6_FORWARDING)) {
723 				if (ip6_mforward(ip6, ifp, m) != 0) {
724 					m_freem(m);
725 					goto done;
726 				}
727 			}
728 		}
729 		/*
730 		 * Multicasts with a hoplimit of zero may be looped back,
731 		 * above, but must not be transmitted on a network.
732 		 * Also, multicasts addressed to the loopback interface
733 		 * are not sent -- the above call to ip6_mloopback() will
734 		 * loop back a copy if this host actually belongs to the
735 		 * destination group on the loopback interface.
736 		 */
737 		if (ip6->ip6_hlim == 0 || (ifp->if_flags & IFF_LOOPBACK)) {
738 			m_freem(m);
739 			goto done;
740 		}
741 	}
742 
743 	/*
744 	 * Fill the outgoing inteface to tell the upper layer
745 	 * to increment per-interface statistics.
746 	 */
747 	if (ifpp)
748 		*ifpp = ifp;
749 
750 	/* Determine path MTU. */
751 	if ((error = ip6_getpmtu(ro_pmtu, ro, ifp, &finaldst, &mtu,
752 	    &alwaysfrag)) != 0)
753 		goto bad;
754 
755 	/*
756 	 * The caller of this function may specify to use the minimum MTU
757 	 * in some cases.
758 	 * An advanced API option (IPV6_USE_MIN_MTU) can also override MTU
759 	 * setting.  The logic is a bit complicated; by default, unicast
760 	 * packets will follow path MTU while multicast packets will be sent at
761 	 * the minimum MTU.  If IP6PO_MINMTU_ALL is specified, all packets
762 	 * including unicast ones will be sent at the minimum MTU.  Multicast
763 	 * packets will always be sent at the minimum MTU unless
764 	 * IP6PO_MINMTU_DISABLE is explicitly specified.
765 	 * See RFC 3542 for more details.
766 	 */
767 	if (mtu > IPV6_MMTU) {
768 		if ((flags & IPV6_MINMTU))
769 			mtu = IPV6_MMTU;
770 		else if (opt && opt->ip6po_minmtu == IP6PO_MINMTU_ALL)
771 			mtu = IPV6_MMTU;
772 		else if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) &&
773 			 (opt == NULL ||
774 			  opt->ip6po_minmtu != IP6PO_MINMTU_DISABLE)) {
775 			mtu = IPV6_MMTU;
776 		}
777 	}
778 
779 	/* Fake scoped addresses */
780 	if ((ifp->if_flags & IFF_LOOPBACK) != 0) {
781 		/*
782 		 * If source or destination address is a scoped address, and
783 		 * the packet is going to be sent to a loopback interface,
784 		 * we should keep the original interface.
785 		 */
786 
787 		/*
788 		 * XXX: this is a very experimental and temporary solution.
789 		 * We eventually have sockaddr_in6 and use the sin6_scope_id
790 		 * field of the structure here.
791 		 * We rely on the consistency between two scope zone ids
792 		 * of source and destination, which should already be assured.
793 		 * Larger scopes than link will be supported in the future.
794 		 */
795 		origifp = NULL;
796 		if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_src))
797 			origifp = ifindex2ifnet[ntohs(ip6->ip6_src.s6_addr16[1])];
798 		else if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_dst))
799 			origifp = ifindex2ifnet[ntohs(ip6->ip6_dst.s6_addr16[1])];
800 		/*
801 		 * XXX: origifp can be NULL even in those two cases above.
802 		 * For example, if we remove the (only) link-local address
803 		 * from the loopback interface, and try to send a link-local
804 		 * address without link-id information.  Then the source
805 		 * address is ::1, and the destination address is the
806 		 * link-local address with its s6_addr16[1] being zero.
807 		 * What is worse, if the packet goes to the loopback interface
808 		 * by a default rejected route, the null pointer would be
809 		 * passed to looutput, and the kernel would hang.
810 		 * The following last resort would prevent such disaster.
811 		 */
812 		if (origifp == NULL)
813 			origifp = ifp;
814 	}
815 	else
816 		origifp = ifp;
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 
824 	/*
825 	 * Check with the firewall...
826 	 */
827 	if (ip6_fw_enable && ip6_fw_chk_ptr) {
828 		u_short port = 0;
829 
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 	/*
878 	 * Run through list of hooks for output packets.
879 	 */
880 	if (pfil_has_hooks(&inet6_pfil_hook)) {
881 		error = pfil_run_hooks(&inet6_pfil_hook, &m, ifp, PFIL_OUT);
882 		if (error != 0 || m == NULL)
883 			goto done;
884 		ip6 = mtod(m, struct ip6_hdr *);
885 	}
886 
887 	/*
888 	 * Send the packet to the outgoing interface.
889 	 * If necessary, do IPv6 fragmentation before sending.
890 	 *
891 	 * the logic here is rather complex:
892 	 * 1: normal case (dontfrag == 0, alwaysfrag == 0)
893 	 * 1-a:	send as is if tlen <= path mtu
894 	 * 1-b:	fragment if tlen > path mtu
895 	 *
896 	 * 2: if user asks us not to fragment (dontfrag == 1)
897 	 * 2-a:	send as is if tlen <= interface mtu
898 	 * 2-b:	error if tlen > interface mtu
899 	 *
900 	 * 3: if we always need to attach fragment header (alwaysfrag == 1)
901 	 *	always fragment
902 	 *
903 	 * 4: if dontfrag == 1 && alwaysfrag == 1
904 	 *	error, as we cannot handle this conflicting request
905 	 */
906 	tlen = m->m_pkthdr.len;
907 
908 	if (opt && (opt->ip6po_flags & IP6PO_DONTFRAG))
909 		dontfrag = 1;
910 	else
911 		dontfrag = 0;
912 	if (dontfrag && alwaysfrag) {	/* case 4 */
913 		/* conflicting request - can't transmit */
914 		error = EMSGSIZE;
915 		goto bad;
916 	}
917 	if (dontfrag && tlen > IN6_LINKMTU(ifp)) {	/* case 2-b */
918 		/*
919 		 * Even if the DONTFRAG option is specified, we cannot send the
920 		 * packet when the data length is larger than the MTU of the
921 		 * outgoing interface.
922 		 * Notify the error by sending IPV6_PATHMTU ancillary data as
923 		 * well as returning an error code (the latter is not described
924 		 * in the API spec.)
925 		 */
926 		u_int32_t mtu32;
927 		struct ip6ctlparam ip6cp;
928 
929 		mtu32 = (u_int32_t)mtu;
930 		bzero(&ip6cp, sizeof(ip6cp));
931 		ip6cp.ip6c_cmdarg = (void *)&mtu32;
932 		kpfctlinput2(PRC_MSGSIZE, (struct sockaddr *)&ro_pmtu->ro_dst,
933 		    (void *)&ip6cp);
934 
935 		error = EMSGSIZE;
936 		goto bad;
937 	}
938 
939 	/*
940 	 * transmit packet without fragmentation
941 	 */
942 	if (dontfrag || (!alwaysfrag && tlen <= mtu)) {	/* case 1-a and 2-a */
943 		struct in6_ifaddr *ia6;
944 
945 		ip6 = mtod(m, struct ip6_hdr *);
946 		ia6 = in6_ifawithifp(ifp, &ip6->ip6_src);
947 		if (ia6) {
948 			/* Record statistics for this interface address. */
949 			ia6->ia_ifa.if_opackets++;
950 			ia6->ia_ifa.if_obytes += m->m_pkthdr.len;
951 		}
952 #ifdef IPSEC
953 		/* clean ipsec history once it goes out of the node */
954 		ipsec_delaux(m);
955 #endif
956 		error = nd6_output(ifp, origifp, m, dst, ro->ro_rt);
957 		goto done;
958 	}
959 
960 	/*
961 	 * try to fragment the packet.  case 1-b and 3
962 	 */
963 	if (mtu < IPV6_MMTU) {
964 		/*
965 		 * note that path MTU is never less than IPV6_MMTU
966 		 * (see icmp6_input).
967 		 */
968 		error = EMSGSIZE;
969 		in6_ifstat_inc(ifp, ifs6_out_fragfail);
970 		goto bad;
971 	} else if (ip6->ip6_plen == 0) { /* jumbo payload cannot be fragmented */
972 		error = EMSGSIZE;
973 		in6_ifstat_inc(ifp, ifs6_out_fragfail);
974 		goto bad;
975 	} else {
976 		struct mbuf **mnext, *m_frgpart;
977 		struct ip6_frag *ip6f;
978 		u_int32_t id = htonl(ip6_id++);
979 		int qslots = ifp->if_snd.ifq_maxlen - ifp->if_snd.ifq_len;
980 		u_char nextproto;
981 
982 		/*
983 		 * Too large for the destination or interface;
984 		 * fragment if possible.
985 		 * Must be able to put at least 8 bytes per fragment.
986 		 */
987 		hlen = unfragpartlen;
988 		if (mtu > IPV6_MAXPACKET)
989 			mtu = IPV6_MAXPACKET;
990 
991 		len = (mtu - hlen - sizeof(struct ip6_frag)) & ~7;
992 		if (len < 8) {
993 			error = EMSGSIZE;
994 			in6_ifstat_inc(ifp, ifs6_out_fragfail);
995 			goto bad;
996 		}
997 
998 		/*
999 		 * Verify that we have any chance at all of being able to queue
1000 		 *      the packet or packet fragments
1001 		 */
1002 		if (qslots <= 0 || ((u_int)qslots * (mtu - hlen)
1003 		    < tlen  /* - hlen */)) {
1004 			error = ENOBUFS;
1005 			ip6stat.ip6s_odropped++;
1006 			goto bad;
1007 		}
1008 
1009 		mnext = &m->m_nextpkt;
1010 
1011 		/*
1012 		 * Change the next header field of the last header in the
1013 		 * unfragmentable part.
1014 		 */
1015 		if (exthdrs.ip6e_rthdr) {
1016 			nextproto = *mtod(exthdrs.ip6e_rthdr, u_char *);
1017 			*mtod(exthdrs.ip6e_rthdr, u_char *) = IPPROTO_FRAGMENT;
1018 		} else if (exthdrs.ip6e_dest1) {
1019 			nextproto = *mtod(exthdrs.ip6e_dest1, u_char *);
1020 			*mtod(exthdrs.ip6e_dest1, u_char *) = IPPROTO_FRAGMENT;
1021 		} else if (exthdrs.ip6e_hbh) {
1022 			nextproto = *mtod(exthdrs.ip6e_hbh, u_char *);
1023 			*mtod(exthdrs.ip6e_hbh, u_char *) = IPPROTO_FRAGMENT;
1024 		} else {
1025 			nextproto = ip6->ip6_nxt;
1026 			ip6->ip6_nxt = IPPROTO_FRAGMENT;
1027 		}
1028 
1029 		/*
1030 		 * Loop through length of segment after first fragment,
1031 		 * make new header and copy data of each part and link onto
1032 		 * chain.
1033 		 */
1034 		m0 = m;
1035 		for (off = hlen; off < tlen; off += len) {
1036 			MGETHDR(m, MB_DONTWAIT, MT_HEADER);
1037 			if (!m) {
1038 				error = ENOBUFS;
1039 				ip6stat.ip6s_odropped++;
1040 				goto sendorfree;
1041 			}
1042 			m->m_pkthdr.rcvif = NULL;
1043 			m->m_flags = m0->m_flags & M_COPYFLAGS;
1044 			*mnext = m;
1045 			mnext = &m->m_nextpkt;
1046 			m->m_data += max_linkhdr;
1047 			mhip6 = mtod(m, struct ip6_hdr *);
1048 			*mhip6 = *ip6;
1049 			m->m_len = sizeof(*mhip6);
1050  			error = ip6_insertfraghdr(m0, m, hlen, &ip6f);
1051  			if (error) {
1052 				ip6stat.ip6s_odropped++;
1053 				goto sendorfree;
1054 			}
1055 			ip6f->ip6f_offlg = htons((u_short)((off - hlen) & ~7));
1056 			if (off + len >= tlen)
1057 				len = tlen - off;
1058 			else
1059 				ip6f->ip6f_offlg |= IP6F_MORE_FRAG;
1060 			mhip6->ip6_plen = htons((u_short)(len + hlen +
1061 							  sizeof(*ip6f) -
1062 							  sizeof(struct ip6_hdr)));
1063 			if ((m_frgpart = m_copy(m0, off, len)) == NULL) {
1064 				error = ENOBUFS;
1065 				ip6stat.ip6s_odropped++;
1066 				goto sendorfree;
1067 			}
1068 			m_cat(m, m_frgpart);
1069 			m->m_pkthdr.len = len + hlen + sizeof(*ip6f);
1070 			m->m_pkthdr.rcvif = NULL;
1071 			ip6f->ip6f_reserved = 0;
1072 			ip6f->ip6f_ident = id;
1073 			ip6f->ip6f_nxt = nextproto;
1074 			ip6stat.ip6s_ofragments++;
1075 			in6_ifstat_inc(ifp, ifs6_out_fragcreat);
1076 		}
1077 
1078 		in6_ifstat_inc(ifp, ifs6_out_fragok);
1079 	}
1080 
1081 	/*
1082 	 * Remove leading garbages.
1083 	 */
1084 sendorfree:
1085 	m = m0->m_nextpkt;
1086 	m0->m_nextpkt = NULL;
1087 	m_freem(m0);
1088 	for (m0 = m; m; m = m0) {
1089 		m0 = m->m_nextpkt;
1090 		m->m_nextpkt = NULL;
1091 		if (error == 0) {
1092  			/* Record statistics for this interface address. */
1093  			if (ia) {
1094  				ia->ia_ifa.if_opackets++;
1095  				ia->ia_ifa.if_obytes += m->m_pkthdr.len;
1096  			}
1097 #ifdef IPSEC
1098 			/* clean ipsec history once it goes out of the node */
1099 			ipsec_delaux(m);
1100 #endif
1101 			error = nd6_output(ifp, origifp, m, dst, ro->ro_rt);
1102 		} else
1103 			m_freem(m);
1104 	}
1105 
1106 	if (error == 0)
1107 		ip6stat.ip6s_fragmented++;
1108 
1109 done:
1110 	if (ro == &ip6route && ro->ro_rt) { /* brace necessary for RTFREE */
1111 		RTFREE(ro->ro_rt);
1112 	} else if (ro_pmtu == &ip6route && ro_pmtu->ro_rt) {
1113 		RTFREE(ro_pmtu->ro_rt);
1114 	}
1115 
1116 #ifdef IPSEC
1117 	if (sp != NULL)
1118 		key_freesp(sp);
1119 #endif
1120 #ifdef FAST_IPSEC
1121 	if (sp != NULL)
1122 		KEY_FREESP(&sp);
1123 #endif
1124 
1125 	return (error);
1126 
1127 freehdrs:
1128 	m_freem(exthdrs.ip6e_hbh);	/* m_freem will check if mbuf is 0 */
1129 	m_freem(exthdrs.ip6e_dest1);
1130 	m_freem(exthdrs.ip6e_rthdr);
1131 	m_freem(exthdrs.ip6e_dest2);
1132 	/* fall through */
1133 bad:
1134 	m_freem(m);
1135 	goto done;
1136 }
1137 
1138 static int
1139 copyexthdr(void *h, struct mbuf **mp)
1140 {
1141 	struct ip6_ext *hdr = h;
1142 	int hlen;
1143 	struct mbuf *m;
1144 
1145 	if (hdr == NULL)
1146 		return 0;
1147 
1148 	hlen = (hdr->ip6e_len + 1) * 8;
1149 	if (hlen > MCLBYTES)
1150 		return ENOBUFS;	/* XXX */
1151 
1152 	m = m_getb(hlen, MB_DONTWAIT, MT_DATA, 0);
1153 	if (!m)
1154 		return ENOBUFS;
1155 	m->m_len = hlen;
1156 
1157 	bcopy(hdr, mtod(m, caddr_t), hlen);
1158 
1159 	*mp = m;
1160 	return 0;
1161 }
1162 
1163 /*
1164  * Insert jumbo payload option.
1165  */
1166 static int
1167 ip6_insert_jumboopt(struct ip6_exthdrs *exthdrs, u_int32_t plen)
1168 {
1169 	struct mbuf *mopt;
1170 	u_char *optbuf;
1171 	u_int32_t v;
1172 
1173 #define JUMBOOPTLEN	8	/* length of jumbo payload option and padding */
1174 
1175 	/*
1176 	 * If there is no hop-by-hop options header, allocate new one.
1177 	 * If there is one but it doesn't have enough space to store the
1178 	 * jumbo payload option, allocate a cluster to store the whole options.
1179 	 * Otherwise, use it to store the options.
1180 	 */
1181 	if (exthdrs->ip6e_hbh == NULL) {
1182 		MGET(mopt, MB_DONTWAIT, MT_DATA);
1183 		if (mopt == NULL)
1184 			return (ENOBUFS);
1185 		mopt->m_len = JUMBOOPTLEN;
1186 		optbuf = mtod(mopt, u_char *);
1187 		optbuf[1] = 0;	/* = ((JUMBOOPTLEN) >> 3) - 1 */
1188 		exthdrs->ip6e_hbh = mopt;
1189 	} else {
1190 		struct ip6_hbh *hbh;
1191 
1192 		mopt = exthdrs->ip6e_hbh;
1193 		if (M_TRAILINGSPACE(mopt) < JUMBOOPTLEN) {
1194 			/*
1195 			 * XXX assumption:
1196 			 * - exthdrs->ip6e_hbh is not referenced from places
1197 			 *   other than exthdrs.
1198 			 * - exthdrs->ip6e_hbh is not an mbuf chain.
1199 			 */
1200 			int oldoptlen = mopt->m_len;
1201 			struct mbuf *n;
1202 
1203 			/*
1204 			 * XXX: give up if the whole (new) hbh header does
1205 			 * not fit even in an mbuf cluster.
1206 			 */
1207 			if (oldoptlen + JUMBOOPTLEN > MCLBYTES)
1208 				return (ENOBUFS);
1209 
1210 			/*
1211 			 * As a consequence, we must always prepare a cluster
1212 			 * at this point.
1213 			 */
1214 			n = m_getcl(MB_DONTWAIT, MT_DATA, 0);
1215 			if (!n)
1216 				return (ENOBUFS);
1217 			n->m_len = oldoptlen + JUMBOOPTLEN;
1218 			bcopy(mtod(mopt, caddr_t), mtod(n, caddr_t), oldoptlen);
1219 			optbuf = mtod(n, caddr_t) + oldoptlen;
1220 			m_freem(mopt);
1221 			mopt = exthdrs->ip6e_hbh = n;
1222 		} else {
1223 			optbuf = mtod(mopt, u_char *) + mopt->m_len;
1224 			mopt->m_len += JUMBOOPTLEN;
1225 		}
1226 		optbuf[0] = IP6OPT_PADN;
1227 		optbuf[1] = 1;
1228 
1229 		/*
1230 		 * Adjust the header length according to the pad and
1231 		 * the jumbo payload option.
1232 		 */
1233 		hbh = mtod(mopt, struct ip6_hbh *);
1234 		hbh->ip6h_len += (JUMBOOPTLEN >> 3);
1235 	}
1236 
1237 	/* fill in the option. */
1238 	optbuf[2] = IP6OPT_JUMBO;
1239 	optbuf[3] = 4;
1240 	v = (u_int32_t)htonl(plen + JUMBOOPTLEN);
1241 	bcopy(&v, &optbuf[4], sizeof(u_int32_t));
1242 
1243 	/* finally, adjust the packet header length */
1244 	exthdrs->ip6e_ip6->m_pkthdr.len += JUMBOOPTLEN;
1245 
1246 	return (0);
1247 #undef JUMBOOPTLEN
1248 }
1249 
1250 /*
1251  * Insert fragment header and copy unfragmentable header portions.
1252  */
1253 static int
1254 ip6_insertfraghdr(struct mbuf *m0, struct mbuf *m, int hlen,
1255 		  struct ip6_frag **frghdrp)
1256 {
1257 	struct mbuf *n, *mlast;
1258 
1259 	if (hlen > sizeof(struct ip6_hdr)) {
1260 		n = m_copym(m0, sizeof(struct ip6_hdr),
1261 			    hlen - sizeof(struct ip6_hdr), MB_DONTWAIT);
1262 		if (n == NULL)
1263 			return (ENOBUFS);
1264 		m->m_next = n;
1265 	} else
1266 		n = m;
1267 
1268 	/* Search for the last mbuf of unfragmentable part. */
1269 	for (mlast = n; mlast->m_next; mlast = mlast->m_next)
1270 		;
1271 
1272 	if (!(mlast->m_flags & M_EXT) &&
1273 	    M_TRAILINGSPACE(mlast) >= sizeof(struct ip6_frag)) {
1274 		/* use the trailing space of the last mbuf for the fragment hdr */
1275 		*frghdrp =
1276 			(struct ip6_frag *)(mtod(mlast, caddr_t) + mlast->m_len);
1277 		mlast->m_len += sizeof(struct ip6_frag);
1278 		m->m_pkthdr.len += sizeof(struct ip6_frag);
1279 	} else {
1280 		/* allocate a new mbuf for the fragment header */
1281 		struct mbuf *mfrg;
1282 
1283 		MGET(mfrg, MB_DONTWAIT, MT_DATA);
1284 		if (mfrg == NULL)
1285 			return (ENOBUFS);
1286 		mfrg->m_len = sizeof(struct ip6_frag);
1287 		*frghdrp = mtod(mfrg, struct ip6_frag *);
1288 		mlast->m_next = mfrg;
1289 	}
1290 
1291 	return (0);
1292 }
1293 
1294 static int
1295 ip6_getpmtu(struct route_in6 *ro_pmtu, struct route_in6 *ro,
1296     struct ifnet *ifp, struct in6_addr *dst, u_long *mtup,
1297     int *alwaysfragp)
1298 {
1299 	u_int32_t mtu = 0;
1300 	int alwaysfrag = 0;
1301 	int error = 0;
1302 
1303 	if (ro_pmtu != ro) {
1304 		/* The first hop and the final destination may differ. */
1305 		struct sockaddr_in6 *sa6_dst =
1306 		    (struct sockaddr_in6 *)&ro_pmtu->ro_dst;
1307 		if (ro_pmtu->ro_rt &&
1308 		    ((ro_pmtu->ro_rt->rt_flags & RTF_UP) == 0 ||
1309 		     !IN6_ARE_ADDR_EQUAL(&sa6_dst->sin6_addr, dst))) {
1310 			RTFREE(ro_pmtu->ro_rt);
1311 			ro_pmtu->ro_rt = NULL;
1312 		}
1313 		if (ro_pmtu->ro_rt == NULL) {
1314 			bzero(sa6_dst, sizeof(*sa6_dst));
1315 			sa6_dst->sin6_family = AF_INET6;
1316 			sa6_dst->sin6_len = sizeof(struct sockaddr_in6);
1317 			sa6_dst->sin6_addr = *dst;
1318 
1319 			rtalloc((struct route *)ro_pmtu);
1320 		}
1321 	}
1322 	if (ro_pmtu->ro_rt) {
1323 		u_int32_t ifmtu;
1324 		struct in_conninfo inc;
1325 
1326 		bzero(&inc, sizeof(inc));
1327 		inc.inc_flags = 1; /* IPv6 */
1328 		inc.inc6_faddr = *dst;
1329 
1330 		if (ifp == NULL)
1331 			ifp = ro_pmtu->ro_rt->rt_ifp;
1332 		ifmtu = IN6_LINKMTU(ifp);
1333 		mtu = ro_pmtu->ro_rt->rt_rmx.rmx_mtu;
1334 		if (mtu == 0)
1335 			mtu = ifmtu;
1336 		else if (mtu < IPV6_MMTU) {
1337 			/*
1338 			 * RFC2460 section 5, last paragraph:
1339 			 * if we record ICMPv6 too big message with
1340 			 * mtu < IPV6_MMTU, transmit packets sized IPV6_MMTU
1341 			 * or smaller, with framgent header attached.
1342 			 * (fragment header is needed regardless from the
1343 			 * packet size, for translators to identify packets)
1344 			 */
1345 			alwaysfrag = 1;
1346 			mtu = IPV6_MMTU;
1347 		} else if (mtu > ifmtu) {
1348 			/*
1349 			 * The MTU on the route is larger than the MTU on
1350 			 * the interface!  This shouldn't happen, unless the
1351 			 * MTU of the interface has been changed after the
1352 			 * interface was brought up.  Change the MTU in the
1353 			 * route to match the interface MTU (as long as the
1354 			 * field isn't locked).
1355 			 */
1356 			mtu = ifmtu;
1357 			ro_pmtu->ro_rt->rt_rmx.rmx_mtu = mtu;
1358 		}
1359 	} else if (ifp) {
1360 		mtu = IN6_LINKMTU(ifp);
1361 	} else
1362 		error = EHOSTUNREACH; /* XXX */
1363 
1364 	*mtup = mtu;
1365 	if (alwaysfragp)
1366 		*alwaysfragp = alwaysfrag;
1367 	return (error);
1368 }
1369 
1370 /*
1371  * IP6 socket option processing.
1372  */
1373 int
1374 ip6_ctloutput(struct socket *so, struct sockopt *sopt)
1375 {
1376 	int optdatalen,uproto;
1377 	int privileged;
1378 	struct inpcb *in6p = so->so_pcb;
1379 	void *optdata;
1380 	int error, optval;
1381 	int level, op, optname;
1382 	int optlen;
1383 	struct thread *td;
1384 
1385 	if (sopt) {
1386 		level = sopt->sopt_level;
1387 		op = sopt->sopt_dir;
1388 		optname = sopt->sopt_name;
1389 		optlen = sopt->sopt_valsize;
1390 		td = sopt->sopt_td;
1391 	} else {
1392 		panic("ip6_ctloutput: arg soopt is NULL");
1393 		/* NOT REACHED */
1394 		td = NULL;
1395 	}
1396 	error = optval = 0;
1397 
1398 	uproto = (int)so->so_proto->pr_protocol;
1399 	privileged = (td == NULL || priv_check(td, PRIV_ROOT)) ? 0 : 1;
1400 
1401 	if (level == IPPROTO_IPV6) {
1402 		switch (op) {
1403 
1404 		case SOPT_SET:
1405 			switch (optname) {
1406 			case IPV6_2292PKTOPTIONS:
1407 #ifdef IPV6_PKTOPTIONS
1408 			case IPV6_PKTOPTIONS:
1409 #endif
1410 			{
1411 				struct mbuf *m;
1412 
1413 				error = soopt_getm(sopt, &m); /* XXX */
1414 				if (error != 0)
1415 					break;
1416 				soopt_to_mbuf(sopt, m); /* XXX */
1417 				error = ip6_pcbopts(&in6p->in6p_outputopts,
1418 						    m, so, sopt);
1419 				m_freem(m); /* XXX */
1420 				break;
1421 			}
1422 
1423 			/*
1424 			 * Use of some Hop-by-Hop options or some
1425 			 * Destination options, might require special
1426 			 * privilege.  That is, normal applications
1427 			 * (without special privilege) might be forbidden
1428 			 * from setting certain options in outgoing packets,
1429 			 * and might never see certain options in received
1430 			 * packets. [RFC 2292 Section 6]
1431 			 * KAME specific note:
1432 			 *  KAME prevents non-privileged users from sending or
1433 			 *  receiving ANY hbh/dst options in order to avoid
1434 			 *  overhead of parsing options in the kernel.
1435 			 */
1436 			case IPV6_RECVHOPOPTS:
1437 			case IPV6_RECVDSTOPTS:
1438 			case IPV6_RECVRTHDRDSTOPTS:
1439 				if (!privileged)
1440 					return (EPERM);
1441 			case IPV6_RECVPKTINFO:
1442 			case IPV6_RECVHOPLIMIT:
1443 			case IPV6_RECVRTHDR:
1444 			case IPV6_RECVPATHMTU:
1445 			case IPV6_RECVTCLASS:
1446 			case IPV6_AUTOFLOWLABEL:
1447 			case IPV6_HOPLIMIT:
1448 			/* FALLTHROUGH */
1449 			case IPV6_UNICAST_HOPS:
1450 			case IPV6_FAITH:
1451 
1452 			case IPV6_V6ONLY:
1453 				if (optlen != sizeof(int)) {
1454 					error = EINVAL;
1455 					break;
1456 				}
1457 				error = soopt_to_kbuf(sopt, &optval,
1458 					sizeof optval, sizeof optval);
1459 				if (error)
1460 					break;
1461 				switch (optname) {
1462 
1463 				case IPV6_UNICAST_HOPS:
1464 					if (optval < -1 || optval >= 256)
1465 						error = EINVAL;
1466 					else {
1467 						/* -1 = kernel default */
1468 						in6p->in6p_hops = optval;
1469 
1470 						if ((in6p->in6p_vflag &
1471 						     INP_IPV4) != 0)
1472 							in6p->inp_ip_ttl = optval;
1473 					}
1474 					break;
1475 #define OPTSET(bit) \
1476 do { \
1477 	if (optval) \
1478 		in6p->in6p_flags |= (bit); \
1479 	else \
1480 		in6p->in6p_flags &= ~(bit); \
1481 } while (0)
1482 #define OPTBIT(bit) (in6p->in6p_flags & (bit) ? 1 : 0)
1483 /*
1484  * Although changed to RFC3542, It's better to also support RFC2292 API
1485  */
1486 #define OPTSET2292(bit) \
1487 do { \
1488 	in6p->in6p_flags |= IN6P_RFC2292; \
1489 	if (optval) \
1490 		in6p->in6p_flags |= (bit); \
1491 	else \
1492 		in6p->in6p_flags &= ~(bit); \
1493 } while (/*CONSTCOND*/ 0)
1494 
1495 				case IPV6_RECVPKTINFO:
1496 					/* cannot mix with RFC2292 */
1497 					if (OPTBIT(IN6P_RFC2292)) {
1498 						error = EINVAL;
1499 						break;
1500 					}
1501 					OPTSET(IN6P_PKTINFO);
1502 					break;
1503 
1504 				case IPV6_HOPLIMIT:
1505 				{
1506 					struct ip6_pktopts **optp;
1507 
1508 					/* cannot mix with RFC2292 */
1509 					if (OPTBIT(IN6P_RFC2292)) {
1510 						error = EINVAL;
1511 						break;
1512 					}
1513 					optp = &in6p->in6p_outputopts;
1514 					error = ip6_pcbopt(IPV6_HOPLIMIT,
1515 					    (u_char *)&optval, sizeof(optval),
1516 					    optp, uproto);
1517 					break;
1518 				}
1519 
1520 				case IPV6_RECVHOPLIMIT:
1521 					/* cannot mix with RFC2292 */
1522 					if (OPTBIT(IN6P_RFC2292)) {
1523 						error = EINVAL;
1524 						break;
1525 					}
1526 					OPTSET(IN6P_HOPLIMIT);
1527 					break;
1528 
1529 				case IPV6_RECVHOPOPTS:
1530 					/* cannot mix with RFC2292 */
1531 					if (OPTBIT(IN6P_RFC2292)) {
1532 						error = EINVAL;
1533 						break;
1534 					}
1535 					OPTSET(IN6P_HOPOPTS);
1536 					break;
1537 
1538 				case IPV6_RECVDSTOPTS:
1539 					/* cannot mix with RFC2292 */
1540 					if (OPTBIT(IN6P_RFC2292)) {
1541 						error = EINVAL;
1542 						break;
1543 					}
1544 					OPTSET(IN6P_DSTOPTS);
1545 					break;
1546 
1547 				case IPV6_RECVRTHDRDSTOPTS:
1548 					/* cannot mix with RFC2292 */
1549 					if (OPTBIT(IN6P_RFC2292)) {
1550 						error = EINVAL;
1551 						break;
1552 					}
1553 					OPTSET(IN6P_RTHDRDSTOPTS);
1554 					break;
1555 
1556 				case IPV6_RECVRTHDR:
1557 					/* cannot mix with RFC2292 */
1558 					if (OPTBIT(IN6P_RFC2292)) {
1559 						error = EINVAL;
1560 						break;
1561 					}
1562 					OPTSET(IN6P_RTHDR);
1563 					break;
1564 
1565 				case IPV6_RECVPATHMTU:
1566 					/*
1567 					 * We ignore this option for TCP
1568 					 * sockets.
1569 					 * (RFC3542 leaves this case
1570 					 * unspecified.)
1571 					 */
1572 					if (uproto != IPPROTO_TCP)
1573 						OPTSET(IN6P_MTU);
1574 					break;
1575 
1576 				case IPV6_RECVTCLASS:
1577 					/* cannot mix with RFC2292 XXX */
1578 					if (OPTBIT(IN6P_RFC2292)) {
1579 						error = EINVAL;
1580 						break;
1581 					}
1582 					OPTSET(IN6P_TCLASS);
1583 					break;
1584 
1585 				case IPV6_AUTOFLOWLABEL:
1586 					OPTSET(IN6P_AUTOFLOWLABEL);
1587 					break;
1588 
1589 				case IPV6_FAITH:
1590 					OPTSET(IN6P_FAITH);
1591 					break;
1592 
1593 				case IPV6_V6ONLY:
1594 					/*
1595 					 * make setsockopt(IPV6_V6ONLY)
1596 					 * available only prior to bind(2).
1597 					 */
1598 					if (in6p->in6p_lport ||
1599 					    !IN6_IS_ADDR_UNSPECIFIED(&in6p->in6p_laddr))
1600 					{
1601 						error = EINVAL;
1602 						break;
1603 					}
1604 					OPTSET(IN6P_IPV6_V6ONLY);
1605 					if (optval)
1606 						in6p->in6p_vflag &= ~INP_IPV4;
1607 					else
1608 						in6p->in6p_vflag |= INP_IPV4;
1609 					break;
1610 				}
1611 				break;
1612 
1613 			case IPV6_TCLASS:
1614 			case IPV6_DONTFRAG:
1615 			case IPV6_USE_MIN_MTU:
1616 			case IPV6_PREFER_TEMPADDR:
1617 				if (optlen != sizeof(optval)) {
1618 					error = EINVAL;
1619 					break;
1620 				}
1621 				error = soopt_to_kbuf(sopt, &optval,
1622 					sizeof optval, sizeof optval);
1623 				if (error)
1624 					break;
1625 				{
1626 					struct ip6_pktopts **optp;
1627 					optp = &in6p->in6p_outputopts;
1628 					error = ip6_pcbopt(optname,
1629 					    (u_char *)&optval, sizeof(optval),
1630 					    optp, uproto);
1631 					break;
1632 				}
1633 
1634 			case IPV6_2292PKTINFO:
1635 			case IPV6_2292HOPLIMIT:
1636 			case IPV6_2292HOPOPTS:
1637 			case IPV6_2292DSTOPTS:
1638 			case IPV6_2292RTHDR:
1639 				/* RFC 2292 */
1640 				if (optlen != sizeof(int)) {
1641 					error = EINVAL;
1642 					break;
1643 				}
1644 				error = soopt_to_kbuf(sopt, &optval,
1645 					sizeof optval, sizeof optval);
1646 				if (error)
1647 					break;
1648 				switch (optname) {
1649 				case IPV6_2292PKTINFO:
1650 					OPTSET2292(IN6P_PKTINFO);
1651 					break;
1652 				case IPV6_2292HOPLIMIT:
1653 					OPTSET2292(IN6P_HOPLIMIT);
1654 					break;
1655 				case IPV6_2292HOPOPTS:
1656 					/*
1657 					 * Check super-user privilege.
1658 					 * See comments for IPV6_RECVHOPOPTS.
1659 					 */
1660 					if (!privileged)
1661 						return (EPERM);
1662 					OPTSET2292(IN6P_HOPOPTS);
1663 					break;
1664 				case IPV6_2292DSTOPTS:
1665 					if (!privileged)
1666 						return (EPERM);
1667 					OPTSET2292(IN6P_DSTOPTS|IN6P_RTHDRDSTOPTS); /* XXX */
1668 					break;
1669 				case IPV6_2292RTHDR:
1670 					OPTSET2292(IN6P_RTHDR);
1671 					break;
1672 				}
1673 				break;
1674 
1675 			case IPV6_PKTINFO:
1676 			case IPV6_HOPOPTS:
1677 			case IPV6_RTHDR:
1678 			case IPV6_DSTOPTS:
1679 			case IPV6_RTHDRDSTOPTS:
1680 			case IPV6_NEXTHOP:
1681 			{
1682 				/*
1683 				 * New advanced API (RFC3542)
1684 				 */
1685 				u_char *optbuf;
1686 				u_char optbuf_storage[MCLBYTES];
1687 				int optlen;
1688 				struct ip6_pktopts **optp;
1689 
1690 				/* cannot mix with RFC2292 */
1691 				if (OPTBIT(IN6P_RFC2292)) {
1692 					error = EINVAL;
1693 					break;
1694 				}
1695 
1696 				/*
1697 				 * We only ensure valsize is not too large
1698 				 * here.  Further validation will be done
1699 				 * later.
1700 				 */
1701 				error = soopt_to_kbuf(sopt, optbuf_storage,
1702 				    sizeof(optbuf_storage), 0);
1703 				if (error)
1704 					break;
1705 				optlen = sopt->sopt_valsize;
1706 				optbuf = optbuf_storage;
1707 				optp = &in6p->in6p_outputopts;
1708 				error = ip6_pcbopt(optname, optbuf, optlen,
1709 				    optp, uproto);
1710 				break;
1711 			}
1712 #undef OPTSET
1713 
1714 			case IPV6_MULTICAST_IF:
1715 			case IPV6_MULTICAST_HOPS:
1716 			case IPV6_MULTICAST_LOOP:
1717 			case IPV6_JOIN_GROUP:
1718 			case IPV6_LEAVE_GROUP:
1719 			    {
1720 				struct mbuf *m;
1721 				if (sopt->sopt_valsize > MLEN) {
1722 					error = EMSGSIZE;
1723 					break;
1724 				}
1725 				/* XXX */
1726 				MGET(m, sopt->sopt_td ? MB_WAIT : MB_DONTWAIT, MT_HEADER);
1727 				if (m == NULL) {
1728 					error = ENOBUFS;
1729 					break;
1730 				}
1731 				m->m_len = sopt->sopt_valsize;
1732 				error = soopt_to_kbuf(sopt, mtod(m, char *),
1733 						    m->m_len, m->m_len);
1734 				error =	ip6_setmoptions(sopt->sopt_name,
1735 							&in6p->in6p_moptions,
1736 							m);
1737 				m_free(m);
1738 			    }
1739 				break;
1740 
1741 			case IPV6_PORTRANGE:
1742 				error = soopt_to_kbuf(sopt, &optval,
1743 				    sizeof optval, sizeof optval);
1744 				if (error)
1745 					break;
1746 
1747 				switch (optval) {
1748 				case IPV6_PORTRANGE_DEFAULT:
1749 					in6p->in6p_flags &= ~(IN6P_LOWPORT);
1750 					in6p->in6p_flags &= ~(IN6P_HIGHPORT);
1751 					break;
1752 
1753 				case IPV6_PORTRANGE_HIGH:
1754 					in6p->in6p_flags &= ~(IN6P_LOWPORT);
1755 					in6p->in6p_flags |= IN6P_HIGHPORT;
1756 					break;
1757 
1758 				case IPV6_PORTRANGE_LOW:
1759 					in6p->in6p_flags &= ~(IN6P_HIGHPORT);
1760 					in6p->in6p_flags |= IN6P_LOWPORT;
1761 					break;
1762 
1763 				default:
1764 					error = EINVAL;
1765 					break;
1766 				}
1767 				break;
1768 
1769 #if defined(IPSEC) || defined(FAST_IPSEC)
1770 			case IPV6_IPSEC_POLICY:
1771 			    {
1772 				caddr_t req = NULL;
1773 				size_t len = 0;
1774 				struct mbuf *m;
1775 
1776 				if ((error = soopt_getm(sopt, &m)) != 0) /* XXX */
1777 					break;
1778 				soopt_to_mbuf(sopt, m);		/* XXX */
1779 				if (m) {
1780 					req = mtod(m, caddr_t);
1781 					len = m->m_len;
1782 				}
1783 				error = ipsec6_set_policy(in6p, optname, req,
1784 							  len, privileged);
1785 				m_freem(m);
1786 			    }
1787 				break;
1788 #endif /* KAME IPSEC */
1789 
1790 			case IPV6_FW_ADD:
1791 			case IPV6_FW_DEL:
1792 			case IPV6_FW_FLUSH:
1793 			case IPV6_FW_ZERO:
1794 			    {
1795 				struct mbuf *m;
1796 				struct mbuf **mp = &m;
1797 
1798 				if (ip6_fw_ctl_ptr == NULL)
1799 					return EINVAL;
1800 				/* XXX */
1801 				if ((error = soopt_getm(sopt, &m)) != 0)
1802 					break;
1803 				/* XXX */
1804 				soopt_to_mbuf(sopt, m);
1805 				error = (*ip6_fw_ctl_ptr)(optname, mp);
1806 				m = *mp;
1807 			    }
1808 				break;
1809 
1810 			default:
1811 				error = ENOPROTOOPT;
1812 				break;
1813 			}
1814 			break;
1815 
1816 		case SOPT_GET:
1817 			switch (optname) {
1818 			case IPV6_2292PKTOPTIONS:
1819 #ifdef IPV6_PKTOPTIONS
1820 			case IPV6_PKTOPTIONS:
1821 #endif
1822 				/*
1823 				 * RFC3542 (effectively) deprecated the
1824 				 * semantics of the 2292-style pktoptions.
1825 				 * Since it was not reliable in nature (i.e.,
1826 				 * applications had to expect the lack of some
1827 				 * information after all), it would make sense
1828 				 * to simplify this part by always returning
1829 				 * empty data.
1830 				 */
1831 				if (in6p->in6p_options) {
1832 					struct mbuf *m;
1833 					m = m_copym(in6p->in6p_options,
1834 					    0, M_COPYALL, MB_WAIT);
1835 					error = soopt_from_mbuf(sopt, m);
1836 					if (error == 0)
1837 						m_freem(m);
1838 				} else
1839 					sopt->sopt_valsize = 0;
1840 				break;
1841 
1842 			case IPV6_RECVHOPOPTS:
1843 			case IPV6_RECVDSTOPTS:
1844 			case IPV6_RECVRTHDRDSTOPTS:
1845 			case IPV6_UNICAST_HOPS:
1846 			case IPV6_RECVPKTINFO:
1847 			case IPV6_RECVHOPLIMIT:
1848 			case IPV6_RECVRTHDR:
1849 			case IPV6_RECVPATHMTU:
1850 			case IPV6_RECVTCLASS:
1851 			case IPV6_AUTOFLOWLABEL:
1852 			case IPV6_FAITH:
1853 			case IPV6_V6ONLY:
1854 			case IPV6_PORTRANGE:
1855 				switch (optname) {
1856 
1857 				case IPV6_RECVHOPOPTS:
1858 					optval = OPTBIT(IN6P_HOPOPTS);
1859 					break;
1860 
1861 				case IPV6_RECVDSTOPTS:
1862 					optval = OPTBIT(IN6P_DSTOPTS);
1863 					break;
1864 
1865 				case IPV6_RECVRTHDRDSTOPTS:
1866 					optval = OPTBIT(IN6P_RTHDRDSTOPTS);
1867 					break;
1868 
1869 				case IPV6_RECVPKTINFO:
1870 					optval = OPTBIT(IN6P_PKTINFO);
1871 					break;
1872 
1873 				case IPV6_RECVHOPLIMIT:
1874 					optval = OPTBIT(IN6P_HOPLIMIT);
1875 					break;
1876 
1877 				case IPV6_RECVRTHDR:
1878 					optval = OPTBIT(IN6P_RTHDR);
1879 					break;
1880 
1881 				case IPV6_RECVPATHMTU:
1882 					optval = OPTBIT(IN6P_MTU);
1883 					break;
1884 
1885 				case IPV6_RECVTCLASS:
1886 					optval = OPTBIT(IN6P_TCLASS);
1887 					break;
1888 
1889 				case IPV6_AUTOFLOWLABEL:
1890 					optval = OPTBIT(IN6P_AUTOFLOWLABEL);
1891 					break;
1892 
1893 
1894 				case IPV6_UNICAST_HOPS:
1895 					optval = in6p->in6p_hops;
1896 					break;
1897 
1898 				case IPV6_FAITH:
1899 					optval = OPTBIT(IN6P_FAITH);
1900 					break;
1901 
1902 				case IPV6_V6ONLY:
1903 					optval = OPTBIT(IN6P_IPV6_V6ONLY);
1904 					break;
1905 
1906 				case IPV6_PORTRANGE:
1907 				    {
1908 					int flags;
1909 					flags = in6p->in6p_flags;
1910 					if (flags & IN6P_HIGHPORT)
1911 						optval = IPV6_PORTRANGE_HIGH;
1912 					else if (flags & IN6P_LOWPORT)
1913 						optval = IPV6_PORTRANGE_LOW;
1914 					else
1915 						optval = 0;
1916 					break;
1917 				    }
1918 				}
1919 				soopt_from_kbuf(sopt, &optval,
1920  					sizeof optval);
1921 				break;
1922 
1923 			case IPV6_PATHMTU:
1924 			{
1925 				u_long pmtu = 0;
1926 				struct ip6_mtuinfo mtuinfo;
1927 				struct route_in6 sro;
1928 
1929 				bzero(&sro, sizeof(sro));
1930 
1931 				if (!(so->so_state & SS_ISCONNECTED))
1932 					return (ENOTCONN);
1933 				/*
1934 				 * XXX: we dot not consider the case of source
1935 				 * routing, or optional information to specify
1936 				 * the outgoing interface.
1937 				 */
1938 				error = ip6_getpmtu(&sro, NULL, NULL,
1939 				    &in6p->in6p_faddr, &pmtu, NULL);
1940 				if (sro.ro_rt)
1941 					RTFREE(sro.ro_rt);
1942 				if (error)
1943 					break;
1944 				if (pmtu > IPV6_MAXPACKET)
1945 					pmtu = IPV6_MAXPACKET;
1946 
1947 				bzero(&mtuinfo, sizeof(mtuinfo));
1948 				mtuinfo.ip6m_mtu = (u_int32_t)pmtu;
1949 				optdata = (void *)&mtuinfo;
1950 				optdatalen = sizeof(mtuinfo);
1951 				soopt_from_kbuf(sopt, optdata,
1952 				    optdatalen);
1953 				break;
1954 			}
1955 
1956 			case IPV6_2292PKTINFO:
1957 			case IPV6_2292HOPLIMIT:
1958 			case IPV6_2292HOPOPTS:
1959 			case IPV6_2292RTHDR:
1960 			case IPV6_2292DSTOPTS:
1961 				if (optname == IPV6_2292HOPOPTS ||
1962 				    optname == IPV6_2292DSTOPTS ||
1963 				    !privileged)
1964 					return (EPERM);
1965 				switch (optname) {
1966 				case IPV6_2292PKTINFO:
1967 					optval = OPTBIT(IN6P_PKTINFO);
1968 					break;
1969 				case IPV6_2292HOPLIMIT:
1970 					optval = OPTBIT(IN6P_HOPLIMIT);
1971 					break;
1972 				case IPV6_2292HOPOPTS:
1973 					if (!privileged)
1974 						return (EPERM);
1975 					optval = OPTBIT(IN6P_HOPOPTS);
1976 					break;
1977 				case IPV6_2292RTHDR:
1978 					optval = OPTBIT(IN6P_RTHDR);
1979 					break;
1980 				case IPV6_2292DSTOPTS:
1981 					if (!privileged)
1982 						return (EPERM);
1983 					optval = OPTBIT(IN6P_DSTOPTS|IN6P_RTHDRDSTOPTS);
1984 					break;
1985 				}
1986 				soopt_from_kbuf(sopt, &optval,
1987  					sizeof optval);
1988 				break;
1989 
1990 			case IPV6_PKTINFO:
1991 			case IPV6_HOPOPTS:
1992 			case IPV6_RTHDR:
1993 			case IPV6_DSTOPTS:
1994 			case IPV6_RTHDRDSTOPTS:
1995 			case IPV6_NEXTHOP:
1996 			case IPV6_TCLASS:
1997 			case IPV6_DONTFRAG:
1998 			case IPV6_USE_MIN_MTU:
1999 			case IPV6_PREFER_TEMPADDR:
2000 				error = ip6_getpcbopt(in6p->in6p_outputopts,
2001 				    optname, sopt);
2002 				break;
2003 
2004 			case IPV6_MULTICAST_IF:
2005 			case IPV6_MULTICAST_HOPS:
2006 			case IPV6_MULTICAST_LOOP:
2007 			case IPV6_JOIN_GROUP:
2008 			case IPV6_LEAVE_GROUP:
2009 			    {
2010 				struct mbuf *m;
2011 				error = ip6_getmoptions(sopt->sopt_name,
2012 						in6p->in6p_moptions, &m);
2013 				if (error == 0)
2014 					soopt_from_kbuf(sopt,
2015  						mtod(m, char *), m->m_len);
2016 				m_freem(m);
2017 			    }
2018 				break;
2019 
2020 #if defined(IPSEC) || defined(FAST_IPSEC)
2021 			case IPV6_IPSEC_POLICY:
2022 			  {
2023 				caddr_t req = NULL;
2024 				size_t len = 0;
2025 				struct mbuf *m = NULL;
2026 				struct mbuf **mp = &m;
2027 
2028 				error = soopt_getm(sopt, &m); /* XXX */
2029 				if (error != 0)
2030 					break;
2031 				soopt_to_mbuf(sopt, m); /* XXX */
2032 				if (m) {
2033 					req = mtod(m, caddr_t);
2034 					len = m->m_len;
2035 				}
2036 				error = ipsec6_get_policy(in6p, req, len, mp);
2037 				if (error == 0)
2038 					error = soopt_from_mbuf(sopt, m); /*XXX*/
2039 				if (error == 0 && m != NULL)
2040 					m_freem(m);
2041 				break;
2042 			  }
2043 #endif /* KAME IPSEC */
2044 
2045 			case IPV6_FW_GET:
2046 			  {
2047 				struct mbuf *m;
2048 				struct mbuf **mp = &m;
2049 
2050 				if (ip6_fw_ctl_ptr == NULL)
2051 				{
2052 					return EINVAL;
2053 				}
2054 				error = (*ip6_fw_ctl_ptr)(optname, mp);
2055 				if (error == 0)
2056 					error = soopt_from_mbuf(sopt, m); /* XXX */
2057 				if (error == 0 && m != NULL)
2058 					m_freem(m);
2059 			  }
2060 				break;
2061 
2062 			default:
2063 				error = ENOPROTOOPT;
2064 				break;
2065 			}
2066 			break;
2067 		}
2068 	} else {
2069 		error = EINVAL;
2070 	}
2071 	return (error);
2072 }
2073 
2074 int
2075 ip6_raw_ctloutput(struct socket *so, struct sockopt *sopt)
2076 {
2077 	int error = 0, optval, optlen;
2078 	const int icmp6off = offsetof(struct icmp6_hdr, icmp6_cksum);
2079 	struct in6pcb *in6p = sotoin6pcb(so);
2080 	int level, op, optname;
2081 
2082 	if (sopt) {
2083 		level = sopt->sopt_level;
2084 		op = sopt->sopt_dir;
2085 		optname = sopt->sopt_name;
2086 		optlen = sopt->sopt_valsize;
2087 	} else
2088 		panic("ip6_raw_ctloutput: arg soopt is NULL");
2089 
2090 	if (level != IPPROTO_IPV6) {
2091 		return (EINVAL);
2092 	}
2093 
2094 	switch (optname) {
2095 	case IPV6_CHECKSUM:
2096 		/*
2097 		 * For ICMPv6 sockets, no modification allowed for checksum
2098 		 * offset, permit "no change" values to help existing apps.
2099 		 *
2100 		 * RFC3542 says: "An attempt to set IPV6_CHECKSUM
2101 		 * for an ICMPv6 socket will fail."
2102 		 * The current behavior does not meet RFC3542.
2103 		 */
2104 		switch (op) {
2105 		case SOPT_SET:
2106 			if (optlen != sizeof(int)) {
2107 				error = EINVAL;
2108 				break;
2109 			}
2110 			error = soopt_to_kbuf(sopt, &optval,
2111 				    sizeof optval, sizeof optval);
2112 			if (error)
2113 				break;
2114 			if ((optval % 2) != 0) {
2115 				/* the API assumes even offset values */
2116 				error = EINVAL;
2117 			} else if (so->so_proto->pr_protocol ==
2118 			    IPPROTO_ICMPV6) {
2119 				if (optval != icmp6off)
2120 					error = EINVAL;
2121 			} else
2122 				in6p->in6p_cksum = optval;
2123 			break;
2124 
2125 		case SOPT_GET:
2126 			if (so->so_proto->pr_protocol == IPPROTO_ICMPV6)
2127 				optval = icmp6off;
2128 			else
2129 				optval = in6p->in6p_cksum;
2130 
2131 			soopt_from_kbuf(sopt, &optval, sizeof(optval));
2132 			break;
2133 
2134 		default:
2135 			error = EINVAL;
2136 			break;
2137 		}
2138 		break;
2139 
2140 	default:
2141 		error = ENOPROTOOPT;
2142 		break;
2143 	}
2144 
2145 	return (error);
2146 }
2147 
2148 /*
2149  * Set up IP6 options in pcb for insertion in output packets or
2150  * specifying behavior of outgoing packets.
2151  */
2152 static int
2153 ip6_pcbopts(struct ip6_pktopts **pktopt, struct mbuf *m,
2154     struct socket *so, struct sockopt *sopt)
2155 {
2156 	int priv = 0;
2157 	struct ip6_pktopts *opt = *pktopt;
2158 	int error = 0;
2159 
2160 	/* turn off any old options. */
2161 	if (opt) {
2162 #ifdef DIAGNOSTIC
2163 		if (opt->ip6po_pktinfo || opt->ip6po_nexthop ||
2164 		    opt->ip6po_hbh || opt->ip6po_dest1 || opt->ip6po_dest2 ||
2165 		    opt->ip6po_rhinfo.ip6po_rhi_rthdr)
2166 			kprintf("ip6_pcbopts: all specified options are cleared.\n");
2167 #endif
2168 		ip6_clearpktopts(opt, -1);
2169 	} else
2170 		opt = kmalloc(sizeof(*opt), M_IP6OPT, M_WAITOK);
2171 	*pktopt = NULL;
2172 
2173 	if (!m || m->m_len == 0) {
2174 		/*
2175 		 * Only turning off any previous options, regardless of
2176 		 * whether the opt is just created or given.
2177 		 */
2178 		kfree(opt, M_IP6OPT);
2179 		return (0);
2180 	}
2181 
2182 	/*  set options specified by user. */
2183 	if ((error = ip6_setpktoptions(m, opt, NULL, so->so_proto->pr_protocol, priv)) != 0) {
2184 		ip6_clearpktopts(opt, -1); /* XXX: discard all options */
2185 		kfree(opt, M_IP6OPT);
2186 		return (error);
2187 	}
2188 	*pktopt = opt;
2189 	return (0);
2190 }
2191 
2192 
2193 /*
2194  * Below three functions are introduced by merge to RFC3542
2195  */
2196 
2197 static int
2198 ip6_getpcbopt(struct ip6_pktopts *pktopt, int optname, struct sockopt *sopt)
2199 {
2200 	void *optdata = NULL;
2201 	int optdatalen = 0;
2202 	struct ip6_ext *ip6e;
2203 	int error = 0;
2204 	struct in6_pktinfo null_pktinfo;
2205 	int deftclass = 0, on;
2206 	int defminmtu = IP6PO_MINMTU_MCASTONLY;
2207 	int defpreftemp = IP6PO_TEMPADDR_SYSTEM;
2208 
2209 	switch (optname) {
2210 	case IPV6_PKTINFO:
2211 		if (pktopt && pktopt->ip6po_pktinfo)
2212 			optdata = (void *)pktopt->ip6po_pktinfo;
2213 		else {
2214 			/* XXX: we don't have to do this every time... */
2215 			bzero(&null_pktinfo, sizeof(null_pktinfo));
2216 			optdata = (void *)&null_pktinfo;
2217 		}
2218 		optdatalen = sizeof(struct in6_pktinfo);
2219 		break;
2220 	case IPV6_TCLASS:
2221 		if (pktopt && pktopt->ip6po_tclass >= 0)
2222 			optdata = (void *)&pktopt->ip6po_tclass;
2223 		else
2224 			optdata = (void *)&deftclass;
2225 		optdatalen = sizeof(int);
2226 		break;
2227 	case IPV6_HOPOPTS:
2228 		if (pktopt && pktopt->ip6po_hbh) {
2229 			optdata = (void *)pktopt->ip6po_hbh;
2230 			ip6e = (struct ip6_ext *)pktopt->ip6po_hbh;
2231 			optdatalen = (ip6e->ip6e_len + 1) << 3;
2232 		}
2233 		break;
2234 	case IPV6_RTHDR:
2235 		if (pktopt && pktopt->ip6po_rthdr) {
2236 			optdata = (void *)pktopt->ip6po_rthdr;
2237 			ip6e = (struct ip6_ext *)pktopt->ip6po_rthdr;
2238 			optdatalen = (ip6e->ip6e_len + 1) << 3;
2239 		}
2240 		break;
2241 	case IPV6_RTHDRDSTOPTS:
2242 		if (pktopt && pktopt->ip6po_dest1) {
2243 			optdata = (void *)pktopt->ip6po_dest1;
2244 			ip6e = (struct ip6_ext *)pktopt->ip6po_dest1;
2245 			optdatalen = (ip6e->ip6e_len + 1) << 3;
2246 		}
2247 		break;
2248 	case IPV6_DSTOPTS:
2249 		if (pktopt && pktopt->ip6po_dest2) {
2250 			optdata = (void *)pktopt->ip6po_dest2;
2251 			ip6e = (struct ip6_ext *)pktopt->ip6po_dest2;
2252 			optdatalen = (ip6e->ip6e_len + 1) << 3;
2253 		}
2254 		break;
2255 	case IPV6_NEXTHOP:
2256 		if (pktopt && pktopt->ip6po_nexthop) {
2257 			optdata = (void *)pktopt->ip6po_nexthop;
2258 			optdatalen = pktopt->ip6po_nexthop->sa_len;
2259 		}
2260 		break;
2261 	case IPV6_USE_MIN_MTU:
2262 		if (pktopt)
2263 			optdata = (void *)&pktopt->ip6po_minmtu;
2264 		else
2265 			optdata = (void *)&defminmtu;
2266 		optdatalen = sizeof(int);
2267 		break;
2268 	case IPV6_DONTFRAG:
2269 		if (pktopt && ((pktopt->ip6po_flags) & IP6PO_DONTFRAG))
2270 			on = 1;
2271 		else
2272 			on = 0;
2273 		optdata = (void *)&on;
2274 		optdatalen = sizeof(on);
2275 		break;
2276 	case IPV6_PREFER_TEMPADDR:
2277 		if (pktopt)
2278 			optdata = (void *)&pktopt->ip6po_prefer_tempaddr;
2279 		else
2280 			optdata = (void *)&defpreftemp;
2281 		optdatalen = sizeof(int);
2282 		break;
2283 	default:		/* should not happen */
2284 #ifdef DIAGNOSTIC
2285 		panic("ip6_getpcbopt: unexpected option\n");
2286 #endif
2287 		return (ENOPROTOOPT);
2288 	}
2289 
2290 	soopt_from_kbuf(sopt, optdata, optdatalen);
2291 
2292 	return (error);
2293 }
2294 
2295 /*
2296  * initialize ip6_pktopts.  beware that there are non-zero default values in
2297  * the struct.
2298  */
2299 
2300 static int
2301 ip6_pcbopt(int optname, u_char *buf, int len, struct ip6_pktopts **pktopt, int uproto)
2302 {
2303 	struct ip6_pktopts *opt;
2304 	int priv =0;
2305 	if (*pktopt == NULL) {
2306 		*pktopt = kmalloc(sizeof(*opt), M_IP6OPT, M_WAITOK);
2307 		init_ip6pktopts(*pktopt);
2308 	}
2309 	opt = *pktopt;
2310 
2311 	return (ip6_setpktoption(optname, buf, len, opt, 1, 0, uproto, priv));
2312 }
2313 
2314 /*
2315  * initialize ip6_pktopts.  beware that there are non-zero default values in
2316  * the struct.
2317  */
2318 void
2319 init_ip6pktopts(struct ip6_pktopts *opt)
2320 {
2321 
2322 	bzero(opt, sizeof(*opt));
2323 	opt->ip6po_hlim = -1;	/* -1 means default hop limit */
2324 	opt->ip6po_tclass = -1;	/* -1 means default traffic class */
2325 	opt->ip6po_minmtu = IP6PO_MINMTU_MCASTONLY;
2326 	opt->ip6po_prefer_tempaddr = IP6PO_TEMPADDR_SYSTEM;
2327 }
2328 
2329 void
2330 ip6_clearpktopts(struct ip6_pktopts *pktopt, int optname)
2331 {
2332 	if (pktopt == NULL)
2333 		return;
2334 
2335 	if (optname == -1 || optname == IPV6_PKTINFO) {
2336 		if (pktopt->ip6po_pktinfo)
2337 			kfree(pktopt->ip6po_pktinfo, M_IP6OPT);
2338 		pktopt->ip6po_pktinfo = NULL;
2339 	}
2340 	if (optname == -1 || optname == IPV6_HOPLIMIT)
2341 		pktopt->ip6po_hlim = -1;
2342 	if (optname == -1 || optname == IPV6_TCLASS)
2343 		pktopt->ip6po_tclass = -1;
2344 	if (optname == -1 || optname == IPV6_NEXTHOP) {
2345 		if (pktopt->ip6po_nextroute.ro_rt) {
2346 			RTFREE(pktopt->ip6po_nextroute.ro_rt);
2347 			pktopt->ip6po_nextroute.ro_rt = NULL;
2348 		}
2349 		if (pktopt->ip6po_nexthop)
2350 			kfree(pktopt->ip6po_nexthop, M_IP6OPT);
2351 		pktopt->ip6po_nexthop = NULL;
2352 	}
2353 	if (optname == -1 || optname == IPV6_HOPOPTS) {
2354 		if (pktopt->ip6po_hbh)
2355 			kfree(pktopt->ip6po_hbh, M_IP6OPT);
2356 		pktopt->ip6po_hbh = NULL;
2357 	}
2358 	if (optname == -1 || optname == IPV6_RTHDRDSTOPTS) {
2359 		if (pktopt->ip6po_dest1)
2360 			kfree(pktopt->ip6po_dest1, M_IP6OPT);
2361 		pktopt->ip6po_dest1 = NULL;
2362 	}
2363 	if (optname == -1 || optname == IPV6_RTHDR) {
2364 		if (pktopt->ip6po_rhinfo.ip6po_rhi_rthdr)
2365 			kfree(pktopt->ip6po_rhinfo.ip6po_rhi_rthdr, M_IP6OPT);
2366 		pktopt->ip6po_rhinfo.ip6po_rhi_rthdr = NULL;
2367 		if (pktopt->ip6po_route.ro_rt) {
2368 			RTFREE(pktopt->ip6po_route.ro_rt);
2369 			pktopt->ip6po_route.ro_rt = NULL;
2370 		}
2371 	}
2372 	if (optname == -1 || optname == IPV6_DSTOPTS) {
2373 		if (pktopt->ip6po_dest2)
2374 			kfree(pktopt->ip6po_dest2, M_IP6OPT);
2375 		pktopt->ip6po_dest2 = NULL;
2376 	}
2377 }
2378 
2379 #define PKTOPT_EXTHDRCPY(type) \
2380 do {\
2381 	if (src->type) {\
2382 		int hlen =\
2383 			(((struct ip6_ext *)src->type)->ip6e_len + 1) << 3;\
2384 		dst->type = kmalloc(hlen, M_IP6OPT, canwait);\
2385 		if (dst->type == NULL)\
2386 			goto bad;\
2387 		bcopy(src->type, dst->type, hlen);\
2388 	}\
2389 } while (0)
2390 
2391 struct ip6_pktopts *
2392 ip6_copypktopts(struct ip6_pktopts *src, int canwait)
2393 {
2394 	struct ip6_pktopts *dst;
2395 
2396 	if (src == NULL) {
2397 		kprintf("ip6_clearpktopts: invalid argument\n");
2398 		return (NULL);
2399 	}
2400 
2401 	dst = kmalloc(sizeof(*dst), M_IP6OPT, canwait | M_ZERO);
2402 	if (dst == NULL)
2403 		return (NULL);
2404 
2405 	dst->ip6po_hlim = src->ip6po_hlim;
2406 	if (src->ip6po_pktinfo) {
2407 		dst->ip6po_pktinfo = kmalloc(sizeof(*dst->ip6po_pktinfo),
2408 					    M_IP6OPT, canwait);
2409 		if (dst->ip6po_pktinfo == NULL)
2410 			goto bad;
2411 		*dst->ip6po_pktinfo = *src->ip6po_pktinfo;
2412 	}
2413 	if (src->ip6po_nexthop) {
2414 		dst->ip6po_nexthop = kmalloc(src->ip6po_nexthop->sa_len,
2415 					    M_IP6OPT, canwait);
2416 		if (dst->ip6po_nexthop == NULL)
2417 			goto bad;
2418 		bcopy(src->ip6po_nexthop, dst->ip6po_nexthop,
2419 		      src->ip6po_nexthop->sa_len);
2420 	}
2421 	PKTOPT_EXTHDRCPY(ip6po_hbh);
2422 	PKTOPT_EXTHDRCPY(ip6po_dest1);
2423 	PKTOPT_EXTHDRCPY(ip6po_dest2);
2424 	PKTOPT_EXTHDRCPY(ip6po_rthdr); /* not copy the cached route */
2425 	return (dst);
2426 
2427 bad:
2428 	if (dst->ip6po_pktinfo) kfree(dst->ip6po_pktinfo, M_IP6OPT);
2429 	if (dst->ip6po_nexthop) kfree(dst->ip6po_nexthop, M_IP6OPT);
2430 	if (dst->ip6po_hbh) kfree(dst->ip6po_hbh, M_IP6OPT);
2431 	if (dst->ip6po_dest1) kfree(dst->ip6po_dest1, M_IP6OPT);
2432 	if (dst->ip6po_dest2) kfree(dst->ip6po_dest2, M_IP6OPT);
2433 	if (dst->ip6po_rthdr) kfree(dst->ip6po_rthdr, M_IP6OPT);
2434 	kfree(dst, M_IP6OPT);
2435 	return (NULL);
2436 }
2437 
2438 static int
2439 copypktopts(struct ip6_pktopts *dst, struct ip6_pktopts *src, int canwait)
2440 {
2441 	if (dst == NULL || src == NULL)  {
2442 #ifdef DIAGNOSTIC
2443 		kprintf("ip6_clearpktopts: invalid argument\n");
2444 #endif
2445 		return (EINVAL);
2446 	}
2447 
2448 	dst->ip6po_hlim = src->ip6po_hlim;
2449 	dst->ip6po_tclass = src->ip6po_tclass;
2450 	dst->ip6po_flags = src->ip6po_flags;
2451 	if (src->ip6po_pktinfo) {
2452 		dst->ip6po_pktinfo = kmalloc(sizeof(*dst->ip6po_pktinfo),
2453 		    M_IP6OPT, canwait);
2454 		if (dst->ip6po_pktinfo == NULL)
2455 			goto bad;
2456 		*dst->ip6po_pktinfo = *src->ip6po_pktinfo;
2457 	}
2458 	if (src->ip6po_nexthop) {
2459 		dst->ip6po_nexthop = kmalloc(src->ip6po_nexthop->sa_len,
2460 		    M_IP6OPT, canwait);
2461 		if (dst->ip6po_nexthop == NULL)
2462 			goto bad;
2463 		bcopy(src->ip6po_nexthop, dst->ip6po_nexthop,
2464 		    src->ip6po_nexthop->sa_len);
2465 	}
2466 	PKTOPT_EXTHDRCPY(ip6po_hbh);
2467 	PKTOPT_EXTHDRCPY(ip6po_dest1);
2468 	PKTOPT_EXTHDRCPY(ip6po_dest2);
2469 	PKTOPT_EXTHDRCPY(ip6po_rthdr); /* not copy the cached route */
2470 	return (0);
2471 
2472   bad:
2473 	ip6_clearpktopts(dst, -1);
2474 	return (ENOBUFS);
2475 }
2476 #undef PKTOPT_EXTHDRCPY
2477 
2478 void
2479 ip6_freepcbopts(struct ip6_pktopts *pktopt)
2480 {
2481 	if (pktopt == NULL)
2482 		return;
2483 
2484 	ip6_clearpktopts(pktopt, -1);
2485 
2486 	kfree(pktopt, M_IP6OPT);
2487 }
2488 
2489 /*
2490  * Set the IP6 multicast options in response to user setsockopt().
2491  */
2492 static int
2493 ip6_setmoptions(int optname, struct ip6_moptions **im6op, struct mbuf *m)
2494 {
2495 	int error = 0;
2496 	u_int loop, ifindex;
2497 	struct ipv6_mreq *mreq;
2498 	struct ifnet *ifp;
2499 	struct ip6_moptions *im6o = *im6op;
2500 	struct route_in6 ro;
2501 	struct sockaddr_in6 *dst;
2502 	struct in6_multi_mship *imm;
2503 	struct thread *td = curthread;	/* XXX */
2504 
2505 	if (im6o == NULL) {
2506 		/*
2507 		 * No multicast option buffer attached to the pcb;
2508 		 * allocate one and initialize to default values.
2509 		 */
2510 		im6o = (struct ip6_moptions *)
2511 			kmalloc(sizeof(*im6o), M_IPMOPTS, M_WAITOK);
2512 
2513 		*im6op = im6o;
2514 		im6o->im6o_multicast_ifp = NULL;
2515 		im6o->im6o_multicast_hlim = ip6_defmcasthlim;
2516 		im6o->im6o_multicast_loop = IPV6_DEFAULT_MULTICAST_LOOP;
2517 		LIST_INIT(&im6o->im6o_memberships);
2518 	}
2519 
2520 	switch (optname) {
2521 
2522 	case IPV6_MULTICAST_IF:
2523 		/*
2524 		 * Select the interface for outgoing multicast packets.
2525 		 */
2526 		if (m == NULL || m->m_len != sizeof(u_int)) {
2527 			error = EINVAL;
2528 			break;
2529 		}
2530 		bcopy(mtod(m, u_int *), &ifindex, sizeof(ifindex));
2531 		if (ifindex < 0 || if_index < ifindex) {
2532 			error = ENXIO;	/* XXX EINVAL? */
2533 			break;
2534 		}
2535 		ifp = ifindex2ifnet[ifindex];
2536 		if (ifp == NULL || !(ifp->if_flags & IFF_MULTICAST)) {
2537 			error = EADDRNOTAVAIL;
2538 			break;
2539 		}
2540 		im6o->im6o_multicast_ifp = ifp;
2541 		break;
2542 
2543 	case IPV6_MULTICAST_HOPS:
2544 	    {
2545 		/*
2546 		 * Set the IP6 hoplimit for outgoing multicast packets.
2547 		 */
2548 		int optval;
2549 		if (m == NULL || m->m_len != sizeof(int)) {
2550 			error = EINVAL;
2551 			break;
2552 		}
2553 		bcopy(mtod(m, u_int *), &optval, sizeof(optval));
2554 		if (optval < -1 || optval >= 256)
2555 			error = EINVAL;
2556 		else if (optval == -1)
2557 			im6o->im6o_multicast_hlim = ip6_defmcasthlim;
2558 		else
2559 			im6o->im6o_multicast_hlim = optval;
2560 		break;
2561 	    }
2562 
2563 	case IPV6_MULTICAST_LOOP:
2564 		/*
2565 		 * Set the loopback flag for outgoing multicast packets.
2566 		 * Must be zero or one.
2567 		 */
2568 		if (m == NULL || m->m_len != sizeof(u_int)) {
2569 			error = EINVAL;
2570 			break;
2571 		}
2572 		bcopy(mtod(m, u_int *), &loop, sizeof(loop));
2573 		if (loop > 1) {
2574 			error = EINVAL;
2575 			break;
2576 		}
2577 		im6o->im6o_multicast_loop = loop;
2578 		break;
2579 
2580 	case IPV6_JOIN_GROUP:
2581 		/*
2582 		 * Add a multicast group membership.
2583 		 * Group must be a valid IP6 multicast address.
2584 		 */
2585 		if (m == NULL || m->m_len != sizeof(struct ipv6_mreq)) {
2586 			error = EINVAL;
2587 			break;
2588 		}
2589 		mreq = mtod(m, struct ipv6_mreq *);
2590 		if (IN6_IS_ADDR_UNSPECIFIED(&mreq->ipv6mr_multiaddr)) {
2591 			/*
2592 			 * We use the unspecified address to specify to accept
2593 			 * all multicast addresses. Only super user is allowed
2594 			 * to do this.
2595 			 */
2596 			if (priv_check(td, PRIV_ROOT))
2597 			{
2598 				error = EACCES;
2599 				break;
2600 			}
2601 		} else if (!IN6_IS_ADDR_MULTICAST(&mreq->ipv6mr_multiaddr)) {
2602 			error = EINVAL;
2603 			break;
2604 		}
2605 
2606 		/*
2607 		 * If the interface is specified, validate it.
2608 		 */
2609 		if (mreq->ipv6mr_interface < 0
2610 		 || if_index < mreq->ipv6mr_interface) {
2611 			error = ENXIO;	/* XXX EINVAL? */
2612 			break;
2613 		}
2614 		/*
2615 		 * If no interface was explicitly specified, choose an
2616 		 * appropriate one according to the given multicast address.
2617 		 */
2618 		if (mreq->ipv6mr_interface == 0) {
2619 			/*
2620 			 * If the multicast address is in node-local scope,
2621 			 * the interface should be a loopback interface.
2622 			 * Otherwise, look up the routing table for the
2623 			 * address, and choose the outgoing interface.
2624 			 *   XXX: is it a good approach?
2625 			 */
2626 			if (IN6_IS_ADDR_MC_NODELOCAL(&mreq->ipv6mr_multiaddr)) {
2627 				ifp = &loif[0];
2628 			} else {
2629 				ro.ro_rt = NULL;
2630 				dst = (struct sockaddr_in6 *)&ro.ro_dst;
2631 				bzero(dst, sizeof(*dst));
2632 				dst->sin6_len = sizeof(struct sockaddr_in6);
2633 				dst->sin6_family = AF_INET6;
2634 				dst->sin6_addr = mreq->ipv6mr_multiaddr;
2635 				rtalloc((struct route *)&ro);
2636 				if (ro.ro_rt == NULL) {
2637 					error = EADDRNOTAVAIL;
2638 					break;
2639 				}
2640 				ifp = ro.ro_rt->rt_ifp;
2641 				rtfree(ro.ro_rt);
2642 			}
2643 		} else
2644 			ifp = ifindex2ifnet[mreq->ipv6mr_interface];
2645 
2646 		/*
2647 		 * See if we found an interface, and confirm that it
2648 		 * supports multicast
2649 		 */
2650 		if (ifp == NULL || !(ifp->if_flags & IFF_MULTICAST)) {
2651 			error = EADDRNOTAVAIL;
2652 			break;
2653 		}
2654 		/*
2655 		 * Put interface index into the multicast address,
2656 		 * if the address has link-local scope.
2657 		 */
2658 		if (IN6_IS_ADDR_MC_LINKLOCAL(&mreq->ipv6mr_multiaddr)) {
2659 			mreq->ipv6mr_multiaddr.s6_addr16[1]
2660 				= htons(mreq->ipv6mr_interface);
2661 		}
2662 		/*
2663 		 * See if the membership already exists.
2664 		 */
2665 		for (imm = im6o->im6o_memberships.lh_first;
2666 		     imm != NULL; imm = imm->i6mm_chain.le_next)
2667 			if (imm->i6mm_maddr->in6m_ifp == ifp &&
2668 			    IN6_ARE_ADDR_EQUAL(&imm->i6mm_maddr->in6m_addr,
2669 					       &mreq->ipv6mr_multiaddr))
2670 				break;
2671 		if (imm != NULL) {
2672 			error = EADDRINUSE;
2673 			break;
2674 		}
2675 		/*
2676 		 * Everything looks good; add a new record to the multicast
2677 		 * address list for the given interface.
2678 		 */
2679 		imm = kmalloc(sizeof(*imm), M_IPMADDR, M_WAITOK);
2680 		if ((imm->i6mm_maddr =
2681 		     in6_addmulti(&mreq->ipv6mr_multiaddr, ifp, &error)) == NULL) {
2682 			kfree(imm, M_IPMADDR);
2683 			break;
2684 		}
2685 		LIST_INSERT_HEAD(&im6o->im6o_memberships, imm, i6mm_chain);
2686 		break;
2687 
2688 	case IPV6_LEAVE_GROUP:
2689 		/*
2690 		 * Drop a multicast group membership.
2691 		 * Group must be a valid IP6 multicast address.
2692 		 */
2693 		if (m == NULL || m->m_len != sizeof(struct ipv6_mreq)) {
2694 			error = EINVAL;
2695 			break;
2696 		}
2697 		mreq = mtod(m, struct ipv6_mreq *);
2698 		if (IN6_IS_ADDR_UNSPECIFIED(&mreq->ipv6mr_multiaddr)) {
2699 			if (priv_check(td, PRIV_ROOT)) {
2700 				error = EACCES;
2701 				break;
2702 			}
2703 		} else if (!IN6_IS_ADDR_MULTICAST(&mreq->ipv6mr_multiaddr)) {
2704 			error = EINVAL;
2705 			break;
2706 		}
2707 		/*
2708 		 * If an interface address was specified, get a pointer
2709 		 * to its ifnet structure.
2710 		 */
2711 		if (mreq->ipv6mr_interface < 0
2712 		 || if_index < mreq->ipv6mr_interface) {
2713 			error = ENXIO;	/* XXX EINVAL? */
2714 			break;
2715 		}
2716 		ifp = ifindex2ifnet[mreq->ipv6mr_interface];
2717 		/*
2718 		 * Put interface index into the multicast address,
2719 		 * if the address has link-local scope.
2720 		 */
2721 		if (IN6_IS_ADDR_MC_LINKLOCAL(&mreq->ipv6mr_multiaddr)) {
2722 			mreq->ipv6mr_multiaddr.s6_addr16[1]
2723 				= htons(mreq->ipv6mr_interface);
2724 		}
2725 		/*
2726 		 * Find the membership in the membership list.
2727 		 */
2728 		for (imm = im6o->im6o_memberships.lh_first;
2729 		     imm != NULL; imm = imm->i6mm_chain.le_next) {
2730 			if ((ifp == NULL ||
2731 			     imm->i6mm_maddr->in6m_ifp == ifp) &&
2732 			    IN6_ARE_ADDR_EQUAL(&imm->i6mm_maddr->in6m_addr,
2733 					       &mreq->ipv6mr_multiaddr))
2734 				break;
2735 		}
2736 		if (imm == NULL) {
2737 			/* Unable to resolve interface */
2738 			error = EADDRNOTAVAIL;
2739 			break;
2740 		}
2741 		/*
2742 		 * Give up the multicast address record to which the
2743 		 * membership points.
2744 		 */
2745 		LIST_REMOVE(imm, i6mm_chain);
2746 		in6_delmulti(imm->i6mm_maddr);
2747 		kfree(imm, M_IPMADDR);
2748 		break;
2749 
2750 	default:
2751 		error = EOPNOTSUPP;
2752 		break;
2753 	}
2754 
2755 	/*
2756 	 * If all options have default values, no need to keep the mbuf.
2757 	 */
2758 	if (im6o->im6o_multicast_ifp == NULL &&
2759 	    im6o->im6o_multicast_hlim == ip6_defmcasthlim &&
2760 	    im6o->im6o_multicast_loop == IPV6_DEFAULT_MULTICAST_LOOP &&
2761 	    im6o->im6o_memberships.lh_first == NULL) {
2762 		kfree(*im6op, M_IPMOPTS);
2763 		*im6op = NULL;
2764 	}
2765 
2766 	return (error);
2767 }
2768 
2769 /*
2770  * Return the IP6 multicast options in response to user getsockopt().
2771  */
2772 static int
2773 ip6_getmoptions(int optname, struct ip6_moptions *im6o, struct mbuf **mp)
2774 {
2775 	u_int *hlim, *loop, *ifindex;
2776 
2777 	*mp = m_get(MB_WAIT, MT_HEADER);		/* XXX */
2778 
2779 	switch (optname) {
2780 
2781 	case IPV6_MULTICAST_IF:
2782 		ifindex = mtod(*mp, u_int *);
2783 		(*mp)->m_len = sizeof(u_int);
2784 		if (im6o == NULL || im6o->im6o_multicast_ifp == NULL)
2785 			*ifindex = 0;
2786 		else
2787 			*ifindex = im6o->im6o_multicast_ifp->if_index;
2788 		return (0);
2789 
2790 	case IPV6_MULTICAST_HOPS:
2791 		hlim = mtod(*mp, u_int *);
2792 		(*mp)->m_len = sizeof(u_int);
2793 		if (im6o == NULL)
2794 			*hlim = ip6_defmcasthlim;
2795 		else
2796 			*hlim = im6o->im6o_multicast_hlim;
2797 		return (0);
2798 
2799 	case IPV6_MULTICAST_LOOP:
2800 		loop = mtod(*mp, u_int *);
2801 		(*mp)->m_len = sizeof(u_int);
2802 		if (im6o == NULL)
2803 			*loop = ip6_defmcasthlim;
2804 		else
2805 			*loop = im6o->im6o_multicast_loop;
2806 		return (0);
2807 
2808 	default:
2809 		return (EOPNOTSUPP);
2810 	}
2811 }
2812 
2813 /*
2814  * Discard the IP6 multicast options.
2815  */
2816 void
2817 ip6_freemoptions(struct ip6_moptions *im6o)
2818 {
2819 	struct in6_multi_mship *imm;
2820 
2821 	if (im6o == NULL)
2822 		return;
2823 
2824 	while ((imm = im6o->im6o_memberships.lh_first) != NULL) {
2825 		LIST_REMOVE(imm, i6mm_chain);
2826 		if (imm->i6mm_maddr)
2827 			in6_delmulti(imm->i6mm_maddr);
2828 		kfree(imm, M_IPMADDR);
2829 	}
2830 	kfree(im6o, M_IPMOPTS);
2831 }
2832 
2833 /*
2834  * Set a particular packet option, as a sticky option or an ancillary data
2835  * item.  "len" can be 0 only when it's a sticky option.
2836  * We have 4 cases of combination of "sticky" and "cmsg":
2837  * "sticky=0, cmsg=0": impossible
2838  * "sticky=0, cmsg=1": RFC2292 or RFC3542 ancillary data
2839  * "sticky=1, cmsg=0": RFC3542 socket option
2840  * "sticky=1, cmsg=1": RFC2292 socket option
2841  */
2842 static int
2843 ip6_setpktoption(int optname, u_char *buf, int len, struct ip6_pktopts *opt,
2844      int sticky, int cmsg, int uproto, int priv)
2845 {
2846 	int minmtupolicy, preftemp;
2847 	//int error;
2848 
2849 	if (!sticky && !cmsg) {
2850 		kprintf("ip6_setpktoption: impossible case\n");
2851 		return (EINVAL);
2852 	}
2853 
2854 	/*
2855 	 * IPV6_2292xxx is for backward compatibility to RFC2292, and should
2856 	 * not be specified in the context of RFC3542.  Conversely,
2857 	 * RFC3542 types should not be specified in the context of RFC2292.
2858 	 */
2859 	if (!cmsg) {
2860 		switch (optname) {
2861 		case IPV6_2292PKTINFO:
2862 		case IPV6_2292HOPLIMIT:
2863 		case IPV6_2292NEXTHOP:
2864 		case IPV6_2292HOPOPTS:
2865 		case IPV6_2292DSTOPTS:
2866 		case IPV6_2292RTHDR:
2867 		case IPV6_2292PKTOPTIONS:
2868 			return (ENOPROTOOPT);
2869 		}
2870 	}
2871 	if (sticky && cmsg) {
2872 		switch (optname) {
2873 		case IPV6_PKTINFO:
2874 		case IPV6_HOPLIMIT:
2875 		case IPV6_NEXTHOP:
2876 		case IPV6_HOPOPTS:
2877 		case IPV6_DSTOPTS:
2878 		case IPV6_RTHDRDSTOPTS:
2879 		case IPV6_RTHDR:
2880 		case IPV6_USE_MIN_MTU:
2881 		case IPV6_DONTFRAG:
2882 		case IPV6_TCLASS:
2883 		case IPV6_PREFER_TEMPADDR: /* XXX: not an RFC3542 option */
2884 			return (ENOPROTOOPT);
2885 		}
2886 	}
2887 
2888 	switch (optname) {
2889 	case IPV6_2292PKTINFO:
2890 	case IPV6_PKTINFO:
2891 	{
2892 		struct in6_pktinfo *pktinfo;
2893 		if (len != sizeof(struct in6_pktinfo))
2894 			return (EINVAL);
2895 		pktinfo = (struct in6_pktinfo *)buf;
2896 
2897 		/*
2898 		 * An application can clear any sticky IPV6_PKTINFO option by
2899 		 * doing a "regular" setsockopt with ipi6_addr being
2900 		 * in6addr_any and ipi6_ifindex being zero.
2901 		 * [RFC 3542, Section 6]
2902 		 */
2903 		if (optname == IPV6_PKTINFO && opt->ip6po_pktinfo &&
2904 		    pktinfo->ipi6_ifindex == 0 &&
2905 		    IN6_IS_ADDR_UNSPECIFIED(&pktinfo->ipi6_addr)) {
2906 			ip6_clearpktopts(opt, optname);
2907 			break;
2908 		}
2909 
2910 		if (uproto == IPPROTO_TCP && optname == IPV6_PKTINFO &&
2911 		    sticky && !IN6_IS_ADDR_UNSPECIFIED(&pktinfo->ipi6_addr)) {
2912 			return (EINVAL);
2913 		}
2914 
2915 		/* validate the interface index if specified. */
2916 		if (pktinfo->ipi6_ifindex > if_index ||
2917 		    pktinfo->ipi6_ifindex < 0) {
2918 			 return (ENXIO);
2919 		}
2920 		/*
2921 		 * Check if the requested source address is indeed a
2922 		 * unicast address assigned to the node, and can be
2923 		 * used as the packet's source address.
2924 		 */
2925 		if (opt->ip6po_pktinfo != NULL &&
2926 		    !IN6_IS_ADDR_UNSPECIFIED(&opt->ip6po_pktinfo->ipi6_addr)) {
2927 			struct in6_ifaddr *ia6;
2928 			struct sockaddr_in6 sin6;
2929 
2930 			bzero(&sin6, sizeof(sin6));
2931 			sin6.sin6_len = sizeof(sin6);
2932 			sin6.sin6_family = AF_INET6;
2933 			sin6.sin6_addr =
2934 			opt->ip6po_pktinfo->ipi6_addr;
2935 			ia6 = (struct in6_ifaddr *)ifa_ifwithaddr(sin6tosa(&sin6));
2936 			if (ia6 == NULL ||
2937 				(ia6->ia6_flags & (IN6_IFF_ANYCAST |
2938 					IN6_IFF_NOTREADY)) != 0)
2939 			return (EADDRNOTAVAIL);
2940 		}
2941 
2942 		/*
2943 		 * We store the address anyway, and let in6_selectsrc()
2944 		 * validate the specified address.  This is because ipi6_addr
2945 		 * may not have enough information about its scope zone, and
2946 		 * we may need additional information (such as outgoing
2947 		 * interface or the scope zone of a destination address) to
2948 		 * disambiguate the scope.
2949 		 * XXX: the delay of the validation may confuse the
2950 		 * application when it is used as a sticky option.
2951 		 */
2952 		if (opt->ip6po_pktinfo == NULL) {
2953 			opt->ip6po_pktinfo = kmalloc(sizeof(*pktinfo),
2954 			    M_IP6OPT, M_NOWAIT);
2955 			if (opt->ip6po_pktinfo == NULL)
2956 				return (ENOBUFS);
2957 		}
2958 		bcopy(pktinfo, opt->ip6po_pktinfo, sizeof(*pktinfo));
2959 		break;
2960 	}
2961 
2962 	case IPV6_2292HOPLIMIT:
2963 	case IPV6_HOPLIMIT:
2964 	{
2965 		int *hlimp;
2966 
2967 		/*
2968 		 * RFC 3542 deprecated the usage of sticky IPV6_HOPLIMIT
2969 		 * to simplify the ordering among hoplimit options.
2970 		 */
2971 		if (optname == IPV6_HOPLIMIT && sticky)
2972 			return (ENOPROTOOPT);
2973 
2974 		if (len != sizeof(int))
2975 			return (EINVAL);
2976 		hlimp = (int *)buf;
2977 		if (*hlimp < -1 || *hlimp > 255)
2978 			return (EINVAL);
2979 
2980 		opt->ip6po_hlim = *hlimp;
2981 		break;
2982 	}
2983 
2984 	case IPV6_TCLASS:
2985 	{
2986 		int tclass;
2987 
2988 		if (len != sizeof(int))
2989 			return (EINVAL);
2990 		tclass = *(int *)buf;
2991 		if (tclass < -1 || tclass > 255)
2992 			return (EINVAL);
2993 
2994 		opt->ip6po_tclass = tclass;
2995 		break;
2996 	}
2997 
2998 	case IPV6_2292NEXTHOP:
2999 	case IPV6_NEXTHOP:
3000 		if (!priv)
3001 			return (EPERM);
3002 
3003 		if (len == 0) {	/* just remove the option */
3004 			ip6_clearpktopts(opt, IPV6_NEXTHOP);
3005 			break;
3006 		}
3007 
3008 		/* check if cmsg_len is large enough for sa_len */
3009 		if (len < sizeof(struct sockaddr) || len < *buf)
3010 			return (EINVAL);
3011 
3012 		switch (((struct sockaddr *)buf)->sa_family) {
3013 		case AF_INET6:
3014 		{
3015 			struct sockaddr_in6 *sa6 = (struct sockaddr_in6 *)buf;
3016 			//int error;
3017 
3018 			if (sa6->sin6_len != sizeof(struct sockaddr_in6))
3019 				return (EINVAL);
3020 
3021 			if (IN6_IS_ADDR_UNSPECIFIED(&sa6->sin6_addr) ||
3022 			    IN6_IS_ADDR_MULTICAST(&sa6->sin6_addr)) {
3023 				return (EINVAL);
3024 			}
3025 			break;
3026 		}
3027 		case AF_LINK:	/* should eventually be supported */
3028 		default:
3029 			return (EAFNOSUPPORT);
3030 		}
3031 
3032 		/* turn off the previous option, then set the new option. */
3033 		ip6_clearpktopts(opt, IPV6_NEXTHOP);
3034 		opt->ip6po_nexthop = kmalloc(*buf, M_IP6OPT, M_NOWAIT);
3035 		if (opt->ip6po_nexthop == NULL)
3036 			return (ENOBUFS);
3037 		bcopy(buf, opt->ip6po_nexthop, *buf);
3038 		break;
3039 
3040 	case IPV6_2292HOPOPTS:
3041 	case IPV6_HOPOPTS:
3042 	{
3043 		struct ip6_hbh *hbh;
3044 		int hbhlen;
3045 
3046 		/*
3047 		 * XXX: We don't allow a non-privileged user to set ANY HbH
3048 		 * options, since per-option restriction has too much
3049 		 * overhead.
3050 		 */
3051 		if (!priv)
3052 			return (EPERM);
3053 		if (len == 0) {
3054 			ip6_clearpktopts(opt, IPV6_HOPOPTS);
3055 			break;	/* just remove the option */
3056 		}
3057 
3058 		/* message length validation */
3059 		if (len < sizeof(struct ip6_hbh))
3060 			return (EINVAL);
3061 		hbh = (struct ip6_hbh *)buf;
3062 		hbhlen = (hbh->ip6h_len + 1) << 3;
3063 		if (len != hbhlen)
3064 			return (EINVAL);
3065 
3066 		/* turn off the previous option, then set the new option. */
3067 		ip6_clearpktopts(opt, IPV6_HOPOPTS);
3068 		opt->ip6po_hbh = kmalloc(hbhlen, M_IP6OPT, M_NOWAIT);
3069 		if (opt->ip6po_hbh == NULL)
3070 			return (ENOBUFS);
3071 		bcopy(hbh, opt->ip6po_hbh, hbhlen);
3072 
3073 		break;
3074 	}
3075 
3076 	case IPV6_2292DSTOPTS:
3077 	case IPV6_DSTOPTS:
3078 	case IPV6_RTHDRDSTOPTS:
3079 	{
3080 		struct ip6_dest *dest, **newdest = NULL;
3081 		int destlen;
3082 		if (!priv)
3083 			return (EPERM);
3084 
3085 		if (len == 0) {
3086 			ip6_clearpktopts(opt, optname);
3087 			break;	/* just remove the option */
3088 		}
3089 
3090 		/* message length validation */
3091 		if (len < sizeof(struct ip6_dest))
3092 			return (EINVAL);
3093 		dest = (struct ip6_dest *)buf;
3094 		destlen = (dest->ip6d_len + 1) << 3;
3095 		if (len != destlen)
3096 			return (EINVAL);
3097 
3098 		/*
3099 		 * Determine the position that the destination options header
3100 		 * should be inserted; before or after the routing header.
3101 		 */
3102 		switch (optname) {
3103 		case IPV6_2292DSTOPTS:
3104 			/*
3105 			 * The old advacned API is ambiguous on this point.
3106 			 * Our approach is to determine the position based
3107 			 * according to the existence of a routing header.
3108 			 * Note, however, that this depends on the order of the
3109 			 * extension headers in the ancillary data; the 1st
3110 			 * part of the destination options header must appear
3111 			 * before the routing header in the ancillary data,
3112 			 * too.
3113 			 * RFC3542 solved the ambiguity by introducing
3114 			 * separate ancillary data or option types.
3115 			 */
3116 			if (opt->ip6po_rthdr == NULL)
3117 				newdest = &opt->ip6po_dest1;
3118 			else
3119 				newdest = &opt->ip6po_dest2;
3120 			break;
3121 		case IPV6_RTHDRDSTOPTS:
3122 			newdest = &opt->ip6po_dest1;
3123 			break;
3124 		case IPV6_DSTOPTS:
3125 			newdest = &opt->ip6po_dest2;
3126 			break;
3127 		}
3128 
3129 		/* turn off the previous option, then set the new option. */
3130 		ip6_clearpktopts(opt, optname);
3131 		*newdest = kmalloc(destlen, M_IP6OPT, M_NOWAIT);
3132 		if (*newdest == NULL)
3133 			return (ENOBUFS);
3134 		bcopy(dest, *newdest, destlen);
3135 
3136 		break;
3137 	}
3138 
3139 	case IPV6_2292RTHDR:
3140 	case IPV6_RTHDR:
3141 	{
3142 		struct ip6_rthdr *rth;
3143 		int rthlen;
3144 
3145 		if (len == 0) {
3146 			ip6_clearpktopts(opt, IPV6_RTHDR);
3147 			break;	/* just remove the option */
3148 		}
3149 
3150 		/* message length validation */
3151 		if (len < sizeof(struct ip6_rthdr))
3152 			return (EINVAL);
3153 		rth = (struct ip6_rthdr *)buf;
3154 		rthlen = (rth->ip6r_len + 1) << 3;
3155 		if (len != rthlen)
3156 			return (EINVAL);
3157 
3158 		switch (rth->ip6r_type) {
3159 		default:
3160 			return (EINVAL);	/* not supported */
3161 		}
3162 
3163 		/* turn off the previous option */
3164 		ip6_clearpktopts(opt, IPV6_RTHDR);
3165 		opt->ip6po_rthdr = kmalloc(rthlen, M_IP6OPT, M_NOWAIT);
3166 		if (opt->ip6po_rthdr == NULL)
3167 			return (ENOBUFS);
3168 		bcopy(rth, opt->ip6po_rthdr, rthlen);
3169 
3170 		break;
3171 	}
3172 
3173 	case IPV6_USE_MIN_MTU:
3174 		if (len != sizeof(int))
3175 			return (EINVAL);
3176 		minmtupolicy = *(int *)buf;
3177 		if (minmtupolicy != IP6PO_MINMTU_MCASTONLY &&
3178 		    minmtupolicy != IP6PO_MINMTU_DISABLE &&
3179 		    minmtupolicy != IP6PO_MINMTU_ALL) {
3180 			return (EINVAL);
3181 		}
3182 		opt->ip6po_minmtu = minmtupolicy;
3183 		break;
3184 
3185 	case IPV6_DONTFRAG:
3186 		if (len != sizeof(int))
3187 			return (EINVAL);
3188 
3189 		if (uproto == IPPROTO_TCP || *(int *)buf == 0) {
3190 			/*
3191 			 * we ignore this option for TCP sockets.
3192 			 * (RFC3542 leaves this case unspecified.)
3193 			 */
3194 			opt->ip6po_flags &= ~IP6PO_DONTFRAG;
3195 		} else
3196 			opt->ip6po_flags |= IP6PO_DONTFRAG;
3197 		break;
3198 
3199 	case IPV6_PREFER_TEMPADDR:
3200 		if (len != sizeof(int))
3201 			return (EINVAL);
3202 		preftemp = *(int *)buf;
3203 		if (preftemp != IP6PO_TEMPADDR_SYSTEM &&
3204 		    preftemp != IP6PO_TEMPADDR_NOTPREFER &&
3205 		    preftemp != IP6PO_TEMPADDR_PREFER) {
3206 			return (EINVAL);
3207 		}
3208 		opt->ip6po_prefer_tempaddr = preftemp;
3209 		break;
3210 
3211 	default:
3212 		return (ENOPROTOOPT);
3213 	} /* end of switch */
3214 
3215 	return (0);
3216 }
3217 
3218 
3219 /*
3220  * Set IPv6 outgoing packet options based on advanced API.
3221  */
3222 int
3223 ip6_setpktoptions(struct mbuf *control, struct ip6_pktopts *opt,
3224     struct ip6_pktopts *stickyopt, int uproto, int priv)
3225 {
3226 	struct cmsghdr *cm = NULL;
3227 
3228 	if (control == NULL || opt == NULL)
3229 		return (EINVAL);
3230 
3231 	init_ip6pktopts(opt);
3232 
3233 	/*
3234 	 * XXX: Currently, we assume all the optional information is stored
3235 	 * in a single mbuf.
3236 	 */
3237 	if (stickyopt) {
3238 		int error;
3239 
3240 		/*
3241 		 * If stickyopt is provided, make a local copy of the options
3242 		 * for this particular packet, then override them by ancillary
3243 		 * objects.
3244 		 * XXX: copypktopts() does not copy the cached route to a next
3245 		 * hop (if any).  This is not very good in terms of efficiency,
3246 		 * but we can allow this since this option should be rarely
3247 		 * used.
3248 		 */
3249 		if ((error = copypktopts(opt, stickyopt, M_NOWAIT)) != 0)
3250 			return (error);
3251 	}
3252 
3253 	/*
3254 	 * XXX: Currently, we assume all the optional information is stored
3255 	 * in a single mbuf.
3256 	 */
3257 	if (control->m_next)
3258 		return (EINVAL);
3259 
3260 	for (; control->m_len; control->m_data += CMSG_ALIGN(cm->cmsg_len),
3261 	    control->m_len -= CMSG_ALIGN(cm->cmsg_len)) {
3262 		int error;
3263 
3264 		if (control->m_len < CMSG_LEN(0))
3265 			return (EINVAL);
3266 
3267 		cm = mtod(control, struct cmsghdr *);
3268 		if (cm->cmsg_len == 0 || cm->cmsg_len > control->m_len)
3269 			return (EINVAL);
3270 		if (cm->cmsg_level != IPPROTO_IPV6)
3271 			continue;
3272 
3273 		error = ip6_setpktoption(cm->cmsg_type, CMSG_DATA(cm),
3274 		    cm->cmsg_len - CMSG_LEN(0), opt, 0, 1, uproto, priv);
3275 		if (error)
3276 			return (error);
3277 	}
3278 
3279 	return (0);
3280 }
3281 
3282 /*
3283  * Routine called from ip6_output() to loop back a copy of an IP6 multicast
3284  * packet to the input queue of a specified interface.  Note that this
3285  * calls the output routine of the loopback "driver", but with an interface
3286  * pointer that might NOT be &loif -- easier than replicating that code here.
3287  */
3288 void
3289 ip6_mloopback(struct ifnet *ifp, struct mbuf *m, struct sockaddr_in6 *dst)
3290 {
3291 	struct mbuf *copym;
3292 	struct ip6_hdr *ip6;
3293 
3294 	copym = m_copy(m, 0, M_COPYALL);
3295 	if (copym == NULL)
3296 		return;
3297 
3298 	/*
3299 	 * Make sure to deep-copy IPv6 header portion in case the data
3300 	 * is in an mbuf cluster, so that we can safely override the IPv6
3301 	 * header portion later.
3302 	 */
3303 	if ((copym->m_flags & M_EXT) != 0 ||
3304 	    copym->m_len < sizeof(struct ip6_hdr)) {
3305 		copym = m_pullup(copym, sizeof(struct ip6_hdr));
3306 		if (copym == NULL)
3307 			return;
3308 	}
3309 
3310 #ifdef DIAGNOSTIC
3311 	if (copym->m_len < sizeof(*ip6)) {
3312 		m_freem(copym);
3313 		return;
3314 	}
3315 #endif
3316 
3317 	ip6 = mtod(copym, struct ip6_hdr *);
3318 	/*
3319 	 * clear embedded scope identifiers if necessary.
3320 	 * in6_clearscope will touch the addresses only when necessary.
3321 	 */
3322 	in6_clearscope(&ip6->ip6_src);
3323 	in6_clearscope(&ip6->ip6_dst);
3324 
3325 	if_simloop(ifp, copym, dst->sin6_family, 0);
3326 }
3327 
3328 /*
3329  * Separate the IPv6 header from the payload into its own mbuf.
3330  *
3331  * Returns the new mbuf chain or the original mbuf if no payload.
3332  * Returns NULL if can't allocate new mbuf for header.
3333  */
3334 static struct mbuf *
3335 ip6_splithdr(struct mbuf *m)
3336 {
3337 	struct mbuf *mh;
3338 
3339 	if (m->m_len <= sizeof(struct ip6_hdr))		/* no payload */
3340 		return (m);
3341 
3342 	MGETHDR(mh, MB_DONTWAIT, MT_HEADER);
3343 	if (mh == NULL)
3344 		return (NULL);
3345 	mh->m_len = sizeof(struct ip6_hdr);
3346 	M_MOVE_PKTHDR(mh, m);
3347 	MH_ALIGN(mh, sizeof(struct ip6_hdr));
3348 	bcopy(mtod(m, caddr_t), mtod(mh, caddr_t), sizeof(struct ip6_hdr));
3349 	m->m_data += sizeof(struct ip6_hdr);
3350 	m->m_len -= sizeof(struct ip6_hdr);
3351 	mh->m_next = m;
3352 	return (mh);
3353 }
3354 
3355 /*
3356  * Compute IPv6 extension header length.
3357  */
3358 int
3359 ip6_optlen(struct in6pcb *in6p)
3360 {
3361 	int len;
3362 
3363 	if (!in6p->in6p_outputopts)
3364 		return 0;
3365 
3366 	len = 0;
3367 #define elen(x) \
3368     (((struct ip6_ext *)(x)) ? (((struct ip6_ext *)(x))->ip6e_len + 1) << 3 : 0)
3369 
3370 	len += elen(in6p->in6p_outputopts->ip6po_hbh);
3371 	if (in6p->in6p_outputopts->ip6po_rthdr)
3372 		/* dest1 is valid with rthdr only */
3373 		len += elen(in6p->in6p_outputopts->ip6po_dest1);
3374 	len += elen(in6p->in6p_outputopts->ip6po_rthdr);
3375 	len += elen(in6p->in6p_outputopts->ip6po_dest2);
3376 	return len;
3377 #undef elen
3378 }
3379