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