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