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