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