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