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