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