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