xref: /openbsd-src/sys/netinet6/ip6_output.c (revision 24bb5fcea3ed904bc467217bdaadb5dfc618d5bf)
1 /*	$OpenBSD: ip6_output.c,v 1.258 2021/07/08 15:13:14 bluhm Exp $	*/
2 /*	$KAME: ip6_output.c,v 1.172 2001/03/25 09:55:56 itojun Exp $	*/
3 
4 /*
5  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the project nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32 
33 /*
34  * Copyright (c) 1982, 1986, 1988, 1990, 1993
35  *	The Regents of the University of California.  All rights reserved.
36  *
37  * Redistribution and use in source and binary forms, with or without
38  * modification, are permitted provided that the following conditions
39  * are met:
40  * 1. Redistributions of source code must retain the above copyright
41  *    notice, this list of conditions and the following disclaimer.
42  * 2. Redistributions in binary form must reproduce the above copyright
43  *    notice, this list of conditions and the following disclaimer in the
44  *    documentation and/or other materials provided with the distribution.
45  * 3. Neither the name of the University nor the names of its contributors
46  *    may be used to endorse or promote products derived from this software
47  *    without specific prior written permission.
48  *
49  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
50  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
51  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
52  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
53  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
54  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
55  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
56  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
57  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
58  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
59  * SUCH DAMAGE.
60  *
61  *	@(#)ip_output.c	8.3 (Berkeley) 1/21/94
62  */
63 
64 #include "pf.h"
65 
66 #include <sys/param.h>
67 #include <sys/malloc.h>
68 #include <sys/mbuf.h>
69 #include <sys/errno.h>
70 #include <sys/protosw.h>
71 #include <sys/socket.h>
72 #include <sys/socketvar.h>
73 #include <sys/proc.h>
74 #include <sys/systm.h>
75 
76 #include <net/if.h>
77 #include <net/if_var.h>
78 #include <net/if_enc.h>
79 #include <net/route.h>
80 
81 #include <netinet/in.h>
82 #include <netinet/ip.h>
83 #include <netinet/in_pcb.h>
84 #include <netinet/udp.h>
85 #include <netinet/tcp.h>
86 
87 #include <netinet/ip_var.h>
88 #include <netinet/tcp_timer.h>
89 #include <netinet/tcp_var.h>
90 #include <netinet/udp_var.h>
91 
92 #include <netinet6/in6_var.h>
93 #include <netinet/ip6.h>
94 #include <netinet/icmp6.h>
95 #include <netinet6/ip6_var.h>
96 #include <netinet6/nd6.h>
97 #include <netinet6/ip6protosw.h>
98 
99 #include <crypto/idgen.h>
100 
101 #if NPF > 0
102 #include <net/pfvar.h>
103 #endif
104 
105 #ifdef IPSEC
106 #include <netinet/ip_ipsp.h>
107 #include <netinet/ip_ah.h>
108 #include <netinet/ip_esp.h>
109 
110 #ifdef ENCDEBUG
111 #define DPRINTF(fmt, args...)						\
112 	do {								\
113 		if (encdebug)						\
114 			printf("%s: " fmt "\n", __func__, ## args);	\
115 	} while (0)
116 #else
117 #define DPRINTF(fmt, args...)						\
118 	do { } while (0)
119 #endif
120 #endif /* IPSEC */
121 
122 struct ip6_exthdrs {
123 	struct mbuf *ip6e_ip6;
124 	struct mbuf *ip6e_hbh;
125 	struct mbuf *ip6e_dest1;
126 	struct mbuf *ip6e_rthdr;
127 	struct mbuf *ip6e_dest2;
128 };
129 
130 int ip6_pcbopt(int, u_char *, int, struct ip6_pktopts **, int, int);
131 int ip6_getpcbopt(struct ip6_pktopts *, int, struct mbuf *);
132 int ip6_setpktopt(int, u_char *, int, struct ip6_pktopts *, int, int, int);
133 int ip6_setmoptions(int, struct ip6_moptions **, struct mbuf *, unsigned int);
134 int ip6_getmoptions(int, struct ip6_moptions *, struct mbuf *);
135 int ip6_copyexthdr(struct mbuf **, caddr_t, int);
136 int ip6_insertfraghdr(struct mbuf *, struct mbuf *, int,
137 	struct ip6_frag **);
138 int ip6_insert_jumboopt(struct ip6_exthdrs *, u_int32_t);
139 int ip6_splithdr(struct mbuf *, struct ip6_exthdrs *);
140 int ip6_getpmtu(struct rtentry *, struct ifnet *, u_long *);
141 int copypktopts(struct ip6_pktopts *, struct ip6_pktopts *);
142 static __inline u_int16_t __attribute__((__unused__))
143     in6_cksum_phdr(const struct in6_addr *, const struct in6_addr *,
144     u_int32_t, u_int32_t);
145 void in6_delayed_cksum(struct mbuf *, u_int8_t);
146 
147 /* Context for non-repeating IDs */
148 struct idgen32_ctx ip6_id_ctx;
149 
150 /*
151  * IP6 output. The packet in mbuf chain m contains a skeletal IP6
152  * header (with pri, len, nxt, hlim, src, dst).
153  * This function may modify ver and hlim only.
154  * The mbuf chain containing the packet will be freed.
155  * The mbuf opt, if present, will not be freed.
156  *
157  * type of "mtu": rt_mtu is u_long, ifnet.ifr_mtu is int, and
158  * nd_ifinfo.linkmtu is u_int32_t.  so we use u_long to hold largest one,
159  * which is rt_mtu.
160  */
161 int
162 ip6_output(struct mbuf *m, struct ip6_pktopts *opt, struct route_in6 *ro,
163     int flags, struct ip6_moptions *im6o, struct inpcb *inp)
164 {
165 	struct ip6_hdr *ip6;
166 	struct ifnet *ifp = NULL;
167 	struct mbuf_list fml;
168 	int hlen, tlen;
169 	struct route_in6 ip6route;
170 	struct rtentry *rt = NULL;
171 	struct sockaddr_in6 *dst, dstsock;
172 	int error = 0;
173 	u_long mtu;
174 	int dontfrag;
175 	u_int16_t src_scope, dst_scope;
176 	u_int32_t optlen = 0, plen = 0, unfragpartlen = 0;
177 	struct ip6_exthdrs exthdrs;
178 	struct in6_addr finaldst;
179 	struct route_in6 *ro_pmtu = NULL;
180 	int hdrsplit = 0;
181 	u_int8_t sproto = 0;
182 	u_char nextproto;
183 #ifdef IPSEC
184 	struct tdb *tdb = NULL;
185 #endif /* IPSEC */
186 
187 #ifdef IPSEC
188 	if (inp && (inp->inp_flags & INP_IPV6) == 0)
189 		panic("%s: IPv4 pcb is passed", __func__);
190 #endif /* IPSEC */
191 
192 	ip6 = mtod(m, struct ip6_hdr *);
193 	finaldst = ip6->ip6_dst;
194 
195 #define MAKE_EXTHDR(hp, mp)						\
196     do {								\
197 	if (hp) {							\
198 		struct ip6_ext *eh = (struct ip6_ext *)(hp);		\
199 		error = ip6_copyexthdr((mp), (caddr_t)(hp),		\
200 		    ((eh)->ip6e_len + 1) << 3);				\
201 		if (error)						\
202 			goto freehdrs;					\
203 	}								\
204     } while (0)
205 
206 	bzero(&exthdrs, sizeof(exthdrs));
207 
208 	if (opt) {
209 		/* Hop-by-Hop options header */
210 		MAKE_EXTHDR(opt->ip6po_hbh, &exthdrs.ip6e_hbh);
211 		/* Destination options header(1st part) */
212 		MAKE_EXTHDR(opt->ip6po_dest1, &exthdrs.ip6e_dest1);
213 		/* Routing header */
214 		MAKE_EXTHDR(opt->ip6po_rthdr, &exthdrs.ip6e_rthdr);
215 		/* Destination options header(2nd part) */
216 		MAKE_EXTHDR(opt->ip6po_dest2, &exthdrs.ip6e_dest2);
217 	}
218 
219 #ifdef IPSEC
220 	if (ipsec_in_use || inp) {
221 		tdb = ip6_output_ipsec_lookup(m, &error, inp);
222 		if (error != 0) {
223 			/*
224 			 * -EINVAL is used to indicate that the packet should
225 			 * be silently dropped, typically because we've asked
226 			 * key management for an SA.
227 			 */
228 			if (error == -EINVAL) /* Should silently drop packet */
229 				error = 0;
230 
231 			goto freehdrs;
232 		}
233 	}
234 #endif /* IPSEC */
235 
236 	/*
237 	 * Calculate the total length of the extension header chain.
238 	 * Keep the length of the unfragmentable part for fragmentation.
239 	 */
240 	optlen = 0;
241 	if (exthdrs.ip6e_hbh) optlen += exthdrs.ip6e_hbh->m_len;
242 	if (exthdrs.ip6e_dest1) optlen += exthdrs.ip6e_dest1->m_len;
243 	if (exthdrs.ip6e_rthdr) optlen += exthdrs.ip6e_rthdr->m_len;
244 	unfragpartlen = optlen + sizeof(struct ip6_hdr);
245 	/* NOTE: we don't add AH/ESP length here. do that later. */
246 	if (exthdrs.ip6e_dest2) optlen += exthdrs.ip6e_dest2->m_len;
247 
248 	/*
249 	 * If we need IPsec, or there is at least one extension header,
250 	 * separate IP6 header from the payload.
251 	 */
252 	if ((sproto || optlen) && !hdrsplit) {
253 		if ((error = ip6_splithdr(m, &exthdrs)) != 0) {
254 			m = NULL;
255 			goto freehdrs;
256 		}
257 		m = exthdrs.ip6e_ip6;
258 		hdrsplit++;
259 	}
260 
261 	/* adjust pointer */
262 	ip6 = mtod(m, struct ip6_hdr *);
263 
264 	/* adjust mbuf packet header length */
265 	m->m_pkthdr.len += optlen;
266 	plen = m->m_pkthdr.len - sizeof(*ip6);
267 
268 	/* If this is a jumbo payload, insert a jumbo payload option. */
269 	if (plen > IPV6_MAXPACKET) {
270 		if (!hdrsplit) {
271 			if ((error = ip6_splithdr(m, &exthdrs)) != 0) {
272 				m = NULL;
273 				goto freehdrs;
274 			}
275 			m = exthdrs.ip6e_ip6;
276 			hdrsplit++;
277 		}
278 		/* adjust pointer */
279 		ip6 = mtod(m, struct ip6_hdr *);
280 		if ((error = ip6_insert_jumboopt(&exthdrs, plen)) != 0)
281 			goto freehdrs;
282 		ip6->ip6_plen = 0;
283 	} else
284 		ip6->ip6_plen = htons(plen);
285 
286 	/*
287 	 * Concatenate headers and fill in next header fields.
288 	 * Here we have, on "m"
289 	 *	IPv6 payload
290 	 * and we insert headers accordingly.  Finally, we should be getting:
291 	 *	IPv6 hbh dest1 rthdr ah* [esp* dest2 payload]
292 	 *
293 	 * during the header composing process, "m" points to IPv6 header.
294 	 * "mprev" points to an extension header prior to esp.
295 	 */
296 	{
297 		u_char *nexthdrp = &ip6->ip6_nxt;
298 		struct mbuf *mprev = m;
299 
300 		/*
301 		 * we treat dest2 specially.  this makes IPsec processing
302 		 * much easier.  the goal here is to make mprev point the
303 		 * mbuf prior to dest2.
304 		 *
305 		 * result: IPv6 dest2 payload
306 		 * m and mprev will point to IPv6 header.
307 		 */
308 		if (exthdrs.ip6e_dest2) {
309 			if (!hdrsplit)
310 				panic("%s: assumption failed: hdr not split",
311 				    __func__);
312 			exthdrs.ip6e_dest2->m_next = m->m_next;
313 			m->m_next = exthdrs.ip6e_dest2;
314 			*mtod(exthdrs.ip6e_dest2, u_char *) = ip6->ip6_nxt;
315 			ip6->ip6_nxt = IPPROTO_DSTOPTS;
316 		}
317 
318 #define MAKE_CHAIN(m, mp, p, i)\
319     do {\
320 	if (m) {\
321 		if (!hdrsplit) \
322 			panic("assumption failed: hdr not split"); \
323 		*mtod((m), u_char *) = *(p);\
324 		*(p) = (i);\
325 		p = mtod((m), u_char *);\
326 		(m)->m_next = (mp)->m_next;\
327 		(mp)->m_next = (m);\
328 		(mp) = (m);\
329 	}\
330     } while (0)
331 		/*
332 		 * result: IPv6 hbh dest1 rthdr dest2 payload
333 		 * m will point to IPv6 header.  mprev will point to the
334 		 * extension header prior to dest2 (rthdr in the above case).
335 		 */
336 		MAKE_CHAIN(exthdrs.ip6e_hbh, mprev, nexthdrp, IPPROTO_HOPOPTS);
337 		MAKE_CHAIN(exthdrs.ip6e_dest1, mprev, nexthdrp,
338 		    IPPROTO_DSTOPTS);
339 		MAKE_CHAIN(exthdrs.ip6e_rthdr, mprev, nexthdrp,
340 		    IPPROTO_ROUTING);
341 	}
342 
343 	/*
344 	 * If there is a routing header, replace the destination address field
345 	 * with the first hop of the routing header.
346 	 */
347 	if (exthdrs.ip6e_rthdr) {
348 		struct ip6_rthdr *rh;
349 		struct ip6_rthdr0 *rh0;
350 		struct in6_addr *addr;
351 
352 		rh = (struct ip6_rthdr *)(mtod(exthdrs.ip6e_rthdr,
353 		    struct ip6_rthdr *));
354 		switch (rh->ip6r_type) {
355 		case IPV6_RTHDR_TYPE_0:
356 			rh0 = (struct ip6_rthdr0 *)rh;
357 			addr = (struct in6_addr *)(rh0 + 1);
358 			ip6->ip6_dst = addr[0];
359 			bcopy(&addr[1], &addr[0],
360 			    sizeof(struct in6_addr) * (rh0->ip6r0_segleft - 1));
361 			addr[rh0->ip6r0_segleft - 1] = finaldst;
362 			break;
363 		default:	/* is it possible? */
364 			error = EINVAL;
365 			goto bad;
366 		}
367 	}
368 
369 	/* Source address validation */
370 	if (!(flags & IPV6_UNSPECSRC) &&
371 	    IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
372 		/*
373 		 * XXX: we can probably assume validation in the caller, but
374 		 * we explicitly check the address here for safety.
375 		 */
376 		error = EOPNOTSUPP;
377 		ip6stat_inc(ip6s_badscope);
378 		goto bad;
379 	}
380 	if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_src)) {
381 		error = EOPNOTSUPP;
382 		ip6stat_inc(ip6s_badscope);
383 		goto bad;
384 	}
385 
386 	ip6stat_inc(ip6s_localout);
387 
388 	/*
389 	 * Route packet.
390 	 */
391 #if NPF > 0
392 reroute:
393 #endif
394 
395 	/* initialize cached route */
396 	if (ro == NULL) {
397 		ro = &ip6route;
398 		bzero((caddr_t)ro, sizeof(*ro));
399 	}
400 	ro_pmtu = ro;
401 	if (opt && opt->ip6po_rthdr)
402 		ro = &opt->ip6po_route;
403 	dst = &ro->ro_dst;
404 
405 	/*
406 	 * if specified, try to fill in the traffic class field.
407 	 * do not override if a non-zero value is already set.
408 	 * we check the diffserv field and the ecn field separately.
409 	 */
410 	if (opt && opt->ip6po_tclass >= 0) {
411 		int mask = 0;
412 
413 		if ((ip6->ip6_flow & htonl(0xfc << 20)) == 0)
414 			mask |= 0xfc;
415 		if ((ip6->ip6_flow & htonl(0x03 << 20)) == 0)
416 			mask |= 0x03;
417 		if (mask != 0)
418 			ip6->ip6_flow |=
419 			    htonl((opt->ip6po_tclass & mask) << 20);
420 	}
421 
422 	/* fill in or override the hop limit field, if necessary. */
423 	if (opt && opt->ip6po_hlim != -1)
424 		ip6->ip6_hlim = opt->ip6po_hlim & 0xff;
425 	else if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
426 		if (im6o != NULL)
427 			ip6->ip6_hlim = im6o->im6o_hlim;
428 		else
429 			ip6->ip6_hlim = ip6_defmcasthlim;
430 	}
431 
432 #ifdef IPSEC
433 	if (tdb) {
434 		/*
435 		 * XXX what should we do if ip6_hlim == 0 and the
436 		 * packet gets tunneled?
437 		 */
438 		/*
439 		 * if we are source-routing, do not attempt to tunnel the
440 		 * packet just because ip6_dst is different from what tdb has.
441 		 * XXX
442 		 */
443 		error = ip6_output_ipsec_send(tdb, m, ro,
444 		    exthdrs.ip6e_rthdr ? 1 : 0, 0);
445 		goto done;
446 	}
447 #endif /* IPSEC */
448 
449 	bzero(&dstsock, sizeof(dstsock));
450 	dstsock.sin6_family = AF_INET6;
451 	dstsock.sin6_addr = ip6->ip6_dst;
452 	dstsock.sin6_len = sizeof(dstsock);
453 	ro->ro_tableid = m->m_pkthdr.ph_rtableid;
454 
455 	if (IN6_IS_ADDR_MULTICAST(&dstsock.sin6_addr)) {
456 		struct in6_pktinfo *pi = NULL;
457 
458 		/*
459 		 * If the caller specify the outgoing interface
460 		 * explicitly, use it.
461 		 */
462 		if (opt != NULL && (pi = opt->ip6po_pktinfo) != NULL)
463 			ifp = if_get(pi->ipi6_ifindex);
464 
465 		if (ifp == NULL && im6o != NULL)
466 			ifp = if_get(im6o->im6o_ifidx);
467 	}
468 
469 	if (ifp == NULL) {
470 		rt = in6_selectroute(&dstsock, opt, ro, ro->ro_tableid);
471 		if (rt == NULL) {
472 			ip6stat_inc(ip6s_noroute);
473 			error = EHOSTUNREACH;
474 			goto bad;
475 		}
476 		if (ISSET(rt->rt_flags, RTF_LOCAL))
477 			ifp = if_get(rtable_loindex(m->m_pkthdr.ph_rtableid));
478 		else
479 			ifp = if_get(rt->rt_ifidx);
480 		/*
481 		 * We aren't using rtisvalid() here because the UP/DOWN state
482 		 * machine is broken with some Ethernet drivers like em(4).
483 		 * As a result we might try to use an invalid cached route
484 		 * entry while an interface is being detached.
485 		 */
486 		if (ifp == NULL) {
487 			ip6stat_inc(ip6s_noroute);
488 			error = EHOSTUNREACH;
489 			goto bad;
490 		}
491 	} else {
492 		*dst = dstsock;
493 	}
494 
495 	if (rt && (rt->rt_flags & RTF_GATEWAY) &&
496 	    !IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst))
497 		dst = satosin6(rt->rt_gateway);
498 
499 	if (!IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
500 		/* Unicast */
501 
502 		m->m_flags &= ~(M_BCAST | M_MCAST);	/* just in case */
503 	} else {
504 		/* Multicast */
505 
506 		m->m_flags = (m->m_flags & ~M_BCAST) | M_MCAST;
507 
508 		/*
509 		 * Confirm that the outgoing interface supports multicast.
510 		 */
511 		if ((ifp->if_flags & IFF_MULTICAST) == 0) {
512 			ip6stat_inc(ip6s_noroute);
513 			error = ENETUNREACH;
514 			goto bad;
515 		}
516 
517 		if ((im6o == NULL || im6o->im6o_loop) &&
518 		    in6_hasmulti(&ip6->ip6_dst, ifp)) {
519 			/*
520 			 * If we belong to the destination multicast group
521 			 * on the outgoing interface, and the caller did not
522 			 * forbid loopback, loop back a copy.
523 			 * Can't defer TCP/UDP checksumming, do the
524 			 * computation now.
525 			 */
526 			in6_proto_cksum_out(m, NULL);
527 			ip6_mloopback(ifp, m, dst);
528 		}
529 #ifdef MROUTING
530 		else {
531 			/*
532 			 * If we are acting as a multicast router, perform
533 			 * multicast forwarding as if the packet had just
534 			 * arrived on the interface to which we are about
535 			 * to send.  The multicast forwarding function
536 			 * recursively calls this function, using the
537 			 * IPV6_FORWARDING flag to prevent infinite recursion.
538 			 *
539 			 * Multicasts that are looped back by ip6_mloopback(),
540 			 * above, will be forwarded by the ip6_input() routine,
541 			 * if necessary.
542 			 */
543 			if (ip6_mforwarding && ip6_mrouter[ifp->if_rdomain] &&
544 			    (flags & IPV6_FORWARDING) == 0) {
545 				if (ip6_mforward(ip6, ifp, m) != 0) {
546 					m_freem(m);
547 					goto done;
548 				}
549 			}
550 		}
551 #endif
552 		/*
553 		 * Multicasts with a hoplimit of zero may be looped back,
554 		 * above, but must not be transmitted on a network.
555 		 * Also, multicasts addressed to the loopback interface
556 		 * are not sent -- the above call to ip6_mloopback() will
557 		 * loop back a copy if this host actually belongs to the
558 		 * destination group on the loopback interface.
559 		 */
560 		if (ip6->ip6_hlim == 0 || (ifp->if_flags & IFF_LOOPBACK) ||
561 		    IN6_IS_ADDR_MC_INTFACELOCAL(&ip6->ip6_dst)) {
562 			m_freem(m);
563 			goto done;
564 		}
565 	}
566 
567 	/*
568 	 * If this packet is going through a loopback interface we won't
569 	 * be able to restore its scope ID using the interface index.
570 	 */
571 	if (IN6_IS_SCOPE_EMBED(&ip6->ip6_src)) {
572 		if (ifp->if_flags & IFF_LOOPBACK)
573 			src_scope = ip6->ip6_src.s6_addr16[1];
574 		ip6->ip6_src.s6_addr16[1] = 0;
575 	}
576 	if (IN6_IS_SCOPE_EMBED(&ip6->ip6_dst)) {
577 		if (ifp->if_flags & IFF_LOOPBACK)
578 			dst_scope = ip6->ip6_dst.s6_addr16[1];
579 		ip6->ip6_dst.s6_addr16[1] = 0;
580 	}
581 
582 	/* Determine path MTU. */
583 	if ((error = ip6_getpmtu(ro_pmtu->ro_rt, ifp, &mtu)) != 0)
584 		goto bad;
585 
586 	/*
587 	 * The caller of this function may specify to use the minimum MTU
588 	 * in some cases.
589 	 * An advanced API option (IPV6_USE_MIN_MTU) can also override MTU
590 	 * setting.  The logic is a bit complicated; by default, unicast
591 	 * packets will follow path MTU while multicast packets will be sent at
592 	 * the minimum MTU.  If IP6PO_MINMTU_ALL is specified, all packets
593 	 * including unicast ones will be sent at the minimum MTU.  Multicast
594 	 * packets will always be sent at the minimum MTU unless
595 	 * IP6PO_MINMTU_DISABLE is explicitly specified.
596 	 * See RFC 3542 for more details.
597 	 */
598 	if (mtu > IPV6_MMTU) {
599 		if ((flags & IPV6_MINMTU))
600 			mtu = IPV6_MMTU;
601 		else if (opt && opt->ip6po_minmtu == IP6PO_MINMTU_ALL)
602 			mtu = IPV6_MMTU;
603 		else if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) && (opt == NULL ||
604 		    opt->ip6po_minmtu != IP6PO_MINMTU_DISABLE)) {
605 			mtu = IPV6_MMTU;
606 		}
607 	}
608 
609 	/*
610 	 * If the outgoing packet contains a hop-by-hop options header,
611 	 * it must be examined and processed even by the source node.
612 	 * (RFC 2460, section 4.)
613 	 */
614 	if (exthdrs.ip6e_hbh) {
615 		struct ip6_hbh *hbh = mtod(exthdrs.ip6e_hbh, struct ip6_hbh *);
616 		u_int32_t rtalert; /* returned value is ignored */
617 		u_int32_t plen = 0; /* no more than 1 jumbo payload option! */
618 
619 		m->m_pkthdr.ph_ifidx = ifp->if_index;
620 		if (ip6_process_hopopts(m, (u_int8_t *)(hbh + 1),
621 		    ((hbh->ip6h_len + 1) << 3) - sizeof(struct ip6_hbh),
622 		    &rtalert, &plen) < 0) {
623 			/* m was already freed at this point */
624 			error = EINVAL;/* better error? */
625 			goto done;
626 		}
627 		m->m_pkthdr.ph_ifidx = 0;
628 	}
629 
630 #if NPF > 0
631 	if (pf_test(AF_INET6, PF_OUT, ifp, &m) != PF_PASS) {
632 		error = EACCES;
633 		m_freem(m);
634 		goto done;
635 	}
636 	if (m == NULL)
637 		goto done;
638 	ip6 = mtod(m, struct ip6_hdr *);
639 	if ((m->m_pkthdr.pf.flags & (PF_TAG_REROUTE | PF_TAG_GENERATED)) ==
640 	    (PF_TAG_REROUTE | PF_TAG_GENERATED)) {
641 		/* already rerun the route lookup, go on */
642 		m->m_pkthdr.pf.flags &= ~(PF_TAG_GENERATED | PF_TAG_REROUTE);
643 	} else if (m->m_pkthdr.pf.flags & PF_TAG_REROUTE) {
644 		/* tag as generated to skip over pf_test on rerun */
645 		m->m_pkthdr.pf.flags |= PF_TAG_GENERATED;
646 		finaldst = ip6->ip6_dst;
647 		ro = NULL;
648 		if_put(ifp); /* drop reference since destination changed */
649 		ifp = NULL;
650 		goto reroute;
651 	}
652 #endif
653 
654 	/*
655 	 * If the packet is not going on the wire it can be destinated
656 	 * to any local address.  In this case do not clear its scopes
657 	 * to let ip6_input() find a matching local route.
658 	 */
659 	if (ifp->if_flags & IFF_LOOPBACK) {
660 		if (IN6_IS_SCOPE_EMBED(&ip6->ip6_src))
661 			ip6->ip6_src.s6_addr16[1] = src_scope;
662 		if (IN6_IS_SCOPE_EMBED(&ip6->ip6_dst))
663 			ip6->ip6_dst.s6_addr16[1] = dst_scope;
664 	}
665 
666 	in6_proto_cksum_out(m, ifp);
667 
668 	/*
669 	 * Send the packet to the outgoing interface.
670 	 * If necessary, do IPv6 fragmentation before sending.
671 	 *
672 	 * the logic here is rather complex:
673 	 * 1: normal case (dontfrag == 0)
674 	 * 1-a: send as is if tlen <= path mtu
675 	 * 1-b: fragment if tlen > path mtu
676 	 *
677 	 * 2: if user asks us not to fragment (dontfrag == 1)
678 	 * 2-a: send as is if tlen <= interface mtu
679 	 * 2-b: error if tlen > interface mtu
680 	 */
681 	tlen = m->m_pkthdr.len;
682 
683 	if (ISSET(m->m_pkthdr.csum_flags, M_IPV6_DF_OUT)) {
684 		CLR(m->m_pkthdr.csum_flags, M_IPV6_DF_OUT);
685 		dontfrag = 1;
686 	} else if (opt && ISSET(opt->ip6po_flags, IP6PO_DONTFRAG))
687 		dontfrag = 1;
688 	else
689 		dontfrag = 0;
690 	if (dontfrag && tlen > ifp->if_mtu) {	/* case 2-b */
691 #ifdef IPSEC
692 		if (ip_mtudisc)
693 			ipsec_adjust_mtu(m, mtu);
694 #endif
695 		error = EMSGSIZE;
696 		goto bad;
697 	}
698 
699 	/*
700 	 * transmit packet without fragmentation
701 	 */
702 	if (dontfrag || (tlen <= mtu)) {	/* case 1-a and 2-a */
703 		error = ifp->if_output(ifp, m, sin6tosa(dst), ro->ro_rt);
704 		goto done;
705 	}
706 
707 	/*
708 	 * try to fragment the packet.  case 1-b
709 	 */
710 	if (mtu < IPV6_MMTU) {
711 		/* path MTU cannot be less than IPV6_MMTU */
712 		error = EMSGSIZE;
713 		goto bad;
714 	} else if (ip6->ip6_plen == 0) {
715 		/* jumbo payload cannot be fragmented */
716 		error = EMSGSIZE;
717 		goto bad;
718 	}
719 
720 	/*
721 	 * Too large for the destination or interface;
722 	 * fragment if possible.
723 	 * Must be able to put at least 8 bytes per fragment.
724 	 */
725 	hlen = unfragpartlen;
726 	if (mtu > IPV6_MAXPACKET)
727 		mtu = IPV6_MAXPACKET;
728 
729 	/*
730 	 * Change the next header field of the last header in the
731 	 * unfragmentable part.
732 	 */
733 	if (exthdrs.ip6e_rthdr) {
734 		nextproto = *mtod(exthdrs.ip6e_rthdr, u_char *);
735 		*mtod(exthdrs.ip6e_rthdr, u_char *) = IPPROTO_FRAGMENT;
736 	} else if (exthdrs.ip6e_dest1) {
737 		nextproto = *mtod(exthdrs.ip6e_dest1, u_char *);
738 		*mtod(exthdrs.ip6e_dest1, u_char *) = IPPROTO_FRAGMENT;
739 	} else if (exthdrs.ip6e_hbh) {
740 		nextproto = *mtod(exthdrs.ip6e_hbh, u_char *);
741 		*mtod(exthdrs.ip6e_hbh, u_char *) = IPPROTO_FRAGMENT;
742 	} else {
743 		nextproto = ip6->ip6_nxt;
744 		ip6->ip6_nxt = IPPROTO_FRAGMENT;
745 	}
746 
747 	error = ip6_fragment(m, &fml, hlen, nextproto, mtu);
748 	if (error)
749 		goto done;
750 
751 	while ((m = ml_dequeue(&fml)) != NULL) {
752 		error = ifp->if_output(ifp, m, sin6tosa(dst), ro->ro_rt);
753 		if (error)
754 			break;
755 	}
756 	if (error)
757 		ml_purge(&fml);
758 	else
759 		ip6stat_inc(ip6s_fragmented);
760 
761 done:
762 	if_put(ifp);
763 	if (ro == &ip6route && ro->ro_rt) {
764 		rtfree(ro->ro_rt);
765 	} else if (ro_pmtu == &ip6route && ro_pmtu->ro_rt) {
766 		rtfree(ro_pmtu->ro_rt);
767 	}
768 	return (error);
769 
770 freehdrs:
771 	m_freem(exthdrs.ip6e_hbh);	/* m_freem will check if mbuf is 0 */
772 	m_freem(exthdrs.ip6e_dest1);
773 	m_freem(exthdrs.ip6e_rthdr);
774 	m_freem(exthdrs.ip6e_dest2);
775 	/* FALLTHROUGH */
776 bad:
777 	m_freem(m);
778 	goto done;
779 }
780 
781 int
782 ip6_fragment(struct mbuf *m0, struct mbuf_list *fml, int hlen,
783     u_char nextproto, u_long mtu)
784 {
785 	struct mbuf	*m, *m_frgpart;
786 	struct ip6_hdr	*mhip6;
787 	struct ip6_frag	*ip6f;
788 	u_int32_t	 id;
789 	int		 tlen, len, off;
790 	int		 error;
791 
792 	ml_init(fml);
793 
794 	tlen = m0->m_pkthdr.len;
795 	len = (mtu - hlen - sizeof(struct ip6_frag)) & ~7;
796 	if (len < 8) {
797 		error = EMSGSIZE;
798 		goto bad;
799 	}
800 
801 	id = htonl(ip6_randomid());
802 
803 	/*
804 	 * Loop through length of segment after first fragment,
805 	 * make new header and copy data of each part and link onto chain.
806 	 */
807 	for (off = hlen; off < tlen; off += len) {
808 		struct mbuf *mlast;
809 
810 		MGETHDR(m, M_DONTWAIT, MT_HEADER);
811 		if (m == NULL) {
812 			error = ENOBUFS;
813 			goto bad;
814 		}
815 		ml_enqueue(fml, m);
816 		if ((error = m_dup_pkthdr(m, m0, M_DONTWAIT)) != 0)
817 			goto bad;
818 		m->m_data += max_linkhdr;
819 		mhip6 = mtod(m, struct ip6_hdr *);
820 		*mhip6 = *mtod(m0, struct ip6_hdr *);
821 		m->m_len = sizeof(*mhip6);
822 		if ((error = ip6_insertfraghdr(m0, m, hlen, &ip6f)) != 0)
823 			goto bad;
824 		ip6f->ip6f_offlg = htons((u_int16_t)((off - hlen) & ~7));
825 		if (off + len >= tlen)
826 			len = tlen - off;
827 		else
828 			ip6f->ip6f_offlg |= IP6F_MORE_FRAG;
829 		mhip6->ip6_plen = htons((u_int16_t)(len + hlen +
830 		    sizeof(*ip6f) - sizeof(struct ip6_hdr)));
831 		if ((m_frgpart = m_copym(m0, off, len, M_DONTWAIT)) == NULL) {
832 			error = ENOBUFS;
833 			goto bad;
834 		}
835 		for (mlast = m; mlast->m_next; mlast = mlast->m_next)
836 			;
837 		mlast->m_next = m_frgpart;
838 		m->m_pkthdr.len = len + hlen + sizeof(*ip6f);
839 		ip6f->ip6f_reserved = 0;
840 		ip6f->ip6f_ident = id;
841 		ip6f->ip6f_nxt = nextproto;
842 	}
843 
844 	ip6stat_add(ip6s_ofragments, ml_len(fml));
845 	m_freem(m0);
846 	return (0);
847 
848 bad:
849 	ip6stat_inc(ip6s_odropped);
850 	ml_purge(fml);
851 	m_freem(m0);
852 	return (error);
853 }
854 
855 int
856 ip6_copyexthdr(struct mbuf **mp, caddr_t hdr, int hlen)
857 {
858 	struct mbuf *m;
859 
860 	if (hlen > MCLBYTES)
861 		return (ENOBUFS); /* XXX */
862 
863 	MGET(m, M_DONTWAIT, MT_DATA);
864 	if (!m)
865 		return (ENOBUFS);
866 
867 	if (hlen > MLEN) {
868 		MCLGET(m, M_DONTWAIT);
869 		if ((m->m_flags & M_EXT) == 0) {
870 			m_free(m);
871 			return (ENOBUFS);
872 		}
873 	}
874 	m->m_len = hlen;
875 	if (hdr)
876 		memcpy(mtod(m, caddr_t), hdr, hlen);
877 
878 	*mp = m;
879 	return (0);
880 }
881 
882 /*
883  * Insert jumbo payload option.
884  */
885 int
886 ip6_insert_jumboopt(struct ip6_exthdrs *exthdrs, u_int32_t plen)
887 {
888 	struct mbuf *mopt;
889 	u_int8_t *optbuf;
890 	u_int32_t v;
891 
892 #define JUMBOOPTLEN	8	/* length of jumbo payload option and padding */
893 
894 	/*
895 	 * If there is no hop-by-hop options header, allocate new one.
896 	 * If there is one but it doesn't have enough space to store the
897 	 * jumbo payload option, allocate a cluster to store the whole options.
898 	 * Otherwise, use it to store the options.
899 	 */
900 	if (exthdrs->ip6e_hbh == 0) {
901 		MGET(mopt, M_DONTWAIT, MT_DATA);
902 		if (mopt == NULL)
903 			return (ENOBUFS);
904 		mopt->m_len = JUMBOOPTLEN;
905 		optbuf = mtod(mopt, u_int8_t *);
906 		optbuf[1] = 0;	/* = ((JUMBOOPTLEN) >> 3) - 1 */
907 		exthdrs->ip6e_hbh = mopt;
908 	} else {
909 		struct ip6_hbh *hbh;
910 
911 		mopt = exthdrs->ip6e_hbh;
912 		if (m_trailingspace(mopt) < JUMBOOPTLEN) {
913 			/*
914 			 * XXX assumption:
915 			 * - exthdrs->ip6e_hbh is not referenced from places
916 			 *   other than exthdrs.
917 			 * - exthdrs->ip6e_hbh is not an mbuf chain.
918 			 */
919 			int oldoptlen = mopt->m_len;
920 			struct mbuf *n;
921 
922 			/*
923 			 * XXX: give up if the whole (new) hbh header does
924 			 * not fit even in an mbuf cluster.
925 			 */
926 			if (oldoptlen + JUMBOOPTLEN > MCLBYTES)
927 				return (ENOBUFS);
928 
929 			/*
930 			 * As a consequence, we must always prepare a cluster
931 			 * at this point.
932 			 */
933 			MGET(n, M_DONTWAIT, MT_DATA);
934 			if (n) {
935 				MCLGET(n, M_DONTWAIT);
936 				if ((n->m_flags & M_EXT) == 0) {
937 					m_freem(n);
938 					n = NULL;
939 				}
940 			}
941 			if (!n)
942 				return (ENOBUFS);
943 			n->m_len = oldoptlen + JUMBOOPTLEN;
944 			memcpy(mtod(n, caddr_t), mtod(mopt, caddr_t),
945 			      oldoptlen);
946 			optbuf = mtod(n, u_int8_t *) + oldoptlen;
947 			m_freem(mopt);
948 			mopt = exthdrs->ip6e_hbh = n;
949 		} else {
950 			optbuf = mtod(mopt, u_int8_t *) + mopt->m_len;
951 			mopt->m_len += JUMBOOPTLEN;
952 		}
953 		optbuf[0] = IP6OPT_PADN;
954 		optbuf[1] = 0;
955 
956 		/*
957 		 * Adjust the header length according to the pad and
958 		 * the jumbo payload option.
959 		 */
960 		hbh = mtod(mopt, struct ip6_hbh *);
961 		hbh->ip6h_len += (JUMBOOPTLEN >> 3);
962 	}
963 
964 	/* fill in the option. */
965 	optbuf[2] = IP6OPT_JUMBO;
966 	optbuf[3] = 4;
967 	v = (u_int32_t)htonl(plen + JUMBOOPTLEN);
968 	memcpy(&optbuf[4], &v, sizeof(u_int32_t));
969 
970 	/* finally, adjust the packet header length */
971 	exthdrs->ip6e_ip6->m_pkthdr.len += JUMBOOPTLEN;
972 
973 	return (0);
974 #undef JUMBOOPTLEN
975 }
976 
977 /*
978  * Insert fragment header and copy unfragmentable header portions.
979  */
980 int
981 ip6_insertfraghdr(struct mbuf *m0, struct mbuf *m, int hlen,
982     struct ip6_frag **frghdrp)
983 {
984 	struct mbuf *n, *mlast;
985 
986 	if (hlen > sizeof(struct ip6_hdr)) {
987 		n = m_copym(m0, sizeof(struct ip6_hdr),
988 		    hlen - sizeof(struct ip6_hdr), M_DONTWAIT);
989 		if (n == NULL)
990 			return (ENOBUFS);
991 		m->m_next = n;
992 	} else
993 		n = m;
994 
995 	/* Search for the last mbuf of unfragmentable part. */
996 	for (mlast = n; mlast->m_next; mlast = mlast->m_next)
997 		;
998 
999 	if ((mlast->m_flags & M_EXT) == 0 &&
1000 	    m_trailingspace(mlast) >= sizeof(struct ip6_frag)) {
1001 		/* use the trailing space of the last mbuf for fragment hdr */
1002 		*frghdrp = (struct ip6_frag *)(mtod(mlast, caddr_t) +
1003 		    mlast->m_len);
1004 		mlast->m_len += sizeof(struct ip6_frag);
1005 		m->m_pkthdr.len += sizeof(struct ip6_frag);
1006 	} else {
1007 		/* allocate a new mbuf for the fragment header */
1008 		struct mbuf *mfrg;
1009 
1010 		MGET(mfrg, M_DONTWAIT, MT_DATA);
1011 		if (mfrg == NULL)
1012 			return (ENOBUFS);
1013 		mfrg->m_len = sizeof(struct ip6_frag);
1014 		*frghdrp = mtod(mfrg, struct ip6_frag *);
1015 		mlast->m_next = mfrg;
1016 	}
1017 
1018 	return (0);
1019 }
1020 
1021 int
1022 ip6_getpmtu(struct rtentry *rt, struct ifnet *ifp, u_long *mtup)
1023 {
1024 	u_int32_t mtu = 0;
1025 	int error = 0;
1026 
1027 	if (rt != NULL) {
1028 		mtu = rt->rt_mtu;
1029 		if (mtu == 0)
1030 			mtu = ifp->if_mtu;
1031 		else if (mtu < IPV6_MMTU) {
1032 			/* RFC8021 IPv6 Atomic Fragments Considered Harmful */
1033 			mtu = IPV6_MMTU;
1034 		} else if (mtu > ifp->if_mtu) {
1035 			/*
1036 			 * The MTU on the route is larger than the MTU on
1037 			 * the interface!  This shouldn't happen, unless the
1038 			 * MTU of the interface has been changed after the
1039 			 * interface was brought up.  Change the MTU in the
1040 			 * route to match the interface MTU (as long as the
1041 			 * field isn't locked).
1042 			 */
1043 			mtu = ifp->if_mtu;
1044 			if (!(rt->rt_locks & RTV_MTU))
1045 				rt->rt_mtu = mtu;
1046 		}
1047 	} else {
1048 		mtu = ifp->if_mtu;
1049 	}
1050 
1051 	*mtup = mtu;
1052 	return (error);
1053 }
1054 
1055 /*
1056  * IP6 socket option processing.
1057  */
1058 int
1059 ip6_ctloutput(int op, struct socket *so, int level, int optname,
1060     struct mbuf *m)
1061 {
1062 	int privileged, optdatalen, uproto;
1063 	void *optdata;
1064 	struct inpcb *inp = sotoinpcb(so);
1065 	int error, optval;
1066 	struct proc *p = curproc; /* For IPsec and rdomain */
1067 	u_int rtableid, rtid = 0;
1068 
1069 	error = optval = 0;
1070 
1071 	privileged = (inp->inp_socket->so_state & SS_PRIV);
1072 	uproto = (int)so->so_proto->pr_protocol;
1073 
1074 	if (level != IPPROTO_IPV6)
1075 		return (EINVAL);
1076 
1077 	rtableid = p->p_p->ps_rtableid;
1078 
1079 	switch (op) {
1080 	case PRCO_SETOPT:
1081 		switch (optname) {
1082 		/*
1083 		 * Use of some Hop-by-Hop options or some
1084 		 * Destination options, might require special
1085 		 * privilege.  That is, normal applications
1086 		 * (without special privilege) might be forbidden
1087 		 * from setting certain options in outgoing packets,
1088 		 * and might never see certain options in received
1089 		 * packets. [RFC 2292 Section 6]
1090 		 * KAME specific note:
1091 		 *  KAME prevents non-privileged users from sending or
1092 		 *  receiving ANY hbh/dst options in order to avoid
1093 		 *  overhead of parsing options in the kernel.
1094 		 */
1095 		case IPV6_RECVHOPOPTS:
1096 		case IPV6_RECVDSTOPTS:
1097 			if (!privileged) {
1098 				error = EPERM;
1099 				break;
1100 			}
1101 			/* FALLTHROUGH */
1102 		case IPV6_UNICAST_HOPS:
1103 		case IPV6_MINHOPCOUNT:
1104 		case IPV6_HOPLIMIT:
1105 
1106 		case IPV6_RECVPKTINFO:
1107 		case IPV6_RECVHOPLIMIT:
1108 		case IPV6_RECVRTHDR:
1109 		case IPV6_RECVPATHMTU:
1110 		case IPV6_RECVTCLASS:
1111 		case IPV6_V6ONLY:
1112 		case IPV6_AUTOFLOWLABEL:
1113 		case IPV6_RECVDSTPORT:
1114 			if (m == NULL || m->m_len != sizeof(int)) {
1115 				error = EINVAL;
1116 				break;
1117 			}
1118 			optval = *mtod(m, int *);
1119 			switch (optname) {
1120 
1121 			case IPV6_UNICAST_HOPS:
1122 				if (optval < -1 || optval >= 256)
1123 					error = EINVAL;
1124 				else {
1125 					/* -1 = kernel default */
1126 					inp->inp_hops = optval;
1127 				}
1128 				break;
1129 
1130 			case IPV6_MINHOPCOUNT:
1131 				if (optval < 0 || optval > 255)
1132 					error = EINVAL;
1133 				else
1134 					inp->inp_ip6_minhlim = optval;
1135 				break;
1136 
1137 #define OPTSET(bit) \
1138 do { \
1139 	if (optval) \
1140 		inp->inp_flags |= (bit); \
1141 	else \
1142 		inp->inp_flags &= ~(bit); \
1143 } while (/*CONSTCOND*/ 0)
1144 #define OPTBIT(bit) (inp->inp_flags & (bit) ? 1 : 0)
1145 
1146 			case IPV6_RECVPKTINFO:
1147 				OPTSET(IN6P_PKTINFO);
1148 				break;
1149 
1150 			case IPV6_HOPLIMIT:
1151 			{
1152 				struct ip6_pktopts **optp;
1153 
1154 				optp = &inp->inp_outputopts6;
1155 				error = ip6_pcbopt(IPV6_HOPLIMIT,
1156 				    (u_char *)&optval, sizeof(optval), optp,
1157 				    privileged, uproto);
1158 				break;
1159 			}
1160 
1161 			case IPV6_RECVHOPLIMIT:
1162 				OPTSET(IN6P_HOPLIMIT);
1163 				break;
1164 
1165 			case IPV6_RECVHOPOPTS:
1166 				OPTSET(IN6P_HOPOPTS);
1167 				break;
1168 
1169 			case IPV6_RECVDSTOPTS:
1170 				OPTSET(IN6P_DSTOPTS);
1171 				break;
1172 
1173 			case IPV6_RECVRTHDR:
1174 				OPTSET(IN6P_RTHDR);
1175 				break;
1176 
1177 			case IPV6_RECVPATHMTU:
1178 				/*
1179 				 * We ignore this option for TCP
1180 				 * sockets.
1181 				 * (RFC3542 leaves this case
1182 				 * unspecified.)
1183 				 */
1184 				if (uproto != IPPROTO_TCP)
1185 					OPTSET(IN6P_MTU);
1186 				break;
1187 
1188 			case IPV6_V6ONLY:
1189 				/*
1190 				 * make setsockopt(IPV6_V6ONLY)
1191 				 * available only prior to bind(2).
1192 				 * see ipng mailing list, Jun 22 2001.
1193 				 */
1194 				if (inp->inp_lport || !IN6_IS_ADDR_UNSPECIFIED(
1195 				    &inp->inp_laddr6)) {
1196 					error = EINVAL;
1197 					break;
1198 				}
1199 				/* No support for IPv4-mapped addresses. */
1200 				if (!optval)
1201 					error = EINVAL;
1202 				else
1203 					error = 0;
1204 				break;
1205 			case IPV6_RECVTCLASS:
1206 				OPTSET(IN6P_TCLASS);
1207 				break;
1208 			case IPV6_AUTOFLOWLABEL:
1209 				OPTSET(IN6P_AUTOFLOWLABEL);
1210 				break;
1211 
1212 			case IPV6_RECVDSTPORT:
1213 				OPTSET(IN6P_RECVDSTPORT);
1214 				break;
1215 			}
1216 			break;
1217 
1218 		case IPV6_TCLASS:
1219 		case IPV6_DONTFRAG:
1220 		case IPV6_USE_MIN_MTU:
1221 			if (m == NULL || m->m_len != sizeof(optval)) {
1222 				error = EINVAL;
1223 				break;
1224 			}
1225 			optval = *mtod(m, int *);
1226 			{
1227 				struct ip6_pktopts **optp;
1228 				optp = &inp->inp_outputopts6;
1229 				error = ip6_pcbopt(optname, (u_char *)&optval,
1230 				    sizeof(optval), optp, privileged, uproto);
1231 				break;
1232 			}
1233 
1234 		case IPV6_PKTINFO:
1235 		case IPV6_HOPOPTS:
1236 		case IPV6_RTHDR:
1237 		case IPV6_DSTOPTS:
1238 		case IPV6_RTHDRDSTOPTS:
1239 		{
1240 			/* new advanced API (RFC3542) */
1241 			u_char *optbuf;
1242 			int optbuflen;
1243 			struct ip6_pktopts **optp;
1244 
1245 			if (m && m->m_next) {
1246 				error = EINVAL;	/* XXX */
1247 				break;
1248 			}
1249 			if (m) {
1250 				optbuf = mtod(m, u_char *);
1251 				optbuflen = m->m_len;
1252 			} else {
1253 				optbuf = NULL;
1254 				optbuflen = 0;
1255 			}
1256 			optp = &inp->inp_outputopts6;
1257 			error = ip6_pcbopt(optname, optbuf, optbuflen, optp,
1258 			    privileged, uproto);
1259 			break;
1260 		}
1261 #undef OPTSET
1262 
1263 		case IPV6_MULTICAST_IF:
1264 		case IPV6_MULTICAST_HOPS:
1265 		case IPV6_MULTICAST_LOOP:
1266 		case IPV6_JOIN_GROUP:
1267 		case IPV6_LEAVE_GROUP:
1268 			error =	ip6_setmoptions(optname,
1269 						&inp->inp_moptions6,
1270 						m, inp->inp_rtableid);
1271 			break;
1272 
1273 		case IPV6_PORTRANGE:
1274 			if (m == NULL || m->m_len != sizeof(int)) {
1275 				error = EINVAL;
1276 				break;
1277 			}
1278 			optval = *mtod(m, int *);
1279 
1280 			switch (optval) {
1281 			case IPV6_PORTRANGE_DEFAULT:
1282 				inp->inp_flags &= ~(IN6P_LOWPORT);
1283 				inp->inp_flags &= ~(IN6P_HIGHPORT);
1284 				break;
1285 
1286 			case IPV6_PORTRANGE_HIGH:
1287 				inp->inp_flags &= ~(IN6P_LOWPORT);
1288 				inp->inp_flags |= IN6P_HIGHPORT;
1289 				break;
1290 
1291 			case IPV6_PORTRANGE_LOW:
1292 				inp->inp_flags &= ~(IN6P_HIGHPORT);
1293 				inp->inp_flags |= IN6P_LOWPORT;
1294 				break;
1295 
1296 			default:
1297 				error = EINVAL;
1298 				break;
1299 			}
1300 			break;
1301 
1302 		case IPSEC6_OUTSA:
1303 			error = EINVAL;
1304 			break;
1305 
1306 		case IPV6_AUTH_LEVEL:
1307 		case IPV6_ESP_TRANS_LEVEL:
1308 		case IPV6_ESP_NETWORK_LEVEL:
1309 		case IPV6_IPCOMP_LEVEL:
1310 #ifndef IPSEC
1311 			error = EINVAL;
1312 #else
1313 			if (m == NULL || m->m_len != sizeof(int)) {
1314 				error = EINVAL;
1315 				break;
1316 			}
1317 			optval = *mtod(m, int *);
1318 
1319 			if (optval < IPSEC_LEVEL_BYPASS ||
1320 			    optval > IPSEC_LEVEL_UNIQUE) {
1321 				error = EINVAL;
1322 				break;
1323 			}
1324 
1325 			switch (optname) {
1326 			case IPV6_AUTH_LEVEL:
1327 				if (optval < IPSEC_AUTH_LEVEL_DEFAULT &&
1328 				    suser(p)) {
1329 					error = EACCES;
1330 					break;
1331 				}
1332 				inp->inp_seclevel[SL_AUTH] = optval;
1333 				break;
1334 
1335 			case IPV6_ESP_TRANS_LEVEL:
1336 				if (optval < IPSEC_ESP_TRANS_LEVEL_DEFAULT &&
1337 				    suser(p)) {
1338 					error = EACCES;
1339 					break;
1340 				}
1341 				inp->inp_seclevel[SL_ESP_TRANS] = optval;
1342 				break;
1343 
1344 			case IPV6_ESP_NETWORK_LEVEL:
1345 				if (optval < IPSEC_ESP_NETWORK_LEVEL_DEFAULT &&
1346 				    suser(p)) {
1347 					error = EACCES;
1348 					break;
1349 				}
1350 				inp->inp_seclevel[SL_ESP_NETWORK] = optval;
1351 				break;
1352 
1353 			case IPV6_IPCOMP_LEVEL:
1354 				if (optval < IPSEC_IPCOMP_LEVEL_DEFAULT &&
1355 				    suser(p)) {
1356 					error = EACCES;
1357 					break;
1358 				}
1359 				inp->inp_seclevel[SL_IPCOMP] = optval;
1360 				break;
1361 			}
1362 #endif
1363 			break;
1364 		case SO_RTABLE:
1365 			if (m == NULL || m->m_len < sizeof(u_int)) {
1366 				error = EINVAL;
1367 				break;
1368 			}
1369 			rtid = *mtod(m, u_int *);
1370 			if (inp->inp_rtableid == rtid)
1371 				break;
1372 			/* needs privileges to switch when already set */
1373 			if (rtableid != rtid && rtableid != 0 &&
1374 			    (error = suser(p)) != 0)
1375 				break;
1376 			/* table must exist */
1377 			if (!rtable_exists(rtid)) {
1378 				error = EINVAL;
1379 				break;
1380 			}
1381 			if (inp->inp_lport) {
1382 				error = EBUSY;
1383 				break;
1384 			}
1385 			inp->inp_rtableid = rtid;
1386 			in_pcbrehash(inp);
1387 			break;
1388 		case IPV6_PIPEX:
1389 			if (m != NULL && m->m_len == sizeof(int))
1390 				inp->inp_pipex = *mtod(m, int *);
1391 			else
1392 				error = EINVAL;
1393 			break;
1394 
1395 		default:
1396 			error = ENOPROTOOPT;
1397 			break;
1398 		}
1399 		break;
1400 
1401 	case PRCO_GETOPT:
1402 		switch (optname) {
1403 
1404 		case IPV6_RECVHOPOPTS:
1405 		case IPV6_RECVDSTOPTS:
1406 		case IPV6_UNICAST_HOPS:
1407 		case IPV6_MINHOPCOUNT:
1408 		case IPV6_RECVPKTINFO:
1409 		case IPV6_RECVHOPLIMIT:
1410 		case IPV6_RECVRTHDR:
1411 		case IPV6_RECVPATHMTU:
1412 
1413 		case IPV6_V6ONLY:
1414 		case IPV6_PORTRANGE:
1415 		case IPV6_RECVTCLASS:
1416 		case IPV6_AUTOFLOWLABEL:
1417 		case IPV6_RECVDSTPORT:
1418 			switch (optname) {
1419 
1420 			case IPV6_RECVHOPOPTS:
1421 				optval = OPTBIT(IN6P_HOPOPTS);
1422 				break;
1423 
1424 			case IPV6_RECVDSTOPTS:
1425 				optval = OPTBIT(IN6P_DSTOPTS);
1426 				break;
1427 
1428 			case IPV6_UNICAST_HOPS:
1429 				optval = inp->inp_hops;
1430 				break;
1431 
1432 			case IPV6_MINHOPCOUNT:
1433 				optval = inp->inp_ip6_minhlim;
1434 				break;
1435 
1436 			case IPV6_RECVPKTINFO:
1437 				optval = OPTBIT(IN6P_PKTINFO);
1438 				break;
1439 
1440 			case IPV6_RECVHOPLIMIT:
1441 				optval = OPTBIT(IN6P_HOPLIMIT);
1442 				break;
1443 
1444 			case IPV6_RECVRTHDR:
1445 				optval = OPTBIT(IN6P_RTHDR);
1446 				break;
1447 
1448 			case IPV6_RECVPATHMTU:
1449 				optval = OPTBIT(IN6P_MTU);
1450 				break;
1451 
1452 			case IPV6_V6ONLY:
1453 				optval = 1;
1454 				break;
1455 
1456 			case IPV6_PORTRANGE:
1457 			    {
1458 				int flags;
1459 				flags = inp->inp_flags;
1460 				if (flags & IN6P_HIGHPORT)
1461 					optval = IPV6_PORTRANGE_HIGH;
1462 				else if (flags & IN6P_LOWPORT)
1463 					optval = IPV6_PORTRANGE_LOW;
1464 				else
1465 					optval = 0;
1466 				break;
1467 			    }
1468 			case IPV6_RECVTCLASS:
1469 				optval = OPTBIT(IN6P_TCLASS);
1470 				break;
1471 
1472 			case IPV6_AUTOFLOWLABEL:
1473 				optval = OPTBIT(IN6P_AUTOFLOWLABEL);
1474 				break;
1475 
1476 			case IPV6_RECVDSTPORT:
1477 				optval = OPTBIT(IN6P_RECVDSTPORT);
1478 				break;
1479 			}
1480 			if (error)
1481 				break;
1482 			m->m_len = sizeof(int);
1483 			*mtod(m, int *) = optval;
1484 			break;
1485 
1486 		case IPV6_PATHMTU:
1487 		{
1488 			u_long pmtu = 0;
1489 			struct ip6_mtuinfo mtuinfo;
1490 			struct ifnet *ifp;
1491 			struct rtentry *rt;
1492 
1493 			if (!(so->so_state & SS_ISCONNECTED))
1494 				return (ENOTCONN);
1495 
1496 			rt = in_pcbrtentry(inp);
1497 			if (!rtisvalid(rt))
1498 				return (EHOSTUNREACH);
1499 
1500 			ifp = if_get(rt->rt_ifidx);
1501 			if (ifp == NULL)
1502 				return (EHOSTUNREACH);
1503 			/*
1504 			 * XXX: we dot not consider the case of source
1505 			 * routing, or optional information to specify
1506 			 * the outgoing interface.
1507 			 */
1508 			error = ip6_getpmtu(rt, ifp, &pmtu);
1509 			if_put(ifp);
1510 			if (error)
1511 				break;
1512 			if (pmtu > IPV6_MAXPACKET)
1513 				pmtu = IPV6_MAXPACKET;
1514 
1515 			bzero(&mtuinfo, sizeof(mtuinfo));
1516 			mtuinfo.ip6m_mtu = (u_int32_t)pmtu;
1517 			optdata = (void *)&mtuinfo;
1518 			optdatalen = sizeof(mtuinfo);
1519 			if (optdatalen > MCLBYTES)
1520 				return (EMSGSIZE); /* XXX */
1521 			if (optdatalen > MLEN)
1522 				MCLGET(m, M_WAIT);
1523 			m->m_len = optdatalen;
1524 			bcopy(optdata, mtod(m, void *), optdatalen);
1525 			break;
1526 		}
1527 
1528 		case IPV6_PKTINFO:
1529 		case IPV6_HOPOPTS:
1530 		case IPV6_RTHDR:
1531 		case IPV6_DSTOPTS:
1532 		case IPV6_RTHDRDSTOPTS:
1533 		case IPV6_TCLASS:
1534 		case IPV6_DONTFRAG:
1535 		case IPV6_USE_MIN_MTU:
1536 			error = ip6_getpcbopt(inp->inp_outputopts6,
1537 			    optname, m);
1538 			break;
1539 
1540 		case IPV6_MULTICAST_IF:
1541 		case IPV6_MULTICAST_HOPS:
1542 		case IPV6_MULTICAST_LOOP:
1543 		case IPV6_JOIN_GROUP:
1544 		case IPV6_LEAVE_GROUP:
1545 			error = ip6_getmoptions(optname,
1546 			    inp->inp_moptions6, m);
1547 			break;
1548 
1549 		case IPSEC6_OUTSA:
1550 			error = EINVAL;
1551 			break;
1552 
1553 		case IPV6_AUTH_LEVEL:
1554 		case IPV6_ESP_TRANS_LEVEL:
1555 		case IPV6_ESP_NETWORK_LEVEL:
1556 		case IPV6_IPCOMP_LEVEL:
1557 #ifndef IPSEC
1558 			m->m_len = sizeof(int);
1559 			*mtod(m, int *) = IPSEC_LEVEL_NONE;
1560 #else
1561 			m->m_len = sizeof(int);
1562 			switch (optname) {
1563 			case IPV6_AUTH_LEVEL:
1564 				optval = inp->inp_seclevel[SL_AUTH];
1565 				break;
1566 
1567 			case IPV6_ESP_TRANS_LEVEL:
1568 				optval =
1569 				    inp->inp_seclevel[SL_ESP_TRANS];
1570 				break;
1571 
1572 			case IPV6_ESP_NETWORK_LEVEL:
1573 				optval =
1574 				    inp->inp_seclevel[SL_ESP_NETWORK];
1575 				break;
1576 
1577 			case IPV6_IPCOMP_LEVEL:
1578 				optval = inp->inp_seclevel[SL_IPCOMP];
1579 				break;
1580 			}
1581 			*mtod(m, int *) = optval;
1582 #endif
1583 			break;
1584 		case SO_RTABLE:
1585 			m->m_len = sizeof(u_int);
1586 			*mtod(m, u_int *) = inp->inp_rtableid;
1587 			break;
1588 		case IPV6_PIPEX:
1589 			m->m_len = sizeof(int);
1590 			*mtod(m, int *) = inp->inp_pipex;
1591 			break;
1592 
1593 		default:
1594 			error = ENOPROTOOPT;
1595 			break;
1596 		}
1597 		break;
1598 	}
1599 	return (error);
1600 }
1601 
1602 int
1603 ip6_raw_ctloutput(int op, struct socket *so, int level, int optname,
1604     struct mbuf *m)
1605 {
1606 	int error = 0, optval;
1607 	const int icmp6off = offsetof(struct icmp6_hdr, icmp6_cksum);
1608 	struct inpcb *inp = sotoinpcb(so);
1609 
1610 	if (level != IPPROTO_IPV6)
1611 		return (EINVAL);
1612 
1613 	switch (optname) {
1614 	case IPV6_CHECKSUM:
1615 		/*
1616 		 * For ICMPv6 sockets, no modification allowed for checksum
1617 		 * offset, permit "no change" values to help existing apps.
1618 		 *
1619 		 * RFC3542 says: "An attempt to set IPV6_CHECKSUM
1620 		 * for an ICMPv6 socket will fail."
1621 		 * The current behavior does not meet RFC3542.
1622 		 */
1623 		switch (op) {
1624 		case PRCO_SETOPT:
1625 			if (m == NULL || m->m_len != sizeof(int)) {
1626 				error = EINVAL;
1627 				break;
1628 			}
1629 			optval = *mtod(m, int *);
1630 			if (optval < -1 ||
1631 			    (optval > 0 && (optval % 2) != 0)) {
1632 				/*
1633 				 * The API assumes non-negative even offset
1634 				 * values or -1 as a special value.
1635 				 */
1636 				error = EINVAL;
1637 			} else if (so->so_proto->pr_protocol ==
1638 			    IPPROTO_ICMPV6) {
1639 				if (optval != icmp6off)
1640 					error = EINVAL;
1641 			} else
1642 				inp->inp_cksum6 = optval;
1643 			break;
1644 
1645 		case PRCO_GETOPT:
1646 			if (so->so_proto->pr_protocol == IPPROTO_ICMPV6)
1647 				optval = icmp6off;
1648 			else
1649 				optval = inp->inp_cksum6;
1650 
1651 			m->m_len = sizeof(int);
1652 			*mtod(m, int *) = optval;
1653 			break;
1654 
1655 		default:
1656 			error = EINVAL;
1657 			break;
1658 		}
1659 		break;
1660 
1661 	default:
1662 		error = ENOPROTOOPT;
1663 		break;
1664 	}
1665 
1666 	return (error);
1667 }
1668 
1669 /*
1670  * initialize ip6_pktopts.  beware that there are non-zero default values in
1671  * the struct.
1672  */
1673 void
1674 ip6_initpktopts(struct ip6_pktopts *opt)
1675 {
1676 	bzero(opt, sizeof(*opt));
1677 	opt->ip6po_hlim = -1;	/* -1 means default hop limit */
1678 	opt->ip6po_tclass = -1;	/* -1 means default traffic class */
1679 	opt->ip6po_minmtu = IP6PO_MINMTU_MCASTONLY;
1680 }
1681 
1682 int
1683 ip6_pcbopt(int optname, u_char *buf, int len, struct ip6_pktopts **pktopt,
1684     int priv, int uproto)
1685 {
1686 	struct ip6_pktopts *opt;
1687 
1688 	if (*pktopt == NULL) {
1689 		*pktopt = malloc(sizeof(struct ip6_pktopts), M_IP6OPT,
1690 		    M_WAITOK);
1691 		ip6_initpktopts(*pktopt);
1692 	}
1693 	opt = *pktopt;
1694 
1695 	return (ip6_setpktopt(optname, buf, len, opt, priv, 1, uproto));
1696 }
1697 
1698 int
1699 ip6_getpcbopt(struct ip6_pktopts *pktopt, int optname, struct mbuf *m)
1700 {
1701 	void *optdata = NULL;
1702 	int optdatalen = 0;
1703 	struct ip6_ext *ip6e;
1704 	int error = 0;
1705 	struct in6_pktinfo null_pktinfo;
1706 	int deftclass = 0, on;
1707 	int defminmtu = IP6PO_MINMTU_MCASTONLY;
1708 
1709 	switch (optname) {
1710 	case IPV6_PKTINFO:
1711 		if (pktopt && pktopt->ip6po_pktinfo)
1712 			optdata = (void *)pktopt->ip6po_pktinfo;
1713 		else {
1714 			/* XXX: we don't have to do this every time... */
1715 			bzero(&null_pktinfo, sizeof(null_pktinfo));
1716 			optdata = (void *)&null_pktinfo;
1717 		}
1718 		optdatalen = sizeof(struct in6_pktinfo);
1719 		break;
1720 	case IPV6_TCLASS:
1721 		if (pktopt && pktopt->ip6po_tclass >= 0)
1722 			optdata = (void *)&pktopt->ip6po_tclass;
1723 		else
1724 			optdata = (void *)&deftclass;
1725 		optdatalen = sizeof(int);
1726 		break;
1727 	case IPV6_HOPOPTS:
1728 		if (pktopt && pktopt->ip6po_hbh) {
1729 			optdata = (void *)pktopt->ip6po_hbh;
1730 			ip6e = (struct ip6_ext *)pktopt->ip6po_hbh;
1731 			optdatalen = (ip6e->ip6e_len + 1) << 3;
1732 		}
1733 		break;
1734 	case IPV6_RTHDR:
1735 		if (pktopt && pktopt->ip6po_rthdr) {
1736 			optdata = (void *)pktopt->ip6po_rthdr;
1737 			ip6e = (struct ip6_ext *)pktopt->ip6po_rthdr;
1738 			optdatalen = (ip6e->ip6e_len + 1) << 3;
1739 		}
1740 		break;
1741 	case IPV6_RTHDRDSTOPTS:
1742 		if (pktopt && pktopt->ip6po_dest1) {
1743 			optdata = (void *)pktopt->ip6po_dest1;
1744 			ip6e = (struct ip6_ext *)pktopt->ip6po_dest1;
1745 			optdatalen = (ip6e->ip6e_len + 1) << 3;
1746 		}
1747 		break;
1748 	case IPV6_DSTOPTS:
1749 		if (pktopt && pktopt->ip6po_dest2) {
1750 			optdata = (void *)pktopt->ip6po_dest2;
1751 			ip6e = (struct ip6_ext *)pktopt->ip6po_dest2;
1752 			optdatalen = (ip6e->ip6e_len + 1) << 3;
1753 		}
1754 		break;
1755 	case IPV6_USE_MIN_MTU:
1756 		if (pktopt)
1757 			optdata = (void *)&pktopt->ip6po_minmtu;
1758 		else
1759 			optdata = (void *)&defminmtu;
1760 		optdatalen = sizeof(int);
1761 		break;
1762 	case IPV6_DONTFRAG:
1763 		if (pktopt && ((pktopt->ip6po_flags) & IP6PO_DONTFRAG))
1764 			on = 1;
1765 		else
1766 			on = 0;
1767 		optdata = (void *)&on;
1768 		optdatalen = sizeof(on);
1769 		break;
1770 	default:		/* should not happen */
1771 #ifdef DIAGNOSTIC
1772 		panic("%s: unexpected option", __func__);
1773 #endif
1774 		return (ENOPROTOOPT);
1775 	}
1776 
1777 	if (optdatalen > MCLBYTES)
1778 		return (EMSGSIZE); /* XXX */
1779 	if (optdatalen > MLEN)
1780 		MCLGET(m, M_WAIT);
1781 	m->m_len = optdatalen;
1782 	if (optdatalen)
1783 		bcopy(optdata, mtod(m, void *), optdatalen);
1784 
1785 	return (error);
1786 }
1787 
1788 void
1789 ip6_clearpktopts(struct ip6_pktopts *pktopt, int optname)
1790 {
1791 	if (optname == -1 || optname == IPV6_PKTINFO) {
1792 		if (pktopt->ip6po_pktinfo)
1793 			free(pktopt->ip6po_pktinfo, M_IP6OPT, 0);
1794 		pktopt->ip6po_pktinfo = NULL;
1795 	}
1796 	if (optname == -1 || optname == IPV6_HOPLIMIT)
1797 		pktopt->ip6po_hlim = -1;
1798 	if (optname == -1 || optname == IPV6_TCLASS)
1799 		pktopt->ip6po_tclass = -1;
1800 	if (optname == -1 || optname == IPV6_HOPOPTS) {
1801 		if (pktopt->ip6po_hbh)
1802 			free(pktopt->ip6po_hbh, M_IP6OPT, 0);
1803 		pktopt->ip6po_hbh = NULL;
1804 	}
1805 	if (optname == -1 || optname == IPV6_RTHDRDSTOPTS) {
1806 		if (pktopt->ip6po_dest1)
1807 			free(pktopt->ip6po_dest1, M_IP6OPT, 0);
1808 		pktopt->ip6po_dest1 = NULL;
1809 	}
1810 	if (optname == -1 || optname == IPV6_RTHDR) {
1811 		if (pktopt->ip6po_rhinfo.ip6po_rhi_rthdr)
1812 			free(pktopt->ip6po_rhinfo.ip6po_rhi_rthdr, M_IP6OPT, 0);
1813 		pktopt->ip6po_rhinfo.ip6po_rhi_rthdr = NULL;
1814 		if (pktopt->ip6po_route.ro_rt) {
1815 			rtfree(pktopt->ip6po_route.ro_rt);
1816 			pktopt->ip6po_route.ro_rt = NULL;
1817 		}
1818 	}
1819 	if (optname == -1 || optname == IPV6_DSTOPTS) {
1820 		if (pktopt->ip6po_dest2)
1821 			free(pktopt->ip6po_dest2, M_IP6OPT, 0);
1822 		pktopt->ip6po_dest2 = NULL;
1823 	}
1824 }
1825 
1826 #define PKTOPT_EXTHDRCPY(type) \
1827 do {\
1828 	if (src->type) {\
1829 		size_t hlen;\
1830 		hlen = (((struct ip6_ext *)src->type)->ip6e_len + 1) << 3;\
1831 		dst->type = malloc(hlen, M_IP6OPT, M_NOWAIT);\
1832 		if (dst->type == NULL)\
1833 			goto bad;\
1834 		memcpy(dst->type, src->type, hlen);\
1835 	}\
1836 } while (/*CONSTCOND*/ 0)
1837 
1838 int
1839 copypktopts(struct ip6_pktopts *dst, struct ip6_pktopts *src)
1840 {
1841 	dst->ip6po_hlim = src->ip6po_hlim;
1842 	dst->ip6po_tclass = src->ip6po_tclass;
1843 	dst->ip6po_flags = src->ip6po_flags;
1844 	if (src->ip6po_pktinfo) {
1845 		dst->ip6po_pktinfo = malloc(sizeof(*dst->ip6po_pktinfo),
1846 		    M_IP6OPT, M_NOWAIT);
1847 		if (dst->ip6po_pktinfo == NULL)
1848 			goto bad;
1849 		*dst->ip6po_pktinfo = *src->ip6po_pktinfo;
1850 	}
1851 	PKTOPT_EXTHDRCPY(ip6po_hbh);
1852 	PKTOPT_EXTHDRCPY(ip6po_dest1);
1853 	PKTOPT_EXTHDRCPY(ip6po_dest2);
1854 	PKTOPT_EXTHDRCPY(ip6po_rthdr); /* not copy the cached route */
1855 	return (0);
1856 
1857   bad:
1858 	ip6_clearpktopts(dst, -1);
1859 	return (ENOBUFS);
1860 }
1861 #undef PKTOPT_EXTHDRCPY
1862 
1863 void
1864 ip6_freepcbopts(struct ip6_pktopts *pktopt)
1865 {
1866 	if (pktopt == NULL)
1867 		return;
1868 
1869 	ip6_clearpktopts(pktopt, -1);
1870 
1871 	free(pktopt, M_IP6OPT, 0);
1872 }
1873 
1874 /*
1875  * Set the IP6 multicast options in response to user setsockopt().
1876  */
1877 int
1878 ip6_setmoptions(int optname, struct ip6_moptions **im6op, struct mbuf *m,
1879     unsigned int rtableid)
1880 {
1881 	int error = 0;
1882 	u_int loop, ifindex;
1883 	struct ipv6_mreq *mreq;
1884 	struct ifnet *ifp;
1885 	struct ip6_moptions *im6o = *im6op;
1886 	struct in6_multi_mship *imm;
1887 	struct proc *p = curproc;	/* XXX */
1888 
1889 	if (im6o == NULL) {
1890 		/*
1891 		 * No multicast option buffer attached to the pcb;
1892 		 * allocate one and initialize to default values.
1893 		 */
1894 		im6o = malloc(sizeof(*im6o), M_IPMOPTS, M_WAITOK);
1895 		if (im6o == NULL)
1896 			return (ENOBUFS);
1897 		*im6op = im6o;
1898 		im6o->im6o_ifidx = 0;
1899 		im6o->im6o_hlim = ip6_defmcasthlim;
1900 		im6o->im6o_loop = IPV6_DEFAULT_MULTICAST_LOOP;
1901 		LIST_INIT(&im6o->im6o_memberships);
1902 	}
1903 
1904 	switch (optname) {
1905 
1906 	case IPV6_MULTICAST_IF:
1907 		/*
1908 		 * Select the interface for outgoing multicast packets.
1909 		 */
1910 		if (m == NULL || m->m_len != sizeof(u_int)) {
1911 			error = EINVAL;
1912 			break;
1913 		}
1914 		memcpy(&ifindex, mtod(m, u_int *), sizeof(ifindex));
1915 		if (ifindex != 0) {
1916 			ifp = if_get(ifindex);
1917 			if (ifp == NULL) {
1918 				error = ENXIO;	/* XXX EINVAL? */
1919 				break;
1920 			}
1921 			if (ifp->if_rdomain != rtable_l2(rtableid) ||
1922 			    (ifp->if_flags & IFF_MULTICAST) == 0) {
1923 				error = EADDRNOTAVAIL;
1924 				if_put(ifp);
1925 				break;
1926 			}
1927 			if_put(ifp);
1928 		}
1929 		im6o->im6o_ifidx = ifindex;
1930 		break;
1931 
1932 	case IPV6_MULTICAST_HOPS:
1933 	    {
1934 		/*
1935 		 * Set the IP6 hoplimit for outgoing multicast packets.
1936 		 */
1937 		int optval;
1938 		if (m == NULL || m->m_len != sizeof(int)) {
1939 			error = EINVAL;
1940 			break;
1941 		}
1942 		memcpy(&optval, mtod(m, u_int *), sizeof(optval));
1943 		if (optval < -1 || optval >= 256)
1944 			error = EINVAL;
1945 		else if (optval == -1)
1946 			im6o->im6o_hlim = ip6_defmcasthlim;
1947 		else
1948 			im6o->im6o_hlim = optval;
1949 		break;
1950 	    }
1951 
1952 	case IPV6_MULTICAST_LOOP:
1953 		/*
1954 		 * Set the loopback flag for outgoing multicast packets.
1955 		 * Must be zero or one.
1956 		 */
1957 		if (m == NULL || m->m_len != sizeof(u_int)) {
1958 			error = EINVAL;
1959 			break;
1960 		}
1961 		memcpy(&loop, mtod(m, u_int *), sizeof(loop));
1962 		if (loop > 1) {
1963 			error = EINVAL;
1964 			break;
1965 		}
1966 		im6o->im6o_loop = loop;
1967 		break;
1968 
1969 	case IPV6_JOIN_GROUP:
1970 		/*
1971 		 * Add a multicast group membership.
1972 		 * Group must be a valid IP6 multicast address.
1973 		 */
1974 		if (m == NULL || m->m_len != sizeof(struct ipv6_mreq)) {
1975 			error = EINVAL;
1976 			break;
1977 		}
1978 		mreq = mtod(m, struct ipv6_mreq *);
1979 		if (IN6_IS_ADDR_UNSPECIFIED(&mreq->ipv6mr_multiaddr)) {
1980 			/*
1981 			 * We use the unspecified address to specify to accept
1982 			 * all multicast addresses. Only super user is allowed
1983 			 * to do this.
1984 			 */
1985 			if (suser(p))
1986 			{
1987 				error = EACCES;
1988 				break;
1989 			}
1990 		} else if (!IN6_IS_ADDR_MULTICAST(&mreq->ipv6mr_multiaddr)) {
1991 			error = EINVAL;
1992 			break;
1993 		}
1994 
1995 		/*
1996 		 * If no interface was explicitly specified, choose an
1997 		 * appropriate one according to the given multicast address.
1998 		 */
1999 		if (mreq->ipv6mr_interface == 0) {
2000 			struct rtentry *rt;
2001 			struct sockaddr_in6 dst;
2002 
2003 			memset(&dst, 0, sizeof(dst));
2004 			dst.sin6_len = sizeof(dst);
2005 			dst.sin6_family = AF_INET6;
2006 			dst.sin6_addr = mreq->ipv6mr_multiaddr;
2007 			rt = rtalloc(sin6tosa(&dst), RT_RESOLVE, rtableid);
2008 			if (rt == NULL) {
2009 				error = EADDRNOTAVAIL;
2010 				break;
2011 			}
2012 			ifp = if_get(rt->rt_ifidx);
2013 			rtfree(rt);
2014 		} else {
2015 			/*
2016 			 * If the interface is specified, validate it.
2017 			 */
2018 			ifp = if_get(mreq->ipv6mr_interface);
2019 			if (ifp == NULL) {
2020 				error = ENXIO;	/* XXX EINVAL? */
2021 				break;
2022 			}
2023 		}
2024 
2025 		/*
2026 		 * See if we found an interface, and confirm that it
2027 		 * supports multicast
2028 		 */
2029 		if (ifp == NULL || ifp->if_rdomain != rtable_l2(rtableid) ||
2030 		    (ifp->if_flags & IFF_MULTICAST) == 0) {
2031 			if_put(ifp);
2032 			error = EADDRNOTAVAIL;
2033 			break;
2034 		}
2035 		/*
2036 		 * Put interface index into the multicast address,
2037 		 * if the address has link/interface-local scope.
2038 		 */
2039 		if (IN6_IS_SCOPE_EMBED(&mreq->ipv6mr_multiaddr)) {
2040 			mreq->ipv6mr_multiaddr.s6_addr16[1] =
2041 			    htons(ifp->if_index);
2042 		}
2043 		/*
2044 		 * See if the membership already exists.
2045 		 */
2046 		LIST_FOREACH(imm, &im6o->im6o_memberships, i6mm_chain)
2047 			if (imm->i6mm_maddr->in6m_ifidx == ifp->if_index &&
2048 			    IN6_ARE_ADDR_EQUAL(&imm->i6mm_maddr->in6m_addr,
2049 			    &mreq->ipv6mr_multiaddr))
2050 				break;
2051 		if (imm != NULL) {
2052 			if_put(ifp);
2053 			error = EADDRINUSE;
2054 			break;
2055 		}
2056 		/*
2057 		 * Everything looks good; add a new record to the multicast
2058 		 * address list for the given interface.
2059 		 */
2060 		imm = in6_joingroup(ifp, &mreq->ipv6mr_multiaddr, &error);
2061 		if_put(ifp);
2062 		if (!imm)
2063 			break;
2064 		LIST_INSERT_HEAD(&im6o->im6o_memberships, imm, i6mm_chain);
2065 		break;
2066 
2067 	case IPV6_LEAVE_GROUP:
2068 		/*
2069 		 * Drop a multicast group membership.
2070 		 * Group must be a valid IP6 multicast address.
2071 		 */
2072 		if (m == NULL || m->m_len != sizeof(struct ipv6_mreq)) {
2073 			error = EINVAL;
2074 			break;
2075 		}
2076 		mreq = mtod(m, struct ipv6_mreq *);
2077 		if (IN6_IS_ADDR_UNSPECIFIED(&mreq->ipv6mr_multiaddr)) {
2078 			if (suser(p)) {
2079 				error = EACCES;
2080 				break;
2081 			}
2082 		} else if (!IN6_IS_ADDR_MULTICAST(&mreq->ipv6mr_multiaddr)) {
2083 			error = EINVAL;
2084 			break;
2085 		}
2086 
2087 		/*
2088 		 * Put interface index into the multicast address,
2089 		 * if the address has link-local scope.
2090 		 */
2091 		if (IN6_IS_ADDR_MC_LINKLOCAL(&mreq->ipv6mr_multiaddr)) {
2092 			mreq->ipv6mr_multiaddr.s6_addr16[1] =
2093 			    htons(mreq->ipv6mr_interface);
2094 		}
2095 
2096 		/*
2097 		 * If an interface address was specified, get a pointer
2098 		 * to its ifnet structure.
2099 		 */
2100 		if (mreq->ipv6mr_interface == 0)
2101 			ifp = NULL;
2102 		else {
2103 			ifp = if_get(mreq->ipv6mr_interface);
2104 			if (ifp == NULL) {
2105 				error = ENXIO;	/* XXX EINVAL? */
2106 				break;
2107 			}
2108 		}
2109 
2110 		/*
2111 		 * Find the membership in the membership list.
2112 		 */
2113 		LIST_FOREACH(imm, &im6o->im6o_memberships, i6mm_chain) {
2114 			if ((ifp == NULL ||
2115 			    imm->i6mm_maddr->in6m_ifidx == ifp->if_index) &&
2116 			    IN6_ARE_ADDR_EQUAL(&imm->i6mm_maddr->in6m_addr,
2117 			    &mreq->ipv6mr_multiaddr))
2118 				break;
2119 		}
2120 
2121 		if_put(ifp);
2122 
2123 		if (imm == NULL) {
2124 			/* Unable to resolve interface */
2125 			error = EADDRNOTAVAIL;
2126 			break;
2127 		}
2128 		/*
2129 		 * Give up the multicast address record to which the
2130 		 * membership points.
2131 		 */
2132 		LIST_REMOVE(imm, i6mm_chain);
2133 		in6_leavegroup(imm);
2134 		break;
2135 
2136 	default:
2137 		error = EOPNOTSUPP;
2138 		break;
2139 	}
2140 
2141 	/*
2142 	 * If all options have default values, no need to keep the option
2143 	 * structure.
2144 	 */
2145 	if (im6o->im6o_ifidx == 0 &&
2146 	    im6o->im6o_hlim == ip6_defmcasthlim &&
2147 	    im6o->im6o_loop == IPV6_DEFAULT_MULTICAST_LOOP &&
2148 	    LIST_EMPTY(&im6o->im6o_memberships)) {
2149 		free(*im6op, M_IPMOPTS, sizeof(**im6op));
2150 		*im6op = NULL;
2151 	}
2152 
2153 	return (error);
2154 }
2155 
2156 /*
2157  * Return the IP6 multicast options in response to user getsockopt().
2158  */
2159 int
2160 ip6_getmoptions(int optname, struct ip6_moptions *im6o, struct mbuf *m)
2161 {
2162 	u_int *hlim, *loop, *ifindex;
2163 
2164 	switch (optname) {
2165 	case IPV6_MULTICAST_IF:
2166 		ifindex = mtod(m, u_int *);
2167 		m->m_len = sizeof(u_int);
2168 		if (im6o == NULL || im6o->im6o_ifidx == 0)
2169 			*ifindex = 0;
2170 		else
2171 			*ifindex = im6o->im6o_ifidx;
2172 		return (0);
2173 
2174 	case IPV6_MULTICAST_HOPS:
2175 		hlim = mtod(m, u_int *);
2176 		m->m_len = sizeof(u_int);
2177 		if (im6o == NULL)
2178 			*hlim = ip6_defmcasthlim;
2179 		else
2180 			*hlim = im6o->im6o_hlim;
2181 		return (0);
2182 
2183 	case IPV6_MULTICAST_LOOP:
2184 		loop = mtod(m, u_int *);
2185 		m->m_len = sizeof(u_int);
2186 		if (im6o == NULL)
2187 			*loop = ip6_defmcasthlim;
2188 		else
2189 			*loop = im6o->im6o_loop;
2190 		return (0);
2191 
2192 	default:
2193 		return (EOPNOTSUPP);
2194 	}
2195 }
2196 
2197 /*
2198  * Discard the IP6 multicast options.
2199  */
2200 void
2201 ip6_freemoptions(struct ip6_moptions *im6o)
2202 {
2203 	struct in6_multi_mship *imm;
2204 
2205 	if (im6o == NULL)
2206 		return;
2207 
2208 	while (!LIST_EMPTY(&im6o->im6o_memberships)) {
2209 		imm = LIST_FIRST(&im6o->im6o_memberships);
2210 		LIST_REMOVE(imm, i6mm_chain);
2211 		in6_leavegroup(imm);
2212 	}
2213 	free(im6o, M_IPMOPTS, sizeof(*im6o));
2214 }
2215 
2216 /*
2217  * Set IPv6 outgoing packet options based on advanced API.
2218  */
2219 int
2220 ip6_setpktopts(struct mbuf *control, struct ip6_pktopts *opt,
2221     struct ip6_pktopts *stickyopt, int priv, int uproto)
2222 {
2223 	u_int clen;
2224 	struct cmsghdr *cm = 0;
2225 	caddr_t cmsgs;
2226 	int error;
2227 
2228 	if (control == NULL || opt == NULL)
2229 		return (EINVAL);
2230 
2231 	ip6_initpktopts(opt);
2232 	if (stickyopt) {
2233 		int error;
2234 
2235 		/*
2236 		 * If stickyopt is provided, make a local copy of the options
2237 		 * for this particular packet, then override them by ancillary
2238 		 * objects.
2239 		 * XXX: copypktopts() does not copy the cached route to a next
2240 		 * hop (if any).  This is not very good in terms of efficiency,
2241 		 * but we can allow this since this option should be rarely
2242 		 * used.
2243 		 */
2244 		if ((error = copypktopts(opt, stickyopt)) != 0)
2245 			return (error);
2246 	}
2247 
2248 	/*
2249 	 * XXX: Currently, we assume all the optional information is stored
2250 	 * in a single mbuf.
2251 	 */
2252 	if (control->m_next)
2253 		return (EINVAL);
2254 
2255 	clen = control->m_len;
2256 	cmsgs = mtod(control, caddr_t);
2257 	do {
2258 		if (clen < CMSG_LEN(0))
2259 			return (EINVAL);
2260 		cm = (struct cmsghdr *)cmsgs;
2261 		if (cm->cmsg_len < CMSG_LEN(0) || cm->cmsg_len > clen ||
2262 		    CMSG_ALIGN(cm->cmsg_len) > clen)
2263 			return (EINVAL);
2264 		if (cm->cmsg_level == IPPROTO_IPV6) {
2265 			error = ip6_setpktopt(cm->cmsg_type, CMSG_DATA(cm),
2266 			    cm->cmsg_len - CMSG_LEN(0), opt, priv, 0, uproto);
2267 			if (error)
2268 				return (error);
2269 		}
2270 
2271 		clen -= CMSG_ALIGN(cm->cmsg_len);
2272 		cmsgs += CMSG_ALIGN(cm->cmsg_len);
2273 	} while (clen);
2274 
2275 	return (0);
2276 }
2277 
2278 /*
2279  * Set a particular packet option, as a sticky option or an ancillary data
2280  * item.  "len" can be 0 only when it's a sticky option.
2281  */
2282 int
2283 ip6_setpktopt(int optname, u_char *buf, int len, struct ip6_pktopts *opt,
2284     int priv, int sticky, int uproto)
2285 {
2286 	int minmtupolicy;
2287 
2288 	switch (optname) {
2289 	case IPV6_PKTINFO:
2290 	{
2291 		struct ifnet *ifp = NULL;
2292 		struct in6_pktinfo *pktinfo;
2293 
2294 		if (len != sizeof(struct in6_pktinfo))
2295 			return (EINVAL);
2296 
2297 		pktinfo = (struct in6_pktinfo *)buf;
2298 
2299 		/*
2300 		 * An application can clear any sticky IPV6_PKTINFO option by
2301 		 * doing a "regular" setsockopt with ipi6_addr being
2302 		 * in6addr_any and ipi6_ifindex being zero.
2303 		 * [RFC 3542, Section 6]
2304 		 */
2305 		if (opt->ip6po_pktinfo &&
2306 		    pktinfo->ipi6_ifindex == 0 &&
2307 		    IN6_IS_ADDR_UNSPECIFIED(&pktinfo->ipi6_addr)) {
2308 			ip6_clearpktopts(opt, optname);
2309 			break;
2310 		}
2311 
2312 		if (uproto == IPPROTO_TCP &&
2313 		    sticky && !IN6_IS_ADDR_UNSPECIFIED(&pktinfo->ipi6_addr)) {
2314 			return (EINVAL);
2315 		}
2316 
2317 		if (pktinfo->ipi6_ifindex) {
2318 			ifp = if_get(pktinfo->ipi6_ifindex);
2319 			if (ifp == NULL)
2320 				return (ENXIO);
2321 			if_put(ifp);
2322 		}
2323 
2324 		/*
2325 		 * We store the address anyway, and let in6_selectsrc()
2326 		 * validate the specified address.  This is because ipi6_addr
2327 		 * may not have enough information about its scope zone, and
2328 		 * we may need additional information (such as outgoing
2329 		 * interface or the scope zone of a destination address) to
2330 		 * disambiguate the scope.
2331 		 * XXX: the delay of the validation may confuse the
2332 		 * application when it is used as a sticky option.
2333 		 */
2334 		if (opt->ip6po_pktinfo == NULL) {
2335 			opt->ip6po_pktinfo = malloc(sizeof(*pktinfo),
2336 			    M_IP6OPT, M_NOWAIT);
2337 			if (opt->ip6po_pktinfo == NULL)
2338 				return (ENOBUFS);
2339 		}
2340 		bcopy(pktinfo, opt->ip6po_pktinfo, sizeof(*pktinfo));
2341 		break;
2342 	}
2343 
2344 	case IPV6_HOPLIMIT:
2345 	{
2346 		int *hlimp;
2347 
2348 		/*
2349 		 * RFC 3542 deprecated the usage of sticky IPV6_HOPLIMIT
2350 		 * to simplify the ordering among hoplimit options.
2351 		 */
2352 		if (sticky)
2353 			return (ENOPROTOOPT);
2354 
2355 		if (len != sizeof(int))
2356 			return (EINVAL);
2357 		hlimp = (int *)buf;
2358 		if (*hlimp < -1 || *hlimp > 255)
2359 			return (EINVAL);
2360 
2361 		opt->ip6po_hlim = *hlimp;
2362 		break;
2363 	}
2364 
2365 	case IPV6_TCLASS:
2366 	{
2367 		int tclass;
2368 
2369 		if (len != sizeof(int))
2370 			return (EINVAL);
2371 		tclass = *(int *)buf;
2372 		if (tclass < -1 || tclass > 255)
2373 			return (EINVAL);
2374 
2375 		opt->ip6po_tclass = tclass;
2376 		break;
2377 	}
2378 	case IPV6_HOPOPTS:
2379 	{
2380 		struct ip6_hbh *hbh;
2381 		int hbhlen;
2382 
2383 		/*
2384 		 * XXX: We don't allow a non-privileged user to set ANY HbH
2385 		 * options, since per-option restriction has too much
2386 		 * overhead.
2387 		 */
2388 		if (!priv)
2389 			return (EPERM);
2390 
2391 		if (len == 0) {
2392 			ip6_clearpktopts(opt, IPV6_HOPOPTS);
2393 			break;	/* just remove the option */
2394 		}
2395 
2396 		/* message length validation */
2397 		if (len < sizeof(struct ip6_hbh))
2398 			return (EINVAL);
2399 		hbh = (struct ip6_hbh *)buf;
2400 		hbhlen = (hbh->ip6h_len + 1) << 3;
2401 		if (len != hbhlen)
2402 			return (EINVAL);
2403 
2404 		/* turn off the previous option, then set the new option. */
2405 		ip6_clearpktopts(opt, IPV6_HOPOPTS);
2406 		opt->ip6po_hbh = malloc(hbhlen, M_IP6OPT, M_NOWAIT);
2407 		if (opt->ip6po_hbh == NULL)
2408 			return (ENOBUFS);
2409 		memcpy(opt->ip6po_hbh, hbh, hbhlen);
2410 
2411 		break;
2412 	}
2413 
2414 	case IPV6_DSTOPTS:
2415 	case IPV6_RTHDRDSTOPTS:
2416 	{
2417 		struct ip6_dest *dest, **newdest = NULL;
2418 		int destlen;
2419 
2420 		if (!priv)	/* XXX: see the comment for IPV6_HOPOPTS */
2421 			return (EPERM);
2422 
2423 		if (len == 0) {
2424 			ip6_clearpktopts(opt, optname);
2425 			break;	/* just remove the option */
2426 		}
2427 
2428 		/* message length validation */
2429 		if (len < sizeof(struct ip6_dest))
2430 			return (EINVAL);
2431 		dest = (struct ip6_dest *)buf;
2432 		destlen = (dest->ip6d_len + 1) << 3;
2433 		if (len != destlen)
2434 			return (EINVAL);
2435 		/*
2436 		 * Determine the position that the destination options header
2437 		 * should be inserted; before or after the routing header.
2438 		 */
2439 		switch (optname) {
2440 		case IPV6_RTHDRDSTOPTS:
2441 			newdest = &opt->ip6po_dest1;
2442 			break;
2443 		case IPV6_DSTOPTS:
2444 			newdest = &opt->ip6po_dest2;
2445 			break;
2446 		}
2447 
2448 		/* turn off the previous option, then set the new option. */
2449 		ip6_clearpktopts(opt, optname);
2450 		*newdest = malloc(destlen, M_IP6OPT, M_NOWAIT);
2451 		if (*newdest == NULL)
2452 			return (ENOBUFS);
2453 		memcpy(*newdest, dest, destlen);
2454 
2455 		break;
2456 	}
2457 
2458 	case IPV6_RTHDR:
2459 	{
2460 		struct ip6_rthdr *rth;
2461 		int rthlen;
2462 
2463 		if (len == 0) {
2464 			ip6_clearpktopts(opt, IPV6_RTHDR);
2465 			break;	/* just remove the option */
2466 		}
2467 
2468 		/* message length validation */
2469 		if (len < sizeof(struct ip6_rthdr))
2470 			return (EINVAL);
2471 		rth = (struct ip6_rthdr *)buf;
2472 		rthlen = (rth->ip6r_len + 1) << 3;
2473 		if (len != rthlen)
2474 			return (EINVAL);
2475 
2476 		switch (rth->ip6r_type) {
2477 		case IPV6_RTHDR_TYPE_0:
2478 			if (rth->ip6r_len == 0)	/* must contain one addr */
2479 				return (EINVAL);
2480 			if (rth->ip6r_len % 2) /* length must be even */
2481 				return (EINVAL);
2482 			if (rth->ip6r_len / 2 != rth->ip6r_segleft)
2483 				return (EINVAL);
2484 			break;
2485 		default:
2486 			return (EINVAL);	/* not supported */
2487 		}
2488 		/* turn off the previous option */
2489 		ip6_clearpktopts(opt, IPV6_RTHDR);
2490 		opt->ip6po_rthdr = malloc(rthlen, M_IP6OPT, M_NOWAIT);
2491 		if (opt->ip6po_rthdr == NULL)
2492 			return (ENOBUFS);
2493 		memcpy(opt->ip6po_rthdr, rth, rthlen);
2494 		break;
2495 	}
2496 
2497 	case IPV6_USE_MIN_MTU:
2498 		if (len != sizeof(int))
2499 			return (EINVAL);
2500 		minmtupolicy = *(int *)buf;
2501 		if (minmtupolicy != IP6PO_MINMTU_MCASTONLY &&
2502 		    minmtupolicy != IP6PO_MINMTU_DISABLE &&
2503 		    minmtupolicy != IP6PO_MINMTU_ALL) {
2504 			return (EINVAL);
2505 		}
2506 		opt->ip6po_minmtu = minmtupolicy;
2507 		break;
2508 
2509 	case IPV6_DONTFRAG:
2510 		if (len != sizeof(int))
2511 			return (EINVAL);
2512 
2513 		if (uproto == IPPROTO_TCP || *(int *)buf == 0) {
2514 			/*
2515 			 * we ignore this option for TCP sockets.
2516 			 * (RFC3542 leaves this case unspecified.)
2517 			 */
2518 			opt->ip6po_flags &= ~IP6PO_DONTFRAG;
2519 		} else
2520 			opt->ip6po_flags |= IP6PO_DONTFRAG;
2521 		break;
2522 
2523 	default:
2524 		return (ENOPROTOOPT);
2525 	} /* end of switch */
2526 
2527 	return (0);
2528 }
2529 
2530 /*
2531  * Routine called from ip6_output() to loop back a copy of an IP6 multicast
2532  * packet to the input queue of a specified interface.
2533  */
2534 void
2535 ip6_mloopback(struct ifnet *ifp, struct mbuf *m, struct sockaddr_in6 *dst)
2536 {
2537 	struct mbuf *copym;
2538 	struct ip6_hdr *ip6;
2539 
2540 	/*
2541 	 * Duplicate the packet.
2542 	 */
2543 	copym = m_copym(m, 0, M_COPYALL, M_NOWAIT);
2544 	if (copym == NULL)
2545 		return;
2546 
2547 	/*
2548 	 * Make sure to deep-copy IPv6 header portion in case the data
2549 	 * is in an mbuf cluster, so that we can safely override the IPv6
2550 	 * header portion later.
2551 	 */
2552 	if ((copym->m_flags & M_EXT) != 0 ||
2553 	    copym->m_len < sizeof(struct ip6_hdr)) {
2554 		copym = m_pullup(copym, sizeof(struct ip6_hdr));
2555 		if (copym == NULL)
2556 			return;
2557 	}
2558 
2559 #ifdef DIAGNOSTIC
2560 	if (copym->m_len < sizeof(*ip6)) {
2561 		m_freem(copym);
2562 		return;
2563 	}
2564 #endif
2565 
2566 	ip6 = mtod(copym, struct ip6_hdr *);
2567 	if (IN6_IS_SCOPE_EMBED(&ip6->ip6_src))
2568 		ip6->ip6_src.s6_addr16[1] = 0;
2569 	if (IN6_IS_SCOPE_EMBED(&ip6->ip6_dst))
2570 		ip6->ip6_dst.s6_addr16[1] = 0;
2571 
2572 	if_input_local(ifp, copym, dst->sin6_family);
2573 }
2574 
2575 /*
2576  * Chop IPv6 header off from the payload.
2577  */
2578 int
2579 ip6_splithdr(struct mbuf *m, struct ip6_exthdrs *exthdrs)
2580 {
2581 	struct mbuf *mh;
2582 	struct ip6_hdr *ip6;
2583 
2584 	ip6 = mtod(m, struct ip6_hdr *);
2585 	if (m->m_len > sizeof(*ip6)) {
2586 		MGET(mh, M_DONTWAIT, MT_HEADER);
2587 		if (mh == NULL) {
2588 			m_freem(m);
2589 			return ENOBUFS;
2590 		}
2591 		M_MOVE_PKTHDR(mh, m);
2592 		m_align(mh, sizeof(*ip6));
2593 		m->m_len -= sizeof(*ip6);
2594 		m->m_data += sizeof(*ip6);
2595 		mh->m_next = m;
2596 		m = mh;
2597 		m->m_len = sizeof(*ip6);
2598 		bcopy((caddr_t)ip6, mtod(m, caddr_t), sizeof(*ip6));
2599 	}
2600 	exthdrs->ip6e_ip6 = m;
2601 	return 0;
2602 }
2603 
2604 u_int32_t
2605 ip6_randomid(void)
2606 {
2607 	return idgen32(&ip6_id_ctx);
2608 }
2609 
2610 void
2611 ip6_randomid_init(void)
2612 {
2613 	idgen32_init(&ip6_id_ctx);
2614 }
2615 
2616 /*
2617  *	Compute significant parts of the IPv6 checksum pseudo-header
2618  *	for use in a delayed TCP/UDP checksum calculation.
2619  */
2620 static __inline u_int16_t __attribute__((__unused__))
2621 in6_cksum_phdr(const struct in6_addr *src, const struct in6_addr *dst,
2622     u_int32_t len, u_int32_t nxt)
2623 {
2624 	u_int32_t sum = 0;
2625 	const u_int16_t *w;
2626 
2627 	w = (const u_int16_t *) src;
2628 	sum += w[0];
2629 	if (!IN6_IS_SCOPE_EMBED(src))
2630 		sum += w[1];
2631 	sum += w[2]; sum += w[3]; sum += w[4]; sum += w[5];
2632 	sum += w[6]; sum += w[7];
2633 
2634 	w = (const u_int16_t *) dst;
2635 	sum += w[0];
2636 	if (!IN6_IS_SCOPE_EMBED(dst))
2637 		sum += w[1];
2638 	sum += w[2]; sum += w[3]; sum += w[4]; sum += w[5];
2639 	sum += w[6]; sum += w[7];
2640 
2641 	sum += (u_int16_t)(len >> 16) + (u_int16_t)(len /*& 0xffff*/);
2642 
2643 	sum += (u_int16_t)(nxt >> 16) + (u_int16_t)(nxt /*& 0xffff*/);
2644 
2645 	sum = (u_int16_t)(sum >> 16) + (u_int16_t)(sum /*& 0xffff*/);
2646 
2647 	if (sum > 0xffff)
2648 		sum -= 0xffff;
2649 
2650 	return (sum);
2651 }
2652 
2653 /*
2654  * Process a delayed payload checksum calculation.
2655  */
2656 void
2657 in6_delayed_cksum(struct mbuf *m, u_int8_t nxt)
2658 {
2659 	int nxtp, offset;
2660 	u_int16_t csum;
2661 
2662 	offset = ip6_lasthdr(m, 0, IPPROTO_IPV6, &nxtp);
2663 	if (offset <= 0 || nxtp != nxt)
2664 		/* If the desired next protocol isn't found, punt. */
2665 		return;
2666 	csum = (u_int16_t)(in6_cksum(m, 0, offset, m->m_pkthdr.len - offset));
2667 
2668 	switch (nxt) {
2669 	case IPPROTO_TCP:
2670 		offset += offsetof(struct tcphdr, th_sum);
2671 		break;
2672 
2673 	case IPPROTO_UDP:
2674 		offset += offsetof(struct udphdr, uh_sum);
2675 		if (csum == 0)
2676 			csum = 0xffff;
2677 		break;
2678 
2679 	case IPPROTO_ICMPV6:
2680 		offset += offsetof(struct icmp6_hdr, icmp6_cksum);
2681 		break;
2682 	}
2683 
2684 	if ((offset + sizeof(u_int16_t)) > m->m_len)
2685 		m_copyback(m, offset, sizeof(csum), &csum, M_NOWAIT);
2686 	else
2687 		*(u_int16_t *)(mtod(m, caddr_t) + offset) = csum;
2688 }
2689 
2690 void
2691 in6_proto_cksum_out(struct mbuf *m, struct ifnet *ifp)
2692 {
2693 	struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
2694 
2695 	/* some hw and in6_delayed_cksum need the pseudo header cksum */
2696 	if (m->m_pkthdr.csum_flags &
2697 	    (M_TCP_CSUM_OUT|M_UDP_CSUM_OUT|M_ICMP_CSUM_OUT)) {
2698 		int nxt, offset;
2699 		u_int16_t csum;
2700 
2701 		offset = ip6_lasthdr(m, 0, IPPROTO_IPV6, &nxt);
2702 		csum = in6_cksum_phdr(&ip6->ip6_src, &ip6->ip6_dst,
2703 		    htonl(m->m_pkthdr.len - offset), htonl(nxt));
2704 		if (nxt == IPPROTO_TCP)
2705 			offset += offsetof(struct tcphdr, th_sum);
2706 		else if (nxt == IPPROTO_UDP)
2707 			offset += offsetof(struct udphdr, uh_sum);
2708 		else if (nxt == IPPROTO_ICMPV6)
2709 			offset += offsetof(struct icmp6_hdr, icmp6_cksum);
2710 		if ((offset + sizeof(u_int16_t)) > m->m_len)
2711 			m_copyback(m, offset, sizeof(csum), &csum, M_NOWAIT);
2712 		else
2713 			*(u_int16_t *)(mtod(m, caddr_t) + offset) = csum;
2714 	}
2715 
2716 	if (m->m_pkthdr.csum_flags & M_TCP_CSUM_OUT) {
2717 		if (!ifp || !(ifp->if_capabilities & IFCAP_CSUM_TCPv6) ||
2718 		    ip6->ip6_nxt != IPPROTO_TCP ||
2719 		    ifp->if_bridgeidx != 0) {
2720 			tcpstat_inc(tcps_outswcsum);
2721 			in6_delayed_cksum(m, IPPROTO_TCP);
2722 			m->m_pkthdr.csum_flags &= ~M_TCP_CSUM_OUT; /* Clear */
2723 		}
2724 	} else if (m->m_pkthdr.csum_flags & M_UDP_CSUM_OUT) {
2725 		if (!ifp || !(ifp->if_capabilities & IFCAP_CSUM_UDPv6) ||
2726 		    ip6->ip6_nxt != IPPROTO_UDP ||
2727 		    ifp->if_bridgeidx != 0) {
2728 			udpstat_inc(udps_outswcsum);
2729 			in6_delayed_cksum(m, IPPROTO_UDP);
2730 			m->m_pkthdr.csum_flags &= ~M_UDP_CSUM_OUT; /* Clear */
2731 		}
2732 	} else if (m->m_pkthdr.csum_flags & M_ICMP_CSUM_OUT) {
2733 		in6_delayed_cksum(m, IPPROTO_ICMPV6);
2734 		m->m_pkthdr.csum_flags &= ~M_ICMP_CSUM_OUT; /* Clear */
2735 	}
2736 }
2737 
2738 #ifdef IPSEC
2739 struct tdb *
2740 ip6_output_ipsec_lookup(struct mbuf *m, int *error, struct inpcb *inp)
2741 {
2742 	struct tdb *tdb;
2743 	struct m_tag *mtag;
2744 	struct tdb_ident *tdbi;
2745 
2746 	/*
2747 	 * Check if there was an outgoing SA bound to the flow
2748 	 * from a transport protocol.
2749 	 */
2750 
2751 	/* Do we have any pending SAs to apply ? */
2752 	tdb = ipsp_spd_lookup(m, AF_INET6, sizeof(struct ip6_hdr),
2753 	    error, IPSP_DIRECTION_OUT, NULL, inp, 0);
2754 
2755 	if (tdb == NULL)
2756 		return NULL;
2757 	/* Loop detection */
2758 	for (mtag = m_tag_first(m); mtag != NULL; mtag = m_tag_next(m, mtag)) {
2759 		if (mtag->m_tag_id != PACKET_TAG_IPSEC_OUT_DONE)
2760 			continue;
2761 		tdbi = (struct tdb_ident *)(mtag + 1);
2762 		if (tdbi->spi == tdb->tdb_spi &&
2763 		    tdbi->proto == tdb->tdb_sproto &&
2764 		    tdbi->rdomain == tdb->tdb_rdomain &&
2765 		    !memcmp(&tdbi->dst, &tdb->tdb_dst,
2766 		    sizeof(union sockaddr_union))) {
2767 			/* no IPsec needed */
2768 			return NULL;
2769 		}
2770 	}
2771 	return tdb;
2772 }
2773 
2774 int
2775 ip6_output_ipsec_send(struct tdb *tdb, struct mbuf *m, struct route_in6 *ro,
2776     int tunalready, int fwd)
2777 {
2778 #if NPF > 0
2779 	struct ifnet *encif;
2780 #endif
2781 	struct ip6_hdr *ip6;
2782 	int error;
2783 
2784 #if NPF > 0
2785 	/*
2786 	 * Packet filter
2787 	 */
2788 	if ((encif = enc_getif(tdb->tdb_rdomain, tdb->tdb_tap)) == NULL ||
2789 	    pf_test(AF_INET6, fwd ? PF_FWD : PF_OUT, encif, &m) != PF_PASS) {
2790 		m_freem(m);
2791 		return EACCES;
2792 	}
2793 	if (m == NULL)
2794 		return 0;
2795 	/*
2796 	 * PF_TAG_REROUTE handling or not...
2797 	 * Packet is entering IPsec so the routing is
2798 	 * already overruled by the IPsec policy.
2799 	 * Until now the change was not reconsidered.
2800 	 * What's the behaviour?
2801 	 */
2802 	in6_proto_cksum_out(m, encif);
2803 #endif
2804 
2805 	/* Check if we are allowed to fragment */
2806 	ip6 = mtod(m, struct ip6_hdr *);
2807 	if (ip_mtudisc && tdb->tdb_mtu &&
2808 	    sizeof(struct ip6_hdr) + ntohs(ip6->ip6_plen) > tdb->tdb_mtu &&
2809 	    tdb->tdb_mtutimeout > gettime()) {
2810 		struct rtentry *rt = NULL;
2811 		int rt_mtucloned = 0;
2812 		int transportmode = 0;
2813 
2814 		transportmode = (tdb->tdb_dst.sa.sa_family == AF_INET6) &&
2815 		    (IN6_ARE_ADDR_EQUAL(&tdb->tdb_dst.sin6.sin6_addr,
2816 		    &ip6->ip6_dst));
2817 
2818 		/* Find a host route to store the mtu in */
2819 		if (ro != NULL)
2820 			rt = ro->ro_rt;
2821 		/* but don't add a PMTU route for transport mode SAs */
2822 		if (transportmode)
2823 			rt = NULL;
2824 		else if (rt == NULL || (rt->rt_flags & RTF_HOST) == 0) {
2825 			struct sockaddr_in6 sin6;
2826 
2827 			memset(&sin6, 0, sizeof(sin6));
2828 			sin6.sin6_family = AF_INET6;
2829 			sin6.sin6_len = sizeof(sin6);
2830 			sin6.sin6_addr = ip6->ip6_dst;
2831 			sin6.sin6_scope_id =
2832 			    in6_addr2scopeid(m->m_pkthdr.ph_ifidx,
2833 			    &ip6->ip6_dst);
2834 			error = in6_embedscope(&ip6->ip6_dst, &sin6, NULL);
2835 			if (error) {
2836 				/* should be impossible */
2837 				ipsecstat_inc(ipsec_odrops);
2838 				m_freem(m);
2839 				return error;
2840 			}
2841 			rt = icmp6_mtudisc_clone(&sin6,
2842 			    m->m_pkthdr.ph_rtableid, 1);
2843 			rt_mtucloned = 1;
2844 		}
2845 		DPRINTF("spi %08x mtu %d rt %p cloned %d",
2846 		    ntohl(tdb->tdb_spi), tdb->tdb_mtu, rt, rt_mtucloned);
2847 		if (rt != NULL) {
2848 			rt->rt_mtu = tdb->tdb_mtu;
2849 			if (ro != NULL && ro->ro_rt != NULL) {
2850 				rtfree(ro->ro_rt);
2851 				ro->ro_rt = rtalloc(sin6tosa(&ro->ro_dst),
2852 				    RT_RESOLVE, m->m_pkthdr.ph_rtableid);
2853 			}
2854 			if (rt_mtucloned)
2855 				rtfree(rt);
2856 		}
2857 		ipsec_adjust_mtu(m, tdb->tdb_mtu);
2858 		m_freem(m);
2859 		return EMSGSIZE;
2860 	}
2861 	/* propagate don't fragment for v6-over-v6 */
2862 	if (ip_mtudisc)
2863 		SET(m->m_pkthdr.csum_flags, M_IPV6_DF_OUT);
2864 
2865 	/*
2866 	 * Clear these -- they'll be set in the recursive invocation
2867 	 * as needed.
2868 	 */
2869 	m->m_flags &= ~(M_BCAST | M_MCAST);
2870 
2871 	/* Callee frees mbuf */
2872 	error = ipsp_process_packet(m, tdb, AF_INET6, tunalready);
2873 	if (error) {
2874 		ipsecstat_inc(ipsec_odrops);
2875 		tdb->tdb_odrops++;
2876 	}
2877 	return error;
2878 }
2879 #endif /* IPSEC */
2880