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