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