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