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