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