ip6_output.c revision 79426
1252504Slstewart/*	$FreeBSD: head/sys/netinet6/ip6_output.c 79426 2001-07-08 18:06:03Z ume $	*/
2252504Slstewart/*	$KAME: ip6_output.c,v 1.180 2001/05/21 05:37:50 jinmei Exp $	*/
3252504Slstewart
4252504Slstewart/*
5252504Slstewart * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
6252504Slstewart * All rights reserved.
7252504Slstewart *
8252504Slstewart * Redistribution and use in source and binary forms, with or without
9252504Slstewart * modification, are permitted provided that the following conditions
10252504Slstewart * are met:
11252504Slstewart * 1. Redistributions of source code must retain the above copyright
12252504Slstewart *    notice, this list of conditions and the following disclaimer.
13252504Slstewart * 2. Redistributions in binary form must reproduce the above copyright
14252504Slstewart *    notice, this list of conditions and the following disclaimer in the
15252504Slstewart *    documentation and/or other materials provided with the distribution.
16252504Slstewart * 3. Neither the name of the project nor the names of its contributors
17252504Slstewart *    may be used to endorse or promote products derived from this software
18252504Slstewart *    without specific prior written permission.
19252504Slstewart *
20252504Slstewart * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
21252504Slstewart * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22252504Slstewart * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23252504Slstewart * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
24252504Slstewart * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25252504Slstewart * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26252504Slstewart * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27252504Slstewart * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28252504Slstewart * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29252504Slstewart * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30252504Slstewart * SUCH DAMAGE.
31252504Slstewart */
32252504Slstewart
33252504Slstewart/*
34252504Slstewart * Copyright (c) 1982, 1986, 1988, 1990, 1993
35252504Slstewart *	The Regents of the University of California.  All rights reserved.
36252504Slstewart *
37252504Slstewart * Redistribution and use in source and binary forms, with or without
38252504Slstewart * modification, are permitted provided that the following conditions
39252504Slstewart * are met:
40252504Slstewart * 1. Redistributions of source code must retain the above copyright
41252504Slstewart *    notice, this list of conditions and the following disclaimer.
42252504Slstewart * 2. Redistributions in binary form must reproduce the above copyright
43252504Slstewart *    notice, this list of conditions and the following disclaimer in the
44252504Slstewart *    documentation and/or other materials provided with the distribution.
45252504Slstewart * 3. All advertising materials mentioning features or use of this software
46252504Slstewart *    must display the following acknowledgement:
47252504Slstewart *	This product includes software developed by the University of
48252504Slstewart *	California, Berkeley and its contributors.
49252504Slstewart * 4. Neither the name of the University nor the names of its contributors
50252504Slstewart *    may be used to endorse or promote products derived from this software
51252504Slstewart *    without specific prior written permission.
52252504Slstewart *
53252504Slstewart * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
54252504Slstewart * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
55252504Slstewart * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
56252504Slstewart * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
57252504Slstewart * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
58252504Slstewart * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
59252504Slstewart * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
60252504Slstewart * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
61252504Slstewart * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
62252504Slstewart * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
63252504Slstewart * SUCH DAMAGE.
64252504Slstewart *
65252504Slstewart *	@(#)ip_output.c	8.3 (Berkeley) 1/21/94
66252504Slstewart */
67252504Slstewart
68252504Slstewart#include "opt_ip6fw.h"
69252504Slstewart#include "opt_inet.h"
70252504Slstewart#include "opt_inet6.h"
71252504Slstewart#include "opt_ipsec.h"
72252504Slstewart#include "opt_pfil_hooks.h"
73252504Slstewart
74252504Slstewart#include <sys/param.h>
75252504Slstewart#include <sys/malloc.h>
76252504Slstewart#include <sys/mbuf.h>
77252504Slstewart#include <sys/errno.h>
78252504Slstewart#include <sys/protosw.h>
79252504Slstewart#include <sys/socket.h>
80252504Slstewart#include <sys/socketvar.h>
81252504Slstewart#include <sys/systm.h>
82252504Slstewart#include <sys/kernel.h>
83252504Slstewart
84252504Slstewart#include <net/if.h>
85252504Slstewart#include <net/route.h>
86252504Slstewart#ifdef PFIL_HOOKS
87252504Slstewart#include <net/pfil.h>
88252504Slstewart#endif
89252504Slstewart
90252504Slstewart#include <netinet/in.h>
91252504Slstewart#include <netinet/in_var.h>
92252504Slstewart#include <netinet6/in6_var.h>
93252504Slstewart#include <netinet/ip6.h>
94252504Slstewart#include <netinet/icmp6.h>
95252504Slstewart#include <netinet6/ip6_var.h>
96252504Slstewart#include <netinet/in_pcb.h>
97252504Slstewart#include <netinet6/nd6.h>
98252504Slstewart
99252504Slstewart#ifdef IPSEC
100252504Slstewart#include <netinet6/ipsec.h>
101252504Slstewart#ifdef INET6
102252504Slstewart#include <netinet6/ipsec6.h>
103252504Slstewart#endif
104252504Slstewart#include <netkey/key.h>
105252504Slstewart#endif /* IPSEC */
106252504Slstewart
107252504Slstewart#include <netinet6/ip6_fw.h>
108252504Slstewart
109252504Slstewart#include <net/net_osdep.h>
110252504Slstewart
111252504Slstewart#include <netinet6/ip6protosw.h>
112252504Slstewart
113252504Slstewartstatic MALLOC_DEFINE(M_IPMOPTS, "ip6_moptions", "internet multicast options");
114252504Slstewart
115252504Slstewartstruct ip6_exthdrs {
116252504Slstewart	struct mbuf *ip6e_ip6;
117252504Slstewart	struct mbuf *ip6e_hbh;
118252504Slstewart	struct mbuf *ip6e_dest1;
119252504Slstewart	struct mbuf *ip6e_rthdr;
120252504Slstewart	struct mbuf *ip6e_dest2;
121252504Slstewart};
122252504Slstewart
123252504Slstewartstatic int ip6_pcbopts __P((struct ip6_pktopts **, struct mbuf *,
124252504Slstewart			    struct socket *, struct sockopt *sopt));
125252504Slstewartstatic int ip6_setmoptions __P((int, struct ip6_moptions **, struct mbuf *));
126252504Slstewartstatic int ip6_getmoptions __P((int, struct ip6_moptions *, struct mbuf **));
127252504Slstewartstatic int ip6_copyexthdr __P((struct mbuf **, caddr_t, int));
128252504Slstewartstatic int ip6_insertfraghdr __P((struct mbuf *, struct mbuf *, int,
129252504Slstewart				  struct ip6_frag **));
130252504Slstewartstatic int ip6_insert_jumboopt __P((struct ip6_exthdrs *, u_int32_t));
131252504Slstewartstatic int ip6_splithdr __P((struct mbuf *, struct ip6_exthdrs *));
132252504Slstewart
133252504Slstewartextern struct ip6protosw inet6sw[];
134252504Slstewartextern u_char ip6_protox[IPPROTO_MAX];
135252504Slstewart
136252504Slstewart/*
137252504Slstewart * IP6 output. The packet in mbuf chain m contains a skeletal IP6
138252504Slstewart * header (with pri, len, nxt, hlim, src, dst).
139252504Slstewart * This function may modify ver and hlim only.
140252504Slstewart * The mbuf chain containing the packet will be freed.
141252504Slstewart * The mbuf opt, if present, will not be freed.
142252504Slstewart *
143252504Slstewart * type of "mtu": rt_rmx.rmx_mtu is u_long, ifnet.ifr_mtu is int, and
144252504Slstewart * nd_ifinfo.linkmtu is u_int32_t.  so we use u_long to hold largest one,
145252504Slstewart * which is rt_rmx.rmx_mtu.
146252504Slstewart */
147252504Slstewartint
148252504Slstewartip6_output(m0, opt, ro, flags, im6o, ifpp)
149252504Slstewart	struct mbuf *m0;
150252504Slstewart	struct ip6_pktopts *opt;
151252504Slstewart	struct route_in6 *ro;
152252504Slstewart	int flags;
153252504Slstewart	struct ip6_moptions *im6o;
154252504Slstewart	struct ifnet **ifpp;		/* XXX: just for statistics */
155252504Slstewart{
156252504Slstewart	struct ip6_hdr *ip6, *mhip6;
157252504Slstewart	struct ifnet *ifp, *origifp;
158252504Slstewart	struct mbuf *m = m0;
159252504Slstewart	int hlen, tlen, len, off;
160252504Slstewart	struct route_in6 ip6route;
161252504Slstewart	struct sockaddr_in6 *dst;
162252504Slstewart	int error = 0;
163252504Slstewart	struct in6_ifaddr *ia = NULL;
164252504Slstewart	u_long mtu;
165252504Slstewart	u_int32_t optlen = 0, plen = 0, unfragpartlen = 0;
166252504Slstewart	struct ip6_exthdrs exthdrs;
167252504Slstewart	struct in6_addr finaldst;
168252504Slstewart	struct route_in6 *ro_pmtu = NULL;
169252504Slstewart	int hdrsplit = 0;
170252504Slstewart	int needipsec = 0;
171252504Slstewart#ifdef PFIL_HOOKS
172252504Slstewart	struct packet_filter_hook *pfh;
173252504Slstewart	struct mbuf *m1;
174252504Slstewart	int rv;
175252504Slstewart#endif /* PFIL_HOOKS */
176252504Slstewart#ifdef IPSEC
177252504Slstewart	int needipsectun = 0;
178252504Slstewart	struct socket *so;
179252504Slstewart	struct secpolicy *sp = NULL;
180252504Slstewart
181252504Slstewart	/* for AH processing. stupid to have "socket" variable in IP layer... */
182252504Slstewart	so = ipsec_getsocket(m);
183252504Slstewart	(void)ipsec_setsocket(m, NULL);
184252504Slstewart	ip6 = mtod(m, struct ip6_hdr *);
185252504Slstewart#endif /* IPSEC */
186252504Slstewart
187252504Slstewart#define MAKE_EXTHDR(hp, mp)						\
188252504Slstewart    do {								\
189252504Slstewart	if (hp) {							\
190252504Slstewart		struct ip6_ext *eh = (struct ip6_ext *)(hp);		\
191252504Slstewart		error = ip6_copyexthdr((mp), (caddr_t)(hp), 		\
192252504Slstewart				       ((eh)->ip6e_len + 1) << 3);	\
193252504Slstewart		if (error)						\
194252504Slstewart			goto freehdrs;					\
195252504Slstewart	}								\
196252504Slstewart    } while (0)
197252504Slstewart
198252504Slstewart	bzero(&exthdrs, sizeof(exthdrs));
199252504Slstewart
200252504Slstewart	if (opt) {
201252504Slstewart		/* Hop-by-Hop options header */
202252504Slstewart		MAKE_EXTHDR(opt->ip6po_hbh, &exthdrs.ip6e_hbh);
203252504Slstewart		/* Destination options header(1st part) */
204252504Slstewart		MAKE_EXTHDR(opt->ip6po_dest1, &exthdrs.ip6e_dest1);
205252504Slstewart		/* Routing header */
206252504Slstewart		MAKE_EXTHDR(opt->ip6po_rthdr, &exthdrs.ip6e_rthdr);
207252504Slstewart		/* Destination options header(2nd part) */
208252504Slstewart		MAKE_EXTHDR(opt->ip6po_dest2, &exthdrs.ip6e_dest2);
209252504Slstewart	}
210252504Slstewart
211252504Slstewart#ifdef IPSEC
212252504Slstewart	/* get a security policy for this packet */
213252504Slstewart	if (so == NULL)
214252504Slstewart		sp = ipsec6_getpolicybyaddr(m, IPSEC_DIR_OUTBOUND, 0, &error);
215252504Slstewart	else
216252504Slstewart		sp = ipsec6_getpolicybysock(m, IPSEC_DIR_OUTBOUND, so, &error);
217252504Slstewart
218252504Slstewart	if (sp == NULL) {
219252504Slstewart		ipsec6stat.out_inval++;
220252504Slstewart		goto freehdrs;
221252504Slstewart	}
222252504Slstewart
223252504Slstewart	error = 0;
224252504Slstewart
225252504Slstewart	/* check policy */
226252504Slstewart	switch (sp->policy) {
227252504Slstewart	case IPSEC_POLICY_DISCARD:
228252504Slstewart		/*
229252504Slstewart		 * This packet is just discarded.
230252504Slstewart		 */
231252504Slstewart		ipsec6stat.out_polvio++;
232252504Slstewart		goto freehdrs;
233252504Slstewart
234252504Slstewart	case IPSEC_POLICY_BYPASS:
235252504Slstewart	case IPSEC_POLICY_NONE:
236252504Slstewart		/* no need to do IPsec. */
237252504Slstewart		needipsec = 0;
238252504Slstewart		break;
239252504Slstewart
240252504Slstewart	case IPSEC_POLICY_IPSEC:
241252504Slstewart		if (sp->req == NULL) {
242252504Slstewart			/* acquire a policy */
243252504Slstewart			error = key_spdacquire(sp);
244252504Slstewart			goto freehdrs;
245252504Slstewart		}
246252504Slstewart		needipsec = 1;
247252504Slstewart		break;
248252504Slstewart
249252504Slstewart	case IPSEC_POLICY_ENTRUST:
250252504Slstewart	default:
251252504Slstewart		printf("ip6_output: Invalid policy found. %d\n", sp->policy);
252252504Slstewart	}
253252504Slstewart#endif /* IPSEC */
254252504Slstewart
255252504Slstewart	/*
256252504Slstewart	 * Calculate the total length of the extension header chain.
257252504Slstewart	 * Keep the length of the unfragmentable part for fragmentation.
258252504Slstewart	 */
259252504Slstewart	optlen = 0;
260252504Slstewart	if (exthdrs.ip6e_hbh) optlen += exthdrs.ip6e_hbh->m_len;
261252504Slstewart	if (exthdrs.ip6e_dest1) optlen += exthdrs.ip6e_dest1->m_len;
262252504Slstewart	if (exthdrs.ip6e_rthdr) optlen += exthdrs.ip6e_rthdr->m_len;
263252504Slstewart	unfragpartlen = optlen + sizeof(struct ip6_hdr);
264252504Slstewart	/* NOTE: we don't add AH/ESP length here. do that later. */
265252504Slstewart	if (exthdrs.ip6e_dest2) optlen += exthdrs.ip6e_dest2->m_len;
266252504Slstewart
267252504Slstewart	/*
268252504Slstewart	 * If we need IPsec, or there is at least one extension header,
269252504Slstewart	 * separate IP6 header from the payload.
270252504Slstewart	 */
271252504Slstewart	if ((needipsec || optlen) && !hdrsplit) {
272252504Slstewart		if ((error = ip6_splithdr(m, &exthdrs)) != 0) {
273252504Slstewart			m = NULL;
274252504Slstewart			goto freehdrs;
275252504Slstewart		}
276252504Slstewart		m = exthdrs.ip6e_ip6;
277252504Slstewart		hdrsplit++;
278252504Slstewart	}
279252504Slstewart
280252504Slstewart	/* adjust pointer */
281252504Slstewart	ip6 = mtod(m, struct ip6_hdr *);
282252504Slstewart
283252504Slstewart	/* adjust mbuf packet header length */
284252504Slstewart	m->m_pkthdr.len += optlen;
285252504Slstewart	plen = m->m_pkthdr.len - sizeof(*ip6);
286252504Slstewart
287252504Slstewart	/* If this is a jumbo payload, insert a jumbo payload option. */
288252504Slstewart	if (plen > IPV6_MAXPACKET) {
289252504Slstewart		if (!hdrsplit) {
290252504Slstewart			if ((error = ip6_splithdr(m, &exthdrs)) != 0) {
291252504Slstewart				m = NULL;
292252504Slstewart				goto freehdrs;
293252504Slstewart			}
294252504Slstewart			m = exthdrs.ip6e_ip6;
295252504Slstewart			hdrsplit++;
296252504Slstewart		}
297252504Slstewart		/* adjust pointer */
298252504Slstewart		ip6 = mtod(m, struct ip6_hdr *);
299252504Slstewart		if ((error = ip6_insert_jumboopt(&exthdrs, plen)) != 0)
300252504Slstewart			goto freehdrs;
301252504Slstewart		ip6->ip6_plen = 0;
302252504Slstewart	} else
303252504Slstewart		ip6->ip6_plen = htons(plen);
304252504Slstewart
305252504Slstewart	/*
306252504Slstewart	 * Concatenate headers and fill in next header fields.
307252504Slstewart	 * Here we have, on "m"
308252504Slstewart	 *	IPv6 payload
309252504Slstewart	 * and we insert headers accordingly.  Finally, we should be getting:
310252504Slstewart	 *	IPv6 hbh dest1 rthdr ah* [esp* dest2 payload]
311252504Slstewart	 *
312252504Slstewart	 * during the header composing process, "m" points to IPv6 header.
313252504Slstewart	 * "mprev" points to an extension header prior to esp.
314252504Slstewart	 */
315252504Slstewart	{
316252504Slstewart		u_char *nexthdrp = &ip6->ip6_nxt;
317252504Slstewart		struct mbuf *mprev = m;
318252504Slstewart
319252504Slstewart		/*
320252504Slstewart		 * we treat dest2 specially.  this makes IPsec processing
321252504Slstewart		 * much easier.
322252504Slstewart		 *
323252504Slstewart		 * result: IPv6 dest2 payload
324252504Slstewart		 * m and mprev will point to IPv6 header.
325252504Slstewart		 */
326252504Slstewart		if (exthdrs.ip6e_dest2) {
327252504Slstewart			if (!hdrsplit)
328252504Slstewart				panic("assumption failed: hdr not split");
329252504Slstewart			exthdrs.ip6e_dest2->m_next = m->m_next;
330252504Slstewart			m->m_next = exthdrs.ip6e_dest2;
331252504Slstewart			*mtod(exthdrs.ip6e_dest2, u_char *) = ip6->ip6_nxt;
332252504Slstewart			ip6->ip6_nxt = IPPROTO_DSTOPTS;
333252504Slstewart		}
334252504Slstewart
335252504Slstewart#define MAKE_CHAIN(m, mp, p, i)\
336252504Slstewart    do {\
337252504Slstewart	if (m) {\
338252504Slstewart		if (!hdrsplit) \
339252504Slstewart			panic("assumption failed: hdr not split"); \
340252504Slstewart		*mtod((m), u_char *) = *(p);\
341252504Slstewart		*(p) = (i);\
342252504Slstewart		p = mtod((m), u_char *);\
343252504Slstewart		(m)->m_next = (mp)->m_next;\
344252504Slstewart		(mp)->m_next = (m);\
345252504Slstewart		(mp) = (m);\
346252504Slstewart	}\
347252504Slstewart    } while (0)
348252504Slstewart		/*
349252504Slstewart		 * result: IPv6 hbh dest1 rthdr dest2 payload
350252504Slstewart		 * m will point to IPv6 header.  mprev will point to the
351252504Slstewart		 * extension header prior to dest2 (rthdr in the above case).
352252504Slstewart		 */
353252504Slstewart		MAKE_CHAIN(exthdrs.ip6e_hbh, mprev,
354252504Slstewart			   nexthdrp, IPPROTO_HOPOPTS);
355252504Slstewart		MAKE_CHAIN(exthdrs.ip6e_dest1, mprev,
356252504Slstewart			   nexthdrp, IPPROTO_DSTOPTS);
357252504Slstewart		MAKE_CHAIN(exthdrs.ip6e_rthdr, mprev,
358252504Slstewart			   nexthdrp, IPPROTO_ROUTING);
359252504Slstewart
360252504Slstewart#ifdef IPSEC
361252504Slstewart		if (!needipsec)
362252504Slstewart			goto skip_ipsec2;
363252504Slstewart
364252504Slstewart		/*
365252504Slstewart		 * pointers after IPsec headers are not valid any more.
366252504Slstewart		 * other pointers need a great care too.
367252504Slstewart		 * (IPsec routines should not mangle mbufs prior to AH/ESP)
368252504Slstewart		 */
369252504Slstewart		exthdrs.ip6e_dest2 = NULL;
370252504Slstewart
371252504Slstewart	    {
372252504Slstewart		struct ip6_rthdr *rh = NULL;
373252504Slstewart		int segleft_org = 0;
374252504Slstewart		struct ipsec_output_state state;
375252504Slstewart
376252504Slstewart		if (exthdrs.ip6e_rthdr) {
377252504Slstewart			rh = mtod(exthdrs.ip6e_rthdr, struct ip6_rthdr *);
378252504Slstewart			segleft_org = rh->ip6r_segleft;
379252504Slstewart			rh->ip6r_segleft = 0;
380252504Slstewart		}
381252504Slstewart
382252504Slstewart		bzero(&state, sizeof(state));
383252504Slstewart		state.m = m;
384252504Slstewart		error = ipsec6_output_trans(&state, nexthdrp, mprev, sp, flags,
385252504Slstewart			&needipsectun);
386252504Slstewart		m = state.m;
387252504Slstewart		if (error) {
388252504Slstewart			/* mbuf is already reclaimed in ipsec6_output_trans. */
389252504Slstewart			m = NULL;
390252504Slstewart			switch (error) {
391252504Slstewart			case EHOSTUNREACH:
392252504Slstewart			case ENETUNREACH:
393252504Slstewart			case EMSGSIZE:
394252504Slstewart			case ENOBUFS:
395252504Slstewart			case ENOMEM:
396252504Slstewart				break;
397252504Slstewart			default:
398252504Slstewart				printf("ip6_output (ipsec): error code %d\n", error);
399252504Slstewart				/*fall through*/
400252504Slstewart			case ENOENT:
401252504Slstewart				/* don't show these error codes to the user */
402252504Slstewart				error = 0;
403252504Slstewart				break;
404252504Slstewart			}
405252504Slstewart			goto bad;
406252504Slstewart		}
407252504Slstewart		if (exthdrs.ip6e_rthdr) {
408252504Slstewart			/* ah6_output doesn't modify mbuf chain */
409252504Slstewart			rh->ip6r_segleft = segleft_org;
410252504Slstewart		}
411252504Slstewart	    }
412252504Slstewartskip_ipsec2:;
413252504Slstewart#endif
414252504Slstewart	}
415252504Slstewart
416252504Slstewart	/*
417252504Slstewart	 * If there is a routing header, replace destination address field
418252504Slstewart	 * with the first hop of the routing header.
419252504Slstewart	 */
420252504Slstewart	if (exthdrs.ip6e_rthdr) {
421252504Slstewart		struct ip6_rthdr *rh =
422252504Slstewart			(struct ip6_rthdr *)(mtod(exthdrs.ip6e_rthdr,
423252504Slstewart						  struct ip6_rthdr *));
424252504Slstewart		struct ip6_rthdr0 *rh0;
425252504Slstewart
426252504Slstewart		finaldst = ip6->ip6_dst;
427252504Slstewart		switch (rh->ip6r_type) {
428252504Slstewart		case IPV6_RTHDR_TYPE_0:
429252504Slstewart			 rh0 = (struct ip6_rthdr0 *)rh;
430252504Slstewart			 ip6->ip6_dst = rh0->ip6r0_addr[0];
431252504Slstewart			 bcopy((caddr_t)&rh0->ip6r0_addr[1],
432252504Slstewart			       (caddr_t)&rh0->ip6r0_addr[0],
433252504Slstewart			       sizeof(struct in6_addr)*(rh0->ip6r0_segleft - 1)
434252504Slstewart				 );
435252504Slstewart			 rh0->ip6r0_addr[rh0->ip6r0_segleft - 1] = finaldst;
436252504Slstewart			 break;
437252504Slstewart		default:	/* is it possible? */
438252504Slstewart			 error = EINVAL;
439252504Slstewart			 goto bad;
440252504Slstewart		}
441252504Slstewart	}
442252504Slstewart
443252504Slstewart	/* Source address validation */
444252504Slstewart	if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src) &&
445252504Slstewart	    (flags & IPV6_DADOUTPUT) == 0) {
446252504Slstewart		error = EOPNOTSUPP;
447252504Slstewart		ip6stat.ip6s_badscope++;
448252504Slstewart		goto bad;
449252504Slstewart	}
450252504Slstewart	if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_src)) {
451252504Slstewart		error = EOPNOTSUPP;
452252504Slstewart		ip6stat.ip6s_badscope++;
453252504Slstewart		goto bad;
454252504Slstewart	}
455252504Slstewart
456252504Slstewart	ip6stat.ip6s_localout++;
457252504Slstewart
458252504Slstewart	/*
459252504Slstewart	 * Route packet.
460252504Slstewart	 */
461252504Slstewart	if (ro == 0) {
462252504Slstewart		ro = &ip6route;
463252504Slstewart		bzero((caddr_t)ro, sizeof(*ro));
464252504Slstewart	}
465252504Slstewart	ro_pmtu = ro;
466252504Slstewart	if (opt && opt->ip6po_rthdr)
467252504Slstewart		ro = &opt->ip6po_route;
468252504Slstewart	dst = (struct sockaddr_in6 *)&ro->ro_dst;
469252504Slstewart	/*
470252504Slstewart	 * If there is a cached route,
471252504Slstewart	 * check that it is to the same destination
472252504Slstewart	 * and is still up. If not, free it and try again.
473252504Slstewart	 */
474252504Slstewart	if (ro->ro_rt && ((ro->ro_rt->rt_flags & RTF_UP) == 0 ||
475252504Slstewart			 !IN6_ARE_ADDR_EQUAL(&dst->sin6_addr, &ip6->ip6_dst))) {
476252504Slstewart		RTFREE(ro->ro_rt);
477252504Slstewart		ro->ro_rt = (struct rtentry *)0;
478252504Slstewart	}
479252504Slstewart	if (ro->ro_rt == 0) {
480252504Slstewart		bzero(dst, sizeof(*dst));
481252504Slstewart		dst->sin6_family = AF_INET6;
482252504Slstewart		dst->sin6_len = sizeof(struct sockaddr_in6);
483252504Slstewart		dst->sin6_addr = ip6->ip6_dst;
484252504Slstewart#ifdef SCOPEDROUTING
485252504Slstewart		/* XXX: sin6_scope_id should already be fixed at this point */
486252504Slstewart		if (IN6_IS_SCOPE_LINKLOCAL(&dst->sin6_addr))
487252504Slstewart			dst->sin6_scope_id = ntohs(dst->sin6_addr.s6_addr16[1]);
488252504Slstewart#endif
489252504Slstewart	}
490252504Slstewart#ifdef IPSEC
491252504Slstewart	if (needipsec && needipsectun) {
492252504Slstewart		struct ipsec_output_state state;
493252504Slstewart
494252504Slstewart		/*
495252504Slstewart		 * All the extension headers will become inaccessible
496252504Slstewart		 * (since they can be encrypted).
497252504Slstewart		 * Don't panic, we need no more updates to extension headers
498252504Slstewart		 * on inner IPv6 packet (since they are now encapsulated).
499252504Slstewart		 *
500252504Slstewart		 * IPv6 [ESP|AH] IPv6 [extension headers] payload
501252504Slstewart		 */
502252504Slstewart		bzero(&exthdrs, sizeof(exthdrs));
503252504Slstewart		exthdrs.ip6e_ip6 = m;
504252504Slstewart
505252504Slstewart		bzero(&state, sizeof(state));
506252504Slstewart		state.m = m;
507252504Slstewart		state.ro = (struct route *)ro;
508252504Slstewart		state.dst = (struct sockaddr *)dst;
509252504Slstewart
510252504Slstewart		error = ipsec6_output_tunnel(&state, sp, flags);
511252504Slstewart
512252504Slstewart		m = state.m;
513252504Slstewart		ro = (struct route_in6 *)state.ro;
514252504Slstewart		dst = (struct sockaddr_in6 *)state.dst;
515252504Slstewart		if (error) {
516252504Slstewart			/* mbuf is already reclaimed in ipsec6_output_tunnel. */
517252504Slstewart			m0 = m = NULL;
518252504Slstewart			m = NULL;
519252504Slstewart			switch (error) {
520252504Slstewart			case EHOSTUNREACH:
521252504Slstewart			case ENETUNREACH:
522252504Slstewart			case EMSGSIZE:
523252504Slstewart			case ENOBUFS:
524252504Slstewart			case ENOMEM:
525252504Slstewart				break;
526252504Slstewart			default:
527252504Slstewart				printf("ip6_output (ipsec): error code %d\n", error);
528252504Slstewart				/*fall through*/
529252504Slstewart			case ENOENT:
530252504Slstewart				/* don't show these error codes to the user */
531252504Slstewart				error = 0;
532252504Slstewart				break;
533252504Slstewart			}
534252504Slstewart			goto bad;
535252504Slstewart		}
536252504Slstewart
537252504Slstewart		exthdrs.ip6e_ip6 = m;
538252504Slstewart	}
539252504Slstewart#endif /*IPSEC*/
540252504Slstewart
541252504Slstewart	if (!IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
542252504Slstewart		/* Unicast */
543252504Slstewart
544252504Slstewart#define ifatoia6(ifa)	((struct in6_ifaddr *)(ifa))
545252504Slstewart#define sin6tosa(sin6)	((struct sockaddr *)(sin6))
546252504Slstewart		/* xxx
547252504Slstewart		 * interface selection comes here
548252504Slstewart		 * if an interface is specified from an upper layer,
549252504Slstewart		 * ifp must point it.
550252504Slstewart		 */
551252504Slstewart		if (ro->ro_rt == 0) {
552252504Slstewart			/*
553252504Slstewart			 * non-bsdi always clone routes, if parent is
554252504Slstewart			 * PRF_CLONING.
555252504Slstewart			 */
556252504Slstewart			rtalloc((struct route *)ro);
557252504Slstewart		}
558252504Slstewart		if (ro->ro_rt == 0) {
559252504Slstewart			ip6stat.ip6s_noroute++;
560252504Slstewart			error = EHOSTUNREACH;
561252504Slstewart			/* XXX in6_ifstat_inc(ifp, ifs6_out_discard); */
562252504Slstewart			goto bad;
563252504Slstewart		}
564252504Slstewart		ia = ifatoia6(ro->ro_rt->rt_ifa);
565252504Slstewart		ifp = ro->ro_rt->rt_ifp;
566252504Slstewart		ro->ro_rt->rt_use++;
567252504Slstewart		if (ro->ro_rt->rt_flags & RTF_GATEWAY)
568252504Slstewart			dst = (struct sockaddr_in6 *)ro->ro_rt->rt_gateway;
569252504Slstewart		m->m_flags &= ~(M_BCAST | M_MCAST);	/* just in case */
570252504Slstewart
571252504Slstewart		in6_ifstat_inc(ifp, ifs6_out_request);
572252504Slstewart
573252504Slstewart		/*
574252504Slstewart		 * Check if the outgoing interface conflicts with
575252504Slstewart		 * the interface specified by ifi6_ifindex (if specified).
576252504Slstewart		 * Note that loopback interface is always okay.
577252504Slstewart		 * (this may happen when we are sending a packet to one of
578252504Slstewart		 *  our own addresses.)
579252504Slstewart		 */
580252504Slstewart		if (opt && opt->ip6po_pktinfo
581252504Slstewart		 && opt->ip6po_pktinfo->ipi6_ifindex) {
582252504Slstewart			if (!(ifp->if_flags & IFF_LOOPBACK)
583252504Slstewart			 && ifp->if_index != opt->ip6po_pktinfo->ipi6_ifindex) {
584252504Slstewart				ip6stat.ip6s_noroute++;
585252504Slstewart				in6_ifstat_inc(ifp, ifs6_out_discard);
586252504Slstewart				error = EHOSTUNREACH;
587252504Slstewart				goto bad;
588252504Slstewart			}
589252504Slstewart		}
590252504Slstewart
591252504Slstewart		if (opt && opt->ip6po_hlim != -1)
592252504Slstewart			ip6->ip6_hlim = opt->ip6po_hlim & 0xff;
593252504Slstewart	} else {
594252504Slstewart		/* Multicast */
595252504Slstewart		struct	in6_multi *in6m;
596252504Slstewart
597252504Slstewart		m->m_flags = (m->m_flags & ~M_BCAST) | M_MCAST;
598252504Slstewart
599252504Slstewart		/*
600252504Slstewart		 * See if the caller provided any multicast options
601252504Slstewart		 */
602252504Slstewart		ifp = NULL;
603252504Slstewart		if (im6o != NULL) {
604252504Slstewart			ip6->ip6_hlim = im6o->im6o_multicast_hlim;
605252504Slstewart			if (im6o->im6o_multicast_ifp != NULL)
606252504Slstewart				ifp = im6o->im6o_multicast_ifp;
607252504Slstewart		} else
608252504Slstewart			ip6->ip6_hlim = ip6_defmcasthlim;
609252504Slstewart
610252504Slstewart		/*
611252504Slstewart		 * See if the caller provided the outgoing interface
612252504Slstewart		 * as an ancillary data.
613252504Slstewart		 * Boundary check for ifindex is assumed to be already done.
614252504Slstewart		 */
615252504Slstewart		if (opt && opt->ip6po_pktinfo && opt->ip6po_pktinfo->ipi6_ifindex)
616252504Slstewart			ifp = ifindex2ifnet[opt->ip6po_pktinfo->ipi6_ifindex];
617252504Slstewart
618252504Slstewart		/*
619252504Slstewart		 * If the destination is a node-local scope multicast,
620252504Slstewart		 * the packet should be loop-backed only.
621252504Slstewart		 */
622252504Slstewart		if (IN6_IS_ADDR_MC_NODELOCAL(&ip6->ip6_dst)) {
623252504Slstewart			/*
624252504Slstewart			 * If the outgoing interface is already specified,
625252504Slstewart			 * it should be a loopback interface.
626252504Slstewart			 */
627252504Slstewart			if (ifp && (ifp->if_flags & IFF_LOOPBACK) == 0) {
628252504Slstewart				ip6stat.ip6s_badscope++;
629252504Slstewart				error = ENETUNREACH; /* XXX: better error? */
630252504Slstewart				/* XXX correct ifp? */
631252504Slstewart				in6_ifstat_inc(ifp, ifs6_out_discard);
632252504Slstewart				goto bad;
633252504Slstewart			} else {
634252504Slstewart				ifp = &loif[0];
635252504Slstewart			}
636252504Slstewart		}
637252504Slstewart
638252504Slstewart		if (opt && opt->ip6po_hlim != -1)
639252504Slstewart			ip6->ip6_hlim = opt->ip6po_hlim & 0xff;
640252504Slstewart
641252504Slstewart		/*
642252504Slstewart		 * If caller did not provide an interface lookup a
643252504Slstewart		 * default in the routing table.  This is either a
644252504Slstewart		 * default for the speicfied group (i.e. a host
645252504Slstewart		 * route), or a multicast default (a route for the
646252504Slstewart		 * ``net'' ff00::/8).
647252504Slstewart		 */
648252504Slstewart		if (ifp == NULL) {
649252504Slstewart			if (ro->ro_rt == 0) {
650252504Slstewart				ro->ro_rt = rtalloc1((struct sockaddr *)
651252504Slstewart						&ro->ro_dst, 0, 0UL);
652252504Slstewart			}
653252504Slstewart			if (ro->ro_rt == 0) {
654252504Slstewart				ip6stat.ip6s_noroute++;
655252504Slstewart				error = EHOSTUNREACH;
656252504Slstewart				/* XXX in6_ifstat_inc(ifp, ifs6_out_discard) */
657252504Slstewart				goto bad;
658252504Slstewart			}
659252504Slstewart			ia = ifatoia6(ro->ro_rt->rt_ifa);
660252504Slstewart			ifp = ro->ro_rt->rt_ifp;
661252504Slstewart			ro->ro_rt->rt_use++;
662252504Slstewart		}
663252504Slstewart
664252504Slstewart		if ((flags & IPV6_FORWARDING) == 0)
665252504Slstewart			in6_ifstat_inc(ifp, ifs6_out_request);
666252504Slstewart		in6_ifstat_inc(ifp, ifs6_out_mcast);
667252504Slstewart
668252504Slstewart		/*
669252504Slstewart		 * Confirm that the outgoing interface supports multicast.
670252504Slstewart		 */
671252504Slstewart		if ((ifp->if_flags & IFF_MULTICAST) == 0) {
672252504Slstewart			ip6stat.ip6s_noroute++;
673252504Slstewart			in6_ifstat_inc(ifp, ifs6_out_discard);
674252504Slstewart			error = ENETUNREACH;
675252504Slstewart			goto bad;
676252504Slstewart		}
677252504Slstewart		IN6_LOOKUP_MULTI(ip6->ip6_dst, ifp, in6m);
678252504Slstewart		if (in6m != NULL &&
679252504Slstewart		   (im6o == NULL || im6o->im6o_multicast_loop)) {
680252504Slstewart			/*
681252504Slstewart			 * If we belong to the destination multicast group
682252504Slstewart			 * on the outgoing interface, and the caller did not
683252504Slstewart			 * forbid loopback, loop back a copy.
684252504Slstewart			 */
685252504Slstewart			ip6_mloopback(ifp, m, dst);
686252504Slstewart		} else {
687252504Slstewart			/*
688252504Slstewart			 * If we are acting as a multicast router, perform
689252504Slstewart			 * multicast forwarding as if the packet had just
690252504Slstewart			 * arrived on the interface to which we are about
691252504Slstewart			 * to send.  The multicast forwarding function
692252504Slstewart			 * recursively calls this function, using the
693252504Slstewart			 * IPV6_FORWARDING flag to prevent infinite recursion.
694252504Slstewart			 *
695252504Slstewart			 * Multicasts that are looped back by ip6_mloopback(),
696			 * above, will be forwarded by the ip6_input() routine,
697			 * if necessary.
698			 */
699			if (ip6_mrouter && (flags & IPV6_FORWARDING) == 0) {
700				if (ip6_mforward(ip6, ifp, m) != 0) {
701					m_freem(m);
702					goto done;
703				}
704			}
705		}
706		/*
707		 * Multicasts with a hoplimit of zero may be looped back,
708		 * above, but must not be transmitted on a network.
709		 * Also, multicasts addressed to the loopback interface
710		 * are not sent -- the above call to ip6_mloopback() will
711		 * loop back a copy if this host actually belongs to the
712		 * destination group on the loopback interface.
713		 */
714		if (ip6->ip6_hlim == 0 || (ifp->if_flags & IFF_LOOPBACK)) {
715			m_freem(m);
716			goto done;
717		}
718	}
719
720	/*
721	 * Fill the outgoing inteface to tell the upper layer
722	 * to increment per-interface statistics.
723	 */
724	if (ifpp)
725		*ifpp = ifp;
726
727	/*
728	 * Determine path MTU.
729	 */
730	if (ro_pmtu != ro) {
731		/* The first hop and the final destination may differ. */
732		struct sockaddr_in6 *sin6_fin =
733			(struct sockaddr_in6 *)&ro_pmtu->ro_dst;
734		if (ro_pmtu->ro_rt && ((ro->ro_rt->rt_flags & RTF_UP) == 0 ||
735				       !IN6_ARE_ADDR_EQUAL(&sin6_fin->sin6_addr,
736							   &finaldst))) {
737			RTFREE(ro_pmtu->ro_rt);
738			ro_pmtu->ro_rt = (struct rtentry *)0;
739		}
740		if (ro_pmtu->ro_rt == 0) {
741			bzero(sin6_fin, sizeof(*sin6_fin));
742			sin6_fin->sin6_family = AF_INET6;
743			sin6_fin->sin6_len = sizeof(struct sockaddr_in6);
744			sin6_fin->sin6_addr = finaldst;
745
746			rtalloc((struct route *)ro_pmtu);
747		}
748	}
749	if (ro_pmtu->ro_rt != NULL) {
750		u_int32_t ifmtu = nd_ifinfo[ifp->if_index].linkmtu;
751
752		mtu = ro_pmtu->ro_rt->rt_rmx.rmx_mtu;
753		if (mtu > ifmtu || mtu == 0) {
754			/*
755			 * The MTU on the route is larger than the MTU on
756			 * the interface!  This shouldn't happen, unless the
757			 * MTU of the interface has been changed after the
758			 * interface was brought up.  Change the MTU in the
759			 * route to match the interface MTU (as long as the
760			 * field isn't locked).
761			 *
762			 * if MTU on the route is 0, we need to fix the MTU.
763			 * this case happens with path MTU discovery timeouts.
764			 */
765			 mtu = ifmtu;
766			 if ((ro_pmtu->ro_rt->rt_rmx.rmx_locks & RTV_MTU) == 0)
767				 ro_pmtu->ro_rt->rt_rmx.rmx_mtu = mtu; /* XXX */
768		}
769	} else {
770		mtu = nd_ifinfo[ifp->if_index].linkmtu;
771	}
772
773	/*
774	 * advanced API (IPV6_USE_MIN_MTU) overrides mtu setting
775	 */
776	if ((flags & IPV6_MINMTU) != 0 && mtu > IPV6_MMTU)
777		mtu = IPV6_MMTU;
778
779	/* Fake scoped addresses */
780	if ((ifp->if_flags & IFF_LOOPBACK) != 0) {
781		/*
782		 * If source or destination address is a scoped address, and
783		 * the packet is going to be sent to a loopback interface,
784		 * we should keep the original interface.
785		 */
786
787		/*
788		 * XXX: this is a very experimental and temporary solution.
789		 * We eventually have sockaddr_in6 and use the sin6_scope_id
790		 * field of the structure here.
791		 * We rely on the consistency between two scope zone ids
792		 * of source add destination, which should already be assured
793		 * larger scopes than link will be supported in the near
794		 * future.
795		 */
796		origifp = NULL;
797		if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_src))
798			origifp = ifindex2ifnet[ntohs(ip6->ip6_src.s6_addr16[1])];
799		else if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_dst))
800			origifp = ifindex2ifnet[ntohs(ip6->ip6_dst.s6_addr16[1])];
801		/*
802		 * XXX: origifp can be NULL even in those two cases above.
803		 * For example, if we remove the (only) link-local address
804		 * from the loopback interface, and try to send a link-local
805		 * address without link-id information.  Then the source
806		 * address is ::1, and the destination address is the
807		 * link-local address with its s6_addr16[1] being zero.
808		 * What is worse, if the packet goes to the loopback interface
809		 * by a default rejected route, the null pointer would be
810		 * passed to looutput, and the kernel would hang.
811		 * The following last resort would prevent such disaster.
812		 */
813		if (origifp == NULL)
814			origifp = ifp;
815	}
816	else
817		origifp = ifp;
818#ifndef SCOPEDROUTING
819	/*
820	 * clear embedded scope identifiers if necessary.
821	 * in6_clearscope will touch the addresses only when necessary.
822	 */
823	in6_clearscope(&ip6->ip6_src);
824	in6_clearscope(&ip6->ip6_dst);
825#endif
826
827	/*
828	 * Check with the firewall...
829	 */
830        if (ip6_fw_enable && ip6_fw_chk_ptr) {
831		u_short port = 0;
832		m->m_pkthdr.rcvif = NULL;	/*XXX*/
833		/* If ipfw says divert, we have to just drop packet */
834		if ((*ip6_fw_chk_ptr)(&ip6, ifp, &port, &m)) {
835			m_freem(m);
836			goto done;
837		}
838		if (!m) {
839			error = EACCES;
840			goto done;
841		}
842	}
843
844	/*
845	 * If the outgoing packet contains a hop-by-hop options header,
846	 * it must be examined and processed even by the source node.
847	 * (RFC 2460, section 4.)
848	 */
849	if (exthdrs.ip6e_hbh) {
850		struct ip6_hbh *hbh = mtod(exthdrs.ip6e_hbh, struct ip6_hbh *);
851		u_int32_t dummy1; /* XXX unused */
852		u_int32_t dummy2; /* XXX unused */
853
854#ifdef DIAGNOSTIC
855		if ((hbh->ip6h_len + 1) << 3 > exthdrs.ip6e_hbh->m_len)
856			panic("ip6e_hbh is not continuous");
857#endif
858		/*
859		 *  XXX: if we have to send an ICMPv6 error to the sender,
860		 *       we need the M_LOOP flag since icmp6_error() expects
861		 *       the IPv6 and the hop-by-hop options header are
862		 *       continuous unless the flag is set.
863		 */
864		m->m_flags |= M_LOOP;
865		m->m_pkthdr.rcvif = ifp;
866		if (ip6_process_hopopts(m,
867					(u_int8_t *)(hbh + 1),
868					((hbh->ip6h_len + 1) << 3) -
869					sizeof(struct ip6_hbh),
870					&dummy1, &dummy2) < 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#ifdef PFIL_HOOKS
880	/*
881	 * Run through list of hooks for output packets.
882	 */
883	m1 = m;
884	pfh = pfil_hook_get(PFIL_OUT, &inet6sw[ip6_protox[IPPROTO_IPV6]].pr_pfh);
885	for (; pfh; pfh = pfh->pfil_link.tqe_next)
886		if (pfh->pfil_func) {
887			rv = pfh->pfil_func(ip6, sizeof(*ip6), ifp, 1, &m1);
888			if (rv) {
889				error = EHOSTUNREACH;
890				goto done;
891			}
892			m = m1;
893			if (m == NULL)
894				goto done;
895			ip6 = mtod(m, struct ip6_hdr *);
896		}
897#endif /* PFIL_HOOKS */
898	/*
899	 * Send the packet to the outgoing interface.
900	 * If necessary, do IPv6 fragmentation before sending.
901	 */
902	tlen = m->m_pkthdr.len;
903	if (tlen <= mtu
904#ifdef notyet
905	    /*
906	     * On any link that cannot convey a 1280-octet packet in one piece,
907	     * link-specific fragmentation and reassembly must be provided at
908	     * a layer below IPv6. [RFC 2460, sec.5]
909	     * Thus if the interface has ability of link-level fragmentation,
910	     * we can just send the packet even if the packet size is
911	     * larger than the link's MTU.
912	     * XXX: IFF_FRAGMENTABLE (or such) flag has not been defined yet...
913	     */
914
915	    || ifp->if_flags & IFF_FRAGMENTABLE
916#endif
917	    )
918	{
919 		/* Record statistics for this interface address. */
920 		if (ia && !(flags & IPV6_FORWARDING)) {
921 			ia->ia_ifa.if_opackets++;
922 			ia->ia_ifa.if_obytes += m->m_pkthdr.len;
923 		}
924#ifdef IPSEC
925		/* clean ipsec history once it goes out of the node */
926		ipsec_delaux(m);
927#endif
928		error = nd6_output(ifp, origifp, m, dst, ro->ro_rt);
929		goto done;
930	} else if (mtu < IPV6_MMTU) {
931		/*
932		 * note that path MTU is never less than IPV6_MMTU
933		 * (see icmp6_input).
934		 */
935		error = EMSGSIZE;
936		in6_ifstat_inc(ifp, ifs6_out_fragfail);
937		goto bad;
938	} else if (ip6->ip6_plen == 0) { /* jumbo payload cannot be fragmented */
939		error = EMSGSIZE;
940		in6_ifstat_inc(ifp, ifs6_out_fragfail);
941		goto bad;
942	} else {
943		struct mbuf **mnext, *m_frgpart;
944		struct ip6_frag *ip6f;
945		u_int32_t id = htonl(ip6_id++);
946		u_char nextproto;
947
948		/*
949		 * Too large for the destination or interface;
950		 * fragment if possible.
951		 * Must be able to put at least 8 bytes per fragment.
952		 */
953		hlen = unfragpartlen;
954		if (mtu > IPV6_MAXPACKET)
955			mtu = IPV6_MAXPACKET;
956
957		len = (mtu - hlen - sizeof(struct ip6_frag)) & ~7;
958		if (len < 8) {
959			error = EMSGSIZE;
960			in6_ifstat_inc(ifp, ifs6_out_fragfail);
961			goto bad;
962		}
963
964		mnext = &m->m_nextpkt;
965
966		/*
967		 * Change the next header field of the last header in the
968		 * unfragmentable part.
969		 */
970		if (exthdrs.ip6e_rthdr) {
971			nextproto = *mtod(exthdrs.ip6e_rthdr, u_char *);
972			*mtod(exthdrs.ip6e_rthdr, u_char *) = IPPROTO_FRAGMENT;
973		} else if (exthdrs.ip6e_dest1) {
974			nextproto = *mtod(exthdrs.ip6e_dest1, u_char *);
975			*mtod(exthdrs.ip6e_dest1, u_char *) = IPPROTO_FRAGMENT;
976		} else if (exthdrs.ip6e_hbh) {
977			nextproto = *mtod(exthdrs.ip6e_hbh, u_char *);
978			*mtod(exthdrs.ip6e_hbh, u_char *) = IPPROTO_FRAGMENT;
979		} else {
980			nextproto = ip6->ip6_nxt;
981			ip6->ip6_nxt = IPPROTO_FRAGMENT;
982		}
983
984		/*
985		 * Loop through length of segment after first fragment,
986		 * make new header and copy data of each part and link onto chain.
987		 */
988		m0 = m;
989		for (off = hlen; off < tlen; off += len) {
990			MGETHDR(m, M_DONTWAIT, MT_HEADER);
991			if (!m) {
992				error = ENOBUFS;
993				ip6stat.ip6s_odropped++;
994				goto sendorfree;
995			}
996			m->m_pkthdr.rcvif = NULL;
997			m->m_flags = m0->m_flags & M_COPYFLAGS;
998			*mnext = m;
999			mnext = &m->m_nextpkt;
1000			m->m_data += max_linkhdr;
1001			mhip6 = mtod(m, struct ip6_hdr *);
1002			*mhip6 = *ip6;
1003			m->m_len = sizeof(*mhip6);
1004 			error = ip6_insertfraghdr(m0, m, hlen, &ip6f);
1005 			if (error) {
1006				ip6stat.ip6s_odropped++;
1007				goto sendorfree;
1008			}
1009			ip6f->ip6f_offlg = htons((u_short)((off - hlen) & ~7));
1010			if (off + len >= tlen)
1011				len = tlen - off;
1012			else
1013				ip6f->ip6f_offlg |= IP6F_MORE_FRAG;
1014			mhip6->ip6_plen = htons((u_short)(len + hlen +
1015							  sizeof(*ip6f) -
1016							  sizeof(struct ip6_hdr)));
1017			if ((m_frgpart = m_copy(m0, off, len)) == 0) {
1018				error = ENOBUFS;
1019				ip6stat.ip6s_odropped++;
1020				goto sendorfree;
1021			}
1022			m_cat(m, m_frgpart);
1023			m->m_pkthdr.len = len + hlen + sizeof(*ip6f);
1024			m->m_pkthdr.rcvif = (struct ifnet *)0;
1025			ip6f->ip6f_reserved = 0;
1026			ip6f->ip6f_ident = id;
1027			ip6f->ip6f_nxt = nextproto;
1028			ip6stat.ip6s_ofragments++;
1029			in6_ifstat_inc(ifp, ifs6_out_fragcreat);
1030		}
1031
1032		in6_ifstat_inc(ifp, ifs6_out_fragok);
1033	}
1034
1035	/*
1036	 * Remove leading garbages.
1037	 */
1038sendorfree:
1039	m = m0->m_nextpkt;
1040	m0->m_nextpkt = 0;
1041	m_freem(m0);
1042	for (m0 = m; m; m = m0) {
1043		m0 = m->m_nextpkt;
1044		m->m_nextpkt = 0;
1045		if (error == 0) {
1046 			/* Record statistics for this interface address. */
1047 			if (ia) {
1048 				ia->ia_ifa.if_opackets++;
1049 				ia->ia_ifa.if_obytes += m->m_pkthdr.len;
1050 			}
1051#ifdef IPSEC
1052			/* clean ipsec history once it goes out of the node */
1053			ipsec_delaux(m);
1054#endif
1055			error = nd6_output(ifp, origifp, m, dst, ro->ro_rt);
1056		} else
1057			m_freem(m);
1058	}
1059
1060	if (error == 0)
1061		ip6stat.ip6s_fragmented++;
1062
1063done:
1064	if (ro == &ip6route && ro->ro_rt) { /* brace necessary for RTFREE */
1065		RTFREE(ro->ro_rt);
1066	} else if (ro_pmtu == &ip6route && ro_pmtu->ro_rt) {
1067		RTFREE(ro_pmtu->ro_rt);
1068	}
1069
1070#ifdef IPSEC
1071	if (sp != NULL)
1072		key_freesp(sp);
1073#endif /* IPSEC */
1074
1075	return(error);
1076
1077freehdrs:
1078	m_freem(exthdrs.ip6e_hbh);	/* m_freem will check if mbuf is 0 */
1079	m_freem(exthdrs.ip6e_dest1);
1080	m_freem(exthdrs.ip6e_rthdr);
1081	m_freem(exthdrs.ip6e_dest2);
1082	/* fall through */
1083bad:
1084	m_freem(m);
1085	goto done;
1086}
1087
1088static int
1089ip6_copyexthdr(mp, hdr, hlen)
1090	struct mbuf **mp;
1091	caddr_t hdr;
1092	int hlen;
1093{
1094	struct mbuf *m;
1095
1096	if (hlen > MCLBYTES)
1097		return(ENOBUFS); /* XXX */
1098
1099	MGET(m, M_DONTWAIT, MT_DATA);
1100	if (!m)
1101		return(ENOBUFS);
1102
1103	if (hlen > MLEN) {
1104		MCLGET(m, M_DONTWAIT);
1105		if ((m->m_flags & M_EXT) == 0) {
1106			m_free(m);
1107			return(ENOBUFS);
1108		}
1109	}
1110	m->m_len = hlen;
1111	if (hdr)
1112		bcopy(hdr, mtod(m, caddr_t), hlen);
1113
1114	*mp = m;
1115	return(0);
1116}
1117
1118/*
1119 * Insert jumbo payload option.
1120 */
1121static int
1122ip6_insert_jumboopt(exthdrs, plen)
1123	struct ip6_exthdrs *exthdrs;
1124	u_int32_t plen;
1125{
1126	struct mbuf *mopt;
1127	u_char *optbuf;
1128	u_int32_t v;
1129
1130#define JUMBOOPTLEN	8	/* length of jumbo payload option and padding */
1131
1132	/*
1133	 * If there is no hop-by-hop options header, allocate new one.
1134	 * If there is one but it doesn't have enough space to store the
1135	 * jumbo payload option, allocate a cluster to store the whole options.
1136	 * Otherwise, use it to store the options.
1137	 */
1138	if (exthdrs->ip6e_hbh == 0) {
1139		MGET(mopt, M_DONTWAIT, MT_DATA);
1140		if (mopt == 0)
1141			return(ENOBUFS);
1142		mopt->m_len = JUMBOOPTLEN;
1143		optbuf = mtod(mopt, u_char *);
1144		optbuf[1] = 0;	/* = ((JUMBOOPTLEN) >> 3) - 1 */
1145		exthdrs->ip6e_hbh = mopt;
1146	} else {
1147		struct ip6_hbh *hbh;
1148
1149		mopt = exthdrs->ip6e_hbh;
1150		if (M_TRAILINGSPACE(mopt) < JUMBOOPTLEN) {
1151			/*
1152			 * XXX assumption:
1153			 * - exthdrs->ip6e_hbh is not referenced from places
1154			 *   other than exthdrs.
1155			 * - exthdrs->ip6e_hbh is not an mbuf chain.
1156			 */
1157			int oldoptlen = mopt->m_len;
1158			struct mbuf *n;
1159
1160			/*
1161			 * XXX: give up if the whole (new) hbh header does
1162			 * not fit even in an mbuf cluster.
1163			 */
1164			if (oldoptlen + JUMBOOPTLEN > MCLBYTES)
1165				return(ENOBUFS);
1166
1167			/*
1168			 * As a consequence, we must always prepare a cluster
1169			 * at this point.
1170			 */
1171			MGET(n, M_DONTWAIT, MT_DATA);
1172			if (n) {
1173				MCLGET(n, M_DONTWAIT);
1174				if ((n->m_flags & M_EXT) == 0) {
1175					m_freem(n);
1176					n = NULL;
1177				}
1178			}
1179			if (!n)
1180				return(ENOBUFS);
1181			n->m_len = oldoptlen + JUMBOOPTLEN;
1182			bcopy(mtod(mopt, caddr_t), mtod(n, caddr_t),
1183			      oldoptlen);
1184			optbuf = mtod(n, caddr_t) + oldoptlen;
1185			m_freem(mopt);
1186			mopt = exthdrs->ip6e_hbh = n;
1187		} else {
1188			optbuf = mtod(mopt, u_char *) + mopt->m_len;
1189			mopt->m_len += JUMBOOPTLEN;
1190		}
1191		optbuf[0] = IP6OPT_PADN;
1192		optbuf[1] = 1;
1193
1194		/*
1195		 * Adjust the header length according to the pad and
1196		 * the jumbo payload option.
1197		 */
1198		hbh = mtod(mopt, struct ip6_hbh *);
1199		hbh->ip6h_len += (JUMBOOPTLEN >> 3);
1200	}
1201
1202	/* fill in the option. */
1203	optbuf[2] = IP6OPT_JUMBO;
1204	optbuf[3] = 4;
1205	v = (u_int32_t)htonl(plen + JUMBOOPTLEN);
1206	bcopy(&v, &optbuf[4], sizeof(u_int32_t));
1207
1208	/* finally, adjust the packet header length */
1209	exthdrs->ip6e_ip6->m_pkthdr.len += JUMBOOPTLEN;
1210
1211	return(0);
1212#undef JUMBOOPTLEN
1213}
1214
1215/*
1216 * Insert fragment header and copy unfragmentable header portions.
1217 */
1218static int
1219ip6_insertfraghdr(m0, m, hlen, frghdrp)
1220	struct mbuf *m0, *m;
1221	int hlen;
1222	struct ip6_frag **frghdrp;
1223{
1224	struct mbuf *n, *mlast;
1225
1226	if (hlen > sizeof(struct ip6_hdr)) {
1227		n = m_copym(m0, sizeof(struct ip6_hdr),
1228			    hlen - sizeof(struct ip6_hdr), M_DONTWAIT);
1229		if (n == 0)
1230			return(ENOBUFS);
1231		m->m_next = n;
1232	} else
1233		n = m;
1234
1235	/* Search for the last mbuf of unfragmentable part. */
1236	for (mlast = n; mlast->m_next; mlast = mlast->m_next)
1237		;
1238
1239	if ((mlast->m_flags & M_EXT) == 0 &&
1240	    M_TRAILINGSPACE(mlast) >= sizeof(struct ip6_frag)) {
1241		/* use the trailing space of the last mbuf for the fragment hdr */
1242		*frghdrp =
1243			(struct ip6_frag *)(mtod(mlast, caddr_t) + mlast->m_len);
1244		mlast->m_len += sizeof(struct ip6_frag);
1245		m->m_pkthdr.len += sizeof(struct ip6_frag);
1246	} else {
1247		/* allocate a new mbuf for the fragment header */
1248		struct mbuf *mfrg;
1249
1250		MGET(mfrg, M_DONTWAIT, MT_DATA);
1251		if (mfrg == 0)
1252			return(ENOBUFS);
1253		mfrg->m_len = sizeof(struct ip6_frag);
1254		*frghdrp = mtod(mfrg, struct ip6_frag *);
1255		mlast->m_next = mfrg;
1256	}
1257
1258	return(0);
1259}
1260
1261/*
1262 * IP6 socket option processing.
1263 */
1264int
1265ip6_ctloutput(so, sopt)
1266	struct socket *so;
1267	struct sockopt *sopt;
1268{
1269	int privileged;
1270	struct inpcb *in6p = sotoinpcb(so);
1271	int error, optval;
1272	int level, op, optname;
1273	int optlen;
1274	struct proc *p;
1275
1276	if (sopt) {
1277		level = sopt->sopt_level;
1278		op = sopt->sopt_dir;
1279		optname = sopt->sopt_name;
1280		optlen = sopt->sopt_valsize;
1281		p = sopt->sopt_p;
1282	} else {
1283		panic("ip6_ctloutput: arg soopt is NULL");
1284	}
1285	error = optval = 0;
1286
1287	privileged = (p == 0 || suser(p)) ? 0 : 1;
1288
1289	if (level == IPPROTO_IPV6) {
1290		switch (op) {
1291
1292		case SOPT_SET:
1293			switch (optname) {
1294			case IPV6_PKTOPTIONS:
1295			{
1296				struct mbuf *m;
1297
1298				error = soopt_getm(sopt, &m); /* XXX */
1299				if (error != NULL)
1300					break;
1301				error = soopt_mcopyin(sopt, m); /* XXX */
1302				if (error != NULL)
1303					break;
1304				error = ip6_pcbopts(&in6p->in6p_outputopts,
1305						    m, so, sopt);
1306				m_freem(m); /* XXX */
1307				break;
1308			}
1309
1310			/*
1311			 * Use of some Hop-by-Hop options or some
1312			 * Destination options, might require special
1313			 * privilege.  That is, normal applications
1314			 * (without special privilege) might be forbidden
1315			 * from setting certain options in outgoing packets,
1316			 * and might never see certain options in received
1317			 * packets. [RFC 2292 Section 6]
1318			 * KAME specific note:
1319			 *  KAME prevents non-privileged users from sending or
1320			 *  receiving ANY hbh/dst options in order to avoid
1321			 *  overhead of parsing options in the kernel.
1322			 */
1323			case IPV6_UNICAST_HOPS:
1324			case IPV6_CHECKSUM:
1325			case IPV6_FAITH:
1326
1327			case IPV6_V6ONLY:
1328				if (optlen != sizeof(int)) {
1329					error = EINVAL;
1330					break;
1331				}
1332				error = sooptcopyin(sopt, &optval,
1333					sizeof optval, sizeof optval);
1334				if (error)
1335					break;
1336				switch (optname) {
1337
1338				case IPV6_UNICAST_HOPS:
1339					if (optval < -1 || optval >= 256)
1340						error = EINVAL;
1341					else {
1342						/* -1 = kernel default */
1343						in6p->in6p_hops = optval;
1344
1345						if ((in6p->in6p_vflag &
1346						     INP_IPV4) != 0)
1347							in6p->inp_ip_ttl = optval;
1348					}
1349					break;
1350#define OPTSET(bit) \
1351do { \
1352	if (optval) \
1353		in6p->in6p_flags |= (bit); \
1354	else \
1355		in6p->in6p_flags &= ~(bit); \
1356} while (0)
1357#define OPTBIT(bit) (in6p->in6p_flags & (bit) ? 1 : 0)
1358
1359				case IPV6_CHECKSUM:
1360					in6p->in6p_cksum = optval;
1361					break;
1362
1363				case IPV6_FAITH:
1364					OPTSET(IN6P_FAITH);
1365					break;
1366
1367				case IPV6_V6ONLY:
1368					/*
1369					 * make setsockopt(IPV6_V6ONLY)
1370					 * available only prior to bind(2).
1371					 * see ipng mailing list, Jun 22 2001.
1372					 */
1373					if (in6p->in6p_lport ||
1374					    !IN6_IS_ADDR_UNSPECIFIED(&in6p->in6p_laddr))
1375					{
1376						error = EINVAL;
1377						break;
1378					}
1379					/*
1380					 * XXX: BINDV6ONLY should be integrated
1381					 * into V6ONLY.
1382					 */
1383					OPTSET(IN6P_BINDV6ONLY);
1384					OPTSET(IN6P_IPV6_V6ONLY);
1385					break;
1386				}
1387				break;
1388
1389			case IPV6_PKTINFO:
1390			case IPV6_HOPLIMIT:
1391			case IPV6_HOPOPTS:
1392			case IPV6_DSTOPTS:
1393			case IPV6_RTHDR:
1394				/* RFC 2292 */
1395				if (optlen != sizeof(int)) {
1396					error = EINVAL;
1397					break;
1398				}
1399				error = sooptcopyin(sopt, &optval,
1400					sizeof optval, sizeof optval);
1401				if (error)
1402					break;
1403				switch (optname) {
1404				case IPV6_PKTINFO:
1405					OPTSET(IN6P_PKTINFO);
1406					break;
1407				case IPV6_HOPLIMIT:
1408					OPTSET(IN6P_HOPLIMIT);
1409					break;
1410				case IPV6_HOPOPTS:
1411					/*
1412					 * Check super-user privilege.
1413					 * See comments for IPV6_RECVHOPOPTS.
1414					 */
1415					if (!privileged)
1416						return(EPERM);
1417					OPTSET(IN6P_HOPOPTS);
1418					break;
1419				case IPV6_DSTOPTS:
1420					if (!privileged)
1421						return(EPERM);
1422					OPTSET(IN6P_DSTOPTS|IN6P_RTHDRDSTOPTS); /* XXX */
1423					break;
1424				case IPV6_RTHDR:
1425					OPTSET(IN6P_RTHDR);
1426					break;
1427				}
1428				break;
1429#undef OPTSET
1430
1431			case IPV6_MULTICAST_IF:
1432			case IPV6_MULTICAST_HOPS:
1433			case IPV6_MULTICAST_LOOP:
1434			case IPV6_JOIN_GROUP:
1435			case IPV6_LEAVE_GROUP:
1436			    {
1437				struct mbuf *m;
1438				if (sopt->sopt_valsize > MLEN) {
1439					error = EMSGSIZE;
1440					break;
1441				}
1442				/* XXX */
1443				MGET(m, sopt->sopt_p ? M_TRYWAIT : M_DONTWAIT, MT_HEADER);
1444				if (m == 0) {
1445					error = ENOBUFS;
1446					break;
1447				}
1448				m->m_len = sopt->sopt_valsize;
1449				error = sooptcopyin(sopt, mtod(m, char *),
1450						    m->m_len, m->m_len);
1451				error =	ip6_setmoptions(sopt->sopt_name,
1452							&in6p->in6p_moptions,
1453							m);
1454				(void)m_free(m);
1455			    }
1456				break;
1457
1458			case IPV6_PORTRANGE:
1459				error = sooptcopyin(sopt, &optval,
1460				    sizeof optval, sizeof optval);
1461				if (error)
1462					break;
1463
1464				switch (optval) {
1465				case IPV6_PORTRANGE_DEFAULT:
1466					in6p->in6p_flags &= ~(IN6P_LOWPORT);
1467					in6p->in6p_flags &= ~(IN6P_HIGHPORT);
1468					break;
1469
1470				case IPV6_PORTRANGE_HIGH:
1471					in6p->in6p_flags &= ~(IN6P_LOWPORT);
1472					in6p->in6p_flags |= IN6P_HIGHPORT;
1473					break;
1474
1475				case IPV6_PORTRANGE_LOW:
1476					in6p->in6p_flags &= ~(IN6P_HIGHPORT);
1477					in6p->in6p_flags |= IN6P_LOWPORT;
1478					break;
1479
1480				default:
1481					error = EINVAL;
1482					break;
1483				}
1484				break;
1485
1486#ifdef IPSEC
1487			case IPV6_IPSEC_POLICY:
1488			    {
1489				caddr_t req = NULL;
1490				size_t len = 0;
1491				struct mbuf *m;
1492
1493				if ((error = soopt_getm(sopt, &m)) != 0) /* XXX */
1494					break;
1495				if ((error = soopt_mcopyin(sopt, m)) != 0) /* XXX */
1496					break;
1497				if (m) {
1498					req = mtod(m, caddr_t);
1499					len = m->m_len;
1500				}
1501				error = ipsec6_set_policy(in6p, optname, req,
1502				                          len, privileged);
1503				m_freem(m);
1504			    }
1505				break;
1506#endif /* KAME IPSEC */
1507
1508			case IPV6_FW_ADD:
1509			case IPV6_FW_DEL:
1510			case IPV6_FW_FLUSH:
1511			case IPV6_FW_ZERO:
1512			    {
1513				struct mbuf *m;
1514				struct mbuf **mp = &m;
1515
1516				if (ip6_fw_ctl_ptr == NULL)
1517					return EINVAL;
1518				/* XXX */
1519				if ((error = soopt_getm(sopt, &m)) != 0)
1520					break;
1521				/* XXX */
1522				if ((error = soopt_mcopyin(sopt, m)) != 0)
1523					break;
1524				error = (*ip6_fw_ctl_ptr)(optname, mp);
1525				m = *mp;
1526			    }
1527				break;
1528
1529			default:
1530				error = ENOPROTOOPT;
1531				break;
1532			}
1533			break;
1534
1535		case SOPT_GET:
1536			switch (optname) {
1537
1538			case IPV6_PKTOPTIONS:
1539				if (in6p->in6p_options) {
1540					struct mbuf *m;
1541					m = m_copym(in6p->in6p_options,
1542					    0, M_COPYALL, M_WAIT);
1543					error = soopt_mcopyout(sopt, m);
1544					if (error == 0)
1545						m_freem(m);
1546				} else
1547					sopt->sopt_valsize = 0;
1548				break;
1549
1550			case IPV6_UNICAST_HOPS:
1551			case IPV6_CHECKSUM:
1552
1553			case IPV6_FAITH:
1554			case IPV6_V6ONLY:
1555			case IPV6_PORTRANGE:
1556				switch (optname) {
1557
1558				case IPV6_UNICAST_HOPS:
1559					optval = in6p->in6p_hops;
1560					break;
1561
1562				case IPV6_CHECKSUM:
1563					optval = in6p->in6p_cksum;
1564					break;
1565
1566				case IPV6_FAITH:
1567					optval = OPTBIT(IN6P_FAITH);
1568					break;
1569
1570				case IPV6_V6ONLY:
1571					/* XXX: see the setopt case. */
1572					optval = OPTBIT(IN6P_BINDV6ONLY);
1573					break;
1574
1575				case IPV6_PORTRANGE:
1576				    {
1577					int flags;
1578					flags = in6p->in6p_flags;
1579					if (flags & IN6P_HIGHPORT)
1580						optval = IPV6_PORTRANGE_HIGH;
1581					else if (flags & IN6P_LOWPORT)
1582						optval = IPV6_PORTRANGE_LOW;
1583					else
1584						optval = 0;
1585					break;
1586				    }
1587				}
1588				error = sooptcopyout(sopt, &optval,
1589					sizeof optval);
1590				break;
1591
1592			case IPV6_PKTINFO:
1593			case IPV6_HOPLIMIT:
1594			case IPV6_HOPOPTS:
1595			case IPV6_RTHDR:
1596			case IPV6_DSTOPTS:
1597				if (optname == IPV6_HOPOPTS ||
1598				    optname == IPV6_DSTOPTS ||
1599				    !privileged)
1600					return(EPERM);
1601				switch (optname) {
1602				case IPV6_PKTINFO:
1603					optval = OPTBIT(IN6P_PKTINFO);
1604					break;
1605				case IPV6_HOPLIMIT:
1606					optval = OPTBIT(IN6P_HOPLIMIT);
1607					break;
1608				case IPV6_HOPOPTS:
1609					if (!privileged)
1610						return(EPERM);
1611					optval = OPTBIT(IN6P_HOPOPTS);
1612					break;
1613				case IPV6_RTHDR:
1614					optval = OPTBIT(IN6P_RTHDR);
1615					break;
1616				case IPV6_DSTOPTS:
1617					if (!privileged)
1618						return(EPERM);
1619					optval = OPTBIT(IN6P_DSTOPTS|IN6P_RTHDRDSTOPTS);
1620					break;
1621				}
1622				error = sooptcopyout(sopt, &optval,
1623					sizeof optval);
1624				break;
1625
1626			case IPV6_MULTICAST_IF:
1627			case IPV6_MULTICAST_HOPS:
1628			case IPV6_MULTICAST_LOOP:
1629			case IPV6_JOIN_GROUP:
1630			case IPV6_LEAVE_GROUP:
1631			    {
1632				struct mbuf *m;
1633				error = ip6_getmoptions(sopt->sopt_name,
1634						in6p->in6p_moptions, &m);
1635				if (error == 0)
1636					error = sooptcopyout(sopt,
1637						mtod(m, char *), m->m_len);
1638				m_freem(m);
1639			    }
1640				break;
1641
1642#ifdef IPSEC
1643			case IPV6_IPSEC_POLICY:
1644			  {
1645				caddr_t req = NULL;
1646				size_t len = 0;
1647				struct mbuf *m = NULL;
1648				struct mbuf **mp = &m;
1649
1650				error = soopt_getm(sopt, &m); /* XXX */
1651				if (error != NULL)
1652					break;
1653				error = soopt_mcopyin(sopt, m); /* XXX */
1654				if (error != NULL)
1655					break;
1656				if (m) {
1657					req = mtod(m, caddr_t);
1658					len = m->m_len;
1659				}
1660				error = ipsec6_get_policy(in6p, req, len, mp);
1661				if (error == 0)
1662					error = soopt_mcopyout(sopt, m); /*XXX*/
1663				if (error == 0 && m)
1664					m_freem(m);
1665				break;
1666			  }
1667#endif /* KAME IPSEC */
1668
1669			case IPV6_FW_GET:
1670			  {
1671				struct mbuf *m;
1672				struct mbuf **mp = &m;
1673
1674				if (ip6_fw_ctl_ptr == NULL)
1675			        {
1676					return EINVAL;
1677				}
1678				error = (*ip6_fw_ctl_ptr)(optname, mp);
1679				if (error == 0)
1680					error = soopt_mcopyout(sopt, m); /* XXX */
1681				if (error == 0 && m)
1682					m_freem(m);
1683			  }
1684				break;
1685
1686			default:
1687				error = ENOPROTOOPT;
1688				break;
1689			}
1690			break;
1691		}
1692	} else {
1693		error = EINVAL;
1694	}
1695	return(error);
1696}
1697
1698/*
1699 * Set up IP6 options in pcb for insertion in output packets or
1700 * specifying behavior of outgoing packets.
1701 */
1702static int
1703ip6_pcbopts(pktopt, m, so, sopt)
1704	struct ip6_pktopts **pktopt;
1705	struct mbuf *m;
1706	struct socket *so;
1707	struct sockopt *sopt;
1708{
1709	struct ip6_pktopts *opt = *pktopt;
1710	int error = 0;
1711	struct proc *p = sopt->sopt_p;
1712	int priv = 0;
1713
1714	/* turn off any old options. */
1715	if (opt) {
1716#ifdef DIAGNOSTIC
1717		if (opt->ip6po_pktinfo || opt->ip6po_nexthop ||
1718		    opt->ip6po_hbh || opt->ip6po_dest1 || opt->ip6po_dest2 ||
1719		    opt->ip6po_rhinfo.ip6po_rhi_rthdr)
1720			printf("ip6_pcbopts: all specified options are cleared.\n");
1721#endif
1722		ip6_clearpktopts(opt, 1, -1);
1723	} else
1724		opt = malloc(sizeof(*opt), M_IP6OPT, M_WAITOK);
1725	*pktopt = NULL;
1726
1727	if (!m || m->m_len == 0) {
1728		/*
1729		 * Only turning off any previous options.
1730		 */
1731		if (opt)
1732			free(opt, M_IP6OPT);
1733		return(0);
1734	}
1735
1736	/*  set options specified by user. */
1737	if (p && !suser(p))
1738		priv = 1;
1739	if ((error = ip6_setpktoptions(m, opt, priv, 1)) != 0) {
1740		ip6_clearpktopts(opt, 1, -1); /* XXX: discard all options */
1741		return(error);
1742	}
1743	*pktopt = opt;
1744	return(0);
1745}
1746
1747/*
1748 * initialize ip6_pktopts.  beware that there are non-zero default values in
1749 * the struct.
1750 */
1751void
1752init_ip6pktopts(opt)
1753	struct ip6_pktopts *opt;
1754{
1755
1756	bzero(opt, sizeof(*opt));
1757	opt->ip6po_hlim = -1;	/* -1 means default hop limit */
1758}
1759
1760void
1761ip6_clearpktopts(pktopt, needfree, optname)
1762	struct ip6_pktopts *pktopt;
1763	int needfree, optname;
1764{
1765	if (pktopt == NULL)
1766		return;
1767
1768	if (optname == -1) {
1769		if (needfree && pktopt->ip6po_pktinfo)
1770			free(pktopt->ip6po_pktinfo, M_IP6OPT);
1771		pktopt->ip6po_pktinfo = NULL;
1772	}
1773	if (optname == -1)
1774		pktopt->ip6po_hlim = -1;
1775	if (optname == -1) {
1776		if (needfree && pktopt->ip6po_nexthop)
1777			free(pktopt->ip6po_nexthop, M_IP6OPT);
1778		pktopt->ip6po_nexthop = NULL;
1779	}
1780	if (optname == -1) {
1781		if (needfree && pktopt->ip6po_hbh)
1782			free(pktopt->ip6po_hbh, M_IP6OPT);
1783		pktopt->ip6po_hbh = NULL;
1784	}
1785	if (optname == -1) {
1786		if (needfree && pktopt->ip6po_dest1)
1787			free(pktopt->ip6po_dest1, M_IP6OPT);
1788		pktopt->ip6po_dest1 = NULL;
1789	}
1790	if (optname == -1) {
1791		if (needfree && pktopt->ip6po_rhinfo.ip6po_rhi_rthdr)
1792			free(pktopt->ip6po_rhinfo.ip6po_rhi_rthdr, M_IP6OPT);
1793		pktopt->ip6po_rhinfo.ip6po_rhi_rthdr = NULL;
1794		if (pktopt->ip6po_route.ro_rt) {
1795			RTFREE(pktopt->ip6po_route.ro_rt);
1796			pktopt->ip6po_route.ro_rt = NULL;
1797		}
1798	}
1799	if (optname == -1) {
1800		if (needfree && pktopt->ip6po_dest2)
1801			free(pktopt->ip6po_dest2, M_IP6OPT);
1802		pktopt->ip6po_dest2 = NULL;
1803	}
1804}
1805
1806#define PKTOPT_EXTHDRCPY(type) \
1807do {\
1808	if (src->type) {\
1809		int hlen =\
1810			(((struct ip6_ext *)src->type)->ip6e_len + 1) << 3;\
1811		dst->type = malloc(hlen, M_IP6OPT, canwait);\
1812		if (dst->type == NULL && canwait == M_NOWAIT)\
1813			goto bad;\
1814		bcopy(src->type, dst->type, hlen);\
1815	}\
1816} while (0)
1817
1818struct ip6_pktopts *
1819ip6_copypktopts(src, canwait)
1820	struct ip6_pktopts *src;
1821	int canwait;
1822{
1823	struct ip6_pktopts *dst;
1824
1825	if (src == NULL) {
1826		printf("ip6_clearpktopts: invalid argument\n");
1827		return(NULL);
1828	}
1829
1830	dst = malloc(sizeof(*dst), M_IP6OPT, canwait);
1831	if (dst == NULL && canwait == M_NOWAIT)
1832		goto bad;
1833	bzero(dst, sizeof(*dst));
1834
1835	dst->ip6po_hlim = src->ip6po_hlim;
1836	if (src->ip6po_pktinfo) {
1837		dst->ip6po_pktinfo = malloc(sizeof(*dst->ip6po_pktinfo),
1838					    M_IP6OPT, canwait);
1839		if (dst->ip6po_pktinfo == NULL && canwait == M_NOWAIT)
1840			goto bad;
1841		*dst->ip6po_pktinfo = *src->ip6po_pktinfo;
1842	}
1843	if (src->ip6po_nexthop) {
1844		dst->ip6po_nexthop = malloc(src->ip6po_nexthop->sa_len,
1845					    M_IP6OPT, canwait);
1846		if (dst->ip6po_nexthop == NULL && canwait == M_NOWAIT)
1847			goto bad;
1848		bcopy(src->ip6po_nexthop, dst->ip6po_nexthop,
1849		      src->ip6po_nexthop->sa_len);
1850	}
1851	PKTOPT_EXTHDRCPY(ip6po_hbh);
1852	PKTOPT_EXTHDRCPY(ip6po_dest1);
1853	PKTOPT_EXTHDRCPY(ip6po_dest2);
1854	PKTOPT_EXTHDRCPY(ip6po_rthdr); /* not copy the cached route */
1855	return(dst);
1856
1857  bad:
1858	printf("ip6_copypktopts: copy failed");
1859	if (dst->ip6po_pktinfo) free(dst->ip6po_pktinfo, M_IP6OPT);
1860	if (dst->ip6po_nexthop) free(dst->ip6po_nexthop, M_IP6OPT);
1861	if (dst->ip6po_hbh) free(dst->ip6po_hbh, M_IP6OPT);
1862	if (dst->ip6po_dest1) free(dst->ip6po_dest1, M_IP6OPT);
1863	if (dst->ip6po_dest2) free(dst->ip6po_dest2, M_IP6OPT);
1864	if (dst->ip6po_rthdr) free(dst->ip6po_rthdr, M_IP6OPT);
1865	return(NULL);
1866}
1867#undef PKTOPT_EXTHDRCPY
1868
1869void
1870ip6_freepcbopts(pktopt)
1871	struct ip6_pktopts *pktopt;
1872{
1873	if (pktopt == NULL)
1874		return;
1875
1876	ip6_clearpktopts(pktopt, 1, -1);
1877
1878	free(pktopt, M_IP6OPT);
1879}
1880
1881/*
1882 * Set the IP6 multicast options in response to user setsockopt().
1883 */
1884static int
1885ip6_setmoptions(optname, im6op, m)
1886	int optname;
1887	struct ip6_moptions **im6op;
1888	struct mbuf *m;
1889{
1890	int error = 0;
1891	u_int loop, ifindex;
1892	struct ipv6_mreq *mreq;
1893	struct ifnet *ifp;
1894	struct ip6_moptions *im6o = *im6op;
1895	struct route_in6 ro;
1896	struct sockaddr_in6 *dst;
1897	struct in6_multi_mship *imm;
1898	struct proc *p = curproc;	/* XXX */
1899
1900	if (im6o == NULL) {
1901		/*
1902		 * No multicast option buffer attached to the pcb;
1903		 * allocate one and initialize to default values.
1904		 */
1905		im6o = (struct ip6_moptions *)
1906			malloc(sizeof(*im6o), M_IPMOPTS, M_WAITOK);
1907
1908		if (im6o == NULL)
1909			return(ENOBUFS);
1910		*im6op = im6o;
1911		im6o->im6o_multicast_ifp = NULL;
1912		im6o->im6o_multicast_hlim = ip6_defmcasthlim;
1913		im6o->im6o_multicast_loop = IPV6_DEFAULT_MULTICAST_LOOP;
1914		LIST_INIT(&im6o->im6o_memberships);
1915	}
1916
1917	switch (optname) {
1918
1919	case IPV6_MULTICAST_IF:
1920		/*
1921		 * Select the interface for outgoing multicast packets.
1922		 */
1923		if (m == NULL || m->m_len != sizeof(u_int)) {
1924			error = EINVAL;
1925			break;
1926		}
1927		bcopy(mtod(m, u_int *), &ifindex, sizeof(ifindex));
1928		if (ifindex < 0 || if_index < ifindex) {
1929			error = ENXIO;	/* XXX EINVAL? */
1930			break;
1931		}
1932		ifp = ifindex2ifnet[ifindex];
1933		if (ifp == NULL || (ifp->if_flags & IFF_MULTICAST) == 0) {
1934			error = EADDRNOTAVAIL;
1935			break;
1936		}
1937		im6o->im6o_multicast_ifp = ifp;
1938		break;
1939
1940	case IPV6_MULTICAST_HOPS:
1941	    {
1942		/*
1943		 * Set the IP6 hoplimit for outgoing multicast packets.
1944		 */
1945		int optval;
1946		if (m == NULL || m->m_len != sizeof(int)) {
1947			error = EINVAL;
1948			break;
1949		}
1950		bcopy(mtod(m, u_int *), &optval, sizeof(optval));
1951		if (optval < -1 || optval >= 256)
1952			error = EINVAL;
1953		else if (optval == -1)
1954			im6o->im6o_multicast_hlim = ip6_defmcasthlim;
1955		else
1956			im6o->im6o_multicast_hlim = optval;
1957		break;
1958	    }
1959
1960	case IPV6_MULTICAST_LOOP:
1961		/*
1962		 * Set the loopback flag for outgoing multicast packets.
1963		 * Must be zero or one.
1964		 */
1965		if (m == NULL || m->m_len != sizeof(u_int)) {
1966			error = EINVAL;
1967			break;
1968		}
1969		bcopy(mtod(m, u_int *), &loop, sizeof(loop));
1970		if (loop > 1) {
1971			error = EINVAL;
1972			break;
1973		}
1974		im6o->im6o_multicast_loop = loop;
1975		break;
1976
1977	case IPV6_JOIN_GROUP:
1978		/*
1979		 * Add a multicast group membership.
1980		 * Group must be a valid IP6 multicast address.
1981		 */
1982		if (m == NULL || m->m_len != sizeof(struct ipv6_mreq)) {
1983			error = EINVAL;
1984			break;
1985		}
1986		mreq = mtod(m, struct ipv6_mreq *);
1987		if (IN6_IS_ADDR_UNSPECIFIED(&mreq->ipv6mr_multiaddr)) {
1988			/*
1989			 * We use the unspecified address to specify to accept
1990			 * all multicast addresses. Only super user is allowed
1991			 * to do this.
1992			 */
1993			if (suser(p))
1994			{
1995				error = EACCES;
1996				break;
1997			}
1998		} else if (!IN6_IS_ADDR_MULTICAST(&mreq->ipv6mr_multiaddr)) {
1999			error = EINVAL;
2000			break;
2001		}
2002
2003		/*
2004		 * If the interface is specified, validate it.
2005		 */
2006		if (mreq->ipv6mr_interface < 0
2007		 || if_index < mreq->ipv6mr_interface) {
2008			error = ENXIO;	/* XXX EINVAL? */
2009			break;
2010		}
2011		/*
2012		 * If no interface was explicitly specified, choose an
2013		 * appropriate one according to the given multicast address.
2014		 */
2015		if (mreq->ipv6mr_interface == 0) {
2016			/*
2017			 * If the multicast address is in node-local scope,
2018			 * the interface should be a loopback interface.
2019			 * Otherwise, look up the routing table for the
2020			 * address, and choose the outgoing interface.
2021			 *   XXX: is it a good approach?
2022			 */
2023			if (IN6_IS_ADDR_MC_NODELOCAL(&mreq->ipv6mr_multiaddr)) {
2024				ifp = &loif[0];
2025			} else {
2026				ro.ro_rt = NULL;
2027				dst = (struct sockaddr_in6 *)&ro.ro_dst;
2028				bzero(dst, sizeof(*dst));
2029				dst->sin6_len = sizeof(struct sockaddr_in6);
2030				dst->sin6_family = AF_INET6;
2031				dst->sin6_addr = mreq->ipv6mr_multiaddr;
2032				rtalloc((struct route *)&ro);
2033				if (ro.ro_rt == NULL) {
2034					error = EADDRNOTAVAIL;
2035					break;
2036				}
2037				ifp = ro.ro_rt->rt_ifp;
2038				rtfree(ro.ro_rt);
2039			}
2040		} else
2041			ifp = ifindex2ifnet[mreq->ipv6mr_interface];
2042
2043		/*
2044		 * See if we found an interface, and confirm that it
2045		 * supports multicast
2046		 */
2047		if (ifp == NULL || (ifp->if_flags & IFF_MULTICAST) == 0) {
2048			error = EADDRNOTAVAIL;
2049			break;
2050		}
2051		/*
2052		 * Put interface index into the multicast address,
2053		 * if the address has link-local scope.
2054		 */
2055		if (IN6_IS_ADDR_MC_LINKLOCAL(&mreq->ipv6mr_multiaddr)) {
2056			mreq->ipv6mr_multiaddr.s6_addr16[1]
2057				= htons(mreq->ipv6mr_interface);
2058		}
2059		/*
2060		 * See if the membership already exists.
2061		 */
2062		for (imm = im6o->im6o_memberships.lh_first;
2063		     imm != NULL; imm = imm->i6mm_chain.le_next)
2064			if (imm->i6mm_maddr->in6m_ifp == ifp &&
2065			    IN6_ARE_ADDR_EQUAL(&imm->i6mm_maddr->in6m_addr,
2066					       &mreq->ipv6mr_multiaddr))
2067				break;
2068		if (imm != NULL) {
2069			error = EADDRINUSE;
2070			break;
2071		}
2072		/*
2073		 * Everything looks good; add a new record to the multicast
2074		 * address list for the given interface.
2075		 */
2076		imm = malloc(sizeof(*imm), M_IPMADDR, M_WAITOK);
2077		if (imm == NULL) {
2078			error = ENOBUFS;
2079			break;
2080		}
2081		if ((imm->i6mm_maddr =
2082		     in6_addmulti(&mreq->ipv6mr_multiaddr, ifp, &error)) == NULL) {
2083			free(imm, M_IPMADDR);
2084			break;
2085		}
2086		LIST_INSERT_HEAD(&im6o->im6o_memberships, imm, i6mm_chain);
2087		break;
2088
2089	case IPV6_LEAVE_GROUP:
2090		/*
2091		 * Drop a multicast group membership.
2092		 * Group must be a valid IP6 multicast address.
2093		 */
2094		if (m == NULL || m->m_len != sizeof(struct ipv6_mreq)) {
2095			error = EINVAL;
2096			break;
2097		}
2098		mreq = mtod(m, struct ipv6_mreq *);
2099		if (IN6_IS_ADDR_UNSPECIFIED(&mreq->ipv6mr_multiaddr)) {
2100			if (suser(p)) {
2101				error = EACCES;
2102				break;
2103			}
2104		} else if (!IN6_IS_ADDR_MULTICAST(&mreq->ipv6mr_multiaddr)) {
2105			error = EINVAL;
2106			break;
2107		}
2108		/*
2109		 * If an interface address was specified, get a pointer
2110		 * to its ifnet structure.
2111		 */
2112		if (mreq->ipv6mr_interface < 0
2113		 || if_index < mreq->ipv6mr_interface) {
2114			error = ENXIO;	/* XXX EINVAL? */
2115			break;
2116		}
2117		ifp = ifindex2ifnet[mreq->ipv6mr_interface];
2118		/*
2119		 * Put interface index into the multicast address,
2120		 * if the address has link-local scope.
2121		 */
2122		if (IN6_IS_ADDR_MC_LINKLOCAL(&mreq->ipv6mr_multiaddr)) {
2123			mreq->ipv6mr_multiaddr.s6_addr16[1]
2124				= htons(mreq->ipv6mr_interface);
2125		}
2126		/*
2127		 * Find the membership in the membership list.
2128		 */
2129		for (imm = im6o->im6o_memberships.lh_first;
2130		     imm != NULL; imm = imm->i6mm_chain.le_next) {
2131			if ((ifp == NULL ||
2132			     imm->i6mm_maddr->in6m_ifp == ifp) &&
2133			    IN6_ARE_ADDR_EQUAL(&imm->i6mm_maddr->in6m_addr,
2134					       &mreq->ipv6mr_multiaddr))
2135				break;
2136		}
2137		if (imm == NULL) {
2138			/* Unable to resolve interface */
2139			error = EADDRNOTAVAIL;
2140			break;
2141		}
2142		/*
2143		 * Give up the multicast address record to which the
2144		 * membership points.
2145		 */
2146		LIST_REMOVE(imm, i6mm_chain);
2147		in6_delmulti(imm->i6mm_maddr);
2148		free(imm, M_IPMADDR);
2149		break;
2150
2151	default:
2152		error = EOPNOTSUPP;
2153		break;
2154	}
2155
2156	/*
2157	 * If all options have default values, no need to keep the mbuf.
2158	 */
2159	if (im6o->im6o_multicast_ifp == NULL &&
2160	    im6o->im6o_multicast_hlim == ip6_defmcasthlim &&
2161	    im6o->im6o_multicast_loop == IPV6_DEFAULT_MULTICAST_LOOP &&
2162	    im6o->im6o_memberships.lh_first == NULL) {
2163		free(*im6op, M_IPMOPTS);
2164		*im6op = NULL;
2165	}
2166
2167	return(error);
2168}
2169
2170/*
2171 * Return the IP6 multicast options in response to user getsockopt().
2172 */
2173static int
2174ip6_getmoptions(optname, im6o, mp)
2175	int optname;
2176	struct ip6_moptions *im6o;
2177	struct mbuf **mp;
2178{
2179	u_int *hlim, *loop, *ifindex;
2180
2181	*mp = m_get(M_TRYWAIT, MT_HEADER);		/*XXX*/
2182
2183	switch (optname) {
2184
2185	case IPV6_MULTICAST_IF:
2186		ifindex = mtod(*mp, u_int *);
2187		(*mp)->m_len = sizeof(u_int);
2188		if (im6o == NULL || im6o->im6o_multicast_ifp == NULL)
2189			*ifindex = 0;
2190		else
2191			*ifindex = im6o->im6o_multicast_ifp->if_index;
2192		return(0);
2193
2194	case IPV6_MULTICAST_HOPS:
2195		hlim = mtod(*mp, u_int *);
2196		(*mp)->m_len = sizeof(u_int);
2197		if (im6o == NULL)
2198			*hlim = ip6_defmcasthlim;
2199		else
2200			*hlim = im6o->im6o_multicast_hlim;
2201		return(0);
2202
2203	case IPV6_MULTICAST_LOOP:
2204		loop = mtod(*mp, u_int *);
2205		(*mp)->m_len = sizeof(u_int);
2206		if (im6o == NULL)
2207			*loop = ip6_defmcasthlim;
2208		else
2209			*loop = im6o->im6o_multicast_loop;
2210		return(0);
2211
2212	default:
2213		return(EOPNOTSUPP);
2214	}
2215}
2216
2217/*
2218 * Discard the IP6 multicast options.
2219 */
2220void
2221ip6_freemoptions(im6o)
2222	struct ip6_moptions *im6o;
2223{
2224	struct in6_multi_mship *imm;
2225
2226	if (im6o == NULL)
2227		return;
2228
2229	while ((imm = im6o->im6o_memberships.lh_first) != NULL) {
2230		LIST_REMOVE(imm, i6mm_chain);
2231		if (imm->i6mm_maddr)
2232			in6_delmulti(imm->i6mm_maddr);
2233		free(imm, M_IPMADDR);
2234	}
2235	free(im6o, M_IPMOPTS);
2236}
2237
2238/*
2239 * Set IPv6 outgoing packet options based on advanced API.
2240 */
2241int
2242ip6_setpktoptions(control, opt, priv, needcopy)
2243	struct mbuf *control;
2244	struct ip6_pktopts *opt;
2245	int priv, needcopy;
2246{
2247	struct cmsghdr *cm = 0;
2248
2249	if (control == 0 || opt == 0)
2250		return(EINVAL);
2251
2252	init_ip6pktopts(opt);
2253
2254	/*
2255	 * XXX: Currently, we assume all the optional information is stored
2256	 * in a single mbuf.
2257	 */
2258	if (control->m_next)
2259		return(EINVAL);
2260
2261	for (; control->m_len; control->m_data += CMSG_ALIGN(cm->cmsg_len),
2262		     control->m_len -= CMSG_ALIGN(cm->cmsg_len)) {
2263		cm = mtod(control, struct cmsghdr *);
2264		if (cm->cmsg_len == 0 || cm->cmsg_len > control->m_len)
2265			return(EINVAL);
2266		if (cm->cmsg_level != IPPROTO_IPV6)
2267			continue;
2268
2269		/*
2270		 * XXX should check if RFC2292 API is mixed with 2292bis API
2271		 */
2272		switch (cm->cmsg_type) {
2273		case IPV6_PKTINFO:
2274			if (cm->cmsg_len != CMSG_LEN(sizeof(struct in6_pktinfo)))
2275				return(EINVAL);
2276			if (needcopy) {
2277				/* XXX: Is it really WAITOK? */
2278				opt->ip6po_pktinfo =
2279					malloc(sizeof(struct in6_pktinfo),
2280					       M_IP6OPT, M_WAITOK);
2281				bcopy(CMSG_DATA(cm), opt->ip6po_pktinfo,
2282				    sizeof(struct in6_pktinfo));
2283			} else
2284				opt->ip6po_pktinfo =
2285					(struct in6_pktinfo *)CMSG_DATA(cm);
2286			if (opt->ip6po_pktinfo->ipi6_ifindex &&
2287			    IN6_IS_ADDR_LINKLOCAL(&opt->ip6po_pktinfo->ipi6_addr))
2288				opt->ip6po_pktinfo->ipi6_addr.s6_addr16[1] =
2289					htons(opt->ip6po_pktinfo->ipi6_ifindex);
2290
2291			if (opt->ip6po_pktinfo->ipi6_ifindex > if_index
2292			 || opt->ip6po_pktinfo->ipi6_ifindex < 0) {
2293				return(ENXIO);
2294			}
2295
2296			/*
2297			 * Check if the requested source address is indeed a
2298			 * unicast address assigned to the node, and can be
2299			 * used as the packet's source address.
2300			 */
2301			if (!IN6_IS_ADDR_UNSPECIFIED(&opt->ip6po_pktinfo->ipi6_addr)) {
2302				struct in6_ifaddr *ia6;
2303				struct sockaddr_in6 sin6;
2304
2305				bzero(&sin6, sizeof(sin6));
2306				sin6.sin6_len = sizeof(sin6);
2307				sin6.sin6_family = AF_INET6;
2308				sin6.sin6_addr =
2309					opt->ip6po_pktinfo->ipi6_addr;
2310				ia6 = (struct in6_ifaddr *)ifa_ifwithaddr(sin6tosa(&sin6));
2311				if (ia6 == NULL ||
2312				    (ia6->ia6_flags & (IN6_IFF_ANYCAST |
2313						       IN6_IFF_NOTREADY)) != 0)
2314					return(EADDRNOTAVAIL);
2315			}
2316			break;
2317
2318		case IPV6_HOPLIMIT:
2319			if (cm->cmsg_len != CMSG_LEN(sizeof(int)))
2320				return(EINVAL);
2321
2322			opt->ip6po_hlim = *(int *)CMSG_DATA(cm);
2323			if (opt->ip6po_hlim < -1 || opt->ip6po_hlim > 255)
2324				return(EINVAL);
2325			break;
2326
2327		case IPV6_NEXTHOP:
2328			if (!priv)
2329				return(EPERM);
2330
2331			if (cm->cmsg_len < sizeof(u_char) ||
2332			    /* check if cmsg_len is large enough for sa_len */
2333			    cm->cmsg_len < CMSG_LEN(*CMSG_DATA(cm)))
2334				return(EINVAL);
2335
2336			if (needcopy) {
2337				opt->ip6po_nexthop =
2338					malloc(*CMSG_DATA(cm),
2339					       M_IP6OPT, M_WAITOK);
2340				bcopy(CMSG_DATA(cm),
2341				      opt->ip6po_nexthop,
2342				      *CMSG_DATA(cm));
2343			} else
2344				opt->ip6po_nexthop =
2345					(struct sockaddr *)CMSG_DATA(cm);
2346			break;
2347
2348		case IPV6_HOPOPTS:
2349		{
2350			struct ip6_hbh *hbh;
2351			int hbhlen;
2352
2353			if (cm->cmsg_len < CMSG_LEN(sizeof(struct ip6_hbh)))
2354				return(EINVAL);
2355			hbh = (struct ip6_hbh *)CMSG_DATA(cm);
2356			hbhlen = (hbh->ip6h_len + 1) << 3;
2357			if (cm->cmsg_len != CMSG_LEN(hbhlen))
2358				return(EINVAL);
2359
2360			if (needcopy) {
2361				opt->ip6po_hbh =
2362					malloc(hbhlen, M_IP6OPT, M_WAITOK);
2363				bcopy(hbh, opt->ip6po_hbh, hbhlen);
2364			} else
2365				opt->ip6po_hbh = hbh;
2366			break;
2367		}
2368
2369		case IPV6_DSTOPTS:
2370		{
2371			struct ip6_dest *dest, **newdest;
2372			int destlen;
2373
2374			if (cm->cmsg_len < CMSG_LEN(sizeof(struct ip6_dest)))
2375				return(EINVAL);
2376			dest = (struct ip6_dest *)CMSG_DATA(cm);
2377			destlen = (dest->ip6d_len + 1) << 3;
2378			if (cm->cmsg_len != CMSG_LEN(destlen))
2379				return(EINVAL);
2380
2381			/*
2382			 * The old advacned API is ambiguous on this
2383			 * point. Our approach is to determine the
2384			 * position based according to the existence
2385			 * of a routing header. Note, however, that
2386			 * this depends on the order of the extension
2387			 * headers in the ancillary data; the 1st part
2388			 * of the destination options header must
2389			 * appear before the routing header in the
2390			 * ancillary data, too.
2391			 * RFC2292bis solved the ambiguity by
2392			 * introducing separate cmsg types.
2393			 */
2394			if (opt->ip6po_rthdr == NULL)
2395				newdest = &opt->ip6po_dest1;
2396			else
2397				newdest = &opt->ip6po_dest2;
2398
2399			if (needcopy) {
2400				*newdest = malloc(destlen, M_IP6OPT, M_WAITOK);
2401				bcopy(dest, *newdest, destlen);
2402			} else
2403				*newdest = dest;
2404
2405			break;
2406		}
2407
2408		case IPV6_RTHDR:
2409		{
2410			struct ip6_rthdr *rth;
2411			int rthlen;
2412
2413			if (cm->cmsg_len < CMSG_LEN(sizeof(struct ip6_rthdr)))
2414				return(EINVAL);
2415			rth = (struct ip6_rthdr *)CMSG_DATA(cm);
2416			rthlen = (rth->ip6r_len + 1) << 3;
2417			if (cm->cmsg_len != CMSG_LEN(rthlen))
2418				return(EINVAL);
2419
2420			switch (rth->ip6r_type) {
2421			case IPV6_RTHDR_TYPE_0:
2422				/* must contain one addr */
2423				if (rth->ip6r_len == 0)
2424					return(EINVAL);
2425				/* length must be even */
2426				if (rth->ip6r_len % 2)
2427					return(EINVAL);
2428				if (rth->ip6r_len / 2 != rth->ip6r_segleft)
2429					return(EINVAL);
2430				break;
2431			default:
2432				return(EINVAL);	/* not supported */
2433			}
2434
2435			if (needcopy) {
2436				opt->ip6po_rthdr = malloc(rthlen, M_IP6OPT,
2437							  M_WAITOK);
2438				bcopy(rth, opt->ip6po_rthdr, rthlen);
2439			} else
2440				opt->ip6po_rthdr = rth;
2441
2442			break;
2443		}
2444
2445		default:
2446			return(ENOPROTOOPT);
2447		}
2448	}
2449
2450	return(0);
2451}
2452
2453/*
2454 * Routine called from ip6_output() to loop back a copy of an IP6 multicast
2455 * packet to the input queue of a specified interface.  Note that this
2456 * calls the output routine of the loopback "driver", but with an interface
2457 * pointer that might NOT be &loif -- easier than replicating that code here.
2458 */
2459void
2460ip6_mloopback(ifp, m, dst)
2461	struct ifnet *ifp;
2462	struct mbuf *m;
2463	struct sockaddr_in6 *dst;
2464{
2465	struct mbuf *copym;
2466	struct ip6_hdr *ip6;
2467
2468	copym = m_copy(m, 0, M_COPYALL);
2469	if (copym == NULL)
2470		return;
2471
2472	/*
2473	 * Make sure to deep-copy IPv6 header portion in case the data
2474	 * is in an mbuf cluster, so that we can safely override the IPv6
2475	 * header portion later.
2476	 */
2477	if ((copym->m_flags & M_EXT) != 0 ||
2478	    copym->m_len < sizeof(struct ip6_hdr)) {
2479		copym = m_pullup(copym, sizeof(struct ip6_hdr));
2480		if (copym == NULL)
2481			return;
2482	}
2483
2484#ifdef DIAGNOSTIC
2485	if (copym->m_len < sizeof(*ip6)) {
2486		m_freem(copym);
2487		return;
2488	}
2489#endif
2490
2491	ip6 = mtod(copym, struct ip6_hdr *);
2492#ifndef SCOPEDROUTING
2493	/*
2494	 * clear embedded scope identifiers if necessary.
2495	 * in6_clearscope will touch the addresses only when necessary.
2496	 */
2497	in6_clearscope(&ip6->ip6_src);
2498	in6_clearscope(&ip6->ip6_dst);
2499#endif
2500
2501	(void)if_simloop(ifp, copym, dst->sin6_family, NULL);
2502}
2503
2504/*
2505 * Chop IPv6 header off from the payload.
2506 */
2507static int
2508ip6_splithdr(m, exthdrs)
2509	struct mbuf *m;
2510	struct ip6_exthdrs *exthdrs;
2511{
2512	struct mbuf *mh;
2513	struct ip6_hdr *ip6;
2514
2515	ip6 = mtod(m, struct ip6_hdr *);
2516	if (m->m_len > sizeof(*ip6)) {
2517		MGETHDR(mh, M_DONTWAIT, MT_HEADER);
2518		if (mh == 0) {
2519			m_freem(m);
2520			return ENOBUFS;
2521		}
2522		M_COPY_PKTHDR(mh, m);
2523		MH_ALIGN(mh, sizeof(*ip6));
2524		m->m_flags &= ~M_PKTHDR;
2525		m->m_len -= sizeof(*ip6);
2526		m->m_data += sizeof(*ip6);
2527		mh->m_next = m;
2528		m = mh;
2529		m->m_len = sizeof(*ip6);
2530		bcopy((caddr_t)ip6, mtod(m, caddr_t), sizeof(*ip6));
2531	}
2532	exthdrs->ip6e_ip6 = m;
2533	return 0;
2534}
2535
2536/*
2537 * Compute IPv6 extension header length.
2538 */
2539int
2540ip6_optlen(in6p)
2541	struct in6pcb *in6p;
2542{
2543	int len;
2544
2545	if (!in6p->in6p_outputopts)
2546		return 0;
2547
2548	len = 0;
2549#define elen(x) \
2550    (((struct ip6_ext *)(x)) ? (((struct ip6_ext *)(x))->ip6e_len + 1) << 3 : 0)
2551
2552	len += elen(in6p->in6p_outputopts->ip6po_hbh);
2553	if (in6p->in6p_outputopts->ip6po_rthdr)
2554		/* dest1 is valid with rthdr only */
2555		len += elen(in6p->in6p_outputopts->ip6po_dest1);
2556	len += elen(in6p->in6p_outputopts->ip6po_rthdr);
2557	len += elen(in6p->in6p_outputopts->ip6po_dest2);
2558	return len;
2559#undef elen
2560}
2561