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