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