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