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