xref: /freebsd/sys/netinet6/ip6_output.c (revision 069a67374ed9641ff1ada2aecaac1cc61a560649)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the project nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  *
31  *	$KAME: ip6_output.c,v 1.279 2002/01/26 06:12:30 jinmei Exp $
32  */
33 
34 /*-
35  * Copyright (c) 1982, 1986, 1988, 1990, 1993
36  *	The Regents of the University of California.  All rights reserved.
37  *
38  * Redistribution and use in source and binary forms, with or without
39  * modification, are permitted provided that the following conditions
40  * are met:
41  * 1. Redistributions of source code must retain the above copyright
42  *    notice, this list of conditions and the following disclaimer.
43  * 2. Redistributions in binary form must reproduce the above copyright
44  *    notice, this list of conditions and the following disclaimer in the
45  *    documentation and/or other materials provided with the distribution.
46  * 3. Neither the name of the University nor the names of its contributors
47  *    may be used to endorse or promote products derived from this software
48  *    without specific prior written permission.
49  *
50  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
51  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
52  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
53  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
54  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
55  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
56  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
57  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
58  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
59  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
60  * SUCH DAMAGE.
61  */
62 
63 #include "opt_inet.h"
64 #include "opt_inet6.h"
65 #include "opt_ipsec.h"
66 #include "opt_kern_tls.h"
67 #include "opt_ratelimit.h"
68 #include "opt_route.h"
69 #include "opt_rss.h"
70 #include "opt_sctp.h"
71 
72 #include <sys/param.h>
73 #include <sys/kernel.h>
74 #include <sys/ktls.h>
75 #include <sys/malloc.h>
76 #include <sys/mbuf.h>
77 #include <sys/errno.h>
78 #include <sys/priv.h>
79 #include <sys/proc.h>
80 #include <sys/protosw.h>
81 #include <sys/socket.h>
82 #include <sys/socketvar.h>
83 #include <sys/syslog.h>
84 #include <sys/ucred.h>
85 
86 #include <machine/in_cksum.h>
87 
88 #include <net/if.h>
89 #include <net/if_var.h>
90 #include <net/if_private.h>
91 #include <net/if_vlan_var.h>
92 #include <net/if_llatbl.h>
93 #include <net/ethernet.h>
94 #include <net/netisr.h>
95 #include <net/route.h>
96 #include <net/route/nhop.h>
97 #include <net/pfil.h>
98 #include <net/rss_config.h>
99 #include <net/vnet.h>
100 
101 #include <netinet/in.h>
102 #include <netinet/in_var.h>
103 #include <netinet/ip_var.h>
104 #include <netinet6/in6_fib.h>
105 #include <netinet6/in6_var.h>
106 #include <netinet/ip6.h>
107 #include <netinet/icmp6.h>
108 #include <netinet6/ip6_var.h>
109 #include <netinet/in_pcb.h>
110 #include <netinet/tcp_var.h>
111 #include <netinet6/nd6.h>
112 #include <netinet6/in6_rss.h>
113 
114 #include <netipsec/ipsec_support.h>
115 #if defined(SCTP) || defined(SCTP_SUPPORT)
116 #include <netinet/sctp.h>
117 #include <netinet/sctp_crc32.h>
118 #endif
119 
120 #include <netinet6/scope6_var.h>
121 
122 extern int in6_mcast_loop;
123 
124 struct ip6_exthdrs {
125 	struct mbuf *ip6e_ip6;
126 	struct mbuf *ip6e_hbh;
127 	struct mbuf *ip6e_dest1;
128 	struct mbuf *ip6e_rthdr;
129 	struct mbuf *ip6e_dest2;
130 };
131 
132 static MALLOC_DEFINE(M_IP6OPT, "ip6opt", "IPv6 options");
133 
134 static int ip6_pcbopt(int, u_char *, int, struct ip6_pktopts **,
135 			   struct ucred *, int);
136 static int ip6_pcbopts(struct ip6_pktopts **, struct mbuf *,
137 	struct socket *, struct sockopt *);
138 static int ip6_getpcbopt(struct inpcb *, int, struct sockopt *);
139 static int ip6_setpktopt(int, u_char *, int, struct ip6_pktopts *,
140 	struct ucred *, int, int, int);
141 
142 static int ip6_copyexthdr(struct mbuf **, caddr_t, int);
143 static int ip6_insertfraghdr(struct mbuf *, struct mbuf *, int,
144 	struct ip6_frag **);
145 static int ip6_splithdr(struct mbuf *, struct ip6_exthdrs *);
146 static void ip6_getpmtu(struct route_in6 *, int,
147 	struct ifnet *, const struct in6_addr *, u_long *, u_int, u_int);
148 static void ip6_calcmtu(struct ifnet *, const struct in6_addr *, u_long,
149 	u_long *, u_int);
150 static int ip6_getpmtu_ctl(u_int, const struct in6_addr *, u_long *);
151 static int copypktopts(struct ip6_pktopts *, struct ip6_pktopts *, int);
152 
153 /*
154  * Make an extension header from option data.  hp is the source,
155  * mp is the destination, and _ol is the optlen.
156  */
157 #define	MAKE_EXTHDR(hp, mp, _ol)					\
158     do {								\
159 	struct ip6_ext *eh = (struct ip6_ext *)(hp);		\
160 	error = ip6_copyexthdr((mp), (caddr_t)(hp),		\
161 	    ((eh)->ip6e_len + 1) << 3);				\
162 	if (error)						\
163 		goto freehdrs;					\
164 	(_ol) += (*(mp))->m_len;				\
165     } while (/*CONSTCOND*/ 0)
166 
167 /*
168  * Form a chain of extension headers.
169  * m is the extension header mbuf
170  * mp is the previous mbuf in the chain
171  * p is the next header
172  * i is the type of option.
173  */
174 #define MAKE_CHAIN(m, mp, p, i)\
175     do {\
176 	if (m) {\
177 		if (!hdrsplit) \
178 			panic("%s:%d: assumption failed: "\
179 			    "hdr not split: hdrsplit %d exthdrs %p",\
180 			    __func__, __LINE__, hdrsplit, &exthdrs);\
181 		*mtod((m), u_char *) = *(p);\
182 		*(p) = (i);\
183 		p = mtod((m), u_char *);\
184 		(m)->m_next = (mp)->m_next;\
185 		(mp)->m_next = (m);\
186 		(mp) = (m);\
187 	}\
188     } while (/*CONSTCOND*/ 0)
189 
190 void
in6_delayed_cksum(struct mbuf * m,uint32_t plen,u_short offset)191 in6_delayed_cksum(struct mbuf *m, uint32_t plen, u_short offset)
192 {
193 	u_short csum;
194 
195 	csum = in_cksum_skip(m, offset + plen, offset);
196 	if (m->m_pkthdr.csum_flags & CSUM_UDP_IPV6 && csum == 0)
197 		csum = 0xffff;
198 	offset += m->m_pkthdr.csum_data;	/* checksum offset */
199 
200 	if (offset + sizeof(csum) > m->m_len)
201 		m_copyback(m, offset, sizeof(csum), (caddr_t)&csum);
202 	else
203 		*(u_short *)mtodo(m, offset) = csum;
204 }
205 
206 static void
ip6_output_delayed_csum(struct mbuf * m,struct ifnet * ifp,int csum_flags,int plen,int optlen)207 ip6_output_delayed_csum(struct mbuf *m, struct ifnet *ifp, int csum_flags,
208     int plen, int optlen)
209 {
210 
211 	KASSERT((plen >= optlen), ("%s:%d: plen %d < optlen %d, m %p, ifp %p "
212 	    "csum_flags %#x",
213 	    __func__, __LINE__, plen, optlen, m, ifp, csum_flags));
214 
215 	if (csum_flags & CSUM_DELAY_DATA_IPV6) {
216 		in6_delayed_cksum(m, plen - optlen,
217 		    sizeof(struct ip6_hdr) + optlen);
218 		m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA_IPV6;
219 	}
220 #if defined(SCTP) || defined(SCTP_SUPPORT)
221 	if (csum_flags & CSUM_SCTP_IPV6) {
222 		sctp_delayed_cksum(m, sizeof(struct ip6_hdr) + optlen);
223 		m->m_pkthdr.csum_flags &= ~CSUM_SCTP_IPV6;
224 	}
225 #endif
226 }
227 
228 int
ip6_fragment(struct ifnet * ifp,struct mbuf * m0,int hlen,u_char nextproto,int fraglen,uint32_t id)229 ip6_fragment(struct ifnet *ifp, struct mbuf *m0, int hlen, u_char nextproto,
230     int fraglen , uint32_t id)
231 {
232 	struct mbuf *m, **mnext, *m_frgpart;
233 	struct ip6_hdr *ip6, *mhip6;
234 	struct ip6_frag *ip6f;
235 	int off;
236 	int error;
237 	int tlen = m0->m_pkthdr.len;
238 
239 	KASSERT((fraglen % 8 == 0), ("Fragment length must be a multiple of 8"));
240 
241 	m = m0;
242 	ip6 = mtod(m, struct ip6_hdr *);
243 	mnext = &m->m_nextpkt;
244 
245 	for (off = hlen; off < tlen; off += fraglen) {
246 		m = m_gethdr(M_NOWAIT, MT_DATA);
247 		if (!m) {
248 			IP6STAT_INC(ip6s_odropped);
249 			return (ENOBUFS);
250 		}
251 
252 		/*
253 		 * Make sure the complete packet header gets copied
254 		 * from the originating mbuf to the newly created
255 		 * mbuf. This also ensures that existing firewall
256 		 * classification(s), VLAN tags and so on get copied
257 		 * to the resulting fragmented packet(s):
258 		 */
259 		if (m_dup_pkthdr(m, m0, M_NOWAIT) == 0) {
260 			m_free(m);
261 			IP6STAT_INC(ip6s_odropped);
262 			return (ENOBUFS);
263 		}
264 
265 		*mnext = m;
266 		mnext = &m->m_nextpkt;
267 		m->m_data += max_linkhdr;
268 		mhip6 = mtod(m, struct ip6_hdr *);
269 		*mhip6 = *ip6;
270 		m->m_len = sizeof(*mhip6);
271 		error = ip6_insertfraghdr(m0, m, hlen, &ip6f);
272 		if (error) {
273 			IP6STAT_INC(ip6s_odropped);
274 			return (error);
275 		}
276 		ip6f->ip6f_offlg = htons((u_short)((off - hlen) & ~7));
277 		if (off + fraglen >= tlen)
278 			fraglen = tlen - off;
279 		else
280 			ip6f->ip6f_offlg |= IP6F_MORE_FRAG;
281 		mhip6->ip6_plen = htons((u_short)(fraglen + hlen +
282 		    sizeof(*ip6f) - sizeof(struct ip6_hdr)));
283 		if ((m_frgpart = m_copym(m0, off, fraglen, M_NOWAIT)) == NULL) {
284 			IP6STAT_INC(ip6s_odropped);
285 			return (ENOBUFS);
286 		}
287 		m_cat(m, m_frgpart);
288 		m->m_pkthdr.len = fraglen + hlen + sizeof(*ip6f);
289 		ip6f->ip6f_reserved = 0;
290 		ip6f->ip6f_ident = id;
291 		ip6f->ip6f_nxt = nextproto;
292 		IP6STAT_INC(ip6s_ofragments);
293 		in6_ifstat_inc(ifp, ifs6_out_fragcreat);
294 	}
295 
296 	return (0);
297 }
298 
299 static int
ip6_output_send(struct inpcb * inp,struct ifnet * ifp,struct ifnet * origifp,struct mbuf * m,struct sockaddr_in6 * dst,struct route_in6 * ro,bool stamp_tag)300 ip6_output_send(struct inpcb *inp, struct ifnet *ifp, struct ifnet *origifp,
301     struct mbuf *m, struct sockaddr_in6 *dst, struct route_in6 *ro,
302     bool stamp_tag)
303 {
304 #ifdef KERN_TLS
305 	struct ktls_session *tls = NULL;
306 #endif
307 	struct m_snd_tag *mst;
308 	int error;
309 
310 	MPASS((m->m_pkthdr.csum_flags & CSUM_SND_TAG) == 0);
311 	mst = NULL;
312 
313 #ifdef KERN_TLS
314 	/*
315 	 * If this is an unencrypted TLS record, save a reference to
316 	 * the record.  This local reference is used to call
317 	 * ktls_output_eagain after the mbuf has been freed (thus
318 	 * dropping the mbuf's reference) in if_output.
319 	 */
320 	if (m->m_next != NULL && mbuf_has_tls_session(m->m_next)) {
321 		tls = ktls_hold(m->m_next->m_epg_tls);
322 		mst = tls->snd_tag;
323 
324 		/*
325 		 * If a TLS session doesn't have a valid tag, it must
326 		 * have had an earlier ifp mismatch, so drop this
327 		 * packet.
328 		 */
329 		if (mst == NULL) {
330 			m_freem(m);
331 			error = EAGAIN;
332 			goto done;
333 		}
334 		/*
335 		 * Always stamp tags that include NIC ktls.
336 		 */
337 		stamp_tag = true;
338 	}
339 #endif
340 #ifdef RATELIMIT
341 	if (inp != NULL && mst == NULL) {
342 		if ((inp->inp_flags2 & INP_RATE_LIMIT_CHANGED) != 0 ||
343 		    (inp->inp_snd_tag != NULL &&
344 		    inp->inp_snd_tag->ifp != ifp))
345 			in_pcboutput_txrtlmt(inp, ifp, m);
346 
347 		if (inp->inp_snd_tag != NULL)
348 			mst = inp->inp_snd_tag;
349 	}
350 #endif
351 	if (stamp_tag && mst != NULL) {
352 		KASSERT(m->m_pkthdr.rcvif == NULL,
353 		    ("trying to add a send tag to a forwarded packet"));
354 		if (mst->ifp != ifp) {
355 			m_freem(m);
356 			error = EAGAIN;
357 			goto done;
358 		}
359 
360 		/* stamp send tag on mbuf */
361 		m->m_pkthdr.snd_tag = m_snd_tag_ref(mst);
362 		m->m_pkthdr.csum_flags |= CSUM_SND_TAG;
363 	}
364 
365 	error = nd6_output_ifp(ifp, origifp, m, dst, (struct route *)ro);
366 
367 done:
368 	/* Check for route change invalidating send tags. */
369 #ifdef KERN_TLS
370 	if (tls != NULL) {
371 		if (error == EAGAIN)
372 			error = ktls_output_eagain(inp, tls);
373 		ktls_free(tls);
374 	}
375 #endif
376 #ifdef RATELIMIT
377 	if (error == EAGAIN)
378 		in_pcboutput_eagain(inp);
379 #endif
380 	return (error);
381 }
382 
383 /*
384  * IP6 output.
385  * The packet in mbuf chain m contains a skeletal IP6 header (with pri, len,
386  * nxt, hlim, src, dst).
387  * This function may modify ver and hlim only.
388  * The mbuf chain containing the packet will be freed.
389  * The mbuf opt, if present, will not be freed.
390  * If route_in6 ro is present and has ro_nh initialized, route lookup would be
391  * skipped and ro->ro_nh would be used. If ro is present but ro->ro_nh is NULL,
392  * then result of route lookup is stored in ro->ro_nh.
393  *
394  * Type of "mtu": rt_mtu is u_long, ifnet.ifr_mtu is int, and nd_ifinfo.linkmtu
395  * is uint32_t.  So we use u_long to hold largest one, which is rt_mtu.
396  *
397  * ifpp - XXX: just for statistics
398  */
399 int
ip6_output(struct mbuf * m0,struct ip6_pktopts * opt,struct route_in6 * ro,int flags,struct ip6_moptions * im6o,struct ifnet ** ifpp,struct inpcb * inp)400 ip6_output(struct mbuf *m0, struct ip6_pktopts *opt,
401     struct route_in6 *ro, int flags, struct ip6_moptions *im6o,
402     struct ifnet **ifpp, struct inpcb *inp)
403 {
404 	struct ip6_hdr *ip6;
405 	struct ifnet *ifp, *origifp;
406 	struct mbuf *m = m0;
407 	struct mbuf *mprev;
408 	struct route_in6 *ro_pmtu;
409 	struct nhop_object *nh;
410 	struct sockaddr_in6 *dst, sin6, src_sa, dst_sa;
411 	struct in6_addr odst;
412 	u_char *nexthdrp;
413 	int tlen, len;
414 	int error = 0;
415 	int vlan_pcp = -1;
416 	struct in6_ifaddr *ia = NULL;
417 	u_long mtu;
418 	int dontfrag;
419 	u_int32_t optlen, plen = 0, unfragpartlen;
420 	struct ip6_exthdrs exthdrs;
421 	struct in6_addr src0, dst0;
422 	u_int32_t zone;
423 	bool hdrsplit;
424 	int sw_csum, tso;
425 	int needfiblookup;
426 	uint32_t fibnum;
427 	struct m_tag *fwd_tag = NULL;
428 	uint32_t id;
429 	uint32_t optvalid;
430 
431 	NET_EPOCH_ASSERT();
432 
433 	if (inp != NULL) {
434 		INP_LOCK_ASSERT(inp);
435 		M_SETFIB(m, inp->inp_inc.inc_fibnum);
436 		if ((flags & IP_NODEFAULTFLOWID) == 0) {
437 			/* Unconditionally set flowid. */
438 			m->m_pkthdr.flowid = inp->inp_flowid;
439 			M_HASHTYPE_SET(m, inp->inp_flowtype);
440 		}
441 		if ((inp->inp_flags2 & INP_2PCP_SET) != 0)
442 			vlan_pcp = (inp->inp_flags2 & INP_2PCP_MASK) >>
443 			    INP_2PCP_SHIFT;
444 #ifdef NUMA
445 		m->m_pkthdr.numa_domain = inp->inp_numa_domain;
446 #endif
447 	}
448 
449 	/* Source address validation. */
450 	ip6 = mtod(m, struct ip6_hdr *);
451 	if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src) &&
452 	    (flags & IPV6_UNSPECSRC) == 0) {
453 		error = EOPNOTSUPP;
454 		IP6STAT_INC(ip6s_badscope);
455 		goto bad;
456 	}
457 	if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_src)) {
458 		error = EOPNOTSUPP;
459 		IP6STAT_INC(ip6s_badscope);
460 		goto bad;
461 	}
462 
463 	/*
464 	 * If we are given packet options to add extension headers prepare them.
465 	 * Calculate the total length of the extension header chain.
466 	 * Keep the length of the unfragmentable part for fragmentation.
467 	 */
468 	bzero(&exthdrs, sizeof(exthdrs));
469 	optlen = optvalid = 0;
470 	unfragpartlen = sizeof(struct ip6_hdr);
471 	if (opt) {
472 		optvalid = opt->ip6po_valid;
473 
474 		/* Hop-by-Hop options header. */
475 		if ((optvalid & IP6PO_VALID_HBH) != 0)
476 			MAKE_EXTHDR(opt->ip6po_hbh, &exthdrs.ip6e_hbh, optlen);
477 
478 		/* Destination options header (1st part). */
479 		if ((optvalid & IP6PO_VALID_RHINFO) != 0) {
480 #ifndef RTHDR_SUPPORT_IMPLEMENTED
481 			/*
482 			 * If there is a routing header, discard the packet
483 			 * right away here. RH0/1 are obsolete and we do not
484 			 * currently support RH2/3/4.
485 			 * People trying to use RH253/254 may want to disable
486 			 * this check.
487 			 * The moment we do support any routing header (again)
488 			 * this block should check the routing type more
489 			 * selectively.
490 			 */
491 			error = EINVAL;
492 			goto bad;
493 #endif
494 
495 			/*
496 			 * Destination options header (1st part).
497 			 * This only makes sense with a routing header.
498 			 * See Section 9.2 of RFC 3542.
499 			 * Disabling this part just for MIP6 convenience is
500 			 * a bad idea.  We need to think carefully about a
501 			 * way to make the advanced API coexist with MIP6
502 			 * options, which might automatically be inserted in
503 			 * the kernel.
504 			 */
505 			if ((optvalid & IP6PO_VALID_DEST1) != 0)
506 				MAKE_EXTHDR(opt->ip6po_dest1, &exthdrs.ip6e_dest1,
507 				    optlen);
508 		}
509 		/* Routing header. */
510 		if ((optvalid & IP6PO_VALID_RHINFO) != 0)
511 			MAKE_EXTHDR(opt->ip6po_rthdr, &exthdrs.ip6e_rthdr, optlen);
512 
513 		unfragpartlen += optlen;
514 
515 		/*
516 		 * NOTE: we don't add AH/ESP length here (done in
517 		 * ip6_ipsec_output()).
518 		 */
519 
520 		/* Destination options header (2nd part). */
521 		if ((optvalid & IP6PO_VALID_DEST2) != 0)
522 			MAKE_EXTHDR(opt->ip6po_dest2, &exthdrs.ip6e_dest2, optlen);
523 	}
524 
525 	/*
526 	 * If there is at least one extension header,
527 	 * separate IP6 header from the payload.
528 	 */
529 	hdrsplit = false;
530 	if (optlen) {
531 		if ((error = ip6_splithdr(m, &exthdrs)) != 0) {
532 			m = NULL;
533 			goto freehdrs;
534 		}
535 		m = exthdrs.ip6e_ip6;
536 		ip6 = mtod(m, struct ip6_hdr *);
537 		hdrsplit = true;
538 	}
539 
540 	/* Adjust mbuf packet header length. */
541 	m->m_pkthdr.len += optlen;
542 	plen = m->m_pkthdr.len - sizeof(*ip6);
543 
544 	if (plen > IPV6_MAXPACKET) {
545 		error = EMSGSIZE;
546 		goto freehdrs;
547 	} else
548 		ip6->ip6_plen = htons(plen);
549 	nexthdrp = &ip6->ip6_nxt;
550 
551 	if (optlen) {
552 		/*
553 		 * Concatenate headers and fill in next header fields.
554 		 * Here we have, on "m"
555 		 *	IPv6 payload
556 		 * and we insert headers accordingly.
557 		 * Finally, we should be getting:
558 		 *	IPv6 hbh dest1 rthdr ah* [esp* dest2 payload].
559 		 *
560 		 * During the header composing process "m" points to IPv6
561 		 * header.  "mprev" points to an extension header prior to esp.
562 		 */
563 		mprev = m;
564 
565 		/*
566 		 * We treat dest2 specially.  This makes IPsec processing
567 		 * much easier.  The goal here is to make mprev point the
568 		 * mbuf prior to dest2.
569 		 *
570 		 * Result: IPv6 dest2 payload.
571 		 * m and mprev will point to IPv6 header.
572 		 */
573 		if (exthdrs.ip6e_dest2) {
574 			if (!hdrsplit)
575 				panic("%s:%d: assumption failed: "
576 				    "hdr not split: hdrsplit %d exthdrs %p",
577 				    __func__, __LINE__, hdrsplit, &exthdrs);
578 			exthdrs.ip6e_dest2->m_next = m->m_next;
579 			m->m_next = exthdrs.ip6e_dest2;
580 			*mtod(exthdrs.ip6e_dest2, u_char *) = ip6->ip6_nxt;
581 			ip6->ip6_nxt = IPPROTO_DSTOPTS;
582 		}
583 
584 		/*
585 		 * Result: IPv6 hbh dest1 rthdr dest2 payload.
586 		 * m will point to IPv6 header.  mprev will point to the
587 		 * extension header prior to dest2 (rthdr in the above case).
588 		 */
589 		MAKE_CHAIN(exthdrs.ip6e_hbh, mprev, nexthdrp, IPPROTO_HOPOPTS);
590 		MAKE_CHAIN(exthdrs.ip6e_dest1, mprev, nexthdrp,
591 			   IPPROTO_DSTOPTS);
592 		MAKE_CHAIN(exthdrs.ip6e_rthdr, mprev, nexthdrp,
593 			   IPPROTO_ROUTING);
594 	}
595 
596 	IP6STAT_INC(ip6s_localout);
597 
598 	/* Route packet. */
599 	ro_pmtu = ro;
600 	if ((optvalid & IP6PO_VALID_RHINFO) != 0)
601 		ro = &opt->ip6po_route;
602 	if (ro != NULL)
603 		dst = (struct sockaddr_in6 *)&ro->ro_dst;
604 	else
605 		dst = &sin6;
606 	fibnum = (inp != NULL) ? inp->inp_inc.inc_fibnum : M_GETFIB(m);
607 
608 again:
609 	/*
610 	 * If specified, try to fill in the traffic class field.
611 	 * Do not override if a non-zero value is already set.
612 	 * We check the diffserv field and the ECN field separately.
613 	 */
614 	if ((optvalid & IP6PO_VALID_TC) != 0){
615 		int mask = 0;
616 
617 		if (IPV6_DSCP(ip6) == 0)
618 			mask |= 0xfc;
619 		if (IPV6_ECN(ip6) == 0)
620 			mask |= 0x03;
621 		if (mask != 0)
622 			ip6->ip6_flow |= htonl((opt->ip6po_tclass & mask) << 20);
623 	}
624 
625 	/* Fill in or override the hop limit field, if necessary. */
626 	if ((optvalid & IP6PO_VALID_HLIM) != 0)
627 		ip6->ip6_hlim = opt->ip6po_hlim & 0xff;
628 	else if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
629 		if (im6o != NULL)
630 			ip6->ip6_hlim = im6o->im6o_multicast_hlim;
631 		else
632 			ip6->ip6_hlim = V_ip6_defmcasthlim;
633 	}
634 
635 	if (ro == NULL || ro->ro_nh == NULL) {
636 		bzero(dst, sizeof(*dst));
637 		dst->sin6_family = AF_INET6;
638 		dst->sin6_len = sizeof(*dst);
639 		dst->sin6_addr = ip6->ip6_dst;
640 	}
641 	/*
642 	 * Validate route against routing table changes.
643 	 * Make sure that the address family is set in route.
644 	 */
645 	nh = NULL;
646 	ifp = NULL;
647 	mtu = 0;
648 	if (ro != NULL) {
649 		if (ro->ro_nh != NULL && inp != NULL) {
650 			ro->ro_dst.sin6_family = AF_INET6; /* XXX KASSERT? */
651 			NH_VALIDATE((struct route *)ro, &inp->inp_rt_cookie,
652 			    fibnum);
653 		}
654 		if (ro->ro_nh != NULL && fwd_tag == NULL &&
655 		    (!NH_IS_VALID(ro->ro_nh) ||
656 		    ro->ro_dst.sin6_family != AF_INET6 ||
657 		    !IN6_ARE_ADDR_EQUAL(&ro->ro_dst.sin6_addr, &ip6->ip6_dst)))
658 			RO_INVALIDATE_CACHE(ro);
659 
660 		if (ro->ro_nh != NULL && fwd_tag == NULL &&
661 		    ro->ro_dst.sin6_family == AF_INET6 &&
662 		    IN6_ARE_ADDR_EQUAL(&ro->ro_dst.sin6_addr, &ip6->ip6_dst)) {
663 			/* Nexthop is valid and contains valid ifp */
664 			nh = ro->ro_nh;
665 		} else {
666 			if (ro->ro_lle)
667 				LLE_FREE(ro->ro_lle);	/* zeros ro_lle */
668 			ro->ro_lle = NULL;
669 			if (fwd_tag == NULL) {
670 				bzero(&dst_sa, sizeof(dst_sa));
671 				dst_sa.sin6_family = AF_INET6;
672 				dst_sa.sin6_len = sizeof(dst_sa);
673 				dst_sa.sin6_addr = ip6->ip6_dst;
674 			}
675 			error = in6_selectroute(&dst_sa, opt, im6o, ro, &ifp,
676 			    &nh, fibnum, m->m_pkthdr.flowid);
677 			if (error != 0) {
678 				IP6STAT_INC(ip6s_noroute);
679 				if (ifp != NULL)
680 					in6_ifstat_inc(ifp, ifs6_out_discard);
681 				goto bad;
682 			}
683 			/*
684 			 * At this point at least @ifp is not NULL
685 			 * Can be the case when dst is multicast, link-local or
686 			 * interface is explicitly specificed by the caller.
687 			 */
688 		}
689 		if (nh == NULL) {
690 			/*
691 			 * If in6_selectroute() does not return a nexthop
692 			 * dst may not have been updated.
693 			 */
694 			*dst = dst_sa;	/* XXX */
695 			origifp = ifp;
696 			mtu = ifp->if_mtu;
697 		} else {
698 			ifp = nh->nh_ifp;
699 			origifp = nh->nh_aifp;
700 			ia = (struct in6_ifaddr *)(nh->nh_ifa);
701 			counter_u64_add(nh->nh_pksent, 1);
702 		}
703 	} else {
704 		struct nhop_object *nh;
705 		struct in6_addr kdst;
706 		uint32_t scopeid;
707 
708 		if (fwd_tag == NULL) {
709 			bzero(&dst_sa, sizeof(dst_sa));
710 			dst_sa.sin6_family = AF_INET6;
711 			dst_sa.sin6_len = sizeof(dst_sa);
712 			dst_sa.sin6_addr = ip6->ip6_dst;
713 		}
714 
715 		if (IN6_IS_ADDR_MULTICAST(&dst_sa.sin6_addr) &&
716 		    im6o != NULL &&
717 		    (ifp = im6o->im6o_multicast_ifp) != NULL) {
718 			/* We do not need a route lookup. */
719 			*dst = dst_sa;	/* XXX */
720 			origifp = ifp;
721 			goto nonh6lookup;
722 		}
723 
724 		in6_splitscope(&dst_sa.sin6_addr, &kdst, &scopeid);
725 
726 		if (IN6_IS_ADDR_MC_LINKLOCAL(&dst_sa.sin6_addr) ||
727 		    IN6_IS_ADDR_MC_NODELOCAL(&dst_sa.sin6_addr)) {
728 			if (scopeid > 0) {
729 				ifp = in6_getlinkifnet(scopeid);
730 				if (ifp == NULL) {
731 					error = EHOSTUNREACH;
732 					goto bad;
733 				}
734 				*dst = dst_sa;	/* XXX */
735 				origifp = ifp;
736 				goto nonh6lookup;
737 			}
738 		}
739 
740 		nh = fib6_lookup(fibnum, &kdst, scopeid, NHR_NONE,
741 		    m->m_pkthdr.flowid);
742 		if (nh == NULL) {
743 			IP6STAT_INC(ip6s_noroute);
744 			/* No ifp in6_ifstat_inc(ifp, ifs6_out_discard); */
745 			error = EHOSTUNREACH;
746 			goto bad;
747 		}
748 
749 		ifp = nh->nh_ifp;
750 		origifp = nh->nh_aifp;
751 		ia = ifatoia6(nh->nh_ifa);
752 		if (nh->nh_flags & NHF_GATEWAY)
753 			dst->sin6_addr = nh->gw6_sa.sin6_addr;
754 		else if (fwd_tag != NULL)
755 			dst->sin6_addr = dst_sa.sin6_addr;
756 nonh6lookup:
757 		;
758 	}
759 	/*
760 	 * At this point ifp MUST be pointing to the valid transmit ifp.
761 	 * origifp MUST be valid and pointing to either the same ifp or,
762 	 * in case of loopback output, to the interface which ip6_src
763 	 * belongs to.
764 	 * Examples:
765 	 *  fe80::1%em0 -> fe80::2%em0 -> ifp=em0, origifp=em0
766 	 *  fe80::1%em0 -> fe80::1%em0 -> ifp=lo0, origifp=em0
767 	 *  ::1 -> ::1 -> ifp=lo0, origifp=lo0
768 	 *
769 	 * mtu can be 0 and will be refined later.
770 	 */
771 	KASSERT((ifp != NULL), ("output interface must not be NULL"));
772 	KASSERT((origifp != NULL), ("output address interface must not be NULL"));
773 
774 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
775 	/*
776 	 * IPSec checking which handles several cases.
777 	 * FAST IPSEC: We re-injected the packet.
778 	 * XXX: need scope argument.
779 	 */
780 	if (IPSEC_ENABLED(ipv6)) {
781 		if ((error = IPSEC_OUTPUT(ipv6, ifp, m, inp, mtu == 0 ?
782 		    ifp->if_mtu : mtu)) != 0) {
783 			if (error == EINPROGRESS)
784 				error = 0;
785 			goto done;
786 		}
787 	}
788 #endif /* IPSEC */
789 
790 	if ((flags & IPV6_FORWARDING) == 0) {
791 		/* XXX: the FORWARDING flag can be set for mrouting. */
792 		in6_ifstat_inc(ifp, ifs6_out_request);
793 	}
794 
795 	/* Setup data structures for scope ID checks. */
796 	src0 = ip6->ip6_src;
797 	bzero(&src_sa, sizeof(src_sa));
798 	src_sa.sin6_family = AF_INET6;
799 	src_sa.sin6_len = sizeof(src_sa);
800 	src_sa.sin6_addr = ip6->ip6_src;
801 
802 	dst0 = ip6->ip6_dst;
803 	/* Re-initialize to be sure. */
804 	bzero(&dst_sa, sizeof(dst_sa));
805 	dst_sa.sin6_family = AF_INET6;
806 	dst_sa.sin6_len = sizeof(dst_sa);
807 	dst_sa.sin6_addr = ip6->ip6_dst;
808 
809 	/* Check for valid scope ID. */
810 	if (in6_setscope(&src0, origifp, &zone) == 0 &&
811 	    sa6_recoverscope(&src_sa) == 0 && zone == src_sa.sin6_scope_id &&
812 	    in6_setscope(&dst0, origifp, &zone) == 0 &&
813 	    sa6_recoverscope(&dst_sa) == 0 && zone == dst_sa.sin6_scope_id) {
814 		/*
815 		 * The outgoing interface is in the zone of the source
816 		 * and destination addresses.
817 		 *
818 		 */
819 	} else if ((origifp->if_flags & IFF_LOOPBACK) == 0 ||
820 	    sa6_recoverscope(&src_sa) != 0 ||
821 	    sa6_recoverscope(&dst_sa) != 0 ||
822 	    dst_sa.sin6_scope_id == 0 ||
823 	    (src_sa.sin6_scope_id != 0 &&
824 	    src_sa.sin6_scope_id != dst_sa.sin6_scope_id) ||
825 	    ifnet_byindex(dst_sa.sin6_scope_id) == NULL) {
826 		/*
827 		 * If the destination network interface is not a
828 		 * loopback interface, or the destination network
829 		 * address has no scope ID, or the source address has
830 		 * a scope ID set which is different from the
831 		 * destination address one, or there is no network
832 		 * interface representing this scope ID, the address
833 		 * pair is considered invalid.
834 		 */
835 		IP6STAT_INC(ip6s_badscope);
836 		in6_ifstat_inc(origifp, ifs6_out_discard);
837 		if (error == 0)
838 			error = EHOSTUNREACH; /* XXX */
839 		goto bad;
840 	}
841 	/* All scope ID checks are successful. */
842 
843 	if (nh && !IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
844 		if ((optvalid & IP6PO_VALID_NHINFO) != 0) {
845 			/*
846 			 * The nexthop is explicitly specified by the
847 			 * application.  We assume the next hop is an IPv6
848 			 * address.
849 			 */
850 			dst = (struct sockaddr_in6 *)opt->ip6po_nexthop;
851 		}
852 		else if ((nh->nh_flags & NHF_GATEWAY))
853 			dst = &nh->gw6_sa;
854 	}
855 
856 	if (!IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
857 		m->m_flags &= ~(M_BCAST | M_MCAST); /* Just in case. */
858 	} else {
859 		m->m_flags = (m->m_flags & ~M_BCAST) | M_MCAST;
860 		in6_ifstat_inc(ifp, ifs6_out_mcast);
861 
862 		/* Confirm that the outgoing interface supports multicast. */
863 		if (!(ifp->if_flags & IFF_MULTICAST)) {
864 			IP6STAT_INC(ip6s_noroute);
865 			in6_ifstat_inc(ifp, ifs6_out_discard);
866 			error = ENETUNREACH;
867 			goto bad;
868 		}
869 		if ((im6o == NULL && in6_mcast_loop) ||
870 		    (im6o && im6o->im6o_multicast_loop)) {
871 			/*
872 			 * Loop back multicast datagram if not expressly
873 			 * forbidden to do so, even if we have not joined
874 			 * the address; protocols will filter it later,
875 			 * thus deferring a hash lookup and lock acquisition
876 			 * at the expense of an m_copym().
877 			 */
878 			ip6_mloopback(ifp, m);
879 		} else {
880 			/*
881 			 * If we are acting as a multicast router, perform
882 			 * multicast forwarding as if the packet had just
883 			 * arrived on the interface to which we are about
884 			 * to send.  The multicast forwarding function
885 			 * recursively calls this function, using the
886 			 * IPV6_FORWARDING flag to prevent infinite recursion.
887 			 *
888 			 * Multicasts that are looped back by ip6_mloopback(),
889 			 * above, will be forwarded by the ip6_input() routine,
890 			 * if necessary.
891 			 */
892 			if (V_ip6_mrouter && (flags & IPV6_FORWARDING) == 0) {
893 				/*
894 				 * XXX: ip6_mforward expects that rcvif is NULL
895 				 * when it is called from the originating path.
896 				 * However, it may not always be the case.
897 				 */
898 				m->m_pkthdr.rcvif = NULL;
899 				if (ip6_mforward(ip6, ifp, m) != 0) {
900 					m_freem(m);
901 					goto done;
902 				}
903 			}
904 		}
905 		/*
906 		 * Multicasts with a hoplimit of zero may be looped back,
907 		 * above, but must not be transmitted on a network.
908 		 * Also, multicasts addressed to the loopback interface
909 		 * are not sent -- the above call to ip6_mloopback() will
910 		 * loop back a copy if this host actually belongs to the
911 		 * destination group on the loopback interface.
912 		 */
913 		if (ip6->ip6_hlim == 0 || (ifp->if_flags & IFF_LOOPBACK) ||
914 		    IN6_IS_ADDR_MC_INTFACELOCAL(&ip6->ip6_dst)) {
915 			m_freem(m);
916 			goto done;
917 		}
918 	}
919 
920 	/*
921 	 * Fill the outgoing inteface to tell the upper layer
922 	 * to increment per-interface statistics.
923 	 */
924 	if (ifpp)
925 		*ifpp = ifp;
926 
927 	/* Determine path MTU. */
928 	ip6_getpmtu(ro_pmtu, ro != ro_pmtu, ifp, &ip6->ip6_dst, &mtu, fibnum,
929 	    *nexthdrp);
930 	KASSERT(mtu > 0, ("%s:%d: mtu %ld, ro_pmtu %p ro %p ifp %p fibnum %u",
931 	    __func__, __LINE__, mtu, ro_pmtu, ro, ifp, fibnum));
932 
933 	/*
934 	 * The caller of this function may specify to use the minimum MTU
935 	 * in some cases.
936 	 * An advanced API option (IPV6_USE_MIN_MTU) can also override MTU
937 	 * setting.  The logic is a bit complicated; by default, unicast
938 	 * packets will follow path MTU while multicast packets will be sent at
939 	 * the minimum MTU.  If IP6PO_MINMTU_ALL is specified, all packets
940 	 * including unicast ones will be sent at the minimum MTU.  Multicast
941 	 * packets will always be sent at the minimum MTU unless
942 	 * IP6PO_MINMTU_DISABLE is explicitly specified.
943 	 * See RFC 3542 for more details.
944 	 */
945 	if (mtu > IPV6_MMTU) {
946 		if ((flags & IPV6_MINMTU))
947 			mtu = IPV6_MMTU;
948 		else if (opt && opt->ip6po_minmtu == IP6PO_MINMTU_ALL)
949 			mtu = IPV6_MMTU;
950 		else if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) &&
951 			 (opt == NULL ||
952 			  opt->ip6po_minmtu != IP6PO_MINMTU_DISABLE)) {
953 			mtu = IPV6_MMTU;
954 		}
955 	}
956 
957 	/*
958 	 * Clear embedded scope identifiers if necessary.
959 	 * in6_clearscope() will touch the addresses only when necessary.
960 	 */
961 	in6_clearscope(&ip6->ip6_src);
962 	in6_clearscope(&ip6->ip6_dst);
963 
964 	/*
965 	 * If the outgoing packet contains a hop-by-hop options header,
966 	 * it must be examined and processed even by the source node.
967 	 * (RFC 2460, section 4.)
968 	 */
969 	if (exthdrs.ip6e_hbh) {
970 		struct ip6_hbh *hbh = mtod(exthdrs.ip6e_hbh, struct ip6_hbh *);
971 		u_int32_t dummy; /* XXX unused */
972 
973 #ifdef DIAGNOSTIC
974 		if ((hbh->ip6h_len + 1) << 3 > exthdrs.ip6e_hbh->m_len)
975 			panic("ip6e_hbh is not contiguous");
976 #endif
977 		/*
978 		 *  XXX: if we have to send an ICMPv6 error to the sender,
979 		 *       we need the M_LOOP flag since icmp6_error() expects
980 		 *       the IPv6 and the hop-by-hop options header are
981 		 *       contiguous unless the flag is set.
982 		 */
983 		m->m_flags |= M_LOOP;
984 		m->m_pkthdr.rcvif = ifp;
985 		if (ip6_process_hopopts(m, (u_int8_t *)(hbh + 1),
986 		    ((hbh->ip6h_len + 1) << 3) - sizeof(struct ip6_hbh),
987 		    &dummy) < 0) {
988 			/* m was already freed at this point. */
989 			error = EINVAL;/* better error? */
990 			goto done;
991 		}
992 		m->m_flags &= ~M_LOOP; /* XXX */
993 		m->m_pkthdr.rcvif = NULL;
994 	}
995 
996 	/* Jump over all PFIL processing if hooks are not active. */
997 	if (!PFIL_HOOKED_OUT(V_inet6_pfil_head))
998 		goto passout;
999 
1000 	odst = ip6->ip6_dst;
1001 	/* Run through list of hooks for output packets. */
1002 	switch (pfil_mbuf_out(V_inet6_pfil_head, &m, ifp, inp)) {
1003 	case PFIL_PASS:
1004 		ip6 = mtod(m, struct ip6_hdr *);
1005 		break;
1006 	case PFIL_DROPPED:
1007 		error = EACCES;
1008 		/* FALLTHROUGH */
1009 	case PFIL_CONSUMED:
1010 		goto done;
1011 	}
1012 
1013 	needfiblookup = 0;
1014 	/* See if destination IP address was changed by packet filter. */
1015 	if (!IN6_ARE_ADDR_EQUAL(&odst, &ip6->ip6_dst)) {
1016 		m->m_flags |= M_SKIP_FIREWALL;
1017 		/* If destination is now ourself drop to ip6_input(). */
1018 		if (in6_localip(&ip6->ip6_dst)) {
1019 			m->m_flags |= M_FASTFWD_OURS;
1020 			if (m->m_pkthdr.rcvif == NULL)
1021 				m->m_pkthdr.rcvif = V_loif;
1022 			if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA_IPV6) {
1023 				m->m_pkthdr.csum_flags |=
1024 				    CSUM_DATA_VALID_IPV6 | CSUM_PSEUDO_HDR;
1025 				m->m_pkthdr.csum_data = 0xffff;
1026 			}
1027 #if defined(SCTP) || defined(SCTP_SUPPORT)
1028 			if (m->m_pkthdr.csum_flags & CSUM_SCTP_IPV6)
1029 				m->m_pkthdr.csum_flags |= CSUM_SCTP_VALID;
1030 #endif
1031 			error = netisr_queue(NETISR_IPV6, m);
1032 			goto done;
1033 		} else {
1034 			if (ro != NULL)
1035 				RO_INVALIDATE_CACHE(ro);
1036 			needfiblookup = 1; /* Redo the routing table lookup. */
1037 		}
1038 	}
1039 	/* See if fib was changed by packet filter. */
1040 	if (fibnum != M_GETFIB(m)) {
1041 		m->m_flags |= M_SKIP_FIREWALL;
1042 		fibnum = M_GETFIB(m);
1043 		if (ro != NULL)
1044 			RO_INVALIDATE_CACHE(ro);
1045 		needfiblookup = 1;
1046 	}
1047 	if (needfiblookup)
1048 		goto again;
1049 
1050 	/* See if local, if yes, send it to netisr. */
1051 	if (m->m_flags & M_FASTFWD_OURS) {
1052 		if (m->m_pkthdr.rcvif == NULL)
1053 			m->m_pkthdr.rcvif = V_loif;
1054 		if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA_IPV6) {
1055 			m->m_pkthdr.csum_flags |=
1056 			    CSUM_DATA_VALID_IPV6 | CSUM_PSEUDO_HDR;
1057 			m->m_pkthdr.csum_data = 0xffff;
1058 		}
1059 #if defined(SCTP) || defined(SCTP_SUPPORT)
1060 		if (m->m_pkthdr.csum_flags & CSUM_SCTP_IPV6)
1061 			m->m_pkthdr.csum_flags |= CSUM_SCTP_VALID;
1062 #endif
1063 		error = netisr_queue(NETISR_IPV6, m);
1064 		goto done;
1065 	}
1066 	/* Or forward to some other address? */
1067 	if ((m->m_flags & M_IP6_NEXTHOP) &&
1068 	    (fwd_tag = m_tag_find(m, PACKET_TAG_IPFORWARD, NULL)) != NULL) {
1069 		if (ro != NULL)
1070 			dst = (struct sockaddr_in6 *)&ro->ro_dst;
1071 		else
1072 			dst = &sin6;
1073 		bcopy((fwd_tag+1), &dst_sa, sizeof(struct sockaddr_in6));
1074 		m->m_flags |= M_SKIP_FIREWALL;
1075 		m->m_flags &= ~M_IP6_NEXTHOP;
1076 		m_tag_delete(m, fwd_tag);
1077 		goto again;
1078 	}
1079 
1080 passout:
1081 	if (vlan_pcp > -1)
1082 		EVL_APPLY_PRI(m, vlan_pcp);
1083 
1084 	/* Ensure the packet data is mapped if the interface requires it. */
1085 	if ((ifp->if_capenable & IFCAP_MEXTPG) == 0) {
1086 		struct mbuf *m1;
1087 
1088 		error = mb_unmapped_to_ext(m, &m1);
1089 		if (error != 0) {
1090 			if (error == EINVAL) {
1091 				if_printf(ifp, "TLS packet\n");
1092 				/* XXXKIB */
1093 			} else if (error == ENOMEM) {
1094 				error = ENOBUFS;
1095 			}
1096 			IP6STAT_INC(ip6s_odropped);
1097 			return (error);
1098 		} else {
1099 			m = m1;
1100 		}
1101 	}
1102 
1103 	/*
1104 	 * Send the packet to the outgoing interface.
1105 	 * If necessary, do IPv6 fragmentation before sending.
1106 	 *
1107 	 * 1: normal case (dontfrag == 0)
1108 	 * 1-a:	send as is if tlen <= path mtu
1109 	 * 1-b:	fragment if tlen > path mtu
1110 	 *
1111 	 * 2: if user asks us not to fragment (dontfrag == 1)
1112 	 * 2-a:	send as is if tlen <= interface mtu
1113 	 * 2-b:	error if tlen > interface mtu
1114 	 */
1115 	sw_csum = m->m_pkthdr.csum_flags;
1116 	if (!hdrsplit) {
1117 		tso = ((sw_csum & ifp->if_hwassist &
1118 		    (CSUM_TSO | CSUM_INNER_TSO)) != 0) ? 1 : 0;
1119 		sw_csum &= ~ifp->if_hwassist;
1120 	} else
1121 		tso = 0;
1122 	/*
1123 	 * If we added extension headers, we will not do TSO and calculate the
1124 	 * checksums ourselves for now.
1125 	 * XXX-BZ  Need a framework to know when the NIC can handle it, even
1126 	 * with ext. hdrs.
1127 	 */
1128 	ip6_output_delayed_csum(m, ifp, sw_csum, plen, optlen);
1129 	/* XXX-BZ m->m_pkthdr.csum_flags &= ~ifp->if_hwassist; */
1130 	tlen = m->m_pkthdr.len;
1131 
1132 	if ((opt && (opt->ip6po_flags & IP6PO_DONTFRAG)) || tso)
1133 		dontfrag = 1;
1134 	else
1135 		dontfrag = 0;
1136 	if (dontfrag && tlen > in6_ifmtu(ifp) && !tso) {	/* Case 2-b. */
1137 		/*
1138 		 * If the DONTFRAG option is specified, we cannot send the
1139 		 * packet when the data length is larger than the MTU of the
1140 		 * outgoing interface.
1141 		 * Notify the error by sending IPV6_PATHMTU ancillary data if
1142 		 * application wanted to know the MTU value. Also return an
1143 		 * error code (this is not described in the API spec).
1144 		 */
1145 		if (inp != NULL)
1146 			ip6_notify_pmtu(inp, &dst_sa, (u_int32_t)mtu);
1147 		error = EMSGSIZE;
1148 		goto bad;
1149 	}
1150 
1151 	/* Transmit packet without fragmentation. */
1152 	if (dontfrag || tlen <= mtu) {	/* Cases 1-a and 2-a. */
1153 		struct in6_ifaddr *ia6;
1154 
1155 		ip6 = mtod(m, struct ip6_hdr *);
1156 		ia6 = in6_ifawithifp(ifp, &ip6->ip6_src);
1157 		if (ia6) {
1158 			/* Record statistics for this interface address. */
1159 			counter_u64_add(ia6->ia_ifa.ifa_opackets, 1);
1160 			counter_u64_add(ia6->ia_ifa.ifa_obytes,
1161 			    m->m_pkthdr.len);
1162 		}
1163 		error = ip6_output_send(inp, ifp, origifp, m, dst, ro,
1164 		    (flags & IP_NO_SND_TAG_RL) ? false : true);
1165 		goto done;
1166 	}
1167 
1168 	/* Try to fragment the packet.  Case 1-b. */
1169 	if (mtu < IPV6_MMTU) {
1170 		/* Path MTU cannot be less than IPV6_MMTU. */
1171 		error = EMSGSIZE;
1172 		in6_ifstat_inc(ifp, ifs6_out_fragfail);
1173 		goto bad;
1174 	} else if (ip6->ip6_plen == 0) {
1175 		/* We do not support jumbo payload. */
1176 		error = EMSGSIZE;
1177 		in6_ifstat_inc(ifp, ifs6_out_fragfail);
1178 		goto bad;
1179 	} else {
1180 		u_char nextproto;
1181 
1182 		/*
1183 		 * Too large for the destination or interface;
1184 		 * fragment if possible.
1185 		 * Must be able to put at least 8 bytes per fragment.
1186 		 */
1187 		if (mtu > IPV6_MAXPACKET)
1188 			mtu = IPV6_MAXPACKET;
1189 
1190 		len = (mtu - unfragpartlen - sizeof(struct ip6_frag)) & ~7;
1191 		if (len < 8) {
1192 			error = EMSGSIZE;
1193 			in6_ifstat_inc(ifp, ifs6_out_fragfail);
1194 			goto bad;
1195 		}
1196 
1197 		/*
1198 		 * If the interface will not calculate checksums on
1199 		 * fragmented packets, then do it here.
1200 		 * XXX-BZ handle the hw offloading case.  Need flags.
1201 		 */
1202 		ip6_output_delayed_csum(m, ifp, m->m_pkthdr.csum_flags, plen,
1203 		    optlen);
1204 
1205 		/*
1206 		 * Change the next header field of the last header in the
1207 		 * unfragmentable part.
1208 		 */
1209 		if (exthdrs.ip6e_rthdr) {
1210 			nextproto = *mtod(exthdrs.ip6e_rthdr, u_char *);
1211 			*mtod(exthdrs.ip6e_rthdr, u_char *) = IPPROTO_FRAGMENT;
1212 		} else if (exthdrs.ip6e_dest1) {
1213 			nextproto = *mtod(exthdrs.ip6e_dest1, u_char *);
1214 			*mtod(exthdrs.ip6e_dest1, u_char *) = IPPROTO_FRAGMENT;
1215 		} else if (exthdrs.ip6e_hbh) {
1216 			nextproto = *mtod(exthdrs.ip6e_hbh, u_char *);
1217 			*mtod(exthdrs.ip6e_hbh, u_char *) = IPPROTO_FRAGMENT;
1218 		} else {
1219 			ip6 = mtod(m, struct ip6_hdr *);
1220 			nextproto = ip6->ip6_nxt;
1221 			ip6->ip6_nxt = IPPROTO_FRAGMENT;
1222 		}
1223 
1224 		/*
1225 		 * Loop through length of segment after first fragment,
1226 		 * make new header and copy data of each part and link onto
1227 		 * chain.
1228 		 */
1229 		m0 = m;
1230 		id = htonl(ip6_randomid());
1231 		error = ip6_fragment(ifp, m, unfragpartlen, nextproto,len, id);
1232 		if (error != 0)
1233 			goto sendorfree;
1234 
1235 		in6_ifstat_inc(ifp, ifs6_out_fragok);
1236 	}
1237 
1238 	/* Remove leading garbage. */
1239 sendorfree:
1240 	m = m0->m_nextpkt;
1241 	m0->m_nextpkt = 0;
1242 	m_freem(m0);
1243 	for (; m; m = m0) {
1244 		m0 = m->m_nextpkt;
1245 		m->m_nextpkt = 0;
1246 		if (error == 0) {
1247 			/* Record statistics for this interface address. */
1248 			if (ia) {
1249 				counter_u64_add(ia->ia_ifa.ifa_opackets, 1);
1250 				counter_u64_add(ia->ia_ifa.ifa_obytes,
1251 				    m->m_pkthdr.len);
1252 			}
1253 			if (vlan_pcp > -1)
1254 				EVL_APPLY_PRI(m, vlan_pcp);
1255 			error = ip6_output_send(inp, ifp, origifp, m, dst, ro,
1256 			    true);
1257 		} else
1258 			m_freem(m);
1259 	}
1260 
1261 	if (error == 0)
1262 		IP6STAT_INC(ip6s_fragmented);
1263 
1264 done:
1265 	return (error);
1266 
1267 freehdrs:
1268 	m_freem(exthdrs.ip6e_hbh);	/* m_freem() checks if mbuf is NULL. */
1269 	m_freem(exthdrs.ip6e_dest1);
1270 	m_freem(exthdrs.ip6e_rthdr);
1271 	m_freem(exthdrs.ip6e_dest2);
1272 	/* FALLTHROUGH */
1273 bad:
1274 	if (m)
1275 		m_freem(m);
1276 	goto done;
1277 }
1278 
1279 static int
ip6_copyexthdr(struct mbuf ** mp,caddr_t hdr,int hlen)1280 ip6_copyexthdr(struct mbuf **mp, caddr_t hdr, int hlen)
1281 {
1282 	struct mbuf *m;
1283 
1284 	if (hlen > MCLBYTES)
1285 		return (ENOBUFS); /* XXX */
1286 
1287 	if (hlen > MLEN)
1288 		m = m_getcl(M_NOWAIT, MT_DATA, 0);
1289 	else
1290 		m = m_get(M_NOWAIT, MT_DATA);
1291 	if (m == NULL)
1292 		return (ENOBUFS);
1293 	m->m_len = hlen;
1294 	if (hdr)
1295 		bcopy(hdr, mtod(m, caddr_t), hlen);
1296 
1297 	*mp = m;
1298 	return (0);
1299 }
1300 
1301 /*
1302  * Insert fragment header and copy unfragmentable header portions.
1303  */
1304 static int
ip6_insertfraghdr(struct mbuf * m0,struct mbuf * m,int hlen,struct ip6_frag ** frghdrp)1305 ip6_insertfraghdr(struct mbuf *m0, struct mbuf *m, int hlen,
1306     struct ip6_frag **frghdrp)
1307 {
1308 	struct mbuf *n, *mlast;
1309 
1310 	if (hlen > sizeof(struct ip6_hdr)) {
1311 		n = m_copym(m0, sizeof(struct ip6_hdr),
1312 		    hlen - sizeof(struct ip6_hdr), M_NOWAIT);
1313 		if (n == NULL)
1314 			return (ENOBUFS);
1315 		m->m_next = n;
1316 	} else
1317 		n = m;
1318 
1319 	/* Search for the last mbuf of unfragmentable part. */
1320 	for (mlast = n; mlast->m_next; mlast = mlast->m_next)
1321 		;
1322 
1323 	if (M_WRITABLE(mlast) &&
1324 	    M_TRAILINGSPACE(mlast) >= sizeof(struct ip6_frag)) {
1325 		/* use the trailing space of the last mbuf for the fragment hdr */
1326 		*frghdrp = (struct ip6_frag *)(mtod(mlast, caddr_t) +
1327 		    mlast->m_len);
1328 		mlast->m_len += sizeof(struct ip6_frag);
1329 		m->m_pkthdr.len += sizeof(struct ip6_frag);
1330 	} else {
1331 		/* allocate a new mbuf for the fragment header */
1332 		struct mbuf *mfrg;
1333 
1334 		mfrg = m_get(M_NOWAIT, MT_DATA);
1335 		if (mfrg == NULL)
1336 			return (ENOBUFS);
1337 		mfrg->m_len = sizeof(struct ip6_frag);
1338 		*frghdrp = mtod(mfrg, struct ip6_frag *);
1339 		mlast->m_next = mfrg;
1340 	}
1341 
1342 	return (0);
1343 }
1344 
1345 /*
1346  * Calculates IPv6 path mtu for destination @dst.
1347  * Resulting MTU is stored in @mtup.
1348  *
1349  * Returns 0 on success.
1350  */
1351 static int
ip6_getpmtu_ctl(u_int fibnum,const struct in6_addr * dst,u_long * mtup)1352 ip6_getpmtu_ctl(u_int fibnum, const struct in6_addr *dst, u_long *mtup)
1353 {
1354 	struct epoch_tracker et;
1355 	struct nhop_object *nh;
1356 	struct in6_addr kdst;
1357 	uint32_t scopeid;
1358 	int error;
1359 
1360 	in6_splitscope(dst, &kdst, &scopeid);
1361 
1362 	NET_EPOCH_ENTER(et);
1363 	nh = fib6_lookup(fibnum, &kdst, scopeid, NHR_NONE, 0);
1364 	if (nh != NULL) {
1365 		ip6_calcmtu(nh->nh_ifp, dst, nh->nh_mtu, mtup, 0);
1366 		error = 0;
1367 	} else
1368 		error = EHOSTUNREACH;
1369 	NET_EPOCH_EXIT(et);
1370 
1371 	return (error);
1372 }
1373 
1374 /*
1375  * Calculates IPv6 path MTU for @dst based on transmit @ifp,
1376  * and cached data in @ro_pmtu.
1377  * MTU from (successful) route lookup is saved (along with dst)
1378  * inside @ro_pmtu to avoid subsequent route lookups after packet
1379  * filter processing.
1380  *
1381  * Stores mtu into @mtup.
1382  */
1383 static void
ip6_getpmtu(struct route_in6 * ro_pmtu,int do_lookup,struct ifnet * ifp,const struct in6_addr * dst,u_long * mtup,u_int fibnum,u_int proto)1384 ip6_getpmtu(struct route_in6 *ro_pmtu, int do_lookup,
1385     struct ifnet *ifp, const struct in6_addr *dst, u_long *mtup,
1386     u_int fibnum, u_int proto)
1387 {
1388 	struct nhop_object *nh;
1389 	struct in6_addr kdst;
1390 	uint32_t scopeid;
1391 	struct sockaddr_in6 *sa6_dst, sin6;
1392 	u_long mtu;
1393 
1394 	NET_EPOCH_ASSERT();
1395 
1396 	mtu = 0;
1397 	if (ro_pmtu == NULL || do_lookup) {
1398 		/*
1399 		 * Here ro_pmtu has final destination address, while
1400 		 * ro might represent immediate destination.
1401 		 * Use ro_pmtu destination since mtu might differ.
1402 		 */
1403 		if (ro_pmtu != NULL) {
1404 			sa6_dst = (struct sockaddr_in6 *)&ro_pmtu->ro_dst;
1405 			if (!IN6_ARE_ADDR_EQUAL(&sa6_dst->sin6_addr, dst))
1406 				ro_pmtu->ro_mtu = 0;
1407 		} else
1408 			sa6_dst = &sin6;
1409 
1410 		if (ro_pmtu == NULL || ro_pmtu->ro_mtu == 0) {
1411 			bzero(sa6_dst, sizeof(*sa6_dst));
1412 			sa6_dst->sin6_family = AF_INET6;
1413 			sa6_dst->sin6_len = sizeof(struct sockaddr_in6);
1414 			sa6_dst->sin6_addr = *dst;
1415 
1416 			in6_splitscope(dst, &kdst, &scopeid);
1417 			nh = fib6_lookup(fibnum, &kdst, scopeid, NHR_NONE, 0);
1418 			if (nh != NULL) {
1419 				mtu = nh->nh_mtu;
1420 				if (ro_pmtu != NULL)
1421 					ro_pmtu->ro_mtu = mtu;
1422 			}
1423 		} else
1424 			mtu = ro_pmtu->ro_mtu;
1425 	}
1426 
1427 	if (ro_pmtu != NULL && ro_pmtu->ro_nh != NULL)
1428 		mtu = ro_pmtu->ro_nh->nh_mtu;
1429 
1430 	ip6_calcmtu(ifp, dst, mtu, mtup, proto);
1431 }
1432 
1433 /*
1434  * Calculate MTU based on transmit @ifp, route mtu @rt_mtu and
1435  * hostcache data for @dst.
1436  * Stores mtu into @mtup.
1437  */
1438 static void
ip6_calcmtu(struct ifnet * ifp,const struct in6_addr * dst,u_long rt_mtu,u_long * mtup,u_int proto)1439 ip6_calcmtu(struct ifnet *ifp, const struct in6_addr *dst, u_long rt_mtu,
1440     u_long *mtup, u_int proto)
1441 {
1442 	u_long mtu = 0;
1443 
1444 	if (rt_mtu > 0) {
1445 		/* Skip the hostcache if the protocol handles PMTU changes. */
1446 		if (proto != IPPROTO_TCP && proto != IPPROTO_SCTP) {
1447 			struct in_conninfo inc = {
1448 			    .inc_flags = INC_ISIPV6,
1449 			    .inc6_faddr = *dst,
1450 			};
1451 
1452 			mtu = tcp_hc_getmtu(&inc);
1453 		}
1454 
1455 		if (mtu)
1456 			mtu = min(mtu, rt_mtu);
1457 		else
1458 			mtu = rt_mtu;
1459 	}
1460 
1461 	if (mtu == 0)
1462 		mtu = in6_ifmtu(ifp);
1463 
1464 	*mtup = mtu;
1465 }
1466 
1467 /*
1468  * IP6 socket option processing.
1469  */
1470 int
ip6_ctloutput(struct socket * so,struct sockopt * sopt)1471 ip6_ctloutput(struct socket *so, struct sockopt *sopt)
1472 {
1473 	int optdatalen, uproto;
1474 	void *optdata;
1475 	struct inpcb *inp = sotoinpcb(so);
1476 	int error, optval;
1477 	int level, op, optname;
1478 	int optlen;
1479 	struct thread *td;
1480 #ifdef	RSS
1481 	uint32_t rss_bucket;
1482 	int retval;
1483 #endif
1484 
1485 /*
1486  * Don't use more than a quarter of mbuf clusters.  N.B.:
1487  * nmbclusters is an int, but nmbclusters * MCLBYTES may overflow
1488  * on LP64 architectures, so cast to u_long to avoid undefined
1489  * behavior.  ILP32 architectures cannot have nmbclusters
1490  * large enough to overflow for other reasons.
1491  */
1492 #define IPV6_PKTOPTIONS_MBUF_LIMIT	((u_long)nmbclusters * MCLBYTES / 4)
1493 
1494 	level = sopt->sopt_level;
1495 	op = sopt->sopt_dir;
1496 	optname = sopt->sopt_name;
1497 	optlen = sopt->sopt_valsize;
1498 	td = sopt->sopt_td;
1499 	error = 0;
1500 	optval = 0;
1501 	uproto = (int)so->so_proto->pr_protocol;
1502 
1503 	if (level != IPPROTO_IPV6) {
1504 		error = EINVAL;
1505 
1506 		if (sopt->sopt_level == SOL_SOCKET &&
1507 		    sopt->sopt_dir == SOPT_SET) {
1508 			switch (sopt->sopt_name) {
1509 			case SO_SETFIB:
1510 				error = sooptcopyin(sopt, &optval,
1511 				    sizeof(optval), sizeof(optval));
1512 				if (error != 0)
1513 					break;
1514 
1515 				INP_WLOCK(inp);
1516 				if ((inp->inp_flags & INP_BOUNDFIB) != 0 &&
1517 				    optval != so->so_fibnum) {
1518 					INP_WUNLOCK(inp);
1519 					error = EISCONN;
1520 					break;
1521 				}
1522 				error = sosetfib(inp->inp_socket, optval);
1523 				if (error == 0)
1524 					inp->inp_inc.inc_fibnum = optval;
1525 				INP_WUNLOCK(inp);
1526 				break;
1527 			case SO_MAX_PACING_RATE:
1528 #ifdef RATELIMIT
1529 				INP_WLOCK(inp);
1530 				inp->inp_flags2 |= INP_RATE_LIMIT_CHANGED;
1531 				INP_WUNLOCK(inp);
1532 				error = 0;
1533 #else
1534 				error = EOPNOTSUPP;
1535 #endif
1536 				break;
1537 			default:
1538 				break;
1539 			}
1540 		}
1541 	} else {		/* level == IPPROTO_IPV6 */
1542 		switch (op) {
1543 		case SOPT_SET:
1544 			switch (optname) {
1545 			case IPV6_2292PKTOPTIONS:
1546 #ifdef IPV6_PKTOPTIONS
1547 			case IPV6_PKTOPTIONS:
1548 #endif
1549 			{
1550 				struct mbuf *m;
1551 
1552 				if (optlen > IPV6_PKTOPTIONS_MBUF_LIMIT) {
1553 					printf("ip6_ctloutput: mbuf limit hit\n");
1554 					error = ENOBUFS;
1555 					break;
1556 				}
1557 
1558 				error = soopt_getm(sopt, &m); /* XXX */
1559 				if (error != 0)
1560 					break;
1561 				error = soopt_mcopyin(sopt, m); /* XXX */
1562 				if (error != 0)
1563 					break;
1564 				INP_WLOCK(inp);
1565 				error = ip6_pcbopts(&inp->in6p_outputopts, m,
1566 				    so, sopt);
1567 				INP_WUNLOCK(inp);
1568 				m_freem(m); /* XXX */
1569 				break;
1570 			}
1571 
1572 			/*
1573 			 * Use of some Hop-by-Hop options or some
1574 			 * Destination options, might require special
1575 			 * privilege.  That is, normal applications
1576 			 * (without special privilege) might be forbidden
1577 			 * from setting certain options in outgoing packets,
1578 			 * and might never see certain options in received
1579 			 * packets. [RFC 2292 Section 6]
1580 			 * KAME specific note:
1581 			 *  KAME prevents non-privileged users from sending or
1582 			 *  receiving ANY hbh/dst options in order to avoid
1583 			 *  overhead of parsing options in the kernel.
1584 			 */
1585 			case IPV6_RECVHOPOPTS:
1586 			case IPV6_RECVDSTOPTS:
1587 			case IPV6_RECVRTHDRDSTOPTS:
1588 				if (td != NULL) {
1589 					error = priv_check(td,
1590 					    PRIV_NETINET_SETHDROPTS);
1591 					if (error)
1592 						break;
1593 				}
1594 				/* FALLTHROUGH */
1595 			case IPV6_UNICAST_HOPS:
1596 			case IPV6_HOPLIMIT:
1597 
1598 			case IPV6_RECVPKTINFO:
1599 			case IPV6_RECVHOPLIMIT:
1600 			case IPV6_RECVRTHDR:
1601 			case IPV6_RECVPATHMTU:
1602 			case IPV6_RECVTCLASS:
1603 			case IPV6_RECVFLOWID:
1604 #ifdef	RSS
1605 			case IPV6_RECVRSSBUCKETID:
1606 #endif
1607 			case IPV6_V6ONLY:
1608 			case IPV6_AUTOFLOWLABEL:
1609 			case IPV6_ORIGDSTADDR:
1610 			case IPV6_BINDANY:
1611 			case IPV6_VLAN_PCP:
1612 				if (optname == IPV6_BINDANY && td != NULL) {
1613 					error = priv_check(td,
1614 					    PRIV_NETINET_BINDANY);
1615 					if (error)
1616 						break;
1617 				}
1618 
1619 				if (optlen != sizeof(int)) {
1620 					error = EINVAL;
1621 					break;
1622 				}
1623 				error = sooptcopyin(sopt, &optval,
1624 					sizeof optval, sizeof optval);
1625 				if (error)
1626 					break;
1627 				switch (optname) {
1628 				case IPV6_UNICAST_HOPS:
1629 					if (optval < -1 || optval >= 256)
1630 						error = EINVAL;
1631 					else {
1632 						/* -1 = kernel default */
1633 						inp->in6p_hops = optval;
1634 						if ((inp->inp_vflag &
1635 						     INP_IPV4) != 0)
1636 							inp->inp_ip_ttl = optval;
1637 					}
1638 					break;
1639 #define OPTSET(bit) \
1640 do { \
1641 	INP_WLOCK(inp); \
1642 	if (optval) \
1643 		inp->inp_flags |= (bit); \
1644 	else \
1645 		inp->inp_flags &= ~(bit); \
1646 	INP_WUNLOCK(inp); \
1647 } while (/*CONSTCOND*/ 0)
1648 #define OPTSET2292(bit) \
1649 do { \
1650 	INP_WLOCK(inp); \
1651 	inp->inp_flags |= IN6P_RFC2292; \
1652 	if (optval) \
1653 		inp->inp_flags |= (bit); \
1654 	else \
1655 		inp->inp_flags &= ~(bit); \
1656 	INP_WUNLOCK(inp); \
1657 } while (/*CONSTCOND*/ 0)
1658 #define OPTBIT(bit) (inp->inp_flags & (bit) ? 1 : 0)
1659 
1660 #define OPTSET2_N(bit, val) do {					\
1661 	if (val)							\
1662 		inp->inp_flags2 |= bit;					\
1663 	else								\
1664 		inp->inp_flags2 &= ~bit;				\
1665 } while (0)
1666 #define OPTSET2(bit, val) do {						\
1667 	INP_WLOCK(inp);							\
1668 	OPTSET2_N(bit, val);						\
1669 	INP_WUNLOCK(inp);						\
1670 } while (0)
1671 #define OPTBIT2(bit) (inp->inp_flags2 & (bit) ? 1 : 0)
1672 #define OPTSET2292_EXCLUSIVE(bit)					\
1673 do {									\
1674 	INP_WLOCK(inp);							\
1675 	if (OPTBIT(IN6P_RFC2292)) {					\
1676 		error = EINVAL;						\
1677 	} else {							\
1678 		if (optval)						\
1679 			inp->inp_flags |= (bit);			\
1680 		else							\
1681 			inp->inp_flags &= ~(bit);			\
1682 	}								\
1683 	INP_WUNLOCK(inp);						\
1684 } while (/*CONSTCOND*/ 0)
1685 
1686 				case IPV6_RECVPKTINFO:
1687 					OPTSET2292_EXCLUSIVE(IN6P_PKTINFO);
1688 					break;
1689 
1690 				case IPV6_HOPLIMIT:
1691 				{
1692 					struct ip6_pktopts **optp;
1693 
1694 					/* cannot mix with RFC2292 */
1695 					if (OPTBIT(IN6P_RFC2292)) {
1696 						error = EINVAL;
1697 						break;
1698 					}
1699 					INP_WLOCK(inp);
1700 					if (inp->inp_flags & INP_DROPPED) {
1701 						INP_WUNLOCK(inp);
1702 						return (ECONNRESET);
1703 					}
1704 					optp = &inp->in6p_outputopts;
1705 					error = ip6_pcbopt(IPV6_HOPLIMIT,
1706 					    (u_char *)&optval, sizeof(optval),
1707 					    optp, (td != NULL) ? td->td_ucred :
1708 					    NULL, uproto);
1709 					INP_WUNLOCK(inp);
1710 					break;
1711 				}
1712 
1713 				case IPV6_RECVHOPLIMIT:
1714 					OPTSET2292_EXCLUSIVE(IN6P_HOPLIMIT);
1715 					break;
1716 
1717 				case IPV6_RECVHOPOPTS:
1718 					OPTSET2292_EXCLUSIVE(IN6P_HOPOPTS);
1719 					break;
1720 
1721 				case IPV6_RECVDSTOPTS:
1722 					OPTSET2292_EXCLUSIVE(IN6P_DSTOPTS);
1723 					break;
1724 
1725 				case IPV6_RECVRTHDRDSTOPTS:
1726 					OPTSET2292_EXCLUSIVE(IN6P_RTHDRDSTOPTS);
1727 					break;
1728 
1729 				case IPV6_RECVRTHDR:
1730 					OPTSET2292_EXCLUSIVE(IN6P_RTHDR);
1731 					break;
1732 
1733 				case IPV6_RECVPATHMTU:
1734 					/*
1735 					 * We ignore this option for TCP
1736 					 * sockets.
1737 					 * (RFC3542 leaves this case
1738 					 * unspecified.)
1739 					 */
1740 					if (uproto != IPPROTO_TCP)
1741 						OPTSET(IN6P_MTU);
1742 					break;
1743 
1744 				case IPV6_RECVFLOWID:
1745 					OPTSET2(INP_RECVFLOWID, optval);
1746 					break;
1747 
1748 #ifdef	RSS
1749 				case IPV6_RECVRSSBUCKETID:
1750 					OPTSET2(INP_RECVRSSBUCKETID, optval);
1751 					break;
1752 #endif
1753 
1754 				case IPV6_V6ONLY:
1755 					INP_WLOCK(inp);
1756 					if (inp->inp_lport ||
1757 					    !IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr)) {
1758 						/*
1759 						 * The socket is already bound.
1760 						 */
1761 						INP_WUNLOCK(inp);
1762 						error = EINVAL;
1763 						break;
1764 					}
1765 					if (optval) {
1766 						inp->inp_flags |= IN6P_IPV6_V6ONLY;
1767 						inp->inp_vflag &= ~INP_IPV4;
1768 					} else {
1769 						inp->inp_flags &= ~IN6P_IPV6_V6ONLY;
1770 						inp->inp_vflag |= INP_IPV4;
1771 					}
1772 					INP_WUNLOCK(inp);
1773 					break;
1774 				case IPV6_RECVTCLASS:
1775 					/* cannot mix with RFC2292 XXX */
1776 					OPTSET2292_EXCLUSIVE(IN6P_TCLASS);
1777 					break;
1778 				case IPV6_AUTOFLOWLABEL:
1779 					OPTSET(IN6P_AUTOFLOWLABEL);
1780 					break;
1781 
1782 				case IPV6_ORIGDSTADDR:
1783 					OPTSET2(INP_ORIGDSTADDR, optval);
1784 					break;
1785 				case IPV6_BINDANY:
1786 					OPTSET(INP_BINDANY);
1787 					break;
1788 				case IPV6_VLAN_PCP:
1789 					if ((optval >= -1) && (optval <=
1790 					    (INP_2PCP_MASK >> INP_2PCP_SHIFT))) {
1791 						if (optval == -1) {
1792 							INP_WLOCK(inp);
1793 							inp->inp_flags2 &=
1794 							    ~(INP_2PCP_SET |
1795 							    INP_2PCP_MASK);
1796 							INP_WUNLOCK(inp);
1797 						} else {
1798 							INP_WLOCK(inp);
1799 							inp->inp_flags2 |=
1800 							    INP_2PCP_SET;
1801 							inp->inp_flags2 &=
1802 							    ~INP_2PCP_MASK;
1803 							inp->inp_flags2 |=
1804 							    optval <<
1805 							    INP_2PCP_SHIFT;
1806 							INP_WUNLOCK(inp);
1807 						}
1808 					} else
1809 						error = EINVAL;
1810 					break;
1811 				}
1812 				break;
1813 
1814 			case IPV6_TCLASS:
1815 			case IPV6_DONTFRAG:
1816 			case IPV6_USE_MIN_MTU:
1817 			case IPV6_PREFER_TEMPADDR:
1818 				if (optlen != sizeof(optval)) {
1819 					error = EINVAL;
1820 					break;
1821 				}
1822 				error = sooptcopyin(sopt, &optval,
1823 					sizeof optval, sizeof optval);
1824 				if (error)
1825 					break;
1826 				{
1827 					struct ip6_pktopts **optp;
1828 					INP_WLOCK(inp);
1829 					if (inp->inp_flags & INP_DROPPED) {
1830 						INP_WUNLOCK(inp);
1831 						return (ECONNRESET);
1832 					}
1833 					optp = &inp->in6p_outputopts;
1834 					error = ip6_pcbopt(optname,
1835 					    (u_char *)&optval, sizeof(optval),
1836 					    optp, (td != NULL) ? td->td_ucred :
1837 					    NULL, uproto);
1838 					INP_WUNLOCK(inp);
1839 					break;
1840 				}
1841 
1842 			case IPV6_2292PKTINFO:
1843 			case IPV6_2292HOPLIMIT:
1844 			case IPV6_2292HOPOPTS:
1845 			case IPV6_2292DSTOPTS:
1846 			case IPV6_2292RTHDR:
1847 				/* RFC 2292 */
1848 				if (optlen != sizeof(int)) {
1849 					error = EINVAL;
1850 					break;
1851 				}
1852 				error = sooptcopyin(sopt, &optval,
1853 					sizeof optval, sizeof optval);
1854 				if (error)
1855 					break;
1856 				switch (optname) {
1857 				case IPV6_2292PKTINFO:
1858 					OPTSET2292(IN6P_PKTINFO);
1859 					break;
1860 				case IPV6_2292HOPLIMIT:
1861 					OPTSET2292(IN6P_HOPLIMIT);
1862 					break;
1863 				case IPV6_2292HOPOPTS:
1864 					/*
1865 					 * Check super-user privilege.
1866 					 * See comments for IPV6_RECVHOPOPTS.
1867 					 */
1868 					if (td != NULL) {
1869 						error = priv_check(td,
1870 						    PRIV_NETINET_SETHDROPTS);
1871 						if (error)
1872 							return (error);
1873 					}
1874 					OPTSET2292(IN6P_HOPOPTS);
1875 					break;
1876 				case IPV6_2292DSTOPTS:
1877 					if (td != NULL) {
1878 						error = priv_check(td,
1879 						    PRIV_NETINET_SETHDROPTS);
1880 						if (error)
1881 							return (error);
1882 					}
1883 					OPTSET2292(IN6P_DSTOPTS|IN6P_RTHDRDSTOPTS); /* XXX */
1884 					break;
1885 				case IPV6_2292RTHDR:
1886 					OPTSET2292(IN6P_RTHDR);
1887 					break;
1888 				}
1889 				break;
1890 			case IPV6_PKTINFO:
1891 			case IPV6_HOPOPTS:
1892 			case IPV6_RTHDR:
1893 			case IPV6_DSTOPTS:
1894 			case IPV6_RTHDRDSTOPTS:
1895 			case IPV6_NEXTHOP:
1896 			{
1897 				/* new advanced API (RFC3542) */
1898 				u_char *optbuf;
1899 				u_char optbuf_storage[MCLBYTES];
1900 				int optlen;
1901 				struct ip6_pktopts **optp;
1902 
1903 				/* cannot mix with RFC2292 */
1904 				if (OPTBIT(IN6P_RFC2292)) {
1905 					error = EINVAL;
1906 					break;
1907 				}
1908 
1909 				/*
1910 				 * We only ensure valsize is not too large
1911 				 * here.  Further validation will be done
1912 				 * later.
1913 				 */
1914 				error = sooptcopyin(sopt, optbuf_storage,
1915 				    sizeof(optbuf_storage), 0);
1916 				if (error)
1917 					break;
1918 				optlen = sopt->sopt_valsize;
1919 				optbuf = optbuf_storage;
1920 				INP_WLOCK(inp);
1921 				if (inp->inp_flags & INP_DROPPED) {
1922 					INP_WUNLOCK(inp);
1923 					return (ECONNRESET);
1924 				}
1925 				optp = &inp->in6p_outputopts;
1926 				error = ip6_pcbopt(optname, optbuf, optlen,
1927 				    optp, (td != NULL) ? td->td_ucred : NULL,
1928 				    uproto);
1929 				INP_WUNLOCK(inp);
1930 				break;
1931 			}
1932 #undef OPTSET
1933 
1934 			case IPV6_MULTICAST_IF:
1935 			case IPV6_MULTICAST_HOPS:
1936 			case IPV6_MULTICAST_LOOP:
1937 			case IPV6_JOIN_GROUP:
1938 			case IPV6_LEAVE_GROUP:
1939 			case IPV6_MSFILTER:
1940 			case MCAST_BLOCK_SOURCE:
1941 			case MCAST_UNBLOCK_SOURCE:
1942 			case MCAST_JOIN_GROUP:
1943 			case MCAST_LEAVE_GROUP:
1944 			case MCAST_JOIN_SOURCE_GROUP:
1945 			case MCAST_LEAVE_SOURCE_GROUP:
1946 				error = ip6_setmoptions(inp, sopt);
1947 				break;
1948 
1949 			case IPV6_PORTRANGE:
1950 				error = sooptcopyin(sopt, &optval,
1951 				    sizeof optval, sizeof optval);
1952 				if (error)
1953 					break;
1954 
1955 				INP_WLOCK(inp);
1956 				switch (optval) {
1957 				case IPV6_PORTRANGE_DEFAULT:
1958 					inp->inp_flags &= ~(INP_LOWPORT);
1959 					inp->inp_flags &= ~(INP_HIGHPORT);
1960 					break;
1961 
1962 				case IPV6_PORTRANGE_HIGH:
1963 					inp->inp_flags &= ~(INP_LOWPORT);
1964 					inp->inp_flags |= INP_HIGHPORT;
1965 					break;
1966 
1967 				case IPV6_PORTRANGE_LOW:
1968 					inp->inp_flags &= ~(INP_HIGHPORT);
1969 					inp->inp_flags |= INP_LOWPORT;
1970 					break;
1971 
1972 				default:
1973 					error = EINVAL;
1974 					break;
1975 				}
1976 				INP_WUNLOCK(inp);
1977 				break;
1978 
1979 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
1980 			case IPV6_IPSEC_POLICY:
1981 				if (IPSEC_ENABLED(ipv6)) {
1982 					error = IPSEC_PCBCTL(ipv6, inp, sopt);
1983 					break;
1984 				}
1985 				/* FALLTHROUGH */
1986 #endif /* IPSEC */
1987 
1988 			default:
1989 				error = ENOPROTOOPT;
1990 				break;
1991 			}
1992 			break;
1993 
1994 		case SOPT_GET:
1995 			switch (optname) {
1996 			case IPV6_2292PKTOPTIONS:
1997 #ifdef IPV6_PKTOPTIONS
1998 			case IPV6_PKTOPTIONS:
1999 #endif
2000 				/*
2001 				 * RFC3542 (effectively) deprecated the
2002 				 * semantics of the 2292-style pktoptions.
2003 				 * Since it was not reliable in nature (i.e.,
2004 				 * applications had to expect the lack of some
2005 				 * information after all), it would make sense
2006 				 * to simplify this part by always returning
2007 				 * empty data.
2008 				 */
2009 				sopt->sopt_valsize = 0;
2010 				break;
2011 
2012 			case IPV6_RECVHOPOPTS:
2013 			case IPV6_RECVDSTOPTS:
2014 			case IPV6_RECVRTHDRDSTOPTS:
2015 			case IPV6_UNICAST_HOPS:
2016 			case IPV6_RECVPKTINFO:
2017 			case IPV6_RECVHOPLIMIT:
2018 			case IPV6_RECVRTHDR:
2019 			case IPV6_RECVPATHMTU:
2020 
2021 			case IPV6_V6ONLY:
2022 			case IPV6_PORTRANGE:
2023 			case IPV6_RECVTCLASS:
2024 			case IPV6_AUTOFLOWLABEL:
2025 			case IPV6_BINDANY:
2026 			case IPV6_FLOWID:
2027 			case IPV6_FLOWTYPE:
2028 			case IPV6_RECVFLOWID:
2029 #ifdef	RSS
2030 			case IPV6_RSSBUCKETID:
2031 			case IPV6_RECVRSSBUCKETID:
2032 #endif
2033 			case IPV6_VLAN_PCP:
2034 				switch (optname) {
2035 				case IPV6_RECVHOPOPTS:
2036 					optval = OPTBIT(IN6P_HOPOPTS);
2037 					break;
2038 
2039 				case IPV6_RECVDSTOPTS:
2040 					optval = OPTBIT(IN6P_DSTOPTS);
2041 					break;
2042 
2043 				case IPV6_RECVRTHDRDSTOPTS:
2044 					optval = OPTBIT(IN6P_RTHDRDSTOPTS);
2045 					break;
2046 
2047 				case IPV6_UNICAST_HOPS:
2048 					optval = inp->in6p_hops;
2049 					break;
2050 
2051 				case IPV6_RECVPKTINFO:
2052 					optval = OPTBIT(IN6P_PKTINFO);
2053 					break;
2054 
2055 				case IPV6_RECVHOPLIMIT:
2056 					optval = OPTBIT(IN6P_HOPLIMIT);
2057 					break;
2058 
2059 				case IPV6_RECVRTHDR:
2060 					optval = OPTBIT(IN6P_RTHDR);
2061 					break;
2062 
2063 				case IPV6_RECVPATHMTU:
2064 					optval = OPTBIT(IN6P_MTU);
2065 					break;
2066 
2067 				case IPV6_V6ONLY:
2068 					optval = OPTBIT(IN6P_IPV6_V6ONLY);
2069 					break;
2070 
2071 				case IPV6_PORTRANGE:
2072 				    {
2073 					int flags;
2074 					flags = inp->inp_flags;
2075 					if (flags & INP_HIGHPORT)
2076 						optval = IPV6_PORTRANGE_HIGH;
2077 					else if (flags & INP_LOWPORT)
2078 						optval = IPV6_PORTRANGE_LOW;
2079 					else
2080 						optval = 0;
2081 					break;
2082 				    }
2083 				case IPV6_RECVTCLASS:
2084 					optval = OPTBIT(IN6P_TCLASS);
2085 					break;
2086 
2087 				case IPV6_AUTOFLOWLABEL:
2088 					optval = OPTBIT(IN6P_AUTOFLOWLABEL);
2089 					break;
2090 
2091 				case IPV6_ORIGDSTADDR:
2092 					optval = OPTBIT2(INP_ORIGDSTADDR);
2093 					break;
2094 
2095 				case IPV6_BINDANY:
2096 					optval = OPTBIT(INP_BINDANY);
2097 					break;
2098 
2099 				case IPV6_FLOWID:
2100 					optval = inp->inp_flowid;
2101 					break;
2102 
2103 				case IPV6_FLOWTYPE:
2104 					optval = inp->inp_flowtype;
2105 					break;
2106 
2107 				case IPV6_RECVFLOWID:
2108 					optval = OPTBIT2(INP_RECVFLOWID);
2109 					break;
2110 #ifdef	RSS
2111 				case IPV6_RSSBUCKETID:
2112 					retval =
2113 					    rss_hash2bucket(inp->inp_flowid,
2114 					    inp->inp_flowtype,
2115 					    &rss_bucket);
2116 					if (retval == 0)
2117 						optval = rss_bucket;
2118 					else
2119 						error = EINVAL;
2120 					break;
2121 
2122 				case IPV6_RECVRSSBUCKETID:
2123 					optval = OPTBIT2(INP_RECVRSSBUCKETID);
2124 					break;
2125 #endif
2126 
2127 
2128 				case IPV6_VLAN_PCP:
2129 					if (OPTBIT2(INP_2PCP_SET)) {
2130 						optval = (inp->inp_flags2 &
2131 							    INP_2PCP_MASK) >>
2132 							    INP_2PCP_SHIFT;
2133 					} else {
2134 						optval = -1;
2135 					}
2136 					break;
2137 				}
2138 
2139 				if (error)
2140 					break;
2141 				error = sooptcopyout(sopt, &optval,
2142 					sizeof optval);
2143 				break;
2144 
2145 			case IPV6_PATHMTU:
2146 			{
2147 				u_long pmtu = 0;
2148 				struct ip6_mtuinfo mtuinfo;
2149 				struct in6_addr addr;
2150 
2151 				if (!(so->so_state & SS_ISCONNECTED))
2152 					return (ENOTCONN);
2153 				/*
2154 				 * XXX: we dot not consider the case of source
2155 				 * routing, or optional information to specify
2156 				 * the outgoing interface.
2157 				 * Copy faddr out of inp to avoid holding lock
2158 				 * on inp during route lookup.
2159 				 */
2160 				INP_RLOCK(inp);
2161 				bcopy(&inp->in6p_faddr, &addr, sizeof(addr));
2162 				INP_RUNLOCK(inp);
2163 				error = ip6_getpmtu_ctl(so->so_fibnum,
2164 				    &addr, &pmtu);
2165 				if (error)
2166 					break;
2167 				if (pmtu > IPV6_MAXPACKET)
2168 					pmtu = IPV6_MAXPACKET;
2169 
2170 				bzero(&mtuinfo, sizeof(mtuinfo));
2171 				mtuinfo.ip6m_mtu = (u_int32_t)pmtu;
2172 				optdata = (void *)&mtuinfo;
2173 				optdatalen = sizeof(mtuinfo);
2174 				error = sooptcopyout(sopt, optdata,
2175 				    optdatalen);
2176 				break;
2177 			}
2178 
2179 			case IPV6_2292PKTINFO:
2180 			case IPV6_2292HOPLIMIT:
2181 			case IPV6_2292HOPOPTS:
2182 			case IPV6_2292RTHDR:
2183 			case IPV6_2292DSTOPTS:
2184 				switch (optname) {
2185 				case IPV6_2292PKTINFO:
2186 					optval = OPTBIT(IN6P_PKTINFO);
2187 					break;
2188 				case IPV6_2292HOPLIMIT:
2189 					optval = OPTBIT(IN6P_HOPLIMIT);
2190 					break;
2191 				case IPV6_2292HOPOPTS:
2192 					optval = OPTBIT(IN6P_HOPOPTS);
2193 					break;
2194 				case IPV6_2292RTHDR:
2195 					optval = OPTBIT(IN6P_RTHDR);
2196 					break;
2197 				case IPV6_2292DSTOPTS:
2198 					optval = OPTBIT(IN6P_DSTOPTS|IN6P_RTHDRDSTOPTS);
2199 					break;
2200 				}
2201 				error = sooptcopyout(sopt, &optval,
2202 				    sizeof optval);
2203 				break;
2204 			case IPV6_PKTINFO:
2205 			case IPV6_HOPOPTS:
2206 			case IPV6_RTHDR:
2207 			case IPV6_DSTOPTS:
2208 			case IPV6_RTHDRDSTOPTS:
2209 			case IPV6_NEXTHOP:
2210 			case IPV6_TCLASS:
2211 			case IPV6_DONTFRAG:
2212 			case IPV6_USE_MIN_MTU:
2213 			case IPV6_PREFER_TEMPADDR:
2214 				error = ip6_getpcbopt(inp, optname, sopt);
2215 				break;
2216 
2217 			case IPV6_MULTICAST_IF:
2218 			case IPV6_MULTICAST_HOPS:
2219 			case IPV6_MULTICAST_LOOP:
2220 			case IPV6_MSFILTER:
2221 				error = ip6_getmoptions(inp, sopt);
2222 				break;
2223 
2224 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
2225 			case IPV6_IPSEC_POLICY:
2226 				if (IPSEC_ENABLED(ipv6)) {
2227 					error = IPSEC_PCBCTL(ipv6, inp, sopt);
2228 					break;
2229 				}
2230 				/* FALLTHROUGH */
2231 #endif /* IPSEC */
2232 			default:
2233 				error = ENOPROTOOPT;
2234 				break;
2235 			}
2236 			break;
2237 		}
2238 	}
2239 	return (error);
2240 }
2241 
2242 int
ip6_raw_ctloutput(struct socket * so,struct sockopt * sopt)2243 ip6_raw_ctloutput(struct socket *so, struct sockopt *sopt)
2244 {
2245 	int error = 0, optval, optlen;
2246 	const int icmp6off = offsetof(struct icmp6_hdr, icmp6_cksum);
2247 	struct inpcb *inp = sotoinpcb(so);
2248 	int level, op, optname;
2249 
2250 	level = sopt->sopt_level;
2251 	op = sopt->sopt_dir;
2252 	optname = sopt->sopt_name;
2253 	optlen = sopt->sopt_valsize;
2254 
2255 	if (level != IPPROTO_IPV6) {
2256 		return (EINVAL);
2257 	}
2258 
2259 	switch (optname) {
2260 	case IPV6_CHECKSUM:
2261 		/*
2262 		 * For ICMPv6 sockets, no modification allowed for checksum
2263 		 * offset, permit "no change" values to help existing apps.
2264 		 *
2265 		 * RFC3542 says: "An attempt to set IPV6_CHECKSUM
2266 		 * for an ICMPv6 socket will fail."
2267 		 * The current behavior does not meet RFC3542.
2268 		 */
2269 		switch (op) {
2270 		case SOPT_SET:
2271 			if (optlen != sizeof(int)) {
2272 				error = EINVAL;
2273 				break;
2274 			}
2275 			error = sooptcopyin(sopt, &optval, sizeof(optval),
2276 					    sizeof(optval));
2277 			if (error)
2278 				break;
2279 			if (optval < -1 || (optval % 2) != 0) {
2280 				/*
2281 				 * The API assumes non-negative even offset
2282 				 * values or -1 as a special value.
2283 				 */
2284 				error = EINVAL;
2285 			} else if (inp->inp_ip_p == IPPROTO_ICMPV6) {
2286 				if (optval != icmp6off)
2287 					error = EINVAL;
2288 			} else
2289 				inp->in6p_cksum = optval;
2290 			break;
2291 
2292 		case SOPT_GET:
2293 			if (inp->inp_ip_p == IPPROTO_ICMPV6)
2294 				optval = icmp6off;
2295 			else
2296 				optval = inp->in6p_cksum;
2297 
2298 			error = sooptcopyout(sopt, &optval, sizeof(optval));
2299 			break;
2300 
2301 		default:
2302 			error = EINVAL;
2303 			break;
2304 		}
2305 		break;
2306 
2307 	default:
2308 		error = ENOPROTOOPT;
2309 		break;
2310 	}
2311 
2312 	return (error);
2313 }
2314 
2315 /*
2316  * Set up IP6 options in pcb for insertion in output packets or
2317  * specifying behavior of outgoing packets.
2318  */
2319 static int
ip6_pcbopts(struct ip6_pktopts ** pktopt,struct mbuf * m,struct socket * so,struct sockopt * sopt)2320 ip6_pcbopts(struct ip6_pktopts **pktopt, struct mbuf *m,
2321     struct socket *so, struct sockopt *sopt)
2322 {
2323 	struct ip6_pktopts *opt = *pktopt;
2324 	int error = 0;
2325 	struct thread *td = sopt->sopt_td;
2326 	struct epoch_tracker et;
2327 
2328 	/* turn off any old options. */
2329 	if (opt) {
2330 #ifdef DIAGNOSTIC
2331 		if (opt->ip6po_pktinfo || opt->ip6po_nexthop ||
2332 		    opt->ip6po_hbh || opt->ip6po_dest1 || opt->ip6po_dest2 ||
2333 		    opt->ip6po_rhinfo.ip6po_rhi_rthdr)
2334 			printf("ip6_pcbopts: all specified options are cleared.\n");
2335 #endif
2336 		ip6_clearpktopts(opt, -1);
2337 	} else {
2338 		opt = malloc(sizeof(*opt), M_IP6OPT, M_NOWAIT);
2339 		if (opt == NULL)
2340 			return (ENOMEM);
2341 	}
2342 	*pktopt = NULL;
2343 
2344 	if (!m || m->m_len == 0) {
2345 		/*
2346 		 * Only turning off any previous options, regardless of
2347 		 * whether the opt is just created or given.
2348 		 */
2349 		free(opt, M_IP6OPT);
2350 		return (0);
2351 	}
2352 
2353 	/*  set options specified by user. */
2354 	NET_EPOCH_ENTER(et);
2355 	if ((error = ip6_setpktopts(m, opt, NULL, (td != NULL) ?
2356 	    td->td_ucred : NULL, so->so_proto->pr_protocol)) != 0) {
2357 		ip6_clearpktopts(opt, -1); /* XXX: discard all options */
2358 		free(opt, M_IP6OPT);
2359 		NET_EPOCH_EXIT(et);
2360 		return (error);
2361 	}
2362 	NET_EPOCH_EXIT(et);
2363 	*pktopt = opt;
2364 	return (0);
2365 }
2366 
2367 /*
2368  * initialize ip6_pktopts.  beware that there are non-zero default values in
2369  * the struct.
2370  */
2371 void
ip6_initpktopts(struct ip6_pktopts * opt)2372 ip6_initpktopts(struct ip6_pktopts *opt)
2373 {
2374 
2375 	bzero(opt, sizeof(*opt));
2376 	opt->ip6po_hlim = -1;	/* -1 means default hop limit */
2377 	opt->ip6po_tclass = -1;	/* -1 means default traffic class */
2378 	opt->ip6po_minmtu = IP6PO_MINMTU_MCASTONLY;
2379 	opt->ip6po_prefer_tempaddr = IP6PO_TEMPADDR_SYSTEM;
2380 }
2381 
2382 static int
ip6_pcbopt(int optname,u_char * buf,int len,struct ip6_pktopts ** pktopt,struct ucred * cred,int uproto)2383 ip6_pcbopt(int optname, u_char *buf, int len, struct ip6_pktopts **pktopt,
2384     struct ucred *cred, int uproto)
2385 {
2386 	struct epoch_tracker et;
2387 	struct ip6_pktopts *opt;
2388 	int ret;
2389 
2390 	if (*pktopt == NULL) {
2391 		*pktopt = malloc(sizeof(struct ip6_pktopts), M_IP6OPT,
2392 		    M_NOWAIT);
2393 		if (*pktopt == NULL)
2394 			return (ENOBUFS);
2395 		ip6_initpktopts(*pktopt);
2396 	}
2397 	opt = *pktopt;
2398 
2399 	NET_EPOCH_ENTER(et);
2400 	ret = ip6_setpktopt(optname, buf, len, opt, cred, 1, 0, uproto);
2401 	NET_EPOCH_EXIT(et);
2402 
2403 	return (ret);
2404 }
2405 
2406 #define GET_PKTOPT_VAR(field, lenexpr) do {				\
2407 	if (pktopt && pktopt->field) {					\
2408 		INP_RUNLOCK(inp);					\
2409 		optdata = malloc(sopt->sopt_valsize, M_TEMP, M_WAITOK);	\
2410 		malloc_optdata = true;					\
2411 		INP_RLOCK(inp);						\
2412 		if (inp->inp_flags & INP_DROPPED) {			\
2413 			INP_RUNLOCK(inp);				\
2414 			free(optdata, M_TEMP);				\
2415 			return (ECONNRESET);				\
2416 		}							\
2417 		pktopt = inp->in6p_outputopts;				\
2418 		if (pktopt && pktopt->field) {				\
2419 			optdatalen = min(lenexpr, sopt->sopt_valsize);	\
2420 			bcopy(pktopt->field, optdata, optdatalen);	\
2421 		} else {						\
2422 			free(optdata, M_TEMP);				\
2423 			optdata = NULL;					\
2424 			malloc_optdata = false;				\
2425 		}							\
2426 	}								\
2427 } while(0)
2428 
2429 #define GET_PKTOPT_EXT_HDR(field) GET_PKTOPT_VAR(field,			\
2430 	(((struct ip6_ext *)pktopt->field)->ip6e_len + 1) << 3)
2431 
2432 #define GET_PKTOPT_SOCKADDR(field) GET_PKTOPT_VAR(field,		\
2433 	pktopt->field->sa_len)
2434 
2435 static int
ip6_getpcbopt(struct inpcb * inp,int optname,struct sockopt * sopt)2436 ip6_getpcbopt(struct inpcb *inp, int optname, struct sockopt *sopt)
2437 {
2438 	void *optdata = NULL;
2439 	bool malloc_optdata = false;
2440 	int optdatalen = 0;
2441 	int error = 0;
2442 	struct in6_pktinfo null_pktinfo;
2443 	int deftclass = 0, on;
2444 	int defminmtu = IP6PO_MINMTU_MCASTONLY;
2445 	int defpreftemp = IP6PO_TEMPADDR_SYSTEM;
2446 	struct ip6_pktopts *pktopt;
2447 
2448 	INP_RLOCK(inp);
2449 	pktopt = inp->in6p_outputopts;
2450 
2451 	switch (optname) {
2452 	case IPV6_PKTINFO:
2453 		optdata = (void *)&null_pktinfo;
2454 		if (pktopt && pktopt->ip6po_pktinfo) {
2455 			bcopy(pktopt->ip6po_pktinfo, &null_pktinfo,
2456 			    sizeof(null_pktinfo));
2457 			in6_clearscope(&null_pktinfo.ipi6_addr);
2458 		} else {
2459 			/* XXX: we don't have to do this every time... */
2460 			bzero(&null_pktinfo, sizeof(null_pktinfo));
2461 		}
2462 		optdatalen = sizeof(struct in6_pktinfo);
2463 		break;
2464 	case IPV6_TCLASS:
2465 		if (pktopt && pktopt->ip6po_tclass >= 0)
2466 			deftclass = pktopt->ip6po_tclass;
2467 		optdata = (void *)&deftclass;
2468 		optdatalen = sizeof(int);
2469 		break;
2470 	case IPV6_HOPOPTS:
2471 		GET_PKTOPT_EXT_HDR(ip6po_hbh);
2472 		break;
2473 	case IPV6_RTHDR:
2474 		GET_PKTOPT_EXT_HDR(ip6po_rthdr);
2475 		break;
2476 	case IPV6_RTHDRDSTOPTS:
2477 		GET_PKTOPT_EXT_HDR(ip6po_dest1);
2478 		break;
2479 	case IPV6_DSTOPTS:
2480 		GET_PKTOPT_EXT_HDR(ip6po_dest2);
2481 		break;
2482 	case IPV6_NEXTHOP:
2483 		GET_PKTOPT_SOCKADDR(ip6po_nexthop);
2484 		break;
2485 	case IPV6_USE_MIN_MTU:
2486 		if (pktopt)
2487 			defminmtu = pktopt->ip6po_minmtu;
2488 		optdata = (void *)&defminmtu;
2489 		optdatalen = sizeof(int);
2490 		break;
2491 	case IPV6_DONTFRAG:
2492 		if (pktopt && ((pktopt->ip6po_flags) & IP6PO_DONTFRAG))
2493 			on = 1;
2494 		else
2495 			on = 0;
2496 		optdata = (void *)&on;
2497 		optdatalen = sizeof(on);
2498 		break;
2499 	case IPV6_PREFER_TEMPADDR:
2500 		if (pktopt)
2501 			defpreftemp = pktopt->ip6po_prefer_tempaddr;
2502 		optdata = (void *)&defpreftemp;
2503 		optdatalen = sizeof(int);
2504 		break;
2505 	default:		/* should not happen */
2506 #ifdef DIAGNOSTIC
2507 		panic("ip6_getpcbopt: unexpected option\n");
2508 #endif
2509 		INP_RUNLOCK(inp);
2510 		return (ENOPROTOOPT);
2511 	}
2512 	INP_RUNLOCK(inp);
2513 
2514 	error = sooptcopyout(sopt, optdata, optdatalen);
2515 	if (malloc_optdata)
2516 		free(optdata, M_TEMP);
2517 
2518 	return (error);
2519 }
2520 
2521 void
ip6_clearpktopts(struct ip6_pktopts * pktopt,int optname)2522 ip6_clearpktopts(struct ip6_pktopts *pktopt, int optname)
2523 {
2524 	if (pktopt == NULL)
2525 		return;
2526 
2527 	if (optname == -1 || optname == IPV6_PKTINFO) {
2528 		if (pktopt->ip6po_pktinfo)
2529 			free(pktopt->ip6po_pktinfo, M_IP6OPT);
2530 		pktopt->ip6po_pktinfo = NULL;
2531 	}
2532 	if (optname == -1 || optname == IPV6_HOPLIMIT) {
2533 		pktopt->ip6po_hlim = -1;
2534 		pktopt->ip6po_valid &= ~IP6PO_VALID_HLIM;
2535 	}
2536 	if (optname == -1 || optname == IPV6_TCLASS) {
2537 		pktopt->ip6po_tclass = -1;
2538 		pktopt->ip6po_valid &= ~IP6PO_VALID_TC;
2539 	}
2540 	if (optname == -1 || optname == IPV6_NEXTHOP) {
2541 		if (pktopt->ip6po_nextroute.ro_nh) {
2542 			NH_FREE(pktopt->ip6po_nextroute.ro_nh);
2543 			pktopt->ip6po_nextroute.ro_nh = NULL;
2544 		}
2545 		if (pktopt->ip6po_nexthop)
2546 			free(pktopt->ip6po_nexthop, M_IP6OPT);
2547 		pktopt->ip6po_nexthop = NULL;
2548 		pktopt->ip6po_valid &= ~IP6PO_VALID_NHINFO;
2549 	}
2550 	if (optname == -1 || optname == IPV6_HOPOPTS) {
2551 		if (pktopt->ip6po_hbh)
2552 			free(pktopt->ip6po_hbh, M_IP6OPT);
2553 		pktopt->ip6po_hbh = NULL;
2554 		pktopt->ip6po_valid &= ~IP6PO_VALID_HBH;
2555 	}
2556 	if (optname == -1 || optname == IPV6_RTHDRDSTOPTS) {
2557 		if (pktopt->ip6po_dest1)
2558 			free(pktopt->ip6po_dest1, M_IP6OPT);
2559 		pktopt->ip6po_dest1 = NULL;
2560 		pktopt->ip6po_valid &= ~IP6PO_VALID_DEST1;
2561 	}
2562 	if (optname == -1 || optname == IPV6_RTHDR) {
2563 		if (pktopt->ip6po_rhinfo.ip6po_rhi_rthdr)
2564 			free(pktopt->ip6po_rhinfo.ip6po_rhi_rthdr, M_IP6OPT);
2565 		pktopt->ip6po_rhinfo.ip6po_rhi_rthdr = NULL;
2566 		if (pktopt->ip6po_route.ro_nh) {
2567 			NH_FREE(pktopt->ip6po_route.ro_nh);
2568 			pktopt->ip6po_route.ro_nh = NULL;
2569 		}
2570 		pktopt->ip6po_valid &= ~IP6PO_VALID_RHINFO;
2571 	}
2572 	if (optname == -1 || optname == IPV6_DSTOPTS) {
2573 		if (pktopt->ip6po_dest2)
2574 			free(pktopt->ip6po_dest2, M_IP6OPT);
2575 		pktopt->ip6po_dest2 = NULL;
2576 		pktopt->ip6po_valid &= ~IP6PO_VALID_DEST2;
2577 	}
2578 }
2579 
2580 #define PKTOPT_EXTHDRCPY(type) \
2581 do {\
2582 	if (src->type) {\
2583 		int hlen = (((struct ip6_ext *)src->type)->ip6e_len + 1) << 3;\
2584 		dst->type = malloc(hlen, M_IP6OPT, canwait);\
2585 		if (dst->type == NULL)\
2586 			goto bad;\
2587 		bcopy(src->type, dst->type, hlen);\
2588 	}\
2589 } while (/*CONSTCOND*/ 0)
2590 
2591 static int
copypktopts(struct ip6_pktopts * dst,struct ip6_pktopts * src,int canwait)2592 copypktopts(struct ip6_pktopts *dst, struct ip6_pktopts *src, int canwait)
2593 {
2594 	if (dst == NULL || src == NULL)  {
2595 		printf("ip6_clearpktopts: invalid argument\n");
2596 		return (EINVAL);
2597 	}
2598 
2599 	dst->ip6po_hlim = src->ip6po_hlim;
2600 	dst->ip6po_tclass = src->ip6po_tclass;
2601 	dst->ip6po_flags = src->ip6po_flags;
2602 	dst->ip6po_minmtu = src->ip6po_minmtu;
2603 	dst->ip6po_prefer_tempaddr = src->ip6po_prefer_tempaddr;
2604 	if (src->ip6po_pktinfo) {
2605 		dst->ip6po_pktinfo = malloc(sizeof(*dst->ip6po_pktinfo),
2606 		    M_IP6OPT, canwait);
2607 		if (dst->ip6po_pktinfo == NULL)
2608 			goto bad;
2609 		*dst->ip6po_pktinfo = *src->ip6po_pktinfo;
2610 	}
2611 	if (src->ip6po_nexthop) {
2612 		dst->ip6po_nexthop = malloc(src->ip6po_nexthop->sa_len,
2613 		    M_IP6OPT, canwait);
2614 		if (dst->ip6po_nexthop == NULL)
2615 			goto bad;
2616 		bcopy(src->ip6po_nexthop, dst->ip6po_nexthop,
2617 		    src->ip6po_nexthop->sa_len);
2618 	}
2619 	PKTOPT_EXTHDRCPY(ip6po_hbh);
2620 	PKTOPT_EXTHDRCPY(ip6po_dest1);
2621 	PKTOPT_EXTHDRCPY(ip6po_dest2);
2622 	PKTOPT_EXTHDRCPY(ip6po_rthdr); /* not copy the cached route */
2623 	dst->ip6po_valid = src->ip6po_valid;
2624 	return (0);
2625 
2626   bad:
2627 	ip6_clearpktopts(dst, -1);
2628 	return (ENOBUFS);
2629 }
2630 #undef PKTOPT_EXTHDRCPY
2631 
2632 struct ip6_pktopts *
ip6_copypktopts(struct ip6_pktopts * src,int canwait)2633 ip6_copypktopts(struct ip6_pktopts *src, int canwait)
2634 {
2635 	int error;
2636 	struct ip6_pktopts *dst;
2637 
2638 	dst = malloc(sizeof(*dst), M_IP6OPT, canwait);
2639 	if (dst == NULL)
2640 		return (NULL);
2641 	ip6_initpktopts(dst);
2642 
2643 	if ((error = copypktopts(dst, src, canwait)) != 0) {
2644 		free(dst, M_IP6OPT);
2645 		return (NULL);
2646 	}
2647 
2648 	return (dst);
2649 }
2650 
2651 void
ip6_freepcbopts(struct ip6_pktopts * pktopt)2652 ip6_freepcbopts(struct ip6_pktopts *pktopt)
2653 {
2654 	if (pktopt == NULL)
2655 		return;
2656 
2657 	ip6_clearpktopts(pktopt, -1);
2658 
2659 	free(pktopt, M_IP6OPT);
2660 }
2661 
2662 /*
2663  * Set IPv6 outgoing packet options based on advanced API.
2664  */
2665 int
ip6_setpktopts(struct mbuf * control,struct ip6_pktopts * opt,struct ip6_pktopts * stickyopt,struct ucred * cred,int uproto)2666 ip6_setpktopts(struct mbuf *control, struct ip6_pktopts *opt,
2667     struct ip6_pktopts *stickyopt, struct ucred *cred, int uproto)
2668 {
2669 	struct cmsghdr *cm = NULL;
2670 
2671 	if (control == NULL || opt == NULL)
2672 		return (EINVAL);
2673 
2674 	/*
2675 	 * ip6_setpktopt can call ifnet_byindex(), so it's imperative that we
2676 	 * are in the network epoch here.
2677 	 */
2678 	NET_EPOCH_ASSERT();
2679 
2680 	ip6_initpktopts(opt);
2681 	if (stickyopt) {
2682 		int error;
2683 
2684 		/*
2685 		 * If stickyopt is provided, make a local copy of the options
2686 		 * for this particular packet, then override them by ancillary
2687 		 * objects.
2688 		 * XXX: copypktopts() does not copy the cached route to a next
2689 		 * hop (if any).  This is not very good in terms of efficiency,
2690 		 * but we can allow this since this option should be rarely
2691 		 * used.
2692 		 */
2693 		if ((error = copypktopts(opt, stickyopt, M_NOWAIT)) != 0)
2694 			return (error);
2695 	}
2696 
2697 	/*
2698 	 * XXX: Currently, we assume all the optional information is stored
2699 	 * in a single mbuf.
2700 	 */
2701 	if (control->m_next)
2702 		return (EINVAL);
2703 
2704 	for (; control->m_len > 0; control->m_data += CMSG_ALIGN(cm->cmsg_len),
2705 	    control->m_len -= CMSG_ALIGN(cm->cmsg_len)) {
2706 		int error;
2707 
2708 		if (control->m_len < CMSG_LEN(0))
2709 			return (EINVAL);
2710 
2711 		cm = mtod(control, struct cmsghdr *);
2712 		if (cm->cmsg_len == 0 || cm->cmsg_len > control->m_len)
2713 			return (EINVAL);
2714 		if (cm->cmsg_level != IPPROTO_IPV6)
2715 			continue;
2716 
2717 		error = ip6_setpktopt(cm->cmsg_type, CMSG_DATA(cm),
2718 		    cm->cmsg_len - CMSG_LEN(0), opt, cred, 0, 1, uproto);
2719 		if (error)
2720 			return (error);
2721 	}
2722 
2723 	return (0);
2724 }
2725 
2726 /*
2727  * Set a particular packet option, as a sticky option or an ancillary data
2728  * item.  "len" can be 0 only when it's a sticky option.
2729  * We have 4 cases of combination of "sticky" and "cmsg":
2730  * "sticky=0, cmsg=0": impossible
2731  * "sticky=0, cmsg=1": RFC2292 or RFC3542 ancillary data
2732  * "sticky=1, cmsg=0": RFC3542 socket option
2733  * "sticky=1, cmsg=1": RFC2292 socket option
2734  */
2735 static int
ip6_setpktopt(int optname,u_char * buf,int len,struct ip6_pktopts * opt,struct ucred * cred,int sticky,int cmsg,int uproto)2736 ip6_setpktopt(int optname, u_char *buf, int len, struct ip6_pktopts *opt,
2737     struct ucred *cred, int sticky, int cmsg, int uproto)
2738 {
2739 	int minmtupolicy, preftemp;
2740 	int error;
2741 
2742 	NET_EPOCH_ASSERT();
2743 
2744 	if (!sticky && !cmsg) {
2745 #ifdef DIAGNOSTIC
2746 		printf("ip6_setpktopt: impossible case\n");
2747 #endif
2748 		return (EINVAL);
2749 	}
2750 
2751 	/*
2752 	 * IPV6_2292xxx is for backward compatibility to RFC2292, and should
2753 	 * not be specified in the context of RFC3542.  Conversely,
2754 	 * RFC3542 types should not be specified in the context of RFC2292.
2755 	 */
2756 	if (!cmsg) {
2757 		switch (optname) {
2758 		case IPV6_2292PKTINFO:
2759 		case IPV6_2292HOPLIMIT:
2760 		case IPV6_2292NEXTHOP:
2761 		case IPV6_2292HOPOPTS:
2762 		case IPV6_2292DSTOPTS:
2763 		case IPV6_2292RTHDR:
2764 		case IPV6_2292PKTOPTIONS:
2765 			return (ENOPROTOOPT);
2766 		}
2767 	}
2768 	if (sticky && cmsg) {
2769 		switch (optname) {
2770 		case IPV6_PKTINFO:
2771 		case IPV6_HOPLIMIT:
2772 		case IPV6_NEXTHOP:
2773 		case IPV6_HOPOPTS:
2774 		case IPV6_DSTOPTS:
2775 		case IPV6_RTHDRDSTOPTS:
2776 		case IPV6_RTHDR:
2777 		case IPV6_USE_MIN_MTU:
2778 		case IPV6_DONTFRAG:
2779 		case IPV6_TCLASS:
2780 		case IPV6_PREFER_TEMPADDR: /* XXX: not an RFC3542 option */
2781 			return (ENOPROTOOPT);
2782 		}
2783 	}
2784 
2785 	switch (optname) {
2786 	case IPV6_2292PKTINFO:
2787 	case IPV6_PKTINFO:
2788 	{
2789 		struct ifnet *ifp = NULL;
2790 		struct in6_pktinfo *pktinfo;
2791 
2792 		if (len != sizeof(struct in6_pktinfo))
2793 			return (EINVAL);
2794 
2795 		pktinfo = (struct in6_pktinfo *)buf;
2796 
2797 		/*
2798 		 * An application can clear any sticky IPV6_PKTINFO option by
2799 		 * doing a "regular" setsockopt with ipi6_addr being
2800 		 * in6addr_any and ipi6_ifindex being zero.
2801 		 * [RFC 3542, Section 6]
2802 		 */
2803 		if (optname == IPV6_PKTINFO && opt->ip6po_pktinfo &&
2804 		    pktinfo->ipi6_ifindex == 0 &&
2805 		    IN6_IS_ADDR_UNSPECIFIED(&pktinfo->ipi6_addr)) {
2806 			ip6_clearpktopts(opt, optname);
2807 			break;
2808 		}
2809 
2810 		if (uproto == IPPROTO_TCP && optname == IPV6_PKTINFO &&
2811 		    sticky && !IN6_IS_ADDR_UNSPECIFIED(&pktinfo->ipi6_addr)) {
2812 			return (EINVAL);
2813 		}
2814 		if (IN6_IS_ADDR_MULTICAST(&pktinfo->ipi6_addr))
2815 			return (EINVAL);
2816 		/* validate the interface index if specified. */
2817 		if (pktinfo->ipi6_ifindex) {
2818 			ifp = ifnet_byindex(pktinfo->ipi6_ifindex);
2819 			if (ifp == NULL)
2820 				return (ENXIO);
2821 		}
2822 		if (ifp != NULL && (ifp->if_inet6 == NULL ||
2823 		    (ifp->if_inet6->nd_flags & ND6_IFF_IFDISABLED) != 0))
2824 			return (ENETDOWN);
2825 
2826 		if (ifp != NULL &&
2827 		    !IN6_IS_ADDR_UNSPECIFIED(&pktinfo->ipi6_addr)) {
2828 			struct in6_ifaddr *ia;
2829 
2830 			in6_setscope(&pktinfo->ipi6_addr, ifp, NULL);
2831 			ia = in6ifa_ifpwithaddr(ifp, &pktinfo->ipi6_addr);
2832 			if (ia == NULL)
2833 				return (EADDRNOTAVAIL);
2834 			ifa_free(&ia->ia_ifa);
2835 		}
2836 		/*
2837 		 * We store the address anyway, and let in6_selectsrc()
2838 		 * validate the specified address.  This is because ipi6_addr
2839 		 * may not have enough information about its scope zone, and
2840 		 * we may need additional information (such as outgoing
2841 		 * interface or the scope zone of a destination address) to
2842 		 * disambiguate the scope.
2843 		 * XXX: the delay of the validation may confuse the
2844 		 * application when it is used as a sticky option.
2845 		 */
2846 		if (opt->ip6po_pktinfo == NULL) {
2847 			opt->ip6po_pktinfo = malloc(sizeof(*pktinfo),
2848 			    M_IP6OPT, M_NOWAIT);
2849 			if (opt->ip6po_pktinfo == NULL)
2850 				return (ENOBUFS);
2851 		}
2852 		bcopy(pktinfo, opt->ip6po_pktinfo, sizeof(*pktinfo));
2853 		opt->ip6po_valid |= IP6PO_VALID_PKTINFO;
2854 		break;
2855 	}
2856 
2857 	case IPV6_2292HOPLIMIT:
2858 	case IPV6_HOPLIMIT:
2859 	{
2860 		int *hlimp;
2861 
2862 		/*
2863 		 * RFC 3542 deprecated the usage of sticky IPV6_HOPLIMIT
2864 		 * to simplify the ordering among hoplimit options.
2865 		 */
2866 		if (optname == IPV6_HOPLIMIT && sticky)
2867 			return (ENOPROTOOPT);
2868 
2869 		if (len != sizeof(int))
2870 			return (EINVAL);
2871 		hlimp = (int *)buf;
2872 		if (*hlimp < -1 || *hlimp > 255)
2873 			return (EINVAL);
2874 
2875 		opt->ip6po_hlim = *hlimp;
2876 		opt->ip6po_valid |= IP6PO_VALID_HLIM;
2877 		break;
2878 	}
2879 
2880 	case IPV6_TCLASS:
2881 	{
2882 		int tclass;
2883 
2884 		if (len != sizeof(int))
2885 			return (EINVAL);
2886 		tclass = *(int *)buf;
2887 		if (tclass < -1 || tclass > 255)
2888 			return (EINVAL);
2889 
2890 		opt->ip6po_tclass = tclass;
2891 		opt->ip6po_valid |= IP6PO_VALID_TC;
2892 		break;
2893 	}
2894 
2895 	case IPV6_2292NEXTHOP:
2896 	case IPV6_NEXTHOP:
2897 		if (cred != NULL) {
2898 			error = priv_check_cred(cred, PRIV_NETINET_SETHDROPTS);
2899 			if (error)
2900 				return (error);
2901 		}
2902 
2903 		if (len == 0) {	/* just remove the option */
2904 			ip6_clearpktopts(opt, IPV6_NEXTHOP);
2905 			break;
2906 		}
2907 
2908 		/* check if cmsg_len is large enough for sa_len */
2909 		if (len < sizeof(struct sockaddr) || len < *buf)
2910 			return (EINVAL);
2911 
2912 		switch (((struct sockaddr *)buf)->sa_family) {
2913 		case AF_INET6:
2914 		{
2915 			struct sockaddr_in6 *sa6 = (struct sockaddr_in6 *)buf;
2916 			int error;
2917 
2918 			if (sa6->sin6_len != sizeof(struct sockaddr_in6))
2919 				return (EINVAL);
2920 
2921 			if (IN6_IS_ADDR_UNSPECIFIED(&sa6->sin6_addr) ||
2922 			    IN6_IS_ADDR_MULTICAST(&sa6->sin6_addr)) {
2923 				return (EINVAL);
2924 			}
2925 			if ((error = sa6_embedscope(sa6, V_ip6_use_defzone))
2926 			    != 0) {
2927 				return (error);
2928 			}
2929 			break;
2930 		}
2931 		case AF_LINK:	/* should eventually be supported */
2932 		default:
2933 			return (EAFNOSUPPORT);
2934 		}
2935 
2936 		/* turn off the previous option, then set the new option. */
2937 		ip6_clearpktopts(opt, IPV6_NEXTHOP);
2938 		opt->ip6po_nexthop = malloc(*buf, M_IP6OPT, M_NOWAIT);
2939 		if (opt->ip6po_nexthop == NULL)
2940 			return (ENOBUFS);
2941 		bcopy(buf, opt->ip6po_nexthop, *buf);
2942 		opt->ip6po_valid |= IP6PO_VALID_NHINFO;
2943 		break;
2944 
2945 	case IPV6_2292HOPOPTS:
2946 	case IPV6_HOPOPTS:
2947 	{
2948 		struct ip6_hbh *hbh;
2949 		int hbhlen;
2950 
2951 		/*
2952 		 * XXX: We don't allow a non-privileged user to set ANY HbH
2953 		 * options, since per-option restriction has too much
2954 		 * overhead.
2955 		 */
2956 		if (cred != NULL) {
2957 			error = priv_check_cred(cred, PRIV_NETINET_SETHDROPTS);
2958 			if (error)
2959 				return (error);
2960 		}
2961 
2962 		if (len == 0) {
2963 			ip6_clearpktopts(opt, IPV6_HOPOPTS);
2964 			break;	/* just remove the option */
2965 		}
2966 
2967 		/* message length validation */
2968 		if (len < sizeof(struct ip6_hbh))
2969 			return (EINVAL);
2970 		hbh = (struct ip6_hbh *)buf;
2971 		hbhlen = (hbh->ip6h_len + 1) << 3;
2972 		if (len != hbhlen)
2973 			return (EINVAL);
2974 
2975 		/* turn off the previous option, then set the new option. */
2976 		ip6_clearpktopts(opt, IPV6_HOPOPTS);
2977 		opt->ip6po_hbh = malloc(hbhlen, M_IP6OPT, M_NOWAIT);
2978 		if (opt->ip6po_hbh == NULL)
2979 			return (ENOBUFS);
2980 		bcopy(hbh, opt->ip6po_hbh, hbhlen);
2981 		opt->ip6po_valid |= IP6PO_VALID_HBH;
2982 
2983 		break;
2984 	}
2985 
2986 	case IPV6_2292DSTOPTS:
2987 	case IPV6_DSTOPTS:
2988 	case IPV6_RTHDRDSTOPTS:
2989 	{
2990 		struct ip6_dest *dest, **newdest = NULL;
2991 		int destlen;
2992 
2993 		if (cred != NULL) { /* XXX: see the comment for IPV6_HOPOPTS */
2994 			error = priv_check_cred(cred, PRIV_NETINET_SETHDROPTS);
2995 			if (error)
2996 				return (error);
2997 		}
2998 
2999 		if (len == 0) {
3000 			ip6_clearpktopts(opt, optname);
3001 			break;	/* just remove the option */
3002 		}
3003 
3004 		/* message length validation */
3005 		if (len < sizeof(struct ip6_dest))
3006 			return (EINVAL);
3007 		dest = (struct ip6_dest *)buf;
3008 		destlen = (dest->ip6d_len + 1) << 3;
3009 		if (len != destlen)
3010 			return (EINVAL);
3011 
3012 		/*
3013 		 * Determine the position that the destination options header
3014 		 * should be inserted; before or after the routing header.
3015 		 */
3016 		switch (optname) {
3017 		case IPV6_2292DSTOPTS:
3018 			/*
3019 			 * The old advacned API is ambiguous on this point.
3020 			 * Our approach is to determine the position based
3021 			 * according to the existence of a routing header.
3022 			 * Note, however, that this depends on the order of the
3023 			 * extension headers in the ancillary data; the 1st
3024 			 * part of the destination options header must appear
3025 			 * before the routing header in the ancillary data,
3026 			 * too.
3027 			 * RFC3542 solved the ambiguity by introducing
3028 			 * separate ancillary data or option types.
3029 			 */
3030 			if (opt->ip6po_rthdr == NULL)
3031 				newdest = &opt->ip6po_dest1;
3032 			else
3033 				newdest = &opt->ip6po_dest2;
3034 			break;
3035 		case IPV6_RTHDRDSTOPTS:
3036 			newdest = &opt->ip6po_dest1;
3037 			break;
3038 		case IPV6_DSTOPTS:
3039 			newdest = &opt->ip6po_dest2;
3040 			break;
3041 		}
3042 
3043 		/* turn off the previous option, then set the new option. */
3044 		ip6_clearpktopts(opt, optname);
3045 		*newdest = malloc(destlen, M_IP6OPT, M_NOWAIT);
3046 		if (*newdest == NULL)
3047 			return (ENOBUFS);
3048 		bcopy(dest, *newdest, destlen);
3049 		if (newdest == &opt->ip6po_dest1)
3050 			opt->ip6po_valid |= IP6PO_VALID_DEST1;
3051 		else
3052 			opt->ip6po_valid |= IP6PO_VALID_DEST2;
3053 
3054 		break;
3055 	}
3056 
3057 	case IPV6_2292RTHDR:
3058 	case IPV6_RTHDR:
3059 	{
3060 		struct ip6_rthdr *rth;
3061 		int rthlen;
3062 
3063 		if (len == 0) {
3064 			ip6_clearpktopts(opt, IPV6_RTHDR);
3065 			break;	/* just remove the option */
3066 		}
3067 
3068 		/* message length validation */
3069 		if (len < sizeof(struct ip6_rthdr))
3070 			return (EINVAL);
3071 		rth = (struct ip6_rthdr *)buf;
3072 		rthlen = (rth->ip6r_len + 1) << 3;
3073 		if (len != rthlen)
3074 			return (EINVAL);
3075 
3076 		switch (rth->ip6r_type) {
3077 		case IPV6_RTHDR_TYPE_0:
3078 			if (rth->ip6r_len == 0)	/* must contain one addr */
3079 				return (EINVAL);
3080 			if (rth->ip6r_len % 2) /* length must be even */
3081 				return (EINVAL);
3082 			if (rth->ip6r_len / 2 != rth->ip6r_segleft)
3083 				return (EINVAL);
3084 			break;
3085 		default:
3086 			return (EINVAL);	/* not supported */
3087 		}
3088 
3089 		/* turn off the previous option */
3090 		ip6_clearpktopts(opt, IPV6_RTHDR);
3091 		opt->ip6po_rthdr = malloc(rthlen, M_IP6OPT, M_NOWAIT);
3092 		if (opt->ip6po_rthdr == NULL)
3093 			return (ENOBUFS);
3094 		bcopy(rth, opt->ip6po_rthdr, rthlen);
3095 		opt->ip6po_valid |= IP6PO_VALID_RHINFO;
3096 
3097 		break;
3098 	}
3099 
3100 	case IPV6_USE_MIN_MTU:
3101 		if (len != sizeof(int))
3102 			return (EINVAL);
3103 		minmtupolicy = *(int *)buf;
3104 		if (minmtupolicy != IP6PO_MINMTU_MCASTONLY &&
3105 		    minmtupolicy != IP6PO_MINMTU_DISABLE &&
3106 		    minmtupolicy != IP6PO_MINMTU_ALL) {
3107 			return (EINVAL);
3108 		}
3109 		opt->ip6po_minmtu = minmtupolicy;
3110 		break;
3111 
3112 	case IPV6_DONTFRAG:
3113 		if (len != sizeof(int))
3114 			return (EINVAL);
3115 
3116 		if (uproto == IPPROTO_TCP || *(int *)buf == 0) {
3117 			/*
3118 			 * we ignore this option for TCP sockets.
3119 			 * (RFC3542 leaves this case unspecified.)
3120 			 */
3121 			opt->ip6po_flags &= ~IP6PO_DONTFRAG;
3122 		} else
3123 			opt->ip6po_flags |= IP6PO_DONTFRAG;
3124 		break;
3125 
3126 	case IPV6_PREFER_TEMPADDR:
3127 		if (len != sizeof(int))
3128 			return (EINVAL);
3129 		preftemp = *(int *)buf;
3130 		if (preftemp != IP6PO_TEMPADDR_SYSTEM &&
3131 		    preftemp != IP6PO_TEMPADDR_NOTPREFER &&
3132 		    preftemp != IP6PO_TEMPADDR_PREFER) {
3133 			return (EINVAL);
3134 		}
3135 		opt->ip6po_prefer_tempaddr = preftemp;
3136 		break;
3137 
3138 	default:
3139 		return (ENOPROTOOPT);
3140 	} /* end of switch */
3141 
3142 	return (0);
3143 }
3144 
3145 /*
3146  * Routine called from ip6_output() to loop back a copy of an IP6 multicast
3147  * packet to the input queue of a specified interface.  Note that this
3148  * calls the output routine of the loopback "driver", but with an interface
3149  * pointer that might NOT be &loif -- easier than replicating that code here.
3150  */
3151 void
ip6_mloopback(struct ifnet * ifp,struct mbuf * m)3152 ip6_mloopback(struct ifnet *ifp, struct mbuf *m)
3153 {
3154 	struct mbuf *copym;
3155 	struct ip6_hdr *ip6;
3156 
3157 	copym = m_copym(m, 0, M_COPYALL, M_NOWAIT);
3158 	if (copym == NULL)
3159 		return;
3160 
3161 	/*
3162 	 * Make sure to deep-copy IPv6 header portion in case the data
3163 	 * is in an mbuf cluster, so that we can safely override the IPv6
3164 	 * header portion later.
3165 	 */
3166 	if (!M_WRITABLE(copym) ||
3167 	    copym->m_len < sizeof(struct ip6_hdr)) {
3168 		copym = m_pullup(copym, sizeof(struct ip6_hdr));
3169 		if (copym == NULL)
3170 			return;
3171 	}
3172 	ip6 = mtod(copym, struct ip6_hdr *);
3173 	/*
3174 	 * clear embedded scope identifiers if necessary.
3175 	 * in6_clearscope will touch the addresses only when necessary.
3176 	 */
3177 	in6_clearscope(&ip6->ip6_src);
3178 	in6_clearscope(&ip6->ip6_dst);
3179 	if (copym->m_pkthdr.csum_flags & CSUM_DELAY_DATA_IPV6) {
3180 		copym->m_pkthdr.csum_flags |= CSUM_DATA_VALID_IPV6 |
3181 		    CSUM_PSEUDO_HDR;
3182 		copym->m_pkthdr.csum_data = 0xffff;
3183 	}
3184 	if_simloop(ifp, copym, AF_INET6, 0);
3185 }
3186 
3187 /*
3188  * Chop IPv6 header off from the payload.
3189  */
3190 static int
ip6_splithdr(struct mbuf * m,struct ip6_exthdrs * exthdrs)3191 ip6_splithdr(struct mbuf *m, struct ip6_exthdrs *exthdrs)
3192 {
3193 	struct mbuf *mh;
3194 	struct ip6_hdr *ip6;
3195 
3196 	ip6 = mtod(m, struct ip6_hdr *);
3197 	if (m->m_len > sizeof(*ip6)) {
3198 		mh = m_gethdr(M_NOWAIT, MT_DATA);
3199 		if (mh == NULL) {
3200 			m_freem(m);
3201 			return ENOBUFS;
3202 		}
3203 		m_move_pkthdr(mh, m);
3204 		M_ALIGN(mh, sizeof(*ip6));
3205 		m->m_len -= sizeof(*ip6);
3206 		m->m_data += sizeof(*ip6);
3207 		mh->m_next = m;
3208 		m = mh;
3209 		m->m_len = sizeof(*ip6);
3210 		bcopy((caddr_t)ip6, mtod(m, caddr_t), sizeof(*ip6));
3211 	}
3212 	exthdrs->ip6e_ip6 = m;
3213 	return 0;
3214 }
3215 
3216 /*
3217  * Compute IPv6 extension header length.
3218  */
3219 int
ip6_optlen(struct inpcb * inp)3220 ip6_optlen(struct inpcb *inp)
3221 {
3222 	int len;
3223 
3224 	if (!inp->in6p_outputopts)
3225 		return 0;
3226 
3227 	len = 0;
3228 #define elen(x) \
3229     (((struct ip6_ext *)(x)) ? (((struct ip6_ext *)(x))->ip6e_len + 1) << 3 : 0)
3230 
3231 	len += elen(inp->in6p_outputopts->ip6po_hbh);
3232 	if (inp->in6p_outputopts->ip6po_rthdr)
3233 		/* dest1 is valid with rthdr only */
3234 		len += elen(inp->in6p_outputopts->ip6po_dest1);
3235 	len += elen(inp->in6p_outputopts->ip6po_rthdr);
3236 	len += elen(inp->in6p_outputopts->ip6po_dest2);
3237 	return len;
3238 #undef elen
3239 }
3240