ip6_output.c revision 100508
1/*	$FreeBSD: head/sys/netinet6/ip6_output.c 100508 2002-07-22 15:51:02Z ume $	*/
2/*	$KAME: ip6_output.c,v 1.279 2002/01/26 06:12:30 jinmei Exp $	*/
3
4/*
5 * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
6 * All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 *    notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 *    notice, this list of conditions and the following disclaimer in the
15 *    documentation and/or other materials provided with the distribution.
16 * 3. Neither the name of the project nor the names of its contributors
17 *    may be used to endorse or promote products derived from this software
18 *    without specific prior written permission.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 * SUCH DAMAGE.
31 */
32
33/*
34 * Copyright (c) 1982, 1986, 1988, 1990, 1993
35 *	The Regents of the University of California.  All rights reserved.
36 *
37 * Redistribution and use in source and binary forms, with or without
38 * modification, are permitted provided that the following conditions
39 * are met:
40 * 1. Redistributions of source code must retain the above copyright
41 *    notice, this list of conditions and the following disclaimer.
42 * 2. Redistributions in binary form must reproduce the above copyright
43 *    notice, this list of conditions and the following disclaimer in the
44 *    documentation and/or other materials provided with the distribution.
45 * 3. All advertising materials mentioning features or use of this software
46 *    must display the following acknowledgement:
47 *	This product includes software developed by the University of
48 *	California, Berkeley and its contributors.
49 * 4. Neither the name of the University nor the names of its contributors
50 *    may be used to endorse or promote products derived from this software
51 *    without specific prior written permission.
52 *
53 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
54 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
55 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
56 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
57 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
58 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
59 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
60 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
61 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
62 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
63 * SUCH DAMAGE.
64 *
65 *	@(#)ip_output.c	8.3 (Berkeley) 1/21/94
66 */
67
68#include "opt_ip6fw.h"
69#include "opt_inet.h"
70#include "opt_inet6.h"
71#include "opt_ipsec.h"
72#include "opt_pfil_hooks.h"
73
74#include <sys/param.h>
75#include <sys/malloc.h>
76#include <sys/mbuf.h>
77#include <sys/proc.h>
78#include <sys/errno.h>
79#include <sys/protosw.h>
80#include <sys/socket.h>
81#include <sys/socketvar.h>
82#include <sys/systm.h>
83#include <sys/kernel.h>
84
85#include <net/if.h>
86#include <net/route.h>
87#ifdef PFIL_HOOKS
88#include <net/pfil.h>
89#endif
90
91#include <netinet/in.h>
92#include <netinet/in_var.h>
93#include <netinet6/in6_var.h>
94#include <netinet/ip6.h>
95#include <netinet/icmp6.h>
96#include <netinet6/ip6_var.h>
97#include <netinet/in_pcb.h>
98#include <netinet6/nd6.h>
99
100#ifdef IPSEC
101#include <netinet6/ipsec.h>
102#ifdef INET6
103#include <netinet6/ipsec6.h>
104#endif
105#include <netkey/key.h>
106#endif /* IPSEC */
107
108#include <netinet6/ip6_fw.h>
109
110#include <net/net_osdep.h>
111
112#include <netinet6/ip6protosw.h>
113
114static MALLOC_DEFINE(M_IPMOPTS, "ip6_moptions", "internet multicast options");
115
116struct ip6_exthdrs {
117	struct mbuf *ip6e_ip6;
118	struct mbuf *ip6e_hbh;
119	struct mbuf *ip6e_dest1;
120	struct mbuf *ip6e_rthdr;
121	struct mbuf *ip6e_dest2;
122};
123
124static int ip6_pcbopts __P((struct ip6_pktopts **, struct mbuf *,
125			    struct socket *, struct sockopt *sopt));
126static int ip6_setmoptions __P((int, struct ip6_moptions **, struct mbuf *));
127static int ip6_getmoptions __P((int, struct ip6_moptions *, struct mbuf **));
128static int ip6_copyexthdr __P((struct mbuf **, caddr_t, int));
129static int ip6_insertfraghdr __P((struct mbuf *, struct mbuf *, int,
130				  struct ip6_frag **));
131static int ip6_insert_jumboopt __P((struct ip6_exthdrs *, u_int32_t));
132static int ip6_splithdr __P((struct mbuf *, struct ip6_exthdrs *));
133
134/*
135 * IP6 output. The packet in mbuf chain m contains a skeletal IP6
136 * header (with pri, len, nxt, hlim, src, dst).
137 * This function may modify ver and hlim only.
138 * The mbuf chain containing the packet will be freed.
139 * The mbuf opt, if present, will not be freed.
140 *
141 * type of "mtu": rt_rmx.rmx_mtu is u_long, ifnet.ifr_mtu is int, and
142 * nd_ifinfo.linkmtu is u_int32_t.  so we use u_long to hold largest one,
143 * which is rt_rmx.rmx_mtu.
144 */
145int
146ip6_output(m0, opt, ro, flags, im6o, ifpp)
147	struct mbuf *m0;
148	struct ip6_pktopts *opt;
149	struct route_in6 *ro;
150	int flags;
151	struct ip6_moptions *im6o;
152	struct ifnet **ifpp;		/* XXX: just for statistics */
153{
154	struct ip6_hdr *ip6, *mhip6;
155	struct ifnet *ifp, *origifp;
156	struct mbuf *m = m0;
157	int hlen, tlen, len, off;
158	struct route_in6 ip6route;
159	struct sockaddr_in6 *dst;
160	int error = 0;
161	struct in6_ifaddr *ia = NULL;
162	u_long mtu;
163	u_int32_t optlen = 0, plen = 0, unfragpartlen = 0;
164	struct ip6_exthdrs exthdrs;
165	struct in6_addr finaldst;
166	struct route_in6 *ro_pmtu = NULL;
167	int hdrsplit = 0;
168	int needipsec = 0;
169#ifdef PFIL_HOOKS
170	struct packet_filter_hook *pfh;
171	struct mbuf *m1;
172	int rv;
173#endif /* PFIL_HOOKS */
174#ifdef IPSEC
175	int needipsectun = 0;
176	struct socket *so;
177	struct secpolicy *sp = NULL;
178
179	/* for AH processing. stupid to have "socket" variable in IP layer... */
180	so = ipsec_getsocket(m);
181	(void)ipsec_setsocket(m, NULL);
182	ip6 = mtod(m, struct ip6_hdr *);
183#endif /* IPSEC */
184
185#define MAKE_EXTHDR(hp, mp)						\
186    do {								\
187	if (hp) {							\
188		struct ip6_ext *eh = (struct ip6_ext *)(hp);		\
189		error = ip6_copyexthdr((mp), (caddr_t)(hp), 		\
190				       ((eh)->ip6e_len + 1) << 3);	\
191		if (error)						\
192			goto freehdrs;					\
193	}								\
194    } while (0)
195
196	bzero(&exthdrs, sizeof(exthdrs));
197
198	if (opt) {
199		/* Hop-by-Hop options header */
200		MAKE_EXTHDR(opt->ip6po_hbh, &exthdrs.ip6e_hbh);
201		/* Destination options header(1st part) */
202		MAKE_EXTHDR(opt->ip6po_dest1, &exthdrs.ip6e_dest1);
203		/* Routing header */
204		MAKE_EXTHDR(opt->ip6po_rthdr, &exthdrs.ip6e_rthdr);
205		/* Destination options header(2nd part) */
206		MAKE_EXTHDR(opt->ip6po_dest2, &exthdrs.ip6e_dest2);
207	}
208
209#ifdef IPSEC
210	/* get a security policy for this packet */
211	if (so == NULL)
212		sp = ipsec6_getpolicybyaddr(m, IPSEC_DIR_OUTBOUND, 0, &error);
213	else
214		sp = ipsec6_getpolicybysock(m, IPSEC_DIR_OUTBOUND, so, &error);
215
216	if (sp == NULL) {
217		ipsec6stat.out_inval++;
218		goto freehdrs;
219	}
220
221	error = 0;
222
223	/* check policy */
224	switch (sp->policy) {
225	case IPSEC_POLICY_DISCARD:
226		/*
227		 * This packet is just discarded.
228		 */
229		ipsec6stat.out_polvio++;
230		goto freehdrs;
231
232	case IPSEC_POLICY_BYPASS:
233	case IPSEC_POLICY_NONE:
234		/* no need to do IPsec. */
235		needipsec = 0;
236		break;
237
238	case IPSEC_POLICY_IPSEC:
239		if (sp->req == NULL) {
240			/* acquire a policy */
241			error = key_spdacquire(sp);
242			goto freehdrs;
243		}
244		needipsec = 1;
245		break;
246
247	case IPSEC_POLICY_ENTRUST:
248	default:
249		printf("ip6_output: Invalid policy found. %d\n", sp->policy);
250	}
251#endif /* IPSEC */
252
253	/*
254	 * Calculate the total length of the extension header chain.
255	 * Keep the length of the unfragmentable part for fragmentation.
256	 */
257	optlen = 0;
258	if (exthdrs.ip6e_hbh) optlen += exthdrs.ip6e_hbh->m_len;
259	if (exthdrs.ip6e_dest1) optlen += exthdrs.ip6e_dest1->m_len;
260	if (exthdrs.ip6e_rthdr) optlen += exthdrs.ip6e_rthdr->m_len;
261	unfragpartlen = optlen + sizeof(struct ip6_hdr);
262	/* NOTE: we don't add AH/ESP length here. do that later. */
263	if (exthdrs.ip6e_dest2) optlen += exthdrs.ip6e_dest2->m_len;
264
265	/*
266	 * If we need IPsec, or there is at least one extension header,
267	 * separate IP6 header from the payload.
268	 */
269	if ((needipsec || optlen) && !hdrsplit) {
270		if ((error = ip6_splithdr(m, &exthdrs)) != 0) {
271			m = NULL;
272			goto freehdrs;
273		}
274		m = exthdrs.ip6e_ip6;
275		hdrsplit++;
276	}
277
278	/* adjust pointer */
279	ip6 = mtod(m, struct ip6_hdr *);
280
281	/* adjust mbuf packet header length */
282	m->m_pkthdr.len += optlen;
283	plen = m->m_pkthdr.len - sizeof(*ip6);
284
285	/* If this is a jumbo payload, insert a jumbo payload option. */
286	if (plen > IPV6_MAXPACKET) {
287		if (!hdrsplit) {
288			if ((error = ip6_splithdr(m, &exthdrs)) != 0) {
289				m = NULL;
290				goto freehdrs;
291			}
292			m = exthdrs.ip6e_ip6;
293			hdrsplit++;
294		}
295		/* adjust pointer */
296		ip6 = mtod(m, struct ip6_hdr *);
297		if ((error = ip6_insert_jumboopt(&exthdrs, plen)) != 0)
298			goto freehdrs;
299		ip6->ip6_plen = 0;
300	} else
301		ip6->ip6_plen = htons(plen);
302
303	/*
304	 * Concatenate headers and fill in next header fields.
305	 * Here we have, on "m"
306	 *	IPv6 payload
307	 * and we insert headers accordingly.  Finally, we should be getting:
308	 *	IPv6 hbh dest1 rthdr ah* [esp* dest2 payload]
309	 *
310	 * during the header composing process, "m" points to IPv6 header.
311	 * "mprev" points to an extension header prior to esp.
312	 */
313	{
314		u_char *nexthdrp = &ip6->ip6_nxt;
315		struct mbuf *mprev = m;
316
317		/*
318		 * we treat dest2 specially.  this makes IPsec processing
319		 * much easier.  the goal here is to make mprev point the
320		 * mbuf prior to dest2.
321		 *
322		 * result: IPv6 dest2 payload
323		 * m and mprev will point to IPv6 header.
324		 */
325		if (exthdrs.ip6e_dest2) {
326			if (!hdrsplit)
327				panic("assumption failed: hdr not split");
328			exthdrs.ip6e_dest2->m_next = m->m_next;
329			m->m_next = exthdrs.ip6e_dest2;
330			*mtod(exthdrs.ip6e_dest2, u_char *) = ip6->ip6_nxt;
331			ip6->ip6_nxt = IPPROTO_DSTOPTS;
332		}
333
334#define MAKE_CHAIN(m, mp, p, i)\
335    do {\
336	if (m) {\
337		if (!hdrsplit) \
338			panic("assumption failed: hdr not split"); \
339		*mtod((m), u_char *) = *(p);\
340		*(p) = (i);\
341		p = mtod((m), u_char *);\
342		(m)->m_next = (mp)->m_next;\
343		(mp)->m_next = (m);\
344		(mp) = (m);\
345	}\
346    } while (0)
347		/*
348		 * result: IPv6 hbh dest1 rthdr dest2 payload
349		 * m will point to IPv6 header.  mprev will point to the
350		 * extension header prior to dest2 (rthdr in the above case).
351		 */
352		MAKE_CHAIN(exthdrs.ip6e_hbh, mprev,
353			   nexthdrp, IPPROTO_HOPOPTS);
354		MAKE_CHAIN(exthdrs.ip6e_dest1, mprev,
355			   nexthdrp, IPPROTO_DSTOPTS);
356		MAKE_CHAIN(exthdrs.ip6e_rthdr, mprev,
357			   nexthdrp, IPPROTO_ROUTING);
358
359#ifdef IPSEC
360		if (!needipsec)
361			goto skip_ipsec2;
362
363		/*
364		 * pointers after IPsec headers are not valid any more.
365		 * other pointers need a great care too.
366		 * (IPsec routines should not mangle mbufs prior to AH/ESP)
367		 */
368		exthdrs.ip6e_dest2 = NULL;
369
370	    {
371		struct ip6_rthdr *rh = NULL;
372		int segleft_org = 0;
373		struct ipsec_output_state state;
374
375		if (exthdrs.ip6e_rthdr) {
376			rh = mtod(exthdrs.ip6e_rthdr, struct ip6_rthdr *);
377			segleft_org = rh->ip6r_segleft;
378			rh->ip6r_segleft = 0;
379		}
380
381		bzero(&state, sizeof(state));
382		state.m = m;
383		error = ipsec6_output_trans(&state, nexthdrp, mprev, sp, flags,
384			&needipsectun);
385		m = state.m;
386		if (error) {
387			/* mbuf is already reclaimed in ipsec6_output_trans. */
388			m = NULL;
389			switch (error) {
390			case EHOSTUNREACH:
391			case ENETUNREACH:
392			case EMSGSIZE:
393			case ENOBUFS:
394			case ENOMEM:
395				break;
396			default:
397				printf("ip6_output (ipsec): error code %d\n", error);
398				/* fall through */
399			case ENOENT:
400				/* don't show these error codes to the user */
401				error = 0;
402				break;
403			}
404			goto bad;
405		}
406		if (exthdrs.ip6e_rthdr) {
407			/* ah6_output doesn't modify mbuf chain */
408			rh->ip6r_segleft = segleft_org;
409		}
410	    }
411skip_ipsec2:;
412#endif
413	}
414
415	/*
416	 * If there is a routing header, replace destination address field
417	 * with the first hop of the routing header.
418	 */
419	if (exthdrs.ip6e_rthdr) {
420		struct ip6_rthdr *rh =
421			(struct ip6_rthdr *)(mtod(exthdrs.ip6e_rthdr,
422						  struct ip6_rthdr *));
423		struct ip6_rthdr0 *rh0;
424
425		finaldst = ip6->ip6_dst;
426		switch (rh->ip6r_type) {
427		case IPV6_RTHDR_TYPE_0:
428			 rh0 = (struct ip6_rthdr0 *)rh;
429			 ip6->ip6_dst = rh0->ip6r0_addr[0];
430			 bcopy((caddr_t)&rh0->ip6r0_addr[1],
431			       (caddr_t)&rh0->ip6r0_addr[0],
432			       sizeof(struct in6_addr)*(rh0->ip6r0_segleft - 1)
433				 );
434			 rh0->ip6r0_addr[rh0->ip6r0_segleft - 1] = finaldst;
435			 break;
436		default:	/* is it possible? */
437			 error = EINVAL;
438			 goto bad;
439		}
440	}
441
442	/* Source address validation */
443	if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src) &&
444	    (flags & IPV6_DADOUTPUT) == 0) {
445		error = EOPNOTSUPP;
446		ip6stat.ip6s_badscope++;
447		goto bad;
448	}
449	if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_src)) {
450		error = EOPNOTSUPP;
451		ip6stat.ip6s_badscope++;
452		goto bad;
453	}
454
455	ip6stat.ip6s_localout++;
456
457	/*
458	 * Route packet.
459	 */
460	if (ro == 0) {
461		ro = &ip6route;
462		bzero((caddr_t)ro, sizeof(*ro));
463	}
464	ro_pmtu = ro;
465	if (opt && opt->ip6po_rthdr)
466		ro = &opt->ip6po_route;
467	dst = (struct sockaddr_in6 *)&ro->ro_dst;
468	/*
469	 * If there is a cached route,
470	 * check that it is to the same destination
471	 * and is still up. If not, free it and try again.
472	 */
473	if (ro->ro_rt && ((ro->ro_rt->rt_flags & RTF_UP) == 0 ||
474			 dst->sin6_family != AF_INET6 ||
475			 !IN6_ARE_ADDR_EQUAL(&dst->sin6_addr, &ip6->ip6_dst))) {
476		RTFREE(ro->ro_rt);
477		ro->ro_rt = (struct rtentry *)0;
478	}
479	if (ro->ro_rt == 0) {
480		bzero(dst, sizeof(*dst));
481		dst->sin6_family = AF_INET6;
482		dst->sin6_len = sizeof(struct sockaddr_in6);
483		dst->sin6_addr = ip6->ip6_dst;
484#ifdef SCOPEDROUTING
485		/* XXX: sin6_scope_id should already be fixed at this point */
486		if (IN6_IS_SCOPE_LINKLOCAL(&dst->sin6_addr))
487			dst->sin6_scope_id = ntohs(dst->sin6_addr.s6_addr16[1]);
488#endif
489	}
490#ifdef IPSEC
491	if (needipsec && needipsectun) {
492		struct ipsec_output_state state;
493
494		/*
495		 * All the extension headers will become inaccessible
496		 * (since they can be encrypted).
497		 * Don't panic, we need no more updates to extension headers
498		 * on inner IPv6 packet (since they are now encapsulated).
499		 *
500		 * IPv6 [ESP|AH] IPv6 [extension headers] payload
501		 */
502		bzero(&exthdrs, sizeof(exthdrs));
503		exthdrs.ip6e_ip6 = m;
504
505		bzero(&state, sizeof(state));
506		state.m = m;
507		state.ro = (struct route *)ro;
508		state.dst = (struct sockaddr *)dst;
509
510		error = ipsec6_output_tunnel(&state, sp, flags);
511
512		m = state.m;
513		ro = (struct route_in6 *)state.ro;
514		dst = (struct sockaddr_in6 *)state.dst;
515		if (error) {
516			/* mbuf is already reclaimed in ipsec6_output_tunnel. */
517			m0 = m = NULL;
518			m = NULL;
519			switch (error) {
520			case EHOSTUNREACH:
521			case ENETUNREACH:
522			case EMSGSIZE:
523			case ENOBUFS:
524			case ENOMEM:
525				break;
526			default:
527				printf("ip6_output (ipsec): error code %d\n", error);
528				/* fall through */
529			case ENOENT:
530				/* don't show these error codes to the user */
531				error = 0;
532				break;
533			}
534			goto bad;
535		}
536
537		exthdrs.ip6e_ip6 = m;
538	}
539#endif /* IPSEC */
540
541	if (!IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
542		/* Unicast */
543
544#define ifatoia6(ifa)	((struct in6_ifaddr *)(ifa))
545#define sin6tosa(sin6)	((struct sockaddr *)(sin6))
546		/* xxx
547		 * interface selection comes here
548		 * if an interface is specified from an upper layer,
549		 * ifp must point it.
550		 */
551		if (ro->ro_rt == 0) {
552			/*
553			 * non-bsdi always clone routes, if parent is
554			 * PRF_CLONING.
555			 */
556			rtalloc((struct route *)ro);
557		}
558		if (ro->ro_rt == 0) {
559			ip6stat.ip6s_noroute++;
560			error = EHOSTUNREACH;
561			/* XXX in6_ifstat_inc(ifp, ifs6_out_discard); */
562			goto bad;
563		}
564		ia = ifatoia6(ro->ro_rt->rt_ifa);
565		ifp = ro->ro_rt->rt_ifp;
566		ro->ro_rt->rt_use++;
567		if (ro->ro_rt->rt_flags & RTF_GATEWAY)
568			dst = (struct sockaddr_in6 *)ro->ro_rt->rt_gateway;
569		m->m_flags &= ~(M_BCAST | M_MCAST);	/* just in case */
570
571		in6_ifstat_inc(ifp, ifs6_out_request);
572
573		/*
574		 * Check if the outgoing interface conflicts with
575		 * the interface specified by ifi6_ifindex (if specified).
576		 * Note that loopback interface is always okay.
577		 * (this may happen when we are sending a packet to one of
578		 *  our own addresses.)
579		 */
580		if (opt && opt->ip6po_pktinfo
581		 && opt->ip6po_pktinfo->ipi6_ifindex) {
582			if (!(ifp->if_flags & IFF_LOOPBACK)
583			 && ifp->if_index != opt->ip6po_pktinfo->ipi6_ifindex) {
584				ip6stat.ip6s_noroute++;
585				in6_ifstat_inc(ifp, ifs6_out_discard);
586				error = EHOSTUNREACH;
587				goto bad;
588			}
589		}
590
591		if (opt && opt->ip6po_hlim != -1)
592			ip6->ip6_hlim = opt->ip6po_hlim & 0xff;
593	} else {
594		/* Multicast */
595		struct	in6_multi *in6m;
596
597		m->m_flags = (m->m_flags & ~M_BCAST) | M_MCAST;
598
599		/*
600		 * See if the caller provided any multicast options
601		 */
602		ifp = NULL;
603		if (im6o != NULL) {
604			ip6->ip6_hlim = im6o->im6o_multicast_hlim;
605			if (im6o->im6o_multicast_ifp != NULL)
606				ifp = im6o->im6o_multicast_ifp;
607		} else
608			ip6->ip6_hlim = ip6_defmcasthlim;
609
610		/*
611		 * See if the caller provided the outgoing interface
612		 * as an ancillary data.
613		 * Boundary check for ifindex is assumed to be already done.
614		 */
615		if (opt && opt->ip6po_pktinfo && opt->ip6po_pktinfo->ipi6_ifindex)
616			ifp = ifnet_byindex(opt->ip6po_pktinfo->ipi6_ifindex);
617
618		/*
619		 * If the destination is a node-local scope multicast,
620		 * the packet should be loop-backed only.
621		 */
622		if (IN6_IS_ADDR_MC_NODELOCAL(&ip6->ip6_dst)) {
623			/*
624			 * If the outgoing interface is already specified,
625			 * it should be a loopback interface.
626			 */
627			if (ifp && (ifp->if_flags & IFF_LOOPBACK) == 0) {
628				ip6stat.ip6s_badscope++;
629				error = ENETUNREACH; /* XXX: better error? */
630				/* XXX correct ifp? */
631				in6_ifstat_inc(ifp, ifs6_out_discard);
632				goto bad;
633			} else {
634				ifp = &loif[0];
635			}
636		}
637
638		if (opt && opt->ip6po_hlim != -1)
639			ip6->ip6_hlim = opt->ip6po_hlim & 0xff;
640
641		/*
642		 * If caller did not provide an interface lookup a
643		 * default in the routing table.  This is either a
644		 * default for the speicfied group (i.e. a host
645		 * route), or a multicast default (a route for the
646		 * ``net'' ff00::/8).
647		 */
648		if (ifp == NULL) {
649			if (ro->ro_rt == 0) {
650				ro->ro_rt = rtalloc1((struct sockaddr *)
651						&ro->ro_dst, 0, 0UL);
652			}
653			if (ro->ro_rt == 0) {
654				ip6stat.ip6s_noroute++;
655				error = EHOSTUNREACH;
656				/* XXX in6_ifstat_inc(ifp, ifs6_out_discard) */
657				goto bad;
658			}
659			ia = ifatoia6(ro->ro_rt->rt_ifa);
660			ifp = ro->ro_rt->rt_ifp;
661			ro->ro_rt->rt_use++;
662		}
663
664		if ((flags & IPV6_FORWARDING) == 0)
665			in6_ifstat_inc(ifp, ifs6_out_request);
666		in6_ifstat_inc(ifp, ifs6_out_mcast);
667
668		/*
669		 * Confirm that the outgoing interface supports multicast.
670		 */
671		if ((ifp->if_flags & IFF_MULTICAST) == 0) {
672			ip6stat.ip6s_noroute++;
673			in6_ifstat_inc(ifp, ifs6_out_discard);
674			error = ENETUNREACH;
675			goto bad;
676		}
677		IN6_LOOKUP_MULTI(ip6->ip6_dst, ifp, in6m);
678		if (in6m != NULL &&
679		   (im6o == NULL || im6o->im6o_multicast_loop)) {
680			/*
681			 * If we belong to the destination multicast group
682			 * on the outgoing interface, and the caller did not
683			 * forbid loopback, loop back a copy.
684			 */
685			ip6_mloopback(ifp, m, dst);
686		} else {
687			/*
688			 * If we are acting as a multicast router, perform
689			 * multicast forwarding as if the packet had just
690			 * arrived on the interface to which we are about
691			 * to send.  The multicast forwarding function
692			 * recursively calls this function, using the
693			 * IPV6_FORWARDING flag to prevent infinite recursion.
694			 *
695			 * 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 and destination, which should already be assured.
793		 * Larger scopes than link will be supported in the future.
794		 */
795		origifp = NULL;
796		if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_src))
797			origifp = ifnet_byindex(ntohs(ip6->ip6_src.s6_addr16[1]));
798		else if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_dst))
799			origifp = ifnet_byindex(ntohs(ip6->ip6_dst.s6_addr16[1]));
800		/*
801		 * XXX: origifp can be NULL even in those two cases above.
802		 * For example, if we remove the (only) link-local address
803		 * from the loopback interface, and try to send a link-local
804		 * address without link-id information.  Then the source
805		 * address is ::1, and the destination address is the
806		 * link-local address with its s6_addr16[1] being zero.
807		 * What is worse, if the packet goes to the loopback interface
808		 * by a default rejected route, the null pointer would be
809		 * passed to looutput, and the kernel would hang.
810		 * The following last resort would prevent such disaster.
811		 */
812		if (origifp == NULL)
813			origifp = ifp;
814	}
815	else
816		origifp = ifp;
817#ifndef SCOPEDROUTING
818	/*
819	 * clear embedded scope identifiers if necessary.
820	 * in6_clearscope will touch the addresses only when necessary.
821	 */
822	in6_clearscope(&ip6->ip6_src);
823	in6_clearscope(&ip6->ip6_dst);
824#endif
825
826	/*
827	 * Check with the firewall...
828	 */
829        if (ip6_fw_enable && ip6_fw_chk_ptr) {
830		u_short port = 0;
831		m->m_pkthdr.rcvif = NULL;	/* XXX */
832		/* If ipfw says divert, we have to just drop packet */
833		if ((*ip6_fw_chk_ptr)(&ip6, ifp, &port, &m)) {
834			m_freem(m);
835			goto done;
836		}
837		if (!m) {
838			error = EACCES;
839			goto done;
840		}
841	}
842
843	/*
844	 * If the outgoing packet contains a hop-by-hop options header,
845	 * it must be examined and processed even by the source node.
846	 * (RFC 2460, section 4.)
847	 */
848	if (exthdrs.ip6e_hbh) {
849		struct ip6_hbh *hbh = mtod(exthdrs.ip6e_hbh, struct ip6_hbh *);
850		u_int32_t dummy1; /* XXX unused */
851		u_int32_t dummy2; /* XXX unused */
852
853#ifdef DIAGNOSTIC
854		if ((hbh->ip6h_len + 1) << 3 > exthdrs.ip6e_hbh->m_len)
855			panic("ip6e_hbh is not continuous");
856#endif
857		/*
858		 *  XXX: if we have to send an ICMPv6 error to the sender,
859		 *       we need the M_LOOP flag since icmp6_error() expects
860		 *       the IPv6 and the hop-by-hop options header are
861		 *       continuous unless the flag is set.
862		 */
863		m->m_flags |= M_LOOP;
864		m->m_pkthdr.rcvif = ifp;
865		if (ip6_process_hopopts(m,
866					(u_int8_t *)(hbh + 1),
867					((hbh->ip6h_len + 1) << 3) -
868					sizeof(struct ip6_hbh),
869					&dummy1, &dummy2) < 0) {
870			/* m was already freed at this point */
871			error = EINVAL;/* better error? */
872			goto done;
873		}
874		m->m_flags &= ~M_LOOP; /* XXX */
875		m->m_pkthdr.rcvif = NULL;
876	}
877
878#ifdef PFIL_HOOKS
879	/*
880	 * Run through list of hooks for output packets.
881	 */
882	m1 = m;
883	pfh = pfil_hook_get(PFIL_OUT, &inet6sw[ip6_protox[IPPROTO_IPV6]].pr_pfh);
884	for (; pfh; pfh = pfh->pfil_link.tqe_next)
885		if (pfh->pfil_func) {
886			rv = pfh->pfil_func(ip6, sizeof(*ip6), ifp, 1, &m1);
887			if (rv) {
888				error = EHOSTUNREACH;
889				goto done;
890			}
891			m = m1;
892			if (m == NULL)
893				goto done;
894			ip6 = mtod(m, struct ip6_hdr *);
895		}
896#endif /* PFIL_HOOKS */
897	/*
898	 * Send the packet to the outgoing interface.
899	 * If necessary, do IPv6 fragmentation before sending.
900	 */
901	tlen = m->m_pkthdr.len;
902	if (tlen <= mtu
903#ifdef notyet
904	    /*
905	     * On any link that cannot convey a 1280-octet packet in one piece,
906	     * link-specific fragmentation and reassembly must be provided at
907	     * a layer below IPv6. [RFC 2460, sec.5]
908	     * Thus if the interface has ability of link-level fragmentation,
909	     * we can just send the packet even if the packet size is
910	     * larger than the link's MTU.
911	     * XXX: IFF_FRAGMENTABLE (or such) flag has not been defined yet...
912	     */
913
914	    || ifp->if_flags & IFF_FRAGMENTABLE
915#endif
916	    )
917	{
918 		/* Record statistics for this interface address. */
919 		if (ia && !(flags & IPV6_FORWARDING)) {
920 			ia->ia_ifa.if_opackets++;
921 			ia->ia_ifa.if_obytes += m->m_pkthdr.len;
922 		}
923#ifdef IPSEC
924		/* clean ipsec history once it goes out of the node */
925		ipsec_delaux(m);
926#endif
927		error = nd6_output(ifp, origifp, m, dst, ro->ro_rt);
928		goto done;
929	} else if (mtu < IPV6_MMTU) {
930		/*
931		 * note that path MTU is never less than IPV6_MMTU
932		 * (see icmp6_input).
933		 */
934		error = EMSGSIZE;
935		in6_ifstat_inc(ifp, ifs6_out_fragfail);
936		goto bad;
937	} else if (ip6->ip6_plen == 0) { /* jumbo payload cannot be fragmented */
938		error = EMSGSIZE;
939		in6_ifstat_inc(ifp, ifs6_out_fragfail);
940		goto bad;
941	} else {
942		struct mbuf **mnext, *m_frgpart;
943		struct ip6_frag *ip6f;
944		u_int32_t id = htonl(ip6_id++);
945		u_char nextproto;
946
947		/*
948		 * Too large for the destination or interface;
949		 * fragment if possible.
950		 * Must be able to put at least 8 bytes per fragment.
951		 */
952		hlen = unfragpartlen;
953		if (mtu > IPV6_MAXPACKET)
954			mtu = IPV6_MAXPACKET;
955
956		len = (mtu - hlen - sizeof(struct ip6_frag)) & ~7;
957		if (len < 8) {
958			error = EMSGSIZE;
959			in6_ifstat_inc(ifp, ifs6_out_fragfail);
960			goto bad;
961		}
962
963		mnext = &m->m_nextpkt;
964
965		/*
966		 * Change the next header field of the last header in the
967		 * unfragmentable part.
968		 */
969		if (exthdrs.ip6e_rthdr) {
970			nextproto = *mtod(exthdrs.ip6e_rthdr, u_char *);
971			*mtod(exthdrs.ip6e_rthdr, u_char *) = IPPROTO_FRAGMENT;
972		} else if (exthdrs.ip6e_dest1) {
973			nextproto = *mtod(exthdrs.ip6e_dest1, u_char *);
974			*mtod(exthdrs.ip6e_dest1, u_char *) = IPPROTO_FRAGMENT;
975		} else if (exthdrs.ip6e_hbh) {
976			nextproto = *mtod(exthdrs.ip6e_hbh, u_char *);
977			*mtod(exthdrs.ip6e_hbh, u_char *) = IPPROTO_FRAGMENT;
978		} else {
979			nextproto = ip6->ip6_nxt;
980			ip6->ip6_nxt = IPPROTO_FRAGMENT;
981		}
982
983		/*
984		 * Loop through length of segment after first fragment,
985		 * make new header and copy data of each part and link onto
986		 * 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 thread *td;
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		td = sopt->sopt_td;
1282	} else {
1283		panic("ip6_ctloutput: arg soopt is NULL");
1284	}
1285	error = optval = 0;
1286
1287	privileged = (td == 0 || suser(td)) ? 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					OPTSET(IN6P_IPV6_V6ONLY);
1380					break;
1381				}
1382				break;
1383
1384			case IPV6_PKTINFO:
1385			case IPV6_HOPLIMIT:
1386			case IPV6_HOPOPTS:
1387			case IPV6_DSTOPTS:
1388			case IPV6_RTHDR:
1389				/* RFC 2292 */
1390				if (optlen != sizeof(int)) {
1391					error = EINVAL;
1392					break;
1393				}
1394				error = sooptcopyin(sopt, &optval,
1395					sizeof optval, sizeof optval);
1396				if (error)
1397					break;
1398				switch (optname) {
1399				case IPV6_PKTINFO:
1400					OPTSET(IN6P_PKTINFO);
1401					break;
1402				case IPV6_HOPLIMIT:
1403					OPTSET(IN6P_HOPLIMIT);
1404					break;
1405				case IPV6_HOPOPTS:
1406					/*
1407					 * Check super-user privilege.
1408					 * See comments for IPV6_RECVHOPOPTS.
1409					 */
1410					if (!privileged)
1411						return(EPERM);
1412					OPTSET(IN6P_HOPOPTS);
1413					break;
1414				case IPV6_DSTOPTS:
1415					if (!privileged)
1416						return(EPERM);
1417					OPTSET(IN6P_DSTOPTS|IN6P_RTHDRDSTOPTS); /* XXX */
1418					break;
1419				case IPV6_RTHDR:
1420					OPTSET(IN6P_RTHDR);
1421					break;
1422				}
1423				break;
1424#undef OPTSET
1425
1426			case IPV6_MULTICAST_IF:
1427			case IPV6_MULTICAST_HOPS:
1428			case IPV6_MULTICAST_LOOP:
1429			case IPV6_JOIN_GROUP:
1430			case IPV6_LEAVE_GROUP:
1431			    {
1432				struct mbuf *m;
1433				if (sopt->sopt_valsize > MLEN) {
1434					error = EMSGSIZE;
1435					break;
1436				}
1437				/* XXX */
1438				MGET(m, sopt->sopt_td ? M_TRYWAIT : M_DONTWAIT, MT_HEADER);
1439				if (m == 0) {
1440					error = ENOBUFS;
1441					break;
1442				}
1443				m->m_len = sopt->sopt_valsize;
1444				error = sooptcopyin(sopt, mtod(m, char *),
1445						    m->m_len, m->m_len);
1446				error =	ip6_setmoptions(sopt->sopt_name,
1447							&in6p->in6p_moptions,
1448							m);
1449				(void)m_free(m);
1450			    }
1451				break;
1452
1453			case IPV6_PORTRANGE:
1454				error = sooptcopyin(sopt, &optval,
1455				    sizeof optval, sizeof optval);
1456				if (error)
1457					break;
1458
1459				switch (optval) {
1460				case IPV6_PORTRANGE_DEFAULT:
1461					in6p->in6p_flags &= ~(IN6P_LOWPORT);
1462					in6p->in6p_flags &= ~(IN6P_HIGHPORT);
1463					break;
1464
1465				case IPV6_PORTRANGE_HIGH:
1466					in6p->in6p_flags &= ~(IN6P_LOWPORT);
1467					in6p->in6p_flags |= IN6P_HIGHPORT;
1468					break;
1469
1470				case IPV6_PORTRANGE_LOW:
1471					in6p->in6p_flags &= ~(IN6P_HIGHPORT);
1472					in6p->in6p_flags |= IN6P_LOWPORT;
1473					break;
1474
1475				default:
1476					error = EINVAL;
1477					break;
1478				}
1479				break;
1480
1481#ifdef IPSEC
1482			case IPV6_IPSEC_POLICY:
1483			    {
1484				caddr_t req = NULL;
1485				size_t len = 0;
1486				struct mbuf *m;
1487
1488				if ((error = soopt_getm(sopt, &m)) != 0) /* XXX */
1489					break;
1490				if ((error = soopt_mcopyin(sopt, m)) != 0) /* XXX */
1491					break;
1492				if (m) {
1493					req = mtod(m, caddr_t);
1494					len = m->m_len;
1495				}
1496				error = ipsec6_set_policy(in6p, optname, req,
1497				                          len, privileged);
1498				m_freem(m);
1499			    }
1500				break;
1501#endif /* KAME IPSEC */
1502
1503			case IPV6_FW_ADD:
1504			case IPV6_FW_DEL:
1505			case IPV6_FW_FLUSH:
1506			case IPV6_FW_ZERO:
1507			    {
1508				struct mbuf *m;
1509				struct mbuf **mp = &m;
1510
1511				if (ip6_fw_ctl_ptr == NULL)
1512					return EINVAL;
1513				/* XXX */
1514				if ((error = soopt_getm(sopt, &m)) != 0)
1515					break;
1516				/* XXX */
1517				if ((error = soopt_mcopyin(sopt, m)) != 0)
1518					break;
1519				error = (*ip6_fw_ctl_ptr)(optname, mp);
1520				m = *mp;
1521			    }
1522				break;
1523
1524			default:
1525				error = ENOPROTOOPT;
1526				break;
1527			}
1528			break;
1529
1530		case SOPT_GET:
1531			switch (optname) {
1532
1533			case IPV6_PKTOPTIONS:
1534				if (in6p->in6p_options) {
1535					struct mbuf *m;
1536					m = m_copym(in6p->in6p_options,
1537					    0, M_COPYALL, M_TRYWAIT);
1538					error = soopt_mcopyout(sopt, m);
1539					if (error == 0)
1540						m_freem(m);
1541				} else
1542					sopt->sopt_valsize = 0;
1543				break;
1544
1545			case IPV6_UNICAST_HOPS:
1546			case IPV6_CHECKSUM:
1547
1548			case IPV6_FAITH:
1549			case IPV6_V6ONLY:
1550			case IPV6_PORTRANGE:
1551				switch (optname) {
1552
1553				case IPV6_UNICAST_HOPS:
1554					optval = in6p->in6p_hops;
1555					break;
1556
1557				case IPV6_CHECKSUM:
1558					optval = in6p->in6p_cksum;
1559					break;
1560
1561				case IPV6_FAITH:
1562					optval = OPTBIT(IN6P_FAITH);
1563					break;
1564
1565				case IPV6_V6ONLY:
1566					optval = OPTBIT(IN6P_IPV6_V6ONLY);
1567					break;
1568
1569				case IPV6_PORTRANGE:
1570				    {
1571					int flags;
1572					flags = in6p->in6p_flags;
1573					if (flags & IN6P_HIGHPORT)
1574						optval = IPV6_PORTRANGE_HIGH;
1575					else if (flags & IN6P_LOWPORT)
1576						optval = IPV6_PORTRANGE_LOW;
1577					else
1578						optval = 0;
1579					break;
1580				    }
1581				}
1582				error = sooptcopyout(sopt, &optval,
1583					sizeof optval);
1584				break;
1585
1586			case IPV6_PKTINFO:
1587			case IPV6_HOPLIMIT:
1588			case IPV6_HOPOPTS:
1589			case IPV6_RTHDR:
1590			case IPV6_DSTOPTS:
1591				if (optname == IPV6_HOPOPTS ||
1592				    optname == IPV6_DSTOPTS ||
1593				    !privileged)
1594					return(EPERM);
1595				switch (optname) {
1596				case IPV6_PKTINFO:
1597					optval = OPTBIT(IN6P_PKTINFO);
1598					break;
1599				case IPV6_HOPLIMIT:
1600					optval = OPTBIT(IN6P_HOPLIMIT);
1601					break;
1602				case IPV6_HOPOPTS:
1603					if (!privileged)
1604						return(EPERM);
1605					optval = OPTBIT(IN6P_HOPOPTS);
1606					break;
1607				case IPV6_RTHDR:
1608					optval = OPTBIT(IN6P_RTHDR);
1609					break;
1610				case IPV6_DSTOPTS:
1611					if (!privileged)
1612						return(EPERM);
1613					optval = OPTBIT(IN6P_DSTOPTS|IN6P_RTHDRDSTOPTS);
1614					break;
1615				}
1616				error = sooptcopyout(sopt, &optval,
1617					sizeof optval);
1618				break;
1619
1620			case IPV6_MULTICAST_IF:
1621			case IPV6_MULTICAST_HOPS:
1622			case IPV6_MULTICAST_LOOP:
1623			case IPV6_JOIN_GROUP:
1624			case IPV6_LEAVE_GROUP:
1625			    {
1626				struct mbuf *m;
1627				error = ip6_getmoptions(sopt->sopt_name,
1628						in6p->in6p_moptions, &m);
1629				if (error == 0)
1630					error = sooptcopyout(sopt,
1631						mtod(m, char *), m->m_len);
1632				m_freem(m);
1633			    }
1634				break;
1635
1636#ifdef IPSEC
1637			case IPV6_IPSEC_POLICY:
1638			  {
1639				caddr_t req = NULL;
1640				size_t len = 0;
1641				struct mbuf *m = NULL;
1642				struct mbuf **mp = &m;
1643
1644				error = soopt_getm(sopt, &m); /* XXX */
1645				if (error != NULL)
1646					break;
1647				error = soopt_mcopyin(sopt, m); /* XXX */
1648				if (error != NULL)
1649					break;
1650				if (m) {
1651					req = mtod(m, caddr_t);
1652					len = m->m_len;
1653				}
1654				error = ipsec6_get_policy(in6p, req, len, mp);
1655				if (error == 0)
1656					error = soopt_mcopyout(sopt, m); /*XXX*/
1657				if (error == 0 && m)
1658					m_freem(m);
1659				break;
1660			  }
1661#endif /* KAME IPSEC */
1662
1663			case IPV6_FW_GET:
1664			  {
1665				struct mbuf *m;
1666				struct mbuf **mp = &m;
1667
1668				if (ip6_fw_ctl_ptr == NULL)
1669			        {
1670					return EINVAL;
1671				}
1672				error = (*ip6_fw_ctl_ptr)(optname, mp);
1673				if (error == 0)
1674					error = soopt_mcopyout(sopt, m); /* XXX */
1675				if (error == 0 && m)
1676					m_freem(m);
1677			  }
1678				break;
1679
1680			default:
1681				error = ENOPROTOOPT;
1682				break;
1683			}
1684			break;
1685		}
1686	} else {
1687		error = EINVAL;
1688	}
1689	return(error);
1690}
1691
1692/*
1693 * Set up IP6 options in pcb for insertion in output packets or
1694 * specifying behavior of outgoing packets.
1695 */
1696static int
1697ip6_pcbopts(pktopt, m, so, sopt)
1698	struct ip6_pktopts **pktopt;
1699	struct mbuf *m;
1700	struct socket *so;
1701	struct sockopt *sopt;
1702{
1703	struct ip6_pktopts *opt = *pktopt;
1704	int error = 0;
1705	struct thread *td = sopt->sopt_td;
1706	int priv = 0;
1707
1708	/* turn off any old options. */
1709	if (opt) {
1710#ifdef DIAGNOSTIC
1711		if (opt->ip6po_pktinfo || opt->ip6po_nexthop ||
1712		    opt->ip6po_hbh || opt->ip6po_dest1 || opt->ip6po_dest2 ||
1713		    opt->ip6po_rhinfo.ip6po_rhi_rthdr)
1714			printf("ip6_pcbopts: all specified options are cleared.\n");
1715#endif
1716		ip6_clearpktopts(opt, 1, -1);
1717	} else
1718		opt = malloc(sizeof(*opt), M_IP6OPT, M_WAITOK);
1719	*pktopt = NULL;
1720
1721	if (!m || m->m_len == 0) {
1722		/*
1723		 * Only turning off any previous options.
1724		 */
1725		if (opt)
1726			free(opt, M_IP6OPT);
1727		return(0);
1728	}
1729
1730	/*  set options specified by user. */
1731	if (td && !suser(td))
1732		priv = 1;
1733	if ((error = ip6_setpktoptions(m, opt, priv, 1)) != 0) {
1734		ip6_clearpktopts(opt, 1, -1); /* XXX: discard all options */
1735		return(error);
1736	}
1737	*pktopt = opt;
1738	return(0);
1739}
1740
1741/*
1742 * initialize ip6_pktopts.  beware that there are non-zero default values in
1743 * the struct.
1744 */
1745void
1746init_ip6pktopts(opt)
1747	struct ip6_pktopts *opt;
1748{
1749
1750	bzero(opt, sizeof(*opt));
1751	opt->ip6po_hlim = -1;	/* -1 means default hop limit */
1752}
1753
1754void
1755ip6_clearpktopts(pktopt, needfree, optname)
1756	struct ip6_pktopts *pktopt;
1757	int needfree, optname;
1758{
1759	if (pktopt == NULL)
1760		return;
1761
1762	if (optname == -1) {
1763		if (needfree && pktopt->ip6po_pktinfo)
1764			free(pktopt->ip6po_pktinfo, M_IP6OPT);
1765		pktopt->ip6po_pktinfo = NULL;
1766	}
1767	if (optname == -1)
1768		pktopt->ip6po_hlim = -1;
1769	if (optname == -1) {
1770		if (needfree && pktopt->ip6po_nexthop)
1771			free(pktopt->ip6po_nexthop, M_IP6OPT);
1772		pktopt->ip6po_nexthop = NULL;
1773	}
1774	if (optname == -1) {
1775		if (needfree && pktopt->ip6po_hbh)
1776			free(pktopt->ip6po_hbh, M_IP6OPT);
1777		pktopt->ip6po_hbh = NULL;
1778	}
1779	if (optname == -1) {
1780		if (needfree && pktopt->ip6po_dest1)
1781			free(pktopt->ip6po_dest1, M_IP6OPT);
1782		pktopt->ip6po_dest1 = NULL;
1783	}
1784	if (optname == -1) {
1785		if (needfree && pktopt->ip6po_rhinfo.ip6po_rhi_rthdr)
1786			free(pktopt->ip6po_rhinfo.ip6po_rhi_rthdr, M_IP6OPT);
1787		pktopt->ip6po_rhinfo.ip6po_rhi_rthdr = NULL;
1788		if (pktopt->ip6po_route.ro_rt) {
1789			RTFREE(pktopt->ip6po_route.ro_rt);
1790			pktopt->ip6po_route.ro_rt = NULL;
1791		}
1792	}
1793	if (optname == -1) {
1794		if (needfree && pktopt->ip6po_dest2)
1795			free(pktopt->ip6po_dest2, M_IP6OPT);
1796		pktopt->ip6po_dest2 = NULL;
1797	}
1798}
1799
1800#define PKTOPT_EXTHDRCPY(type) \
1801do {\
1802	if (src->type) {\
1803		int hlen =\
1804			(((struct ip6_ext *)src->type)->ip6e_len + 1) << 3;\
1805		dst->type = malloc(hlen, M_IP6OPT, canwait);\
1806		if (dst->type == NULL && canwait == M_NOWAIT)\
1807			goto bad;\
1808		bcopy(src->type, dst->type, hlen);\
1809	}\
1810} while (0)
1811
1812struct ip6_pktopts *
1813ip6_copypktopts(src, canwait)
1814	struct ip6_pktopts *src;
1815	int canwait;
1816{
1817	struct ip6_pktopts *dst;
1818
1819	if (src == NULL) {
1820		printf("ip6_clearpktopts: invalid argument\n");
1821		return(NULL);
1822	}
1823
1824	dst = malloc(sizeof(*dst), M_IP6OPT, canwait);
1825	if (dst == NULL && canwait == M_NOWAIT)
1826		goto bad;
1827	bzero(dst, sizeof(*dst));
1828
1829	dst->ip6po_hlim = src->ip6po_hlim;
1830	if (src->ip6po_pktinfo) {
1831		dst->ip6po_pktinfo = malloc(sizeof(*dst->ip6po_pktinfo),
1832					    M_IP6OPT, canwait);
1833		if (dst->ip6po_pktinfo == NULL && canwait == M_NOWAIT)
1834			goto bad;
1835		*dst->ip6po_pktinfo = *src->ip6po_pktinfo;
1836	}
1837	if (src->ip6po_nexthop) {
1838		dst->ip6po_nexthop = malloc(src->ip6po_nexthop->sa_len,
1839					    M_IP6OPT, canwait);
1840		if (dst->ip6po_nexthop == NULL && canwait == M_NOWAIT)
1841			goto bad;
1842		bcopy(src->ip6po_nexthop, dst->ip6po_nexthop,
1843		      src->ip6po_nexthop->sa_len);
1844	}
1845	PKTOPT_EXTHDRCPY(ip6po_hbh);
1846	PKTOPT_EXTHDRCPY(ip6po_dest1);
1847	PKTOPT_EXTHDRCPY(ip6po_dest2);
1848	PKTOPT_EXTHDRCPY(ip6po_rthdr); /* not copy the cached route */
1849	return(dst);
1850
1851  bad:
1852	printf("ip6_copypktopts: copy failed");
1853	if (dst->ip6po_pktinfo) free(dst->ip6po_pktinfo, M_IP6OPT);
1854	if (dst->ip6po_nexthop) free(dst->ip6po_nexthop, M_IP6OPT);
1855	if (dst->ip6po_hbh) free(dst->ip6po_hbh, M_IP6OPT);
1856	if (dst->ip6po_dest1) free(dst->ip6po_dest1, M_IP6OPT);
1857	if (dst->ip6po_dest2) free(dst->ip6po_dest2, M_IP6OPT);
1858	if (dst->ip6po_rthdr) free(dst->ip6po_rthdr, M_IP6OPT);
1859	return(NULL);
1860}
1861#undef PKTOPT_EXTHDRCPY
1862
1863void
1864ip6_freepcbopts(pktopt)
1865	struct ip6_pktopts *pktopt;
1866{
1867	if (pktopt == NULL)
1868		return;
1869
1870	ip6_clearpktopts(pktopt, 1, -1);
1871
1872	free(pktopt, M_IP6OPT);
1873}
1874
1875/*
1876 * Set the IP6 multicast options in response to user setsockopt().
1877 */
1878static int
1879ip6_setmoptions(optname, im6op, m)
1880	int optname;
1881	struct ip6_moptions **im6op;
1882	struct mbuf *m;
1883{
1884	int error = 0;
1885	u_int loop, ifindex;
1886	struct ipv6_mreq *mreq;
1887	struct ifnet *ifp;
1888	struct ip6_moptions *im6o = *im6op;
1889	struct route_in6 ro;
1890	struct sockaddr_in6 *dst;
1891	struct in6_multi_mship *imm;
1892	struct thread *td = curthread;	/* XXX */
1893
1894	if (im6o == NULL) {
1895		/*
1896		 * No multicast option buffer attached to the pcb;
1897		 * allocate one and initialize to default values.
1898		 */
1899		im6o = (struct ip6_moptions *)
1900			malloc(sizeof(*im6o), M_IPMOPTS, M_WAITOK);
1901
1902		if (im6o == NULL)
1903			return(ENOBUFS);
1904		*im6op = im6o;
1905		im6o->im6o_multicast_ifp = NULL;
1906		im6o->im6o_multicast_hlim = ip6_defmcasthlim;
1907		im6o->im6o_multicast_loop = IPV6_DEFAULT_MULTICAST_LOOP;
1908		LIST_INIT(&im6o->im6o_memberships);
1909	}
1910
1911	switch (optname) {
1912
1913	case IPV6_MULTICAST_IF:
1914		/*
1915		 * Select the interface for outgoing multicast packets.
1916		 */
1917		if (m == NULL || m->m_len != sizeof(u_int)) {
1918			error = EINVAL;
1919			break;
1920		}
1921		bcopy(mtod(m, u_int *), &ifindex, sizeof(ifindex));
1922		if (ifindex < 0 || if_index < ifindex) {
1923			error = ENXIO;	/* XXX EINVAL? */
1924			break;
1925		}
1926		ifp = ifnet_byindex(ifindex);
1927		if (ifp == NULL || (ifp->if_flags & IFF_MULTICAST) == 0) {
1928			error = EADDRNOTAVAIL;
1929			break;
1930		}
1931		im6o->im6o_multicast_ifp = ifp;
1932		break;
1933
1934	case IPV6_MULTICAST_HOPS:
1935	    {
1936		/*
1937		 * Set the IP6 hoplimit for outgoing multicast packets.
1938		 */
1939		int optval;
1940		if (m == NULL || m->m_len != sizeof(int)) {
1941			error = EINVAL;
1942			break;
1943		}
1944		bcopy(mtod(m, u_int *), &optval, sizeof(optval));
1945		if (optval < -1 || optval >= 256)
1946			error = EINVAL;
1947		else if (optval == -1)
1948			im6o->im6o_multicast_hlim = ip6_defmcasthlim;
1949		else
1950			im6o->im6o_multicast_hlim = optval;
1951		break;
1952	    }
1953
1954	case IPV6_MULTICAST_LOOP:
1955		/*
1956		 * Set the loopback flag for outgoing multicast packets.
1957		 * Must be zero or one.
1958		 */
1959		if (m == NULL || m->m_len != sizeof(u_int)) {
1960			error = EINVAL;
1961			break;
1962		}
1963		bcopy(mtod(m, u_int *), &loop, sizeof(loop));
1964		if (loop > 1) {
1965			error = EINVAL;
1966			break;
1967		}
1968		im6o->im6o_multicast_loop = loop;
1969		break;
1970
1971	case IPV6_JOIN_GROUP:
1972		/*
1973		 * Add a multicast group membership.
1974		 * Group must be a valid IP6 multicast address.
1975		 */
1976		if (m == NULL || m->m_len != sizeof(struct ipv6_mreq)) {
1977			error = EINVAL;
1978			break;
1979		}
1980		mreq = mtod(m, struct ipv6_mreq *);
1981		if (IN6_IS_ADDR_UNSPECIFIED(&mreq->ipv6mr_multiaddr)) {
1982			/*
1983			 * We use the unspecified address to specify to accept
1984			 * all multicast addresses. Only super user is allowed
1985			 * to do this.
1986			 */
1987			if (suser(td))
1988			{
1989				error = EACCES;
1990				break;
1991			}
1992		} else if (!IN6_IS_ADDR_MULTICAST(&mreq->ipv6mr_multiaddr)) {
1993			error = EINVAL;
1994			break;
1995		}
1996
1997		/*
1998		 * If the interface is specified, validate it.
1999		 */
2000		if (mreq->ipv6mr_interface < 0
2001		 || if_index < mreq->ipv6mr_interface) {
2002			error = ENXIO;	/* XXX EINVAL? */
2003			break;
2004		}
2005		/*
2006		 * If no interface was explicitly specified, choose an
2007		 * appropriate one according to the given multicast address.
2008		 */
2009		if (mreq->ipv6mr_interface == 0) {
2010			/*
2011			 * If the multicast address is in node-local scope,
2012			 * the interface should be a loopback interface.
2013			 * Otherwise, look up the routing table for the
2014			 * address, and choose the outgoing interface.
2015			 *   XXX: is it a good approach?
2016			 */
2017			if (IN6_IS_ADDR_MC_NODELOCAL(&mreq->ipv6mr_multiaddr)) {
2018				ifp = &loif[0];
2019			} else {
2020				ro.ro_rt = NULL;
2021				dst = (struct sockaddr_in6 *)&ro.ro_dst;
2022				bzero(dst, sizeof(*dst));
2023				dst->sin6_len = sizeof(struct sockaddr_in6);
2024				dst->sin6_family = AF_INET6;
2025				dst->sin6_addr = mreq->ipv6mr_multiaddr;
2026				rtalloc((struct route *)&ro);
2027				if (ro.ro_rt == NULL) {
2028					error = EADDRNOTAVAIL;
2029					break;
2030				}
2031				ifp = ro.ro_rt->rt_ifp;
2032				rtfree(ro.ro_rt);
2033			}
2034		} else
2035			ifp = ifnet_byindex(mreq->ipv6mr_interface);
2036
2037		/*
2038		 * See if we found an interface, and confirm that it
2039		 * supports multicast
2040		 */
2041		if (ifp == NULL || (ifp->if_flags & IFF_MULTICAST) == 0) {
2042			error = EADDRNOTAVAIL;
2043			break;
2044		}
2045		/*
2046		 * Put interface index into the multicast address,
2047		 * if the address has link-local scope.
2048		 */
2049		if (IN6_IS_ADDR_MC_LINKLOCAL(&mreq->ipv6mr_multiaddr)) {
2050			mreq->ipv6mr_multiaddr.s6_addr16[1]
2051				= htons(mreq->ipv6mr_interface);
2052		}
2053		/*
2054		 * See if the membership already exists.
2055		 */
2056		for (imm = im6o->im6o_memberships.lh_first;
2057		     imm != NULL; imm = imm->i6mm_chain.le_next)
2058			if (imm->i6mm_maddr->in6m_ifp == ifp &&
2059			    IN6_ARE_ADDR_EQUAL(&imm->i6mm_maddr->in6m_addr,
2060					       &mreq->ipv6mr_multiaddr))
2061				break;
2062		if (imm != NULL) {
2063			error = EADDRINUSE;
2064			break;
2065		}
2066		/*
2067		 * Everything looks good; add a new record to the multicast
2068		 * address list for the given interface.
2069		 */
2070		imm = malloc(sizeof(*imm), M_IPMADDR, M_WAITOK);
2071		if (imm == NULL) {
2072			error = ENOBUFS;
2073			break;
2074		}
2075		if ((imm->i6mm_maddr =
2076		     in6_addmulti(&mreq->ipv6mr_multiaddr, ifp, &error)) == NULL) {
2077			free(imm, M_IPMADDR);
2078			break;
2079		}
2080		LIST_INSERT_HEAD(&im6o->im6o_memberships, imm, i6mm_chain);
2081		break;
2082
2083	case IPV6_LEAVE_GROUP:
2084		/*
2085		 * Drop a multicast group membership.
2086		 * Group must be a valid IP6 multicast address.
2087		 */
2088		if (m == NULL || m->m_len != sizeof(struct ipv6_mreq)) {
2089			error = EINVAL;
2090			break;
2091		}
2092		mreq = mtod(m, struct ipv6_mreq *);
2093		if (IN6_IS_ADDR_UNSPECIFIED(&mreq->ipv6mr_multiaddr)) {
2094			if (suser(td)) {
2095				error = EACCES;
2096				break;
2097			}
2098		} else if (!IN6_IS_ADDR_MULTICAST(&mreq->ipv6mr_multiaddr)) {
2099			error = EINVAL;
2100			break;
2101		}
2102		/*
2103		 * If an interface address was specified, get a pointer
2104		 * to its ifnet structure.
2105		 */
2106		if (mreq->ipv6mr_interface < 0
2107		 || if_index < mreq->ipv6mr_interface) {
2108			error = ENXIO;	/* XXX EINVAL? */
2109			break;
2110		}
2111		ifp = ifnet_byindex(mreq->ipv6mr_interface);
2112		/*
2113		 * Put interface index into the multicast address,
2114		 * if the address has link-local scope.
2115		 */
2116		if (IN6_IS_ADDR_MC_LINKLOCAL(&mreq->ipv6mr_multiaddr)) {
2117			mreq->ipv6mr_multiaddr.s6_addr16[1]
2118				= htons(mreq->ipv6mr_interface);
2119		}
2120		/*
2121		 * Find the membership in the membership list.
2122		 */
2123		for (imm = im6o->im6o_memberships.lh_first;
2124		     imm != NULL; imm = imm->i6mm_chain.le_next) {
2125			if ((ifp == NULL ||
2126			     imm->i6mm_maddr->in6m_ifp == ifp) &&
2127			    IN6_ARE_ADDR_EQUAL(&imm->i6mm_maddr->in6m_addr,
2128					       &mreq->ipv6mr_multiaddr))
2129				break;
2130		}
2131		if (imm == NULL) {
2132			/* Unable to resolve interface */
2133			error = EADDRNOTAVAIL;
2134			break;
2135		}
2136		/*
2137		 * Give up the multicast address record to which the
2138		 * membership points.
2139		 */
2140		LIST_REMOVE(imm, i6mm_chain);
2141		in6_delmulti(imm->i6mm_maddr);
2142		free(imm, M_IPMADDR);
2143		break;
2144
2145	default:
2146		error = EOPNOTSUPP;
2147		break;
2148	}
2149
2150	/*
2151	 * If all options have default values, no need to keep the mbuf.
2152	 */
2153	if (im6o->im6o_multicast_ifp == NULL &&
2154	    im6o->im6o_multicast_hlim == ip6_defmcasthlim &&
2155	    im6o->im6o_multicast_loop == IPV6_DEFAULT_MULTICAST_LOOP &&
2156	    im6o->im6o_memberships.lh_first == NULL) {
2157		free(*im6op, M_IPMOPTS);
2158		*im6op = NULL;
2159	}
2160
2161	return(error);
2162}
2163
2164/*
2165 * Return the IP6 multicast options in response to user getsockopt().
2166 */
2167static int
2168ip6_getmoptions(optname, im6o, mp)
2169	int optname;
2170	struct ip6_moptions *im6o;
2171	struct mbuf **mp;
2172{
2173	u_int *hlim, *loop, *ifindex;
2174
2175	*mp = m_get(M_TRYWAIT, MT_HEADER);		/* XXX */
2176
2177	switch (optname) {
2178
2179	case IPV6_MULTICAST_IF:
2180		ifindex = mtod(*mp, u_int *);
2181		(*mp)->m_len = sizeof(u_int);
2182		if (im6o == NULL || im6o->im6o_multicast_ifp == NULL)
2183			*ifindex = 0;
2184		else
2185			*ifindex = im6o->im6o_multicast_ifp->if_index;
2186		return(0);
2187
2188	case IPV6_MULTICAST_HOPS:
2189		hlim = mtod(*mp, u_int *);
2190		(*mp)->m_len = sizeof(u_int);
2191		if (im6o == NULL)
2192			*hlim = ip6_defmcasthlim;
2193		else
2194			*hlim = im6o->im6o_multicast_hlim;
2195		return(0);
2196
2197	case IPV6_MULTICAST_LOOP:
2198		loop = mtod(*mp, u_int *);
2199		(*mp)->m_len = sizeof(u_int);
2200		if (im6o == NULL)
2201			*loop = ip6_defmcasthlim;
2202		else
2203			*loop = im6o->im6o_multicast_loop;
2204		return(0);
2205
2206	default:
2207		return(EOPNOTSUPP);
2208	}
2209}
2210
2211/*
2212 * Discard the IP6 multicast options.
2213 */
2214void
2215ip6_freemoptions(im6o)
2216	struct ip6_moptions *im6o;
2217{
2218	struct in6_multi_mship *imm;
2219
2220	if (im6o == NULL)
2221		return;
2222
2223	while ((imm = im6o->im6o_memberships.lh_first) != NULL) {
2224		LIST_REMOVE(imm, i6mm_chain);
2225		if (imm->i6mm_maddr)
2226			in6_delmulti(imm->i6mm_maddr);
2227		free(imm, M_IPMADDR);
2228	}
2229	free(im6o, M_IPMOPTS);
2230}
2231
2232/*
2233 * Set IPv6 outgoing packet options based on advanced API.
2234 */
2235int
2236ip6_setpktoptions(control, opt, priv, needcopy)
2237	struct mbuf *control;
2238	struct ip6_pktopts *opt;
2239	int priv, needcopy;
2240{
2241	struct cmsghdr *cm = 0;
2242
2243	if (control == 0 || opt == 0)
2244		return(EINVAL);
2245
2246	init_ip6pktopts(opt);
2247
2248	/*
2249	 * XXX: Currently, we assume all the optional information is stored
2250	 * in a single mbuf.
2251	 */
2252	if (control->m_next)
2253		return(EINVAL);
2254
2255	for (; control->m_len; control->m_data += CMSG_ALIGN(cm->cmsg_len),
2256		     control->m_len -= CMSG_ALIGN(cm->cmsg_len)) {
2257		cm = mtod(control, struct cmsghdr *);
2258		if (cm->cmsg_len == 0 || cm->cmsg_len > control->m_len)
2259			return(EINVAL);
2260		if (cm->cmsg_level != IPPROTO_IPV6)
2261			continue;
2262
2263		/*
2264		 * XXX should check if RFC2292 API is mixed with 2292bis API
2265		 */
2266		switch (cm->cmsg_type) {
2267		case IPV6_PKTINFO:
2268			if (cm->cmsg_len != CMSG_LEN(sizeof(struct in6_pktinfo)))
2269				return(EINVAL);
2270			if (needcopy) {
2271				/* XXX: Is it really WAITOK? */
2272				opt->ip6po_pktinfo =
2273					malloc(sizeof(struct in6_pktinfo),
2274					       M_IP6OPT, M_WAITOK);
2275				bcopy(CMSG_DATA(cm), opt->ip6po_pktinfo,
2276				    sizeof(struct in6_pktinfo));
2277			} else
2278				opt->ip6po_pktinfo =
2279					(struct in6_pktinfo *)CMSG_DATA(cm);
2280			if (opt->ip6po_pktinfo->ipi6_ifindex &&
2281			    IN6_IS_ADDR_LINKLOCAL(&opt->ip6po_pktinfo->ipi6_addr))
2282				opt->ip6po_pktinfo->ipi6_addr.s6_addr16[1] =
2283					htons(opt->ip6po_pktinfo->ipi6_ifindex);
2284
2285			if (opt->ip6po_pktinfo->ipi6_ifindex > if_index
2286			 || opt->ip6po_pktinfo->ipi6_ifindex < 0) {
2287				return(ENXIO);
2288			}
2289
2290			/*
2291			 * Check if the requested source address is indeed a
2292			 * unicast address assigned to the node, and can be
2293			 * used as the packet's source address.
2294			 */
2295			if (!IN6_IS_ADDR_UNSPECIFIED(&opt->ip6po_pktinfo->ipi6_addr)) {
2296				struct in6_ifaddr *ia6;
2297				struct sockaddr_in6 sin6;
2298
2299				bzero(&sin6, sizeof(sin6));
2300				sin6.sin6_len = sizeof(sin6);
2301				sin6.sin6_family = AF_INET6;
2302				sin6.sin6_addr =
2303					opt->ip6po_pktinfo->ipi6_addr;
2304				ia6 = (struct in6_ifaddr *)ifa_ifwithaddr(sin6tosa(&sin6));
2305				if (ia6 == NULL ||
2306				    (ia6->ia6_flags & (IN6_IFF_ANYCAST |
2307						       IN6_IFF_NOTREADY)) != 0)
2308					return(EADDRNOTAVAIL);
2309			}
2310			break;
2311
2312		case IPV6_HOPLIMIT:
2313			if (cm->cmsg_len != CMSG_LEN(sizeof(int)))
2314				return(EINVAL);
2315
2316			opt->ip6po_hlim = *(int *)CMSG_DATA(cm);
2317			if (opt->ip6po_hlim < -1 || opt->ip6po_hlim > 255)
2318				return(EINVAL);
2319			break;
2320
2321		case IPV6_NEXTHOP:
2322			if (!priv)
2323				return(EPERM);
2324
2325			if (cm->cmsg_len < sizeof(u_char) ||
2326			    /* check if cmsg_len is large enough for sa_len */
2327			    cm->cmsg_len < CMSG_LEN(*CMSG_DATA(cm)))
2328				return(EINVAL);
2329
2330			if (needcopy) {
2331				opt->ip6po_nexthop =
2332					malloc(*CMSG_DATA(cm),
2333					       M_IP6OPT, M_WAITOK);
2334				bcopy(CMSG_DATA(cm),
2335				      opt->ip6po_nexthop,
2336				      *CMSG_DATA(cm));
2337			} else
2338				opt->ip6po_nexthop =
2339					(struct sockaddr *)CMSG_DATA(cm);
2340			break;
2341
2342		case IPV6_HOPOPTS:
2343		{
2344			struct ip6_hbh *hbh;
2345			int hbhlen;
2346
2347			if (cm->cmsg_len < CMSG_LEN(sizeof(struct ip6_hbh)))
2348				return(EINVAL);
2349			hbh = (struct ip6_hbh *)CMSG_DATA(cm);
2350			hbhlen = (hbh->ip6h_len + 1) << 3;
2351			if (cm->cmsg_len != CMSG_LEN(hbhlen))
2352				return(EINVAL);
2353
2354			if (needcopy) {
2355				opt->ip6po_hbh =
2356					malloc(hbhlen, M_IP6OPT, M_WAITOK);
2357				bcopy(hbh, opt->ip6po_hbh, hbhlen);
2358			} else
2359				opt->ip6po_hbh = hbh;
2360			break;
2361		}
2362
2363		case IPV6_DSTOPTS:
2364		{
2365			struct ip6_dest *dest, **newdest;
2366			int destlen;
2367
2368			if (cm->cmsg_len < CMSG_LEN(sizeof(struct ip6_dest)))
2369				return(EINVAL);
2370			dest = (struct ip6_dest *)CMSG_DATA(cm);
2371			destlen = (dest->ip6d_len + 1) << 3;
2372			if (cm->cmsg_len != CMSG_LEN(destlen))
2373				return(EINVAL);
2374
2375			/*
2376			 * The old advacned API is ambiguous on this
2377			 * point. Our approach is to determine the
2378			 * position based according to the existence
2379			 * of a routing header. Note, however, that
2380			 * this depends on the order of the extension
2381			 * headers in the ancillary data; the 1st part
2382			 * of the destination options header must
2383			 * appear before the routing header in the
2384			 * ancillary data, too.
2385			 * RFC2292bis solved the ambiguity by
2386			 * introducing separate cmsg types.
2387			 */
2388			if (opt->ip6po_rthdr == NULL)
2389				newdest = &opt->ip6po_dest1;
2390			else
2391				newdest = &opt->ip6po_dest2;
2392
2393			if (needcopy) {
2394				*newdest = malloc(destlen, M_IP6OPT, M_WAITOK);
2395				bcopy(dest, *newdest, destlen);
2396			} else
2397				*newdest = dest;
2398
2399			break;
2400		}
2401
2402		case IPV6_RTHDR:
2403		{
2404			struct ip6_rthdr *rth;
2405			int rthlen;
2406
2407			if (cm->cmsg_len < CMSG_LEN(sizeof(struct ip6_rthdr)))
2408				return(EINVAL);
2409			rth = (struct ip6_rthdr *)CMSG_DATA(cm);
2410			rthlen = (rth->ip6r_len + 1) << 3;
2411			if (cm->cmsg_len != CMSG_LEN(rthlen))
2412				return(EINVAL);
2413
2414			switch (rth->ip6r_type) {
2415			case IPV6_RTHDR_TYPE_0:
2416				/* must contain one addr */
2417				if (rth->ip6r_len == 0)
2418					return(EINVAL);
2419				/* length must be even */
2420				if (rth->ip6r_len % 2)
2421					return(EINVAL);
2422				if (rth->ip6r_len / 2 != rth->ip6r_segleft)
2423					return(EINVAL);
2424				break;
2425			default:
2426				return(EINVAL);	/* not supported */
2427			}
2428
2429			if (needcopy) {
2430				opt->ip6po_rthdr = malloc(rthlen, M_IP6OPT,
2431							  M_WAITOK);
2432				bcopy(rth, opt->ip6po_rthdr, rthlen);
2433			} else
2434				opt->ip6po_rthdr = rth;
2435
2436			break;
2437		}
2438
2439		default:
2440			return(ENOPROTOOPT);
2441		}
2442	}
2443
2444	return(0);
2445}
2446
2447/*
2448 * Routine called from ip6_output() to loop back a copy of an IP6 multicast
2449 * packet to the input queue of a specified interface.  Note that this
2450 * calls the output routine of the loopback "driver", but with an interface
2451 * pointer that might NOT be &loif -- easier than replicating that code here.
2452 */
2453void
2454ip6_mloopback(ifp, m, dst)
2455	struct ifnet *ifp;
2456	struct mbuf *m;
2457	struct sockaddr_in6 *dst;
2458{
2459	struct mbuf *copym;
2460	struct ip6_hdr *ip6;
2461
2462	copym = m_copy(m, 0, M_COPYALL);
2463	if (copym == NULL)
2464		return;
2465
2466	/*
2467	 * Make sure to deep-copy IPv6 header portion in case the data
2468	 * is in an mbuf cluster, so that we can safely override the IPv6
2469	 * header portion later.
2470	 */
2471	if ((copym->m_flags & M_EXT) != 0 ||
2472	    copym->m_len < sizeof(struct ip6_hdr)) {
2473		copym = m_pullup(copym, sizeof(struct ip6_hdr));
2474		if (copym == NULL)
2475			return;
2476	}
2477
2478#ifdef DIAGNOSTIC
2479	if (copym->m_len < sizeof(*ip6)) {
2480		m_freem(copym);
2481		return;
2482	}
2483#endif
2484
2485	ip6 = mtod(copym, struct ip6_hdr *);
2486#ifndef SCOPEDROUTING
2487	/*
2488	 * clear embedded scope identifiers if necessary.
2489	 * in6_clearscope will touch the addresses only when necessary.
2490	 */
2491	in6_clearscope(&ip6->ip6_src);
2492	in6_clearscope(&ip6->ip6_dst);
2493#endif
2494
2495	(void)if_simloop(ifp, copym, dst->sin6_family, NULL);
2496}
2497
2498/*
2499 * Chop IPv6 header off from the payload.
2500 */
2501static int
2502ip6_splithdr(m, exthdrs)
2503	struct mbuf *m;
2504	struct ip6_exthdrs *exthdrs;
2505{
2506	struct mbuf *mh;
2507	struct ip6_hdr *ip6;
2508
2509	ip6 = mtod(m, struct ip6_hdr *);
2510	if (m->m_len > sizeof(*ip6)) {
2511		MGETHDR(mh, M_DONTWAIT, MT_HEADER);
2512		if (mh == 0) {
2513			m_freem(m);
2514			return ENOBUFS;
2515		}
2516		M_COPY_PKTHDR(mh, m);
2517		MH_ALIGN(mh, sizeof(*ip6));
2518		m->m_flags &= ~M_PKTHDR;
2519		m->m_len -= sizeof(*ip6);
2520		m->m_data += sizeof(*ip6);
2521		mh->m_next = m;
2522		m = mh;
2523		m->m_len = sizeof(*ip6);
2524		bcopy((caddr_t)ip6, mtod(m, caddr_t), sizeof(*ip6));
2525	}
2526	exthdrs->ip6e_ip6 = m;
2527	return 0;
2528}
2529
2530/*
2531 * Compute IPv6 extension header length.
2532 */
2533int
2534ip6_optlen(in6p)
2535	struct in6pcb *in6p;
2536{
2537	int len;
2538
2539	if (!in6p->in6p_outputopts)
2540		return 0;
2541
2542	len = 0;
2543#define elen(x) \
2544    (((struct ip6_ext *)(x)) ? (((struct ip6_ext *)(x))->ip6e_len + 1) << 3 : 0)
2545
2546	len += elen(in6p->in6p_outputopts->ip6po_hbh);
2547	if (in6p->in6p_outputopts->ip6po_rthdr)
2548		/* dest1 is valid with rthdr only */
2549		len += elen(in6p->in6p_outputopts->ip6po_dest1);
2550	len += elen(in6p->in6p_outputopts->ip6po_rthdr);
2551	len += elen(in6p->in6p_outputopts->ip6po_dest2);
2552	return len;
2553#undef elen
2554}
2555