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