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