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