xref: /openbsd/sys/netinet6/ip6_output.c (revision 097a140d)
1 /*	$OpenBSD: ip6_output.c,v 1.256 2021/03/10 10:21:49 jsg 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 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 	switch (op) {
1073 	case PRCO_SETOPT:
1074 		switch (optname) {
1075 		/*
1076 		 * Use of some Hop-by-Hop options or some
1077 		 * Destination options, might require special
1078 		 * privilege.  That is, normal applications
1079 		 * (without special privilege) might be forbidden
1080 		 * from setting certain options in outgoing packets,
1081 		 * and might never see certain options in received
1082 		 * packets. [RFC 2292 Section 6]
1083 		 * KAME specific note:
1084 		 *  KAME prevents non-privileged users from sending or
1085 		 *  receiving ANY hbh/dst options in order to avoid
1086 		 *  overhead of parsing options in the kernel.
1087 		 */
1088 		case IPV6_RECVHOPOPTS:
1089 		case IPV6_RECVDSTOPTS:
1090 			if (!privileged) {
1091 				error = EPERM;
1092 				break;
1093 			}
1094 			/* FALLTHROUGH */
1095 		case IPV6_UNICAST_HOPS:
1096 		case IPV6_MINHOPCOUNT:
1097 		case IPV6_HOPLIMIT:
1098 
1099 		case IPV6_RECVPKTINFO:
1100 		case IPV6_RECVHOPLIMIT:
1101 		case IPV6_RECVRTHDR:
1102 		case IPV6_RECVPATHMTU:
1103 		case IPV6_RECVTCLASS:
1104 		case IPV6_V6ONLY:
1105 		case IPV6_AUTOFLOWLABEL:
1106 		case IPV6_RECVDSTPORT:
1107 			if (m == NULL || m->m_len != sizeof(int)) {
1108 				error = EINVAL;
1109 				break;
1110 			}
1111 			optval = *mtod(m, int *);
1112 			switch (optname) {
1113 
1114 			case IPV6_UNICAST_HOPS:
1115 				if (optval < -1 || optval >= 256)
1116 					error = EINVAL;
1117 				else {
1118 					/* -1 = kernel default */
1119 					inp->inp_hops = optval;
1120 				}
1121 				break;
1122 
1123 			case IPV6_MINHOPCOUNT:
1124 				if (optval < 0 || optval > 255)
1125 					error = EINVAL;
1126 				else
1127 					inp->inp_ip6_minhlim = optval;
1128 				break;
1129 
1130 #define OPTSET(bit) \
1131 do { \
1132 	if (optval) \
1133 		inp->inp_flags |= (bit); \
1134 	else \
1135 		inp->inp_flags &= ~(bit); \
1136 } while (/*CONSTCOND*/ 0)
1137 #define OPTBIT(bit) (inp->inp_flags & (bit) ? 1 : 0)
1138 
1139 			case IPV6_RECVPKTINFO:
1140 				OPTSET(IN6P_PKTINFO);
1141 				break;
1142 
1143 			case IPV6_HOPLIMIT:
1144 			{
1145 				struct ip6_pktopts **optp;
1146 
1147 				optp = &inp->inp_outputopts6;
1148 				error = ip6_pcbopt(IPV6_HOPLIMIT,
1149 				    (u_char *)&optval, sizeof(optval), optp,
1150 				    privileged, uproto);
1151 				break;
1152 			}
1153 
1154 			case IPV6_RECVHOPLIMIT:
1155 				OPTSET(IN6P_HOPLIMIT);
1156 				break;
1157 
1158 			case IPV6_RECVHOPOPTS:
1159 				OPTSET(IN6P_HOPOPTS);
1160 				break;
1161 
1162 			case IPV6_RECVDSTOPTS:
1163 				OPTSET(IN6P_DSTOPTS);
1164 				break;
1165 
1166 			case IPV6_RECVRTHDR:
1167 				OPTSET(IN6P_RTHDR);
1168 				break;
1169 
1170 			case IPV6_RECVPATHMTU:
1171 				/*
1172 				 * We ignore this option for TCP
1173 				 * sockets.
1174 				 * (RFC3542 leaves this case
1175 				 * unspecified.)
1176 				 */
1177 				if (uproto != IPPROTO_TCP)
1178 					OPTSET(IN6P_MTU);
1179 				break;
1180 
1181 			case IPV6_V6ONLY:
1182 				/*
1183 				 * make setsockopt(IPV6_V6ONLY)
1184 				 * available only prior to bind(2).
1185 				 * see ipng mailing list, Jun 22 2001.
1186 				 */
1187 				if (inp->inp_lport || !IN6_IS_ADDR_UNSPECIFIED(
1188 				    &inp->inp_laddr6)) {
1189 					error = EINVAL;
1190 					break;
1191 				}
1192 				/* No support for IPv4-mapped addresses. */
1193 				if (!optval)
1194 					error = EINVAL;
1195 				else
1196 					error = 0;
1197 				break;
1198 			case IPV6_RECVTCLASS:
1199 				OPTSET(IN6P_TCLASS);
1200 				break;
1201 			case IPV6_AUTOFLOWLABEL:
1202 				OPTSET(IN6P_AUTOFLOWLABEL);
1203 				break;
1204 
1205 			case IPV6_RECVDSTPORT:
1206 				OPTSET(IN6P_RECVDSTPORT);
1207 				break;
1208 			}
1209 			break;
1210 
1211 		case IPV6_TCLASS:
1212 		case IPV6_DONTFRAG:
1213 		case IPV6_USE_MIN_MTU:
1214 			if (m == NULL || m->m_len != sizeof(optval)) {
1215 				error = EINVAL;
1216 				break;
1217 			}
1218 			optval = *mtod(m, int *);
1219 			{
1220 				struct ip6_pktopts **optp;
1221 				optp = &inp->inp_outputopts6;
1222 				error = ip6_pcbopt(optname, (u_char *)&optval,
1223 				    sizeof(optval), optp, privileged, uproto);
1224 				break;
1225 			}
1226 
1227 		case IPV6_PKTINFO:
1228 		case IPV6_HOPOPTS:
1229 		case IPV6_RTHDR:
1230 		case IPV6_DSTOPTS:
1231 		case IPV6_RTHDRDSTOPTS:
1232 		{
1233 			/* new advanced API (RFC3542) */
1234 			u_char *optbuf;
1235 			int optbuflen;
1236 			struct ip6_pktopts **optp;
1237 
1238 			if (m && m->m_next) {
1239 				error = EINVAL;	/* XXX */
1240 				break;
1241 			}
1242 			if (m) {
1243 				optbuf = mtod(m, u_char *);
1244 				optbuflen = m->m_len;
1245 			} else {
1246 				optbuf = NULL;
1247 				optbuflen = 0;
1248 			}
1249 			optp = &inp->inp_outputopts6;
1250 			error = ip6_pcbopt(optname, optbuf, optbuflen, optp,
1251 			    privileged, uproto);
1252 			break;
1253 		}
1254 #undef OPTSET
1255 
1256 		case IPV6_MULTICAST_IF:
1257 		case IPV6_MULTICAST_HOPS:
1258 		case IPV6_MULTICAST_LOOP:
1259 		case IPV6_JOIN_GROUP:
1260 		case IPV6_LEAVE_GROUP:
1261 			error =	ip6_setmoptions(optname,
1262 						&inp->inp_moptions6,
1263 						m, inp->inp_rtableid);
1264 			break;
1265 
1266 		case IPV6_PORTRANGE:
1267 			if (m == NULL || m->m_len != sizeof(int)) {
1268 				error = EINVAL;
1269 				break;
1270 			}
1271 			optval = *mtod(m, int *);
1272 
1273 			switch (optval) {
1274 			case IPV6_PORTRANGE_DEFAULT:
1275 				inp->inp_flags &= ~(IN6P_LOWPORT);
1276 				inp->inp_flags &= ~(IN6P_HIGHPORT);
1277 				break;
1278 
1279 			case IPV6_PORTRANGE_HIGH:
1280 				inp->inp_flags &= ~(IN6P_LOWPORT);
1281 				inp->inp_flags |= IN6P_HIGHPORT;
1282 				break;
1283 
1284 			case IPV6_PORTRANGE_LOW:
1285 				inp->inp_flags &= ~(IN6P_HIGHPORT);
1286 				inp->inp_flags |= IN6P_LOWPORT;
1287 				break;
1288 
1289 			default:
1290 				error = EINVAL;
1291 				break;
1292 			}
1293 			break;
1294 
1295 		case IPSEC6_OUTSA:
1296 			error = EINVAL;
1297 			break;
1298 
1299 		case IPV6_AUTH_LEVEL:
1300 		case IPV6_ESP_TRANS_LEVEL:
1301 		case IPV6_ESP_NETWORK_LEVEL:
1302 		case IPV6_IPCOMP_LEVEL:
1303 #ifndef IPSEC
1304 			error = EINVAL;
1305 #else
1306 			if (m == NULL || m->m_len != sizeof(int)) {
1307 				error = EINVAL;
1308 				break;
1309 			}
1310 			optval = *mtod(m, int *);
1311 
1312 			if (optval < IPSEC_LEVEL_BYPASS ||
1313 			    optval > IPSEC_LEVEL_UNIQUE) {
1314 				error = EINVAL;
1315 				break;
1316 			}
1317 
1318 			switch (optname) {
1319 			case IPV6_AUTH_LEVEL:
1320 				if (optval < IPSEC_AUTH_LEVEL_DEFAULT &&
1321 				    suser(p)) {
1322 					error = EACCES;
1323 					break;
1324 				}
1325 				inp->inp_seclevel[SL_AUTH] = optval;
1326 				break;
1327 
1328 			case IPV6_ESP_TRANS_LEVEL:
1329 				if (optval < IPSEC_ESP_TRANS_LEVEL_DEFAULT &&
1330 				    suser(p)) {
1331 					error = EACCES;
1332 					break;
1333 				}
1334 				inp->inp_seclevel[SL_ESP_TRANS] = optval;
1335 				break;
1336 
1337 			case IPV6_ESP_NETWORK_LEVEL:
1338 				if (optval < IPSEC_ESP_NETWORK_LEVEL_DEFAULT &&
1339 				    suser(p)) {
1340 					error = EACCES;
1341 					break;
1342 				}
1343 				inp->inp_seclevel[SL_ESP_NETWORK] = optval;
1344 				break;
1345 
1346 			case IPV6_IPCOMP_LEVEL:
1347 				if (optval < IPSEC_IPCOMP_LEVEL_DEFAULT &&
1348 				    suser(p)) {
1349 					error = EACCES;
1350 					break;
1351 				}
1352 				inp->inp_seclevel[SL_IPCOMP] = optval;
1353 				break;
1354 			}
1355 #endif
1356 			break;
1357 		case SO_RTABLE:
1358 			if (m == NULL || m->m_len < sizeof(u_int)) {
1359 				error = EINVAL;
1360 				break;
1361 			}
1362 			rtid = *mtod(m, u_int *);
1363 			if (inp->inp_rtableid == rtid)
1364 				break;
1365 			/* needs privileges to switch when already set */
1366 			if (p->p_p->ps_rtableid != rtid &&
1367 			    p->p_p->ps_rtableid != 0 &&
1368 			    (error = suser(p)) != 0)
1369 				break;
1370 			/* table must exist */
1371 			if (!rtable_exists(rtid)) {
1372 				error = EINVAL;
1373 				break;
1374 			}
1375 			if (inp->inp_lport) {
1376 				error = EBUSY;
1377 				break;
1378 			}
1379 			inp->inp_rtableid = rtid;
1380 			in_pcbrehash(inp);
1381 			break;
1382 		case IPV6_PIPEX:
1383 			if (m != NULL && m->m_len == sizeof(int))
1384 				inp->inp_pipex = *mtod(m, int *);
1385 			else
1386 				error = EINVAL;
1387 			break;
1388 
1389 		default:
1390 			error = ENOPROTOOPT;
1391 			break;
1392 		}
1393 		break;
1394 
1395 	case PRCO_GETOPT:
1396 		switch (optname) {
1397 
1398 		case IPV6_RECVHOPOPTS:
1399 		case IPV6_RECVDSTOPTS:
1400 		case IPV6_UNICAST_HOPS:
1401 		case IPV6_MINHOPCOUNT:
1402 		case IPV6_RECVPKTINFO:
1403 		case IPV6_RECVHOPLIMIT:
1404 		case IPV6_RECVRTHDR:
1405 		case IPV6_RECVPATHMTU:
1406 
1407 		case IPV6_V6ONLY:
1408 		case IPV6_PORTRANGE:
1409 		case IPV6_RECVTCLASS:
1410 		case IPV6_AUTOFLOWLABEL:
1411 		case IPV6_RECVDSTPORT:
1412 			switch (optname) {
1413 
1414 			case IPV6_RECVHOPOPTS:
1415 				optval = OPTBIT(IN6P_HOPOPTS);
1416 				break;
1417 
1418 			case IPV6_RECVDSTOPTS:
1419 				optval = OPTBIT(IN6P_DSTOPTS);
1420 				break;
1421 
1422 			case IPV6_UNICAST_HOPS:
1423 				optval = inp->inp_hops;
1424 				break;
1425 
1426 			case IPV6_MINHOPCOUNT:
1427 				optval = inp->inp_ip6_minhlim;
1428 				break;
1429 
1430 			case IPV6_RECVPKTINFO:
1431 				optval = OPTBIT(IN6P_PKTINFO);
1432 				break;
1433 
1434 			case IPV6_RECVHOPLIMIT:
1435 				optval = OPTBIT(IN6P_HOPLIMIT);
1436 				break;
1437 
1438 			case IPV6_RECVRTHDR:
1439 				optval = OPTBIT(IN6P_RTHDR);
1440 				break;
1441 
1442 			case IPV6_RECVPATHMTU:
1443 				optval = OPTBIT(IN6P_MTU);
1444 				break;
1445 
1446 			case IPV6_V6ONLY:
1447 				optval = 1;
1448 				break;
1449 
1450 			case IPV6_PORTRANGE:
1451 			    {
1452 				int flags;
1453 				flags = inp->inp_flags;
1454 				if (flags & IN6P_HIGHPORT)
1455 					optval = IPV6_PORTRANGE_HIGH;
1456 				else if (flags & IN6P_LOWPORT)
1457 					optval = IPV6_PORTRANGE_LOW;
1458 				else
1459 					optval = 0;
1460 				break;
1461 			    }
1462 			case IPV6_RECVTCLASS:
1463 				optval = OPTBIT(IN6P_TCLASS);
1464 				break;
1465 
1466 			case IPV6_AUTOFLOWLABEL:
1467 				optval = OPTBIT(IN6P_AUTOFLOWLABEL);
1468 				break;
1469 
1470 			case IPV6_RECVDSTPORT:
1471 				optval = OPTBIT(IN6P_RECVDSTPORT);
1472 				break;
1473 			}
1474 			if (error)
1475 				break;
1476 			m->m_len = sizeof(int);
1477 			*mtod(m, int *) = optval;
1478 			break;
1479 
1480 		case IPV6_PATHMTU:
1481 		{
1482 			u_long pmtu = 0;
1483 			struct ip6_mtuinfo mtuinfo;
1484 			struct ifnet *ifp;
1485 			struct rtentry *rt;
1486 
1487 			if (!(so->so_state & SS_ISCONNECTED))
1488 				return (ENOTCONN);
1489 
1490 			rt = in_pcbrtentry(inp);
1491 			if (!rtisvalid(rt))
1492 				return (EHOSTUNREACH);
1493 
1494 			ifp = if_get(rt->rt_ifidx);
1495 			if (ifp == NULL)
1496 				return (EHOSTUNREACH);
1497 			/*
1498 			 * XXX: we dot not consider the case of source
1499 			 * routing, or optional information to specify
1500 			 * the outgoing interface.
1501 			 */
1502 			error = ip6_getpmtu(rt, ifp, &pmtu);
1503 			if_put(ifp);
1504 			if (error)
1505 				break;
1506 			if (pmtu > IPV6_MAXPACKET)
1507 				pmtu = IPV6_MAXPACKET;
1508 
1509 			bzero(&mtuinfo, sizeof(mtuinfo));
1510 			mtuinfo.ip6m_mtu = (u_int32_t)pmtu;
1511 			optdata = (void *)&mtuinfo;
1512 			optdatalen = sizeof(mtuinfo);
1513 			if (optdatalen > MCLBYTES)
1514 				return (EMSGSIZE); /* XXX */
1515 			if (optdatalen > MLEN)
1516 				MCLGET(m, M_WAIT);
1517 			m->m_len = optdatalen;
1518 			bcopy(optdata, mtod(m, void *), optdatalen);
1519 			break;
1520 		}
1521 
1522 		case IPV6_PKTINFO:
1523 		case IPV6_HOPOPTS:
1524 		case IPV6_RTHDR:
1525 		case IPV6_DSTOPTS:
1526 		case IPV6_RTHDRDSTOPTS:
1527 		case IPV6_TCLASS:
1528 		case IPV6_DONTFRAG:
1529 		case IPV6_USE_MIN_MTU:
1530 			error = ip6_getpcbopt(inp->inp_outputopts6,
1531 			    optname, m);
1532 			break;
1533 
1534 		case IPV6_MULTICAST_IF:
1535 		case IPV6_MULTICAST_HOPS:
1536 		case IPV6_MULTICAST_LOOP:
1537 		case IPV6_JOIN_GROUP:
1538 		case IPV6_LEAVE_GROUP:
1539 			error = ip6_getmoptions(optname,
1540 			    inp->inp_moptions6, m);
1541 			break;
1542 
1543 		case IPSEC6_OUTSA:
1544 			error = EINVAL;
1545 			break;
1546 
1547 		case IPV6_AUTH_LEVEL:
1548 		case IPV6_ESP_TRANS_LEVEL:
1549 		case IPV6_ESP_NETWORK_LEVEL:
1550 		case IPV6_IPCOMP_LEVEL:
1551 #ifndef IPSEC
1552 			m->m_len = sizeof(int);
1553 			*mtod(m, int *) = IPSEC_LEVEL_NONE;
1554 #else
1555 			m->m_len = sizeof(int);
1556 			switch (optname) {
1557 			case IPV6_AUTH_LEVEL:
1558 				optval = inp->inp_seclevel[SL_AUTH];
1559 				break;
1560 
1561 			case IPV6_ESP_TRANS_LEVEL:
1562 				optval =
1563 				    inp->inp_seclevel[SL_ESP_TRANS];
1564 				break;
1565 
1566 			case IPV6_ESP_NETWORK_LEVEL:
1567 				optval =
1568 				    inp->inp_seclevel[SL_ESP_NETWORK];
1569 				break;
1570 
1571 			case IPV6_IPCOMP_LEVEL:
1572 				optval = inp->inp_seclevel[SL_IPCOMP];
1573 				break;
1574 			}
1575 			*mtod(m, int *) = optval;
1576 #endif
1577 			break;
1578 		case SO_RTABLE:
1579 			m->m_len = sizeof(u_int);
1580 			*mtod(m, u_int *) = inp->inp_rtableid;
1581 			break;
1582 		case IPV6_PIPEX:
1583 			m->m_len = sizeof(int);
1584 			*mtod(m, int *) = inp->inp_pipex;
1585 			break;
1586 
1587 		default:
1588 			error = ENOPROTOOPT;
1589 			break;
1590 		}
1591 		break;
1592 	}
1593 	return (error);
1594 }
1595 
1596 int
1597 ip6_raw_ctloutput(int op, struct socket *so, int level, int optname,
1598     struct mbuf *m)
1599 {
1600 	int error = 0, optval;
1601 	const int icmp6off = offsetof(struct icmp6_hdr, icmp6_cksum);
1602 	struct inpcb *inp = sotoinpcb(so);
1603 
1604 	if (level != IPPROTO_IPV6)
1605 		return (EINVAL);
1606 
1607 	switch (optname) {
1608 	case IPV6_CHECKSUM:
1609 		/*
1610 		 * For ICMPv6 sockets, no modification allowed for checksum
1611 		 * offset, permit "no change" values to help existing apps.
1612 		 *
1613 		 * RFC3542 says: "An attempt to set IPV6_CHECKSUM
1614 		 * for an ICMPv6 socket will fail."
1615 		 * The current behavior does not meet RFC3542.
1616 		 */
1617 		switch (op) {
1618 		case PRCO_SETOPT:
1619 			if (m == NULL || m->m_len != sizeof(int)) {
1620 				error = EINVAL;
1621 				break;
1622 			}
1623 			optval = *mtod(m, int *);
1624 			if (optval < -1 ||
1625 			    (optval > 0 && (optval % 2) != 0)) {
1626 				/*
1627 				 * The API assumes non-negative even offset
1628 				 * values or -1 as a special value.
1629 				 */
1630 				error = EINVAL;
1631 			} else if (so->so_proto->pr_protocol ==
1632 			    IPPROTO_ICMPV6) {
1633 				if (optval != icmp6off)
1634 					error = EINVAL;
1635 			} else
1636 				inp->inp_cksum6 = optval;
1637 			break;
1638 
1639 		case PRCO_GETOPT:
1640 			if (so->so_proto->pr_protocol == IPPROTO_ICMPV6)
1641 				optval = icmp6off;
1642 			else
1643 				optval = inp->inp_cksum6;
1644 
1645 			m->m_len = sizeof(int);
1646 			*mtod(m, int *) = optval;
1647 			break;
1648 
1649 		default:
1650 			error = EINVAL;
1651 			break;
1652 		}
1653 		break;
1654 
1655 	default:
1656 		error = ENOPROTOOPT;
1657 		break;
1658 	}
1659 
1660 	return (error);
1661 }
1662 
1663 /*
1664  * initialize ip6_pktopts.  beware that there are non-zero default values in
1665  * the struct.
1666  */
1667 void
1668 ip6_initpktopts(struct ip6_pktopts *opt)
1669 {
1670 	bzero(opt, sizeof(*opt));
1671 	opt->ip6po_hlim = -1;	/* -1 means default hop limit */
1672 	opt->ip6po_tclass = -1;	/* -1 means default traffic class */
1673 	opt->ip6po_minmtu = IP6PO_MINMTU_MCASTONLY;
1674 }
1675 
1676 int
1677 ip6_pcbopt(int optname, u_char *buf, int len, struct ip6_pktopts **pktopt,
1678     int priv, int uproto)
1679 {
1680 	struct ip6_pktopts *opt;
1681 
1682 	if (*pktopt == NULL) {
1683 		*pktopt = malloc(sizeof(struct ip6_pktopts), M_IP6OPT,
1684 		    M_WAITOK);
1685 		ip6_initpktopts(*pktopt);
1686 	}
1687 	opt = *pktopt;
1688 
1689 	return (ip6_setpktopt(optname, buf, len, opt, priv, 1, uproto));
1690 }
1691 
1692 int
1693 ip6_getpcbopt(struct ip6_pktopts *pktopt, int optname, struct mbuf *m)
1694 {
1695 	void *optdata = NULL;
1696 	int optdatalen = 0;
1697 	struct ip6_ext *ip6e;
1698 	int error = 0;
1699 	struct in6_pktinfo null_pktinfo;
1700 	int deftclass = 0, on;
1701 	int defminmtu = IP6PO_MINMTU_MCASTONLY;
1702 
1703 	switch (optname) {
1704 	case IPV6_PKTINFO:
1705 		if (pktopt && pktopt->ip6po_pktinfo)
1706 			optdata = (void *)pktopt->ip6po_pktinfo;
1707 		else {
1708 			/* XXX: we don't have to do this every time... */
1709 			bzero(&null_pktinfo, sizeof(null_pktinfo));
1710 			optdata = (void *)&null_pktinfo;
1711 		}
1712 		optdatalen = sizeof(struct in6_pktinfo);
1713 		break;
1714 	case IPV6_TCLASS:
1715 		if (pktopt && pktopt->ip6po_tclass >= 0)
1716 			optdata = (void *)&pktopt->ip6po_tclass;
1717 		else
1718 			optdata = (void *)&deftclass;
1719 		optdatalen = sizeof(int);
1720 		break;
1721 	case IPV6_HOPOPTS:
1722 		if (pktopt && pktopt->ip6po_hbh) {
1723 			optdata = (void *)pktopt->ip6po_hbh;
1724 			ip6e = (struct ip6_ext *)pktopt->ip6po_hbh;
1725 			optdatalen = (ip6e->ip6e_len + 1) << 3;
1726 		}
1727 		break;
1728 	case IPV6_RTHDR:
1729 		if (pktopt && pktopt->ip6po_rthdr) {
1730 			optdata = (void *)pktopt->ip6po_rthdr;
1731 			ip6e = (struct ip6_ext *)pktopt->ip6po_rthdr;
1732 			optdatalen = (ip6e->ip6e_len + 1) << 3;
1733 		}
1734 		break;
1735 	case IPV6_RTHDRDSTOPTS:
1736 		if (pktopt && pktopt->ip6po_dest1) {
1737 			optdata = (void *)pktopt->ip6po_dest1;
1738 			ip6e = (struct ip6_ext *)pktopt->ip6po_dest1;
1739 			optdatalen = (ip6e->ip6e_len + 1) << 3;
1740 		}
1741 		break;
1742 	case IPV6_DSTOPTS:
1743 		if (pktopt && pktopt->ip6po_dest2) {
1744 			optdata = (void *)pktopt->ip6po_dest2;
1745 			ip6e = (struct ip6_ext *)pktopt->ip6po_dest2;
1746 			optdatalen = (ip6e->ip6e_len + 1) << 3;
1747 		}
1748 		break;
1749 	case IPV6_USE_MIN_MTU:
1750 		if (pktopt)
1751 			optdata = (void *)&pktopt->ip6po_minmtu;
1752 		else
1753 			optdata = (void *)&defminmtu;
1754 		optdatalen = sizeof(int);
1755 		break;
1756 	case IPV6_DONTFRAG:
1757 		if (pktopt && ((pktopt->ip6po_flags) & IP6PO_DONTFRAG))
1758 			on = 1;
1759 		else
1760 			on = 0;
1761 		optdata = (void *)&on;
1762 		optdatalen = sizeof(on);
1763 		break;
1764 	default:		/* should not happen */
1765 #ifdef DIAGNOSTIC
1766 		panic("%s: unexpected option", __func__);
1767 #endif
1768 		return (ENOPROTOOPT);
1769 	}
1770 
1771 	if (optdatalen > MCLBYTES)
1772 		return (EMSGSIZE); /* XXX */
1773 	if (optdatalen > MLEN)
1774 		MCLGET(m, M_WAIT);
1775 	m->m_len = optdatalen;
1776 	if (optdatalen)
1777 		bcopy(optdata, mtod(m, void *), optdatalen);
1778 
1779 	return (error);
1780 }
1781 
1782 void
1783 ip6_clearpktopts(struct ip6_pktopts *pktopt, int optname)
1784 {
1785 	if (optname == -1 || optname == IPV6_PKTINFO) {
1786 		if (pktopt->ip6po_pktinfo)
1787 			free(pktopt->ip6po_pktinfo, M_IP6OPT, 0);
1788 		pktopt->ip6po_pktinfo = NULL;
1789 	}
1790 	if (optname == -1 || optname == IPV6_HOPLIMIT)
1791 		pktopt->ip6po_hlim = -1;
1792 	if (optname == -1 || optname == IPV6_TCLASS)
1793 		pktopt->ip6po_tclass = -1;
1794 	if (optname == -1 || optname == IPV6_HOPOPTS) {
1795 		if (pktopt->ip6po_hbh)
1796 			free(pktopt->ip6po_hbh, M_IP6OPT, 0);
1797 		pktopt->ip6po_hbh = NULL;
1798 	}
1799 	if (optname == -1 || optname == IPV6_RTHDRDSTOPTS) {
1800 		if (pktopt->ip6po_dest1)
1801 			free(pktopt->ip6po_dest1, M_IP6OPT, 0);
1802 		pktopt->ip6po_dest1 = NULL;
1803 	}
1804 	if (optname == -1 || optname == IPV6_RTHDR) {
1805 		if (pktopt->ip6po_rhinfo.ip6po_rhi_rthdr)
1806 			free(pktopt->ip6po_rhinfo.ip6po_rhi_rthdr, M_IP6OPT, 0);
1807 		pktopt->ip6po_rhinfo.ip6po_rhi_rthdr = NULL;
1808 		if (pktopt->ip6po_route.ro_rt) {
1809 			rtfree(pktopt->ip6po_route.ro_rt);
1810 			pktopt->ip6po_route.ro_rt = NULL;
1811 		}
1812 	}
1813 	if (optname == -1 || optname == IPV6_DSTOPTS) {
1814 		if (pktopt->ip6po_dest2)
1815 			free(pktopt->ip6po_dest2, M_IP6OPT, 0);
1816 		pktopt->ip6po_dest2 = NULL;
1817 	}
1818 }
1819 
1820 #define PKTOPT_EXTHDRCPY(type) \
1821 do {\
1822 	if (src->type) {\
1823 		size_t hlen;\
1824 		hlen = (((struct ip6_ext *)src->type)->ip6e_len + 1) << 3;\
1825 		dst->type = malloc(hlen, M_IP6OPT, M_NOWAIT);\
1826 		if (dst->type == NULL)\
1827 			goto bad;\
1828 		memcpy(dst->type, src->type, hlen);\
1829 	}\
1830 } while (/*CONSTCOND*/ 0)
1831 
1832 int
1833 copypktopts(struct ip6_pktopts *dst, struct ip6_pktopts *src)
1834 {
1835 	dst->ip6po_hlim = src->ip6po_hlim;
1836 	dst->ip6po_tclass = src->ip6po_tclass;
1837 	dst->ip6po_flags = src->ip6po_flags;
1838 	if (src->ip6po_pktinfo) {
1839 		dst->ip6po_pktinfo = malloc(sizeof(*dst->ip6po_pktinfo),
1840 		    M_IP6OPT, M_NOWAIT);
1841 		if (dst->ip6po_pktinfo == NULL)
1842 			goto bad;
1843 		*dst->ip6po_pktinfo = *src->ip6po_pktinfo;
1844 	}
1845 	PKTOPT_EXTHDRCPY(ip6po_hbh);
1846 	PKTOPT_EXTHDRCPY(ip6po_dest1);
1847 	PKTOPT_EXTHDRCPY(ip6po_dest2);
1848 	PKTOPT_EXTHDRCPY(ip6po_rthdr); /* not copy the cached route */
1849 	return (0);
1850 
1851   bad:
1852 	ip6_clearpktopts(dst, -1);
1853 	return (ENOBUFS);
1854 }
1855 #undef PKTOPT_EXTHDRCPY
1856 
1857 void
1858 ip6_freepcbopts(struct ip6_pktopts *pktopt)
1859 {
1860 	if (pktopt == NULL)
1861 		return;
1862 
1863 	ip6_clearpktopts(pktopt, -1);
1864 
1865 	free(pktopt, M_IP6OPT, 0);
1866 }
1867 
1868 /*
1869  * Set the IP6 multicast options in response to user setsockopt().
1870  */
1871 int
1872 ip6_setmoptions(int optname, struct ip6_moptions **im6op, struct mbuf *m,
1873     unsigned int rtableid)
1874 {
1875 	int error = 0;
1876 	u_int loop, ifindex;
1877 	struct ipv6_mreq *mreq;
1878 	struct ifnet *ifp;
1879 	struct ip6_moptions *im6o = *im6op;
1880 	struct in6_multi_mship *imm;
1881 	struct proc *p = curproc;	/* XXX */
1882 
1883 	if (im6o == NULL) {
1884 		/*
1885 		 * No multicast option buffer attached to the pcb;
1886 		 * allocate one and initialize to default values.
1887 		 */
1888 		im6o = malloc(sizeof(*im6o), M_IPMOPTS, M_WAITOK);
1889 		if (im6o == NULL)
1890 			return (ENOBUFS);
1891 		*im6op = im6o;
1892 		im6o->im6o_ifidx = 0;
1893 		im6o->im6o_hlim = ip6_defmcasthlim;
1894 		im6o->im6o_loop = IPV6_DEFAULT_MULTICAST_LOOP;
1895 		LIST_INIT(&im6o->im6o_memberships);
1896 	}
1897 
1898 	switch (optname) {
1899 
1900 	case IPV6_MULTICAST_IF:
1901 		/*
1902 		 * Select the interface for outgoing multicast packets.
1903 		 */
1904 		if (m == NULL || m->m_len != sizeof(u_int)) {
1905 			error = EINVAL;
1906 			break;
1907 		}
1908 		memcpy(&ifindex, mtod(m, u_int *), sizeof(ifindex));
1909 		if (ifindex != 0) {
1910 			ifp = if_get(ifindex);
1911 			if (ifp == NULL) {
1912 				error = ENXIO;	/* XXX EINVAL? */
1913 				break;
1914 			}
1915 			if (ifp->if_rdomain != rtable_l2(rtableid) ||
1916 			    (ifp->if_flags & IFF_MULTICAST) == 0) {
1917 				error = EADDRNOTAVAIL;
1918 				if_put(ifp);
1919 				break;
1920 			}
1921 			if_put(ifp);
1922 		}
1923 		im6o->im6o_ifidx = ifindex;
1924 		break;
1925 
1926 	case IPV6_MULTICAST_HOPS:
1927 	    {
1928 		/*
1929 		 * Set the IP6 hoplimit for outgoing multicast packets.
1930 		 */
1931 		int optval;
1932 		if (m == NULL || m->m_len != sizeof(int)) {
1933 			error = EINVAL;
1934 			break;
1935 		}
1936 		memcpy(&optval, mtod(m, u_int *), sizeof(optval));
1937 		if (optval < -1 || optval >= 256)
1938 			error = EINVAL;
1939 		else if (optval == -1)
1940 			im6o->im6o_hlim = ip6_defmcasthlim;
1941 		else
1942 			im6o->im6o_hlim = optval;
1943 		break;
1944 	    }
1945 
1946 	case IPV6_MULTICAST_LOOP:
1947 		/*
1948 		 * Set the loopback flag for outgoing multicast packets.
1949 		 * Must be zero or one.
1950 		 */
1951 		if (m == NULL || m->m_len != sizeof(u_int)) {
1952 			error = EINVAL;
1953 			break;
1954 		}
1955 		memcpy(&loop, mtod(m, u_int *), sizeof(loop));
1956 		if (loop > 1) {
1957 			error = EINVAL;
1958 			break;
1959 		}
1960 		im6o->im6o_loop = loop;
1961 		break;
1962 
1963 	case IPV6_JOIN_GROUP:
1964 		/*
1965 		 * Add a multicast group membership.
1966 		 * Group must be a valid IP6 multicast address.
1967 		 */
1968 		if (m == NULL || m->m_len != sizeof(struct ipv6_mreq)) {
1969 			error = EINVAL;
1970 			break;
1971 		}
1972 		mreq = mtod(m, struct ipv6_mreq *);
1973 		if (IN6_IS_ADDR_UNSPECIFIED(&mreq->ipv6mr_multiaddr)) {
1974 			/*
1975 			 * We use the unspecified address to specify to accept
1976 			 * all multicast addresses. Only super user is allowed
1977 			 * to do this.
1978 			 */
1979 			if (suser(p))
1980 			{
1981 				error = EACCES;
1982 				break;
1983 			}
1984 		} else if (!IN6_IS_ADDR_MULTICAST(&mreq->ipv6mr_multiaddr)) {
1985 			error = EINVAL;
1986 			break;
1987 		}
1988 
1989 		/*
1990 		 * If no interface was explicitly specified, choose an
1991 		 * appropriate one according to the given multicast address.
1992 		 */
1993 		if (mreq->ipv6mr_interface == 0) {
1994 			struct rtentry *rt;
1995 			struct sockaddr_in6 dst;
1996 
1997 			memset(&dst, 0, sizeof(dst));
1998 			dst.sin6_len = sizeof(dst);
1999 			dst.sin6_family = AF_INET6;
2000 			dst.sin6_addr = mreq->ipv6mr_multiaddr;
2001 			rt = rtalloc(sin6tosa(&dst), RT_RESOLVE, rtableid);
2002 			if (rt == NULL) {
2003 				error = EADDRNOTAVAIL;
2004 				break;
2005 			}
2006 			ifp = if_get(rt->rt_ifidx);
2007 			rtfree(rt);
2008 		} else {
2009 			/*
2010 			 * If the interface is specified, validate it.
2011 			 */
2012 			ifp = if_get(mreq->ipv6mr_interface);
2013 			if (ifp == NULL) {
2014 				error = ENXIO;	/* XXX EINVAL? */
2015 				break;
2016 			}
2017 		}
2018 
2019 		/*
2020 		 * See if we found an interface, and confirm that it
2021 		 * supports multicast
2022 		 */
2023 		if (ifp == NULL || ifp->if_rdomain != rtable_l2(rtableid) ||
2024 		    (ifp->if_flags & IFF_MULTICAST) == 0) {
2025 			if_put(ifp);
2026 			error = EADDRNOTAVAIL;
2027 			break;
2028 		}
2029 		/*
2030 		 * Put interface index into the multicast address,
2031 		 * if the address has link/interface-local scope.
2032 		 */
2033 		if (IN6_IS_SCOPE_EMBED(&mreq->ipv6mr_multiaddr)) {
2034 			mreq->ipv6mr_multiaddr.s6_addr16[1] =
2035 			    htons(ifp->if_index);
2036 		}
2037 		/*
2038 		 * See if the membership already exists.
2039 		 */
2040 		LIST_FOREACH(imm, &im6o->im6o_memberships, i6mm_chain)
2041 			if (imm->i6mm_maddr->in6m_ifidx == ifp->if_index &&
2042 			    IN6_ARE_ADDR_EQUAL(&imm->i6mm_maddr->in6m_addr,
2043 			    &mreq->ipv6mr_multiaddr))
2044 				break;
2045 		if (imm != NULL) {
2046 			if_put(ifp);
2047 			error = EADDRINUSE;
2048 			break;
2049 		}
2050 		/*
2051 		 * Everything looks good; add a new record to the multicast
2052 		 * address list for the given interface.
2053 		 */
2054 		imm = in6_joingroup(ifp, &mreq->ipv6mr_multiaddr, &error);
2055 		if_put(ifp);
2056 		if (!imm)
2057 			break;
2058 		LIST_INSERT_HEAD(&im6o->im6o_memberships, imm, i6mm_chain);
2059 		break;
2060 
2061 	case IPV6_LEAVE_GROUP:
2062 		/*
2063 		 * Drop a multicast group membership.
2064 		 * Group must be a valid IP6 multicast address.
2065 		 */
2066 		if (m == NULL || m->m_len != sizeof(struct ipv6_mreq)) {
2067 			error = EINVAL;
2068 			break;
2069 		}
2070 		mreq = mtod(m, struct ipv6_mreq *);
2071 		if (IN6_IS_ADDR_UNSPECIFIED(&mreq->ipv6mr_multiaddr)) {
2072 			if (suser(p)) {
2073 				error = EACCES;
2074 				break;
2075 			}
2076 		} else if (!IN6_IS_ADDR_MULTICAST(&mreq->ipv6mr_multiaddr)) {
2077 			error = EINVAL;
2078 			break;
2079 		}
2080 
2081 		/*
2082 		 * Put interface index into the multicast address,
2083 		 * if the address has link-local scope.
2084 		 */
2085 		if (IN6_IS_ADDR_MC_LINKLOCAL(&mreq->ipv6mr_multiaddr)) {
2086 			mreq->ipv6mr_multiaddr.s6_addr16[1] =
2087 			    htons(mreq->ipv6mr_interface);
2088 		}
2089 
2090 		/*
2091 		 * If an interface address was specified, get a pointer
2092 		 * to its ifnet structure.
2093 		 */
2094 		if (mreq->ipv6mr_interface == 0)
2095 			ifp = NULL;
2096 		else {
2097 			ifp = if_get(mreq->ipv6mr_interface);
2098 			if (ifp == NULL) {
2099 				error = ENXIO;	/* XXX EINVAL? */
2100 				break;
2101 			}
2102 		}
2103 
2104 		/*
2105 		 * Find the membership in the membership list.
2106 		 */
2107 		LIST_FOREACH(imm, &im6o->im6o_memberships, i6mm_chain) {
2108 			if ((ifp == NULL ||
2109 			    imm->i6mm_maddr->in6m_ifidx == ifp->if_index) &&
2110 			    IN6_ARE_ADDR_EQUAL(&imm->i6mm_maddr->in6m_addr,
2111 			    &mreq->ipv6mr_multiaddr))
2112 				break;
2113 		}
2114 
2115 		if_put(ifp);
2116 
2117 		if (imm == NULL) {
2118 			/* Unable to resolve interface */
2119 			error = EADDRNOTAVAIL;
2120 			break;
2121 		}
2122 		/*
2123 		 * Give up the multicast address record to which the
2124 		 * membership points.
2125 		 */
2126 		LIST_REMOVE(imm, i6mm_chain);
2127 		in6_leavegroup(imm);
2128 		break;
2129 
2130 	default:
2131 		error = EOPNOTSUPP;
2132 		break;
2133 	}
2134 
2135 	/*
2136 	 * If all options have default values, no need to keep the option
2137 	 * structure.
2138 	 */
2139 	if (im6o->im6o_ifidx == 0 &&
2140 	    im6o->im6o_hlim == ip6_defmcasthlim &&
2141 	    im6o->im6o_loop == IPV6_DEFAULT_MULTICAST_LOOP &&
2142 	    LIST_EMPTY(&im6o->im6o_memberships)) {
2143 		free(*im6op, M_IPMOPTS, sizeof(**im6op));
2144 		*im6op = NULL;
2145 	}
2146 
2147 	return (error);
2148 }
2149 
2150 /*
2151  * Return the IP6 multicast options in response to user getsockopt().
2152  */
2153 int
2154 ip6_getmoptions(int optname, struct ip6_moptions *im6o, struct mbuf *m)
2155 {
2156 	u_int *hlim, *loop, *ifindex;
2157 
2158 	switch (optname) {
2159 	case IPV6_MULTICAST_IF:
2160 		ifindex = mtod(m, u_int *);
2161 		m->m_len = sizeof(u_int);
2162 		if (im6o == NULL || im6o->im6o_ifidx == 0)
2163 			*ifindex = 0;
2164 		else
2165 			*ifindex = im6o->im6o_ifidx;
2166 		return (0);
2167 
2168 	case IPV6_MULTICAST_HOPS:
2169 		hlim = mtod(m, u_int *);
2170 		m->m_len = sizeof(u_int);
2171 		if (im6o == NULL)
2172 			*hlim = ip6_defmcasthlim;
2173 		else
2174 			*hlim = im6o->im6o_hlim;
2175 		return (0);
2176 
2177 	case IPV6_MULTICAST_LOOP:
2178 		loop = mtod(m, u_int *);
2179 		m->m_len = sizeof(u_int);
2180 		if (im6o == NULL)
2181 			*loop = ip6_defmcasthlim;
2182 		else
2183 			*loop = im6o->im6o_loop;
2184 		return (0);
2185 
2186 	default:
2187 		return (EOPNOTSUPP);
2188 	}
2189 }
2190 
2191 /*
2192  * Discard the IP6 multicast options.
2193  */
2194 void
2195 ip6_freemoptions(struct ip6_moptions *im6o)
2196 {
2197 	struct in6_multi_mship *imm;
2198 
2199 	if (im6o == NULL)
2200 		return;
2201 
2202 	while (!LIST_EMPTY(&im6o->im6o_memberships)) {
2203 		imm = LIST_FIRST(&im6o->im6o_memberships);
2204 		LIST_REMOVE(imm, i6mm_chain);
2205 		in6_leavegroup(imm);
2206 	}
2207 	free(im6o, M_IPMOPTS, sizeof(*im6o));
2208 }
2209 
2210 /*
2211  * Set IPv6 outgoing packet options based on advanced API.
2212  */
2213 int
2214 ip6_setpktopts(struct mbuf *control, struct ip6_pktopts *opt,
2215     struct ip6_pktopts *stickyopt, int priv, int uproto)
2216 {
2217 	u_int clen;
2218 	struct cmsghdr *cm = 0;
2219 	caddr_t cmsgs;
2220 	int error;
2221 
2222 	if (control == NULL || opt == NULL)
2223 		return (EINVAL);
2224 
2225 	ip6_initpktopts(opt);
2226 	if (stickyopt) {
2227 		int error;
2228 
2229 		/*
2230 		 * If stickyopt is provided, make a local copy of the options
2231 		 * for this particular packet, then override them by ancillary
2232 		 * objects.
2233 		 * XXX: copypktopts() does not copy the cached route to a next
2234 		 * hop (if any).  This is not very good in terms of efficiency,
2235 		 * but we can allow this since this option should be rarely
2236 		 * used.
2237 		 */
2238 		if ((error = copypktopts(opt, stickyopt)) != 0)
2239 			return (error);
2240 	}
2241 
2242 	/*
2243 	 * XXX: Currently, we assume all the optional information is stored
2244 	 * in a single mbuf.
2245 	 */
2246 	if (control->m_next)
2247 		return (EINVAL);
2248 
2249 	clen = control->m_len;
2250 	cmsgs = mtod(control, caddr_t);
2251 	do {
2252 		if (clen < CMSG_LEN(0))
2253 			return (EINVAL);
2254 		cm = (struct cmsghdr *)cmsgs;
2255 		if (cm->cmsg_len < CMSG_LEN(0) || cm->cmsg_len > clen ||
2256 		    CMSG_ALIGN(cm->cmsg_len) > clen)
2257 			return (EINVAL);
2258 		if (cm->cmsg_level == IPPROTO_IPV6) {
2259 			error = ip6_setpktopt(cm->cmsg_type, CMSG_DATA(cm),
2260 			    cm->cmsg_len - CMSG_LEN(0), opt, priv, 0, uproto);
2261 			if (error)
2262 				return (error);
2263 		}
2264 
2265 		clen -= CMSG_ALIGN(cm->cmsg_len);
2266 		cmsgs += CMSG_ALIGN(cm->cmsg_len);
2267 	} while (clen);
2268 
2269 	return (0);
2270 }
2271 
2272 /*
2273  * Set a particular packet option, as a sticky option or an ancillary data
2274  * item.  "len" can be 0 only when it's a sticky option.
2275  */
2276 int
2277 ip6_setpktopt(int optname, u_char *buf, int len, struct ip6_pktopts *opt,
2278     int priv, int sticky, int uproto)
2279 {
2280 	int minmtupolicy;
2281 
2282 	switch (optname) {
2283 	case IPV6_PKTINFO:
2284 	{
2285 		struct ifnet *ifp = NULL;
2286 		struct in6_pktinfo *pktinfo;
2287 
2288 		if (len != sizeof(struct in6_pktinfo))
2289 			return (EINVAL);
2290 
2291 		pktinfo = (struct in6_pktinfo *)buf;
2292 
2293 		/*
2294 		 * An application can clear any sticky IPV6_PKTINFO option by
2295 		 * doing a "regular" setsockopt with ipi6_addr being
2296 		 * in6addr_any and ipi6_ifindex being zero.
2297 		 * [RFC 3542, Section 6]
2298 		 */
2299 		if (opt->ip6po_pktinfo &&
2300 		    pktinfo->ipi6_ifindex == 0 &&
2301 		    IN6_IS_ADDR_UNSPECIFIED(&pktinfo->ipi6_addr)) {
2302 			ip6_clearpktopts(opt, optname);
2303 			break;
2304 		}
2305 
2306 		if (uproto == IPPROTO_TCP &&
2307 		    sticky && !IN6_IS_ADDR_UNSPECIFIED(&pktinfo->ipi6_addr)) {
2308 			return (EINVAL);
2309 		}
2310 
2311 		if (pktinfo->ipi6_ifindex) {
2312 			ifp = if_get(pktinfo->ipi6_ifindex);
2313 			if (ifp == NULL)
2314 				return (ENXIO);
2315 			if_put(ifp);
2316 		}
2317 
2318 		/*
2319 		 * We store the address anyway, and let in6_selectsrc()
2320 		 * validate the specified address.  This is because ipi6_addr
2321 		 * may not have enough information about its scope zone, and
2322 		 * we may need additional information (such as outgoing
2323 		 * interface or the scope zone of a destination address) to
2324 		 * disambiguate the scope.
2325 		 * XXX: the delay of the validation may confuse the
2326 		 * application when it is used as a sticky option.
2327 		 */
2328 		if (opt->ip6po_pktinfo == NULL) {
2329 			opt->ip6po_pktinfo = malloc(sizeof(*pktinfo),
2330 			    M_IP6OPT, M_NOWAIT);
2331 			if (opt->ip6po_pktinfo == NULL)
2332 				return (ENOBUFS);
2333 		}
2334 		bcopy(pktinfo, opt->ip6po_pktinfo, sizeof(*pktinfo));
2335 		break;
2336 	}
2337 
2338 	case IPV6_HOPLIMIT:
2339 	{
2340 		int *hlimp;
2341 
2342 		/*
2343 		 * RFC 3542 deprecated the usage of sticky IPV6_HOPLIMIT
2344 		 * to simplify the ordering among hoplimit options.
2345 		 */
2346 		if (sticky)
2347 			return (ENOPROTOOPT);
2348 
2349 		if (len != sizeof(int))
2350 			return (EINVAL);
2351 		hlimp = (int *)buf;
2352 		if (*hlimp < -1 || *hlimp > 255)
2353 			return (EINVAL);
2354 
2355 		opt->ip6po_hlim = *hlimp;
2356 		break;
2357 	}
2358 
2359 	case IPV6_TCLASS:
2360 	{
2361 		int tclass;
2362 
2363 		if (len != sizeof(int))
2364 			return (EINVAL);
2365 		tclass = *(int *)buf;
2366 		if (tclass < -1 || tclass > 255)
2367 			return (EINVAL);
2368 
2369 		opt->ip6po_tclass = tclass;
2370 		break;
2371 	}
2372 	case IPV6_HOPOPTS:
2373 	{
2374 		struct ip6_hbh *hbh;
2375 		int hbhlen;
2376 
2377 		/*
2378 		 * XXX: We don't allow a non-privileged user to set ANY HbH
2379 		 * options, since per-option restriction has too much
2380 		 * overhead.
2381 		 */
2382 		if (!priv)
2383 			return (EPERM);
2384 
2385 		if (len == 0) {
2386 			ip6_clearpktopts(opt, IPV6_HOPOPTS);
2387 			break;	/* just remove the option */
2388 		}
2389 
2390 		/* message length validation */
2391 		if (len < sizeof(struct ip6_hbh))
2392 			return (EINVAL);
2393 		hbh = (struct ip6_hbh *)buf;
2394 		hbhlen = (hbh->ip6h_len + 1) << 3;
2395 		if (len != hbhlen)
2396 			return (EINVAL);
2397 
2398 		/* turn off the previous option, then set the new option. */
2399 		ip6_clearpktopts(opt, IPV6_HOPOPTS);
2400 		opt->ip6po_hbh = malloc(hbhlen, M_IP6OPT, M_NOWAIT);
2401 		if (opt->ip6po_hbh == NULL)
2402 			return (ENOBUFS);
2403 		memcpy(opt->ip6po_hbh, hbh, hbhlen);
2404 
2405 		break;
2406 	}
2407 
2408 	case IPV6_DSTOPTS:
2409 	case IPV6_RTHDRDSTOPTS:
2410 	{
2411 		struct ip6_dest *dest, **newdest = NULL;
2412 		int destlen;
2413 
2414 		if (!priv)	/* XXX: see the comment for IPV6_HOPOPTS */
2415 			return (EPERM);
2416 
2417 		if (len == 0) {
2418 			ip6_clearpktopts(opt, optname);
2419 			break;	/* just remove the option */
2420 		}
2421 
2422 		/* message length validation */
2423 		if (len < sizeof(struct ip6_dest))
2424 			return (EINVAL);
2425 		dest = (struct ip6_dest *)buf;
2426 		destlen = (dest->ip6d_len + 1) << 3;
2427 		if (len != destlen)
2428 			return (EINVAL);
2429 		/*
2430 		 * Determine the position that the destination options header
2431 		 * should be inserted; before or after the routing header.
2432 		 */
2433 		switch (optname) {
2434 		case IPV6_RTHDRDSTOPTS:
2435 			newdest = &opt->ip6po_dest1;
2436 			break;
2437 		case IPV6_DSTOPTS:
2438 			newdest = &opt->ip6po_dest2;
2439 			break;
2440 		}
2441 
2442 		/* turn off the previous option, then set the new option. */
2443 		ip6_clearpktopts(opt, optname);
2444 		*newdest = malloc(destlen, M_IP6OPT, M_NOWAIT);
2445 		if (*newdest == NULL)
2446 			return (ENOBUFS);
2447 		memcpy(*newdest, dest, destlen);
2448 
2449 		break;
2450 	}
2451 
2452 	case IPV6_RTHDR:
2453 	{
2454 		struct ip6_rthdr *rth;
2455 		int rthlen;
2456 
2457 		if (len == 0) {
2458 			ip6_clearpktopts(opt, IPV6_RTHDR);
2459 			break;	/* just remove the option */
2460 		}
2461 
2462 		/* message length validation */
2463 		if (len < sizeof(struct ip6_rthdr))
2464 			return (EINVAL);
2465 		rth = (struct ip6_rthdr *)buf;
2466 		rthlen = (rth->ip6r_len + 1) << 3;
2467 		if (len != rthlen)
2468 			return (EINVAL);
2469 
2470 		switch (rth->ip6r_type) {
2471 		case IPV6_RTHDR_TYPE_0:
2472 			if (rth->ip6r_len == 0)	/* must contain one addr */
2473 				return (EINVAL);
2474 			if (rth->ip6r_len % 2) /* length must be even */
2475 				return (EINVAL);
2476 			if (rth->ip6r_len / 2 != rth->ip6r_segleft)
2477 				return (EINVAL);
2478 			break;
2479 		default:
2480 			return (EINVAL);	/* not supported */
2481 		}
2482 		/* turn off the previous option */
2483 		ip6_clearpktopts(opt, IPV6_RTHDR);
2484 		opt->ip6po_rthdr = malloc(rthlen, M_IP6OPT, M_NOWAIT);
2485 		if (opt->ip6po_rthdr == NULL)
2486 			return (ENOBUFS);
2487 		memcpy(opt->ip6po_rthdr, rth, rthlen);
2488 		break;
2489 	}
2490 
2491 	case IPV6_USE_MIN_MTU:
2492 		if (len != sizeof(int))
2493 			return (EINVAL);
2494 		minmtupolicy = *(int *)buf;
2495 		if (minmtupolicy != IP6PO_MINMTU_MCASTONLY &&
2496 		    minmtupolicy != IP6PO_MINMTU_DISABLE &&
2497 		    minmtupolicy != IP6PO_MINMTU_ALL) {
2498 			return (EINVAL);
2499 		}
2500 		opt->ip6po_minmtu = minmtupolicy;
2501 		break;
2502 
2503 	case IPV6_DONTFRAG:
2504 		if (len != sizeof(int))
2505 			return (EINVAL);
2506 
2507 		if (uproto == IPPROTO_TCP || *(int *)buf == 0) {
2508 			/*
2509 			 * we ignore this option for TCP sockets.
2510 			 * (RFC3542 leaves this case unspecified.)
2511 			 */
2512 			opt->ip6po_flags &= ~IP6PO_DONTFRAG;
2513 		} else
2514 			opt->ip6po_flags |= IP6PO_DONTFRAG;
2515 		break;
2516 
2517 	default:
2518 		return (ENOPROTOOPT);
2519 	} /* end of switch */
2520 
2521 	return (0);
2522 }
2523 
2524 /*
2525  * Routine called from ip6_output() to loop back a copy of an IP6 multicast
2526  * packet to the input queue of a specified interface.
2527  */
2528 void
2529 ip6_mloopback(struct ifnet *ifp, struct mbuf *m, struct sockaddr_in6 *dst)
2530 {
2531 	struct mbuf *copym;
2532 	struct ip6_hdr *ip6;
2533 
2534 	/*
2535 	 * Duplicate the packet.
2536 	 */
2537 	copym = m_copym(m, 0, M_COPYALL, M_NOWAIT);
2538 	if (copym == NULL)
2539 		return;
2540 
2541 	/*
2542 	 * Make sure to deep-copy IPv6 header portion in case the data
2543 	 * is in an mbuf cluster, so that we can safely override the IPv6
2544 	 * header portion later.
2545 	 */
2546 	if ((copym->m_flags & M_EXT) != 0 ||
2547 	    copym->m_len < sizeof(struct ip6_hdr)) {
2548 		copym = m_pullup(copym, sizeof(struct ip6_hdr));
2549 		if (copym == NULL)
2550 			return;
2551 	}
2552 
2553 #ifdef DIAGNOSTIC
2554 	if (copym->m_len < sizeof(*ip6)) {
2555 		m_freem(copym);
2556 		return;
2557 	}
2558 #endif
2559 
2560 	ip6 = mtod(copym, struct ip6_hdr *);
2561 	if (IN6_IS_SCOPE_EMBED(&ip6->ip6_src))
2562 		ip6->ip6_src.s6_addr16[1] = 0;
2563 	if (IN6_IS_SCOPE_EMBED(&ip6->ip6_dst))
2564 		ip6->ip6_dst.s6_addr16[1] = 0;
2565 
2566 	if_input_local(ifp, copym, dst->sin6_family);
2567 }
2568 
2569 /*
2570  * Chop IPv6 header off from the payload.
2571  */
2572 int
2573 ip6_splithdr(struct mbuf *m, struct ip6_exthdrs *exthdrs)
2574 {
2575 	struct mbuf *mh;
2576 	struct ip6_hdr *ip6;
2577 
2578 	ip6 = mtod(m, struct ip6_hdr *);
2579 	if (m->m_len > sizeof(*ip6)) {
2580 		MGET(mh, M_DONTWAIT, MT_HEADER);
2581 		if (mh == NULL) {
2582 			m_freem(m);
2583 			return ENOBUFS;
2584 		}
2585 		M_MOVE_PKTHDR(mh, m);
2586 		m_align(mh, sizeof(*ip6));
2587 		m->m_len -= sizeof(*ip6);
2588 		m->m_data += sizeof(*ip6);
2589 		mh->m_next = m;
2590 		m = mh;
2591 		m->m_len = sizeof(*ip6);
2592 		bcopy((caddr_t)ip6, mtod(m, caddr_t), sizeof(*ip6));
2593 	}
2594 	exthdrs->ip6e_ip6 = m;
2595 	return 0;
2596 }
2597 
2598 u_int32_t
2599 ip6_randomid(void)
2600 {
2601 	return idgen32(&ip6_id_ctx);
2602 }
2603 
2604 void
2605 ip6_randomid_init(void)
2606 {
2607 	idgen32_init(&ip6_id_ctx);
2608 }
2609 
2610 /*
2611  *	Compute significant parts of the IPv6 checksum pseudo-header
2612  *	for use in a delayed TCP/UDP checksum calculation.
2613  */
2614 static __inline u_int16_t __attribute__((__unused__))
2615 in6_cksum_phdr(const struct in6_addr *src, const struct in6_addr *dst,
2616     u_int32_t len, u_int32_t nxt)
2617 {
2618 	u_int32_t sum = 0;
2619 	const u_int16_t *w;
2620 
2621 	w = (const u_int16_t *) src;
2622 	sum += w[0];
2623 	if (!IN6_IS_SCOPE_EMBED(src))
2624 		sum += w[1];
2625 	sum += w[2]; sum += w[3]; sum += w[4]; sum += w[5];
2626 	sum += w[6]; sum += w[7];
2627 
2628 	w = (const u_int16_t *) dst;
2629 	sum += w[0];
2630 	if (!IN6_IS_SCOPE_EMBED(dst))
2631 		sum += w[1];
2632 	sum += w[2]; sum += w[3]; sum += w[4]; sum += w[5];
2633 	sum += w[6]; sum += w[7];
2634 
2635 	sum += (u_int16_t)(len >> 16) + (u_int16_t)(len /*& 0xffff*/);
2636 
2637 	sum += (u_int16_t)(nxt >> 16) + (u_int16_t)(nxt /*& 0xffff*/);
2638 
2639 	sum = (u_int16_t)(sum >> 16) + (u_int16_t)(sum /*& 0xffff*/);
2640 
2641 	if (sum > 0xffff)
2642 		sum -= 0xffff;
2643 
2644 	return (sum);
2645 }
2646 
2647 /*
2648  * Process a delayed payload checksum calculation.
2649  */
2650 void
2651 in6_delayed_cksum(struct mbuf *m, u_int8_t nxt)
2652 {
2653 	int nxtp, offset;
2654 	u_int16_t csum;
2655 
2656 	offset = ip6_lasthdr(m, 0, IPPROTO_IPV6, &nxtp);
2657 	if (offset <= 0 || nxtp != nxt)
2658 		/* If the desired next protocol isn't found, punt. */
2659 		return;
2660 	csum = (u_int16_t)(in6_cksum(m, 0, offset, m->m_pkthdr.len - offset));
2661 
2662 	switch (nxt) {
2663 	case IPPROTO_TCP:
2664 		offset += offsetof(struct tcphdr, th_sum);
2665 		break;
2666 
2667 	case IPPROTO_UDP:
2668 		offset += offsetof(struct udphdr, uh_sum);
2669 		if (csum == 0)
2670 			csum = 0xffff;
2671 		break;
2672 
2673 	case IPPROTO_ICMPV6:
2674 		offset += offsetof(struct icmp6_hdr, icmp6_cksum);
2675 		break;
2676 	}
2677 
2678 	if ((offset + sizeof(u_int16_t)) > m->m_len)
2679 		m_copyback(m, offset, sizeof(csum), &csum, M_NOWAIT);
2680 	else
2681 		*(u_int16_t *)(mtod(m, caddr_t) + offset) = csum;
2682 }
2683 
2684 void
2685 in6_proto_cksum_out(struct mbuf *m, struct ifnet *ifp)
2686 {
2687 	struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
2688 
2689 	/* some hw and in6_delayed_cksum need the pseudo header cksum */
2690 	if (m->m_pkthdr.csum_flags &
2691 	    (M_TCP_CSUM_OUT|M_UDP_CSUM_OUT|M_ICMP_CSUM_OUT)) {
2692 		int nxt, offset;
2693 		u_int16_t csum;
2694 
2695 		offset = ip6_lasthdr(m, 0, IPPROTO_IPV6, &nxt);
2696 		csum = in6_cksum_phdr(&ip6->ip6_src, &ip6->ip6_dst,
2697 		    htonl(m->m_pkthdr.len - offset), htonl(nxt));
2698 		if (nxt == IPPROTO_TCP)
2699 			offset += offsetof(struct tcphdr, th_sum);
2700 		else if (nxt == IPPROTO_UDP)
2701 			offset += offsetof(struct udphdr, uh_sum);
2702 		else if (nxt == IPPROTO_ICMPV6)
2703 			offset += offsetof(struct icmp6_hdr, icmp6_cksum);
2704 		if ((offset + sizeof(u_int16_t)) > m->m_len)
2705 			m_copyback(m, offset, sizeof(csum), &csum, M_NOWAIT);
2706 		else
2707 			*(u_int16_t *)(mtod(m, caddr_t) + offset) = csum;
2708 	}
2709 
2710 	if (m->m_pkthdr.csum_flags & M_TCP_CSUM_OUT) {
2711 		if (!ifp || !(ifp->if_capabilities & IFCAP_CSUM_TCPv6) ||
2712 		    ip6->ip6_nxt != IPPROTO_TCP ||
2713 		    ifp->if_bridgeidx != 0) {
2714 			tcpstat_inc(tcps_outswcsum);
2715 			in6_delayed_cksum(m, IPPROTO_TCP);
2716 			m->m_pkthdr.csum_flags &= ~M_TCP_CSUM_OUT; /* Clear */
2717 		}
2718 	} else if (m->m_pkthdr.csum_flags & M_UDP_CSUM_OUT) {
2719 		if (!ifp || !(ifp->if_capabilities & IFCAP_CSUM_UDPv6) ||
2720 		    ip6->ip6_nxt != IPPROTO_UDP ||
2721 		    ifp->if_bridgeidx != 0) {
2722 			udpstat_inc(udps_outswcsum);
2723 			in6_delayed_cksum(m, IPPROTO_UDP);
2724 			m->m_pkthdr.csum_flags &= ~M_UDP_CSUM_OUT; /* Clear */
2725 		}
2726 	} else if (m->m_pkthdr.csum_flags & M_ICMP_CSUM_OUT) {
2727 		in6_delayed_cksum(m, IPPROTO_ICMPV6);
2728 		m->m_pkthdr.csum_flags &= ~M_ICMP_CSUM_OUT; /* Clear */
2729 	}
2730 }
2731 
2732 #ifdef IPSEC
2733 struct tdb *
2734 ip6_output_ipsec_lookup(struct mbuf *m, int *error, struct inpcb *inp)
2735 {
2736 	struct tdb *tdb;
2737 	struct m_tag *mtag;
2738 	struct tdb_ident *tdbi;
2739 
2740 	/*
2741 	 * Check if there was an outgoing SA bound to the flow
2742 	 * from a transport protocol.
2743 	 */
2744 
2745 	/* Do we have any pending SAs to apply ? */
2746 	tdb = ipsp_spd_lookup(m, AF_INET6, sizeof(struct ip6_hdr),
2747 	    error, IPSP_DIRECTION_OUT, NULL, inp, 0);
2748 
2749 	if (tdb == NULL)
2750 		return NULL;
2751 	/* Loop detection */
2752 	for (mtag = m_tag_first(m); mtag != NULL; mtag = m_tag_next(m, mtag)) {
2753 		if (mtag->m_tag_id != PACKET_TAG_IPSEC_OUT_DONE)
2754 			continue;
2755 		tdbi = (struct tdb_ident *)(mtag + 1);
2756 		if (tdbi->spi == tdb->tdb_spi &&
2757 		    tdbi->proto == tdb->tdb_sproto &&
2758 		    tdbi->rdomain == tdb->tdb_rdomain &&
2759 		    !memcmp(&tdbi->dst, &tdb->tdb_dst,
2760 		    sizeof(union sockaddr_union))) {
2761 			/* no IPsec needed */
2762 			return NULL;
2763 		}
2764 	}
2765 	return tdb;
2766 }
2767 
2768 int
2769 ip6_output_ipsec_send(struct tdb *tdb, struct mbuf *m, struct route_in6 *ro,
2770     int tunalready, int fwd)
2771 {
2772 #if NPF > 0
2773 	struct ifnet *encif;
2774 #endif
2775 	struct ip6_hdr *ip6;
2776 	int error;
2777 
2778 #if NPF > 0
2779 	/*
2780 	 * Packet filter
2781 	 */
2782 	if ((encif = enc_getif(tdb->tdb_rdomain, tdb->tdb_tap)) == NULL ||
2783 	    pf_test(AF_INET6, fwd ? PF_FWD : PF_OUT, encif, &m) != PF_PASS) {
2784 		m_freem(m);
2785 		return EACCES;
2786 	}
2787 	if (m == NULL)
2788 		return 0;
2789 	/*
2790 	 * PF_TAG_REROUTE handling or not...
2791 	 * Packet is entering IPsec so the routing is
2792 	 * already overruled by the IPsec policy.
2793 	 * Until now the change was not reconsidered.
2794 	 * What's the behaviour?
2795 	 */
2796 	in6_proto_cksum_out(m, encif);
2797 #endif
2798 
2799 	/* Check if we are allowed to fragment */
2800 	ip6 = mtod(m, struct ip6_hdr *);
2801 	if (ip_mtudisc && tdb->tdb_mtu &&
2802 	    sizeof(struct ip6_hdr) + ntohs(ip6->ip6_plen) > tdb->tdb_mtu &&
2803 	    tdb->tdb_mtutimeout > gettime()) {
2804 		struct rtentry *rt = NULL;
2805 		int rt_mtucloned = 0;
2806 		int transportmode = 0;
2807 
2808 		transportmode = (tdb->tdb_dst.sa.sa_family == AF_INET6) &&
2809 		    (IN6_ARE_ADDR_EQUAL(&tdb->tdb_dst.sin6.sin6_addr,
2810 		    &ip6->ip6_dst));
2811 
2812 		/* Find a host route to store the mtu in */
2813 		if (ro != NULL)
2814 			rt = ro->ro_rt;
2815 		/* but don't add a PMTU route for transport mode SAs */
2816 		if (transportmode)
2817 			rt = NULL;
2818 		else if (rt == NULL || (rt->rt_flags & RTF_HOST) == 0) {
2819 			struct sockaddr_in6 sin6;
2820 
2821 			memset(&sin6, 0, sizeof(sin6));
2822 			sin6.sin6_family = AF_INET6;
2823 			sin6.sin6_len = sizeof(sin6);
2824 			sin6.sin6_addr = ip6->ip6_dst;
2825 			sin6.sin6_scope_id =
2826 			    in6_addr2scopeid(m->m_pkthdr.ph_ifidx,
2827 			    &ip6->ip6_dst);
2828 			error = in6_embedscope(&ip6->ip6_dst, &sin6, NULL);
2829 			if (error) {
2830 				/* should be impossible */
2831 				ipsecstat_inc(ipsec_odrops);
2832 				m_freem(m);
2833 				return error;
2834 			}
2835 			rt = icmp6_mtudisc_clone(&sin6,
2836 			    m->m_pkthdr.ph_rtableid, 1);
2837 			rt_mtucloned = 1;
2838 		}
2839 		DPRINTF(("%s: spi %08x mtu %d rt %p cloned %d\n", __func__,
2840 		    ntohl(tdb->tdb_spi), tdb->tdb_mtu, rt, rt_mtucloned));
2841 		if (rt != NULL) {
2842 			rt->rt_mtu = tdb->tdb_mtu;
2843 			if (ro != NULL && ro->ro_rt != NULL) {
2844 				rtfree(ro->ro_rt);
2845 				ro->ro_rt = rtalloc(sin6tosa(&ro->ro_dst),
2846 				    RT_RESOLVE, m->m_pkthdr.ph_rtableid);
2847 			}
2848 			if (rt_mtucloned)
2849 				rtfree(rt);
2850 		}
2851 		ipsec_adjust_mtu(m, tdb->tdb_mtu);
2852 		m_freem(m);
2853 		return EMSGSIZE;
2854 	}
2855 	/* propagate don't fragment for v6-over-v6 */
2856 	if (ip_mtudisc)
2857 		SET(m->m_pkthdr.csum_flags, M_IPV6_DF_OUT);
2858 
2859 	/*
2860 	 * Clear these -- they'll be set in the recursive invocation
2861 	 * as needed.
2862 	 */
2863 	m->m_flags &= ~(M_BCAST | M_MCAST);
2864 
2865 	/* Callee frees mbuf */
2866 	error = ipsp_process_packet(m, tdb, AF_INET6, tunalready);
2867 	if (error) {
2868 		ipsecstat_inc(ipsec_odrops);
2869 		tdb->tdb_odrops++;
2870 	}
2871 	return error;
2872 }
2873 #endif /* IPSEC */
2874