xref: /netbsd-src/sys/netinet6/ip6_output.c (revision 21a3d2f02241c56556f4b2305ef1b8036f268f70)
1 /*	$NetBSD: ip6_output.c,v 1.38 2001/10/17 08:23:06 itojun Exp $	*/
2 /*	$KAME: ip6_output.c,v 1.172 2001/03/25 09:55:56 itojun 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_inet.h"
69 #include "opt_ipsec.h"
70 #include "opt_pfil_hooks.h"
71 
72 #include <sys/param.h>
73 #include <sys/malloc.h>
74 #include <sys/mbuf.h>
75 #include <sys/errno.h>
76 #include <sys/protosw.h>
77 #include <sys/socket.h>
78 #include <sys/socketvar.h>
79 #include <sys/systm.h>
80 #include <sys/proc.h>
81 
82 #include <net/if.h>
83 #include <net/route.h>
84 #ifdef PFIL_HOOKS
85 #include <net/pfil.h>
86 #endif
87 
88 #include <netinet/in.h>
89 #include <netinet/in_var.h>
90 #include <netinet/ip6.h>
91 #include <netinet/icmp6.h>
92 #include <netinet6/ip6_var.h>
93 #include <netinet6/in6_pcb.h>
94 #include <netinet6/nd6.h>
95 
96 #ifdef IPSEC
97 #include <netinet6/ipsec.h>
98 #include <netkey/key.h>
99 #endif /* IPSEC */
100 
101 #include "loop.h"
102 
103 #include <net/net_osdep.h>
104 
105 #ifdef PFIL_HOOKS
106 extern struct pfil_head inet6_pfil_hook;	/* XXX */
107 #endif
108 
109 struct ip6_exthdrs {
110 	struct mbuf *ip6e_ip6;
111 	struct mbuf *ip6e_hbh;
112 	struct mbuf *ip6e_dest1;
113 	struct mbuf *ip6e_rthdr;
114 	struct mbuf *ip6e_dest2;
115 };
116 
117 static int ip6_pcbopts __P((struct ip6_pktopts **, struct mbuf *,
118 			    struct socket *));
119 static int ip6_setmoptions __P((int, struct ip6_moptions **, struct mbuf *));
120 static int ip6_getmoptions __P((int, struct ip6_moptions *, struct mbuf **));
121 static int ip6_copyexthdr __P((struct mbuf **, caddr_t, int));
122 static int ip6_insertfraghdr __P((struct mbuf *, struct mbuf *, int,
123 				  struct ip6_frag **));
124 static int ip6_insert_jumboopt __P((struct ip6_exthdrs *, u_int32_t));
125 static int ip6_splithdr __P((struct mbuf *, struct ip6_exthdrs *));
126 
127 extern struct ifnet loif[NLOOP];
128 
129 /*
130  * IP6 output. The packet in mbuf chain m contains a skeletal IP6
131  * header (with pri, len, nxt, hlim, src, dst).
132  * This function may modify ver and hlim only.
133  * The mbuf chain containing the packet will be freed.
134  * The mbuf opt, if present, will not be freed.
135  */
136 int
137 ip6_output(m0, opt, ro, flags, im6o, ifpp)
138 	struct mbuf *m0;
139 	struct ip6_pktopts *opt;
140 	struct route_in6 *ro;
141 	int flags;
142 	struct ip6_moptions *im6o;
143 	struct ifnet **ifpp;		/* XXX: just for statistics */
144 {
145 	struct ip6_hdr *ip6, *mhip6;
146 	struct ifnet *ifp, *origifp;
147 	struct mbuf *m = m0;
148 	int hlen, tlen, len, off;
149 	struct route_in6 ip6route;
150 	struct sockaddr_in6 *dst;
151 	int error = 0;
152 	struct in6_ifaddr *ia;
153 	u_long mtu;
154 	u_int32_t optlen = 0, plen = 0, unfragpartlen = 0;
155 	struct ip6_exthdrs exthdrs;
156 	struct in6_addr finaldst;
157 	struct route_in6 *ro_pmtu = NULL;
158 	int hdrsplit = 0;
159 	int needipsec = 0;
160 #ifdef IPSEC
161 	int needipsectun = 0;
162 	struct socket *so;
163 	struct secpolicy *sp = NULL;
164 
165 	/* for AH processing. stupid to have "socket" variable in IP layer... */
166 	so = ipsec_getsocket(m);
167 	(void)ipsec_setsocket(m, NULL);
168 	ip6 = mtod(m, struct ip6_hdr *);
169 #endif /* IPSEC */
170 
171 #define MAKE_EXTHDR(hp, mp)						\
172     do {								\
173 	if (hp) {							\
174 		struct ip6_ext *eh = (struct ip6_ext *)(hp);		\
175 		error = ip6_copyexthdr((mp), (caddr_t)(hp), 		\
176 				       ((eh)->ip6e_len + 1) << 3);	\
177 		if (error)						\
178 			goto freehdrs;					\
179 	}								\
180     } while (0)
181 
182 	bzero(&exthdrs, sizeof(exthdrs));
183 	if (opt) {
184 		/* Hop-by-Hop options header */
185 		MAKE_EXTHDR(opt->ip6po_hbh, &exthdrs.ip6e_hbh);
186 		/* Destination options header(1st part) */
187 		MAKE_EXTHDR(opt->ip6po_dest1, &exthdrs.ip6e_dest1);
188 		/* Routing header */
189 		MAKE_EXTHDR(opt->ip6po_rthdr, &exthdrs.ip6e_rthdr);
190 		/* Destination options header(2nd part) */
191 		MAKE_EXTHDR(opt->ip6po_dest2, &exthdrs.ip6e_dest2);
192 	}
193 
194 #ifdef IPSEC
195 	/* get a security policy for this packet */
196 	if (so == NULL)
197 		sp = ipsec6_getpolicybyaddr(m, IPSEC_DIR_OUTBOUND, 0, &error);
198 	else
199 		sp = ipsec6_getpolicybysock(m, IPSEC_DIR_OUTBOUND, so, &error);
200 
201 	if (sp == NULL) {
202 		ipsec6stat.out_inval++;
203 		goto freehdrs;
204 	}
205 
206 	error = 0;
207 
208 	/* check policy */
209 	switch (sp->policy) {
210 	case IPSEC_POLICY_DISCARD:
211 		/*
212 		 * This packet is just discarded.
213 		 */
214 		ipsec6stat.out_polvio++;
215 		goto freehdrs;
216 
217 	case IPSEC_POLICY_BYPASS:
218 	case IPSEC_POLICY_NONE:
219 		/* no need to do IPsec. */
220 		needipsec = 0;
221 		break;
222 
223 	case IPSEC_POLICY_IPSEC:
224 		if (sp->req == NULL) {
225 			/* XXX should be panic ? */
226 			printf("ip6_output: No IPsec request specified.\n");
227 			error = EINVAL;
228 			goto freehdrs;
229 		}
230 		needipsec = 1;
231 		break;
232 
233 	case IPSEC_POLICY_ENTRUST:
234 	default:
235 		printf("ip6_output: Invalid policy found. %d\n", sp->policy);
236 	}
237 #endif /* IPSEC */
238 
239 	/*
240 	 * Calculate the total length of the extension header chain.
241 	 * Keep the length of the unfragmentable part for fragmentation.
242 	 */
243 	optlen = 0;
244 	if (exthdrs.ip6e_hbh) optlen += exthdrs.ip6e_hbh->m_len;
245 	if (exthdrs.ip6e_dest1) optlen += exthdrs.ip6e_dest1->m_len;
246 	if (exthdrs.ip6e_rthdr) optlen += exthdrs.ip6e_rthdr->m_len;
247 	unfragpartlen = optlen + sizeof(struct ip6_hdr);
248 	/* NOTE: we don't add AH/ESP length here. do that later. */
249 	if (exthdrs.ip6e_dest2) optlen += exthdrs.ip6e_dest2->m_len;
250 
251 	/*
252 	 * If we need IPsec, or there is at least one extension header,
253 	 * separate IP6 header from the payload.
254 	 */
255 	if ((needipsec || optlen) && !hdrsplit) {
256 		if ((error = ip6_splithdr(m, &exthdrs)) != 0) {
257 			m = NULL;
258 			goto freehdrs;
259 		}
260 		m = exthdrs.ip6e_ip6;
261 		hdrsplit++;
262 	}
263 
264 	/* adjust pointer */
265 	ip6 = mtod(m, struct ip6_hdr *);
266 
267 	/* adjust mbuf packet header length */
268 	m->m_pkthdr.len += optlen;
269 	plen = m->m_pkthdr.len - sizeof(*ip6);
270 
271 	/* If this is a jumbo payload, insert a jumbo payload option. */
272 	if (plen > IPV6_MAXPACKET) {
273 		if (!hdrsplit) {
274 			if ((error = ip6_splithdr(m, &exthdrs)) != 0) {
275 				m = NULL;
276 				goto freehdrs;
277 			}
278 			m = exthdrs.ip6e_ip6;
279 			hdrsplit++;
280 		}
281 		/* adjust pointer */
282 		ip6 = mtod(m, struct ip6_hdr *);
283 		if ((error = ip6_insert_jumboopt(&exthdrs, plen)) != 0)
284 			goto freehdrs;
285 		ip6->ip6_plen = 0;
286 	} else
287 		ip6->ip6_plen = htons(plen);
288 
289 	/*
290 	 * Concatenate headers and fill in next header fields.
291 	 * Here we have, on "m"
292 	 *	IPv6 payload
293 	 * and we insert headers accordingly.  Finally, we should be getting:
294 	 *	IPv6 hbh dest1 rthdr ah* [esp* dest2 payload]
295 	 *
296 	 * during the header composing process, "m" points to IPv6 header.
297 	 * "mprev" points to an extension header prior to esp.
298 	 */
299 	{
300 		u_char *nexthdrp = &ip6->ip6_nxt;
301 		struct mbuf *mprev = m;
302 
303 		/*
304 		 * we treat dest2 specially.  this makes IPsec processing
305 		 * much easier.
306 		 *
307 		 * result: IPv6 dest2 payload
308 		 * m and mprev will point to IPv6 header.
309 		 */
310 		if (exthdrs.ip6e_dest2) {
311 			if (!hdrsplit)
312 				panic("assumption failed: hdr not split");
313 			exthdrs.ip6e_dest2->m_next = m->m_next;
314 			m->m_next = exthdrs.ip6e_dest2;
315 			*mtod(exthdrs.ip6e_dest2, u_char *) = ip6->ip6_nxt;
316 			ip6->ip6_nxt = IPPROTO_DSTOPTS;
317 		}
318 
319 #define MAKE_CHAIN(m, mp, p, i)\
320     do {\
321 	if (m) {\
322 		if (!hdrsplit) \
323 			panic("assumption failed: hdr not split"); \
324 		*mtod((m), u_char *) = *(p);\
325 		*(p) = (i);\
326 		p = mtod((m), u_char *);\
327 		(m)->m_next = (mp)->m_next;\
328 		(mp)->m_next = (m);\
329 		(mp) = (m);\
330 	}\
331     } while (0)
332 		/*
333 		 * result: IPv6 hbh dest1 rthdr dest2 payload
334 		 * m will point to IPv6 header.  mprev will point to the
335 		 * extension header prior to dest2 (rthdr in the above case).
336 		 */
337 		MAKE_CHAIN(exthdrs.ip6e_hbh, mprev,
338 			   nexthdrp, IPPROTO_HOPOPTS);
339 		MAKE_CHAIN(exthdrs.ip6e_dest1, mprev,
340 			   nexthdrp, IPPROTO_DSTOPTS);
341 		MAKE_CHAIN(exthdrs.ip6e_rthdr, mprev,
342 			   nexthdrp, IPPROTO_ROUTING);
343 
344 #ifdef IPSEC
345 		if (!needipsec)
346 			goto skip_ipsec2;
347 
348 		/*
349 		 * pointers after IPsec headers are not valid any more.
350 		 * other pointers need a great care too.
351 		 * (IPsec routines should not mangle mbufs prior to AH/ESP)
352 		 */
353 		exthdrs.ip6e_dest2 = NULL;
354 
355 	    {
356 		struct ip6_rthdr *rh = NULL;
357 		int segleft_org = 0;
358 		struct ipsec_output_state state;
359 
360 		if (exthdrs.ip6e_rthdr) {
361 			rh = mtod(exthdrs.ip6e_rthdr, struct ip6_rthdr *);
362 			segleft_org = rh->ip6r_segleft;
363 			rh->ip6r_segleft = 0;
364 		}
365 
366 		bzero(&state, sizeof(state));
367 		state.m = m;
368 		error = ipsec6_output_trans(&state, nexthdrp, mprev, sp, flags,
369 			&needipsectun);
370 		m = state.m;
371 		if (error) {
372 			/* mbuf is already reclaimed in ipsec6_output_trans. */
373 			m = NULL;
374 			switch (error) {
375 			case EHOSTUNREACH:
376 			case ENETUNREACH:
377 			case EMSGSIZE:
378 			case ENOBUFS:
379 			case ENOMEM:
380 				break;
381 			default:
382 				printf("ip6_output (ipsec): error code %d\n", error);
383 				/*fall through*/
384 			case ENOENT:
385 				/* don't show these error codes to the user */
386 				error = 0;
387 				break;
388 			}
389 			goto bad;
390 		}
391 		if (exthdrs.ip6e_rthdr) {
392 			/* ah6_output doesn't modify mbuf chain */
393 			rh->ip6r_segleft = segleft_org;
394 		}
395 	    }
396 skip_ipsec2:;
397 #endif
398 	}
399 
400 	/*
401 	 * If there is a routing header, replace destination address field
402 	 * with the first hop of the routing header.
403 	 */
404 	if (exthdrs.ip6e_rthdr) {
405 		struct ip6_rthdr *rh =
406 			(struct ip6_rthdr *)(mtod(exthdrs.ip6e_rthdr,
407 						  struct ip6_rthdr *));
408 		struct ip6_rthdr0 *rh0;
409 
410 		finaldst = ip6->ip6_dst;
411 		switch (rh->ip6r_type) {
412 		case IPV6_RTHDR_TYPE_0:
413 			 rh0 = (struct ip6_rthdr0 *)rh;
414 			 ip6->ip6_dst = rh0->ip6r0_addr[0];
415 			 bcopy((caddr_t)&rh0->ip6r0_addr[1],
416 				 (caddr_t)&rh0->ip6r0_addr[0],
417 				 sizeof(struct in6_addr) * (rh0->ip6r0_segleft - 1)
418 				 );
419 			 rh0->ip6r0_addr[rh0->ip6r0_segleft - 1] = finaldst;
420 			 break;
421 		default:	/* is it possible? */
422 			 error = EINVAL;
423 			 goto bad;
424 		}
425 	}
426 
427 	/* Source address validation */
428 	if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src) &&
429 	    (flags & IPV6_DADOUTPUT) == 0) {
430 		error = EOPNOTSUPP;
431 		ip6stat.ip6s_badscope++;
432 		goto bad;
433 	}
434 	if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_src)) {
435 		error = EOPNOTSUPP;
436 		ip6stat.ip6s_badscope++;
437 		goto bad;
438 	}
439 
440 	ip6stat.ip6s_localout++;
441 
442 	/*
443 	 * Route packet.
444 	 */
445 	if (ro == 0) {
446 		ro = &ip6route;
447 		bzero((caddr_t)ro, sizeof(*ro));
448 	}
449 	ro_pmtu = ro;
450 	if (opt && opt->ip6po_rthdr)
451 		ro = &opt->ip6po_route;
452 	dst = (struct sockaddr_in6 *)&ro->ro_dst;
453 	/*
454 	 * If there is a cached route,
455 	 * check that it is to the same destination
456 	 * and is still up. If not, free it and try again.
457 	 */
458 	if (ro->ro_rt && ((ro->ro_rt->rt_flags & RTF_UP) == 0 ||
459 			 !IN6_ARE_ADDR_EQUAL(&dst->sin6_addr, &ip6->ip6_dst))) {
460 		RTFREE(ro->ro_rt);
461 		ro->ro_rt = (struct rtentry *)0;
462 	}
463 	if (ro->ro_rt == 0) {
464 		bzero(dst, sizeof(*dst));
465 		dst->sin6_family = AF_INET6;
466 		dst->sin6_len = sizeof(struct sockaddr_in6);
467 		dst->sin6_addr = ip6->ip6_dst;
468 	}
469 #ifdef IPSEC
470 	if (needipsec && needipsectun) {
471 		struct ipsec_output_state state;
472 
473 		/*
474 		 * All the extension headers will become inaccessible
475 		 * (since they can be encrypted).
476 		 * Don't panic, we need no more updates to extension headers
477 		 * on inner IPv6 packet (since they are now encapsulated).
478 		 *
479 		 * IPv6 [ESP|AH] IPv6 [extension headers] payload
480 		 */
481 		bzero(&exthdrs, sizeof(exthdrs));
482 		exthdrs.ip6e_ip6 = m;
483 
484 		bzero(&state, sizeof(state));
485 		state.m = m;
486 		state.ro = (struct route *)ro;
487 		state.dst = (struct sockaddr *)dst;
488 
489 		error = ipsec6_output_tunnel(&state, sp, flags);
490 
491 		m = state.m;
492 		ro = (struct route_in6 *)state.ro;
493 		dst = (struct sockaddr_in6 *)state.dst;
494 		if (error) {
495 			/* mbuf is already reclaimed in ipsec6_output_tunnel. */
496 			m0 = m = NULL;
497 			m = NULL;
498 			switch (error) {
499 			case EHOSTUNREACH:
500 			case ENETUNREACH:
501 			case EMSGSIZE:
502 			case ENOBUFS:
503 			case ENOMEM:
504 				break;
505 			default:
506 				printf("ip6_output (ipsec): error code %d\n", error);
507 				/*fall through*/
508 			case ENOENT:
509 				/* don't show these error codes to the user */
510 				error = 0;
511 				break;
512 			}
513 			goto bad;
514 		}
515 
516 		exthdrs.ip6e_ip6 = m;
517 	}
518 #endif /*IPSEC*/
519 
520 	if (!IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
521 		/* Unicast */
522 
523 #define ifatoia6(ifa)	((struct in6_ifaddr *)(ifa))
524 #define sin6tosa(sin6)	((struct sockaddr *)(sin6))
525 		/* xxx
526 		 * interface selection comes here
527 		 * if an interface is specified from an upper layer,
528 		 * ifp must point it.
529 		 */
530 		if (ro->ro_rt == 0) {
531 			/*
532 			 * non-bsdi always clone routes, if parent is
533 			 * PRF_CLONING.
534 			 */
535 			rtalloc((struct route *)ro);
536 		}
537 		if (ro->ro_rt == 0) {
538 			ip6stat.ip6s_noroute++;
539 			error = EHOSTUNREACH;
540 			/* XXX in6_ifstat_inc(ifp, ifs6_out_discard); */
541 			goto bad;
542 		}
543 		ia = ifatoia6(ro->ro_rt->rt_ifa);
544 		ifp = ro->ro_rt->rt_ifp;
545 		ro->ro_rt->rt_use++;
546 		if (ro->ro_rt->rt_flags & RTF_GATEWAY)
547 			dst = (struct sockaddr_in6 *)ro->ro_rt->rt_gateway;
548 		m->m_flags &= ~(M_BCAST | M_MCAST);	/* just in case */
549 
550 		in6_ifstat_inc(ifp, ifs6_out_request);
551 
552 		/*
553 		 * Check if the outgoing interface conflicts with
554 		 * the interface specified by ifi6_ifindex (if specified).
555 		 * Note that loopback interface is always okay.
556 		 * (this may happen when we are sending a packet to one of
557 		 *  our own addresses.)
558 		 */
559 		if (opt && opt->ip6po_pktinfo
560 		 && opt->ip6po_pktinfo->ipi6_ifindex) {
561 			if (!(ifp->if_flags & IFF_LOOPBACK)
562 			 && ifp->if_index != opt->ip6po_pktinfo->ipi6_ifindex) {
563 				ip6stat.ip6s_noroute++;
564 				in6_ifstat_inc(ifp, ifs6_out_discard);
565 				error = EHOSTUNREACH;
566 				goto bad;
567 			}
568 		}
569 
570 		if (opt && opt->ip6po_hlim != -1)
571 			ip6->ip6_hlim = opt->ip6po_hlim & 0xff;
572 	} else {
573 		/* Multicast */
574 		struct	in6_multi *in6m;
575 
576 		m->m_flags = (m->m_flags & ~M_BCAST) | M_MCAST;
577 
578 		/*
579 		 * See if the caller provided any multicast options
580 		 */
581 		ifp = NULL;
582 		if (im6o != NULL) {
583 			ip6->ip6_hlim = im6o->im6o_multicast_hlim;
584 			if (im6o->im6o_multicast_ifp != NULL)
585 				ifp = im6o->im6o_multicast_ifp;
586 		} else
587 			ip6->ip6_hlim = ip6_defmcasthlim;
588 
589 		/*
590 		 * See if the caller provided the outgoing interface
591 		 * as an ancillary data.
592 		 * Boundary check for ifindex is assumed to be already done.
593 		 */
594 		if (opt && opt->ip6po_pktinfo && opt->ip6po_pktinfo->ipi6_ifindex)
595 			ifp = ifindex2ifnet[opt->ip6po_pktinfo->ipi6_ifindex];
596 
597 		/*
598 		 * If the destination is a node-local scope multicast,
599 		 * the packet should be loop-backed only.
600 		 */
601 		if (IN6_IS_ADDR_MC_NODELOCAL(&ip6->ip6_dst)) {
602 			/*
603 			 * If the outgoing interface is already specified,
604 			 * it should be a loopback interface.
605 			 */
606 			if (ifp && (ifp->if_flags & IFF_LOOPBACK) == 0) {
607 				ip6stat.ip6s_badscope++;
608 				error = ENETUNREACH; /* XXX: better error? */
609 				/* XXX correct ifp? */
610 				in6_ifstat_inc(ifp, ifs6_out_discard);
611 				goto bad;
612 			} else {
613 				ifp = &loif[0];
614 			}
615 		}
616 
617 		if (opt && opt->ip6po_hlim != -1)
618 			ip6->ip6_hlim = opt->ip6po_hlim & 0xff;
619 
620 		/*
621 		 * If caller did not provide an interface lookup a
622 		 * default in the routing table.  This is either a
623 		 * default for the speicfied group (i.e. a host
624 		 * route), or a multicast default (a route for the
625 		 * ``net'' ff00::/8).
626 		 */
627 		if (ifp == NULL) {
628 			if (ro->ro_rt == 0) {
629 				ro->ro_rt = rtalloc1((struct sockaddr *)
630 						&ro->ro_dst, 0
631 						);
632 			}
633 			if (ro->ro_rt == 0) {
634 				ip6stat.ip6s_noroute++;
635 				error = EHOSTUNREACH;
636 				/* XXX in6_ifstat_inc(ifp, ifs6_out_discard) */
637 				goto bad;
638 			}
639 			ia = ifatoia6(ro->ro_rt->rt_ifa);
640 			ifp = ro->ro_rt->rt_ifp;
641 			ro->ro_rt->rt_use++;
642 		}
643 
644 		if ((flags & IPV6_FORWARDING) == 0)
645 			in6_ifstat_inc(ifp, ifs6_out_request);
646 		in6_ifstat_inc(ifp, ifs6_out_mcast);
647 
648 		/*
649 		 * Confirm that the outgoing interface supports multicast.
650 		 */
651 		if ((ifp->if_flags & IFF_MULTICAST) == 0) {
652 			ip6stat.ip6s_noroute++;
653 			in6_ifstat_inc(ifp, ifs6_out_discard);
654 			error = ENETUNREACH;
655 			goto bad;
656 		}
657 		IN6_LOOKUP_MULTI(ip6->ip6_dst, ifp, in6m);
658 		if (in6m != NULL &&
659 		   (im6o == NULL || im6o->im6o_multicast_loop)) {
660 			/*
661 			 * If we belong to the destination multicast group
662 			 * on the outgoing interface, and the caller did not
663 			 * forbid loopback, loop back a copy.
664 			 */
665 			ip6_mloopback(ifp, m, dst);
666 		} else {
667 			/*
668 			 * If we are acting as a multicast router, perform
669 			 * multicast forwarding as if the packet had just
670 			 * arrived on the interface to which we are about
671 			 * to send.  The multicast forwarding function
672 			 * recursively calls this function, using the
673 			 * IPV6_FORWARDING flag to prevent infinite recursion.
674 			 *
675 			 * Multicasts that are looped back by ip6_mloopback(),
676 			 * above, will be forwarded by the ip6_input() routine,
677 			 * if necessary.
678 			 */
679 			if (ip6_mrouter && (flags & IPV6_FORWARDING) == 0) {
680 				if (ip6_mforward(ip6, ifp, m) != 0) {
681 					m_freem(m);
682 					goto done;
683 				}
684 			}
685 		}
686 		/*
687 		 * Multicasts with a hoplimit of zero may be looped back,
688 		 * above, but must not be transmitted on a network.
689 		 * Also, multicasts addressed to the loopback interface
690 		 * are not sent -- the above call to ip6_mloopback() will
691 		 * loop back a copy if this host actually belongs to the
692 		 * destination group on the loopback interface.
693 		 */
694 		if (ip6->ip6_hlim == 0 || (ifp->if_flags & IFF_LOOPBACK)) {
695 			m_freem(m);
696 			goto done;
697 		}
698 	}
699 
700 	/*
701 	 * Fill the outgoing inteface to tell the upper layer
702 	 * to increment per-interface statistics.
703 	 */
704 	if (ifpp)
705 		*ifpp = ifp;
706 
707 	/*
708 	 * Determine path MTU.
709 	 */
710 	if (ro_pmtu != ro) {
711 		/* The first hop and the final destination may differ. */
712 		struct sockaddr_in6 *sin6_fin =
713 			(struct sockaddr_in6 *)&ro_pmtu->ro_dst;
714 		if (ro_pmtu->ro_rt && ((ro->ro_rt->rt_flags & RTF_UP) == 0 ||
715 				       !IN6_ARE_ADDR_EQUAL(&sin6_fin->sin6_addr,
716 							   &finaldst))) {
717 			RTFREE(ro_pmtu->ro_rt);
718 			ro_pmtu->ro_rt = (struct rtentry *)0;
719 		}
720 		if (ro_pmtu->ro_rt == 0) {
721 			bzero(sin6_fin, sizeof(*sin6_fin));
722 			sin6_fin->sin6_family = AF_INET6;
723 			sin6_fin->sin6_len = sizeof(struct sockaddr_in6);
724 			sin6_fin->sin6_addr = finaldst;
725 
726 			rtalloc((struct route *)ro_pmtu);
727 		}
728 	}
729 	if (ro_pmtu->ro_rt != NULL) {
730 		u_int32_t ifmtu = nd_ifinfo[ifp->if_index].linkmtu;
731 
732 		mtu = ro_pmtu->ro_rt->rt_rmx.rmx_mtu;
733 		if (mtu > ifmtu || mtu == 0) {
734 			/*
735 			 * The MTU on the route is larger than the MTU on
736 			 * the interface!  This shouldn't happen, unless the
737 			 * MTU of the interface has been changed after the
738 			 * interface was brought up.  Change the MTU in the
739 			 * route to match the interface MTU (as long as the
740 			 * field isn't locked).
741 			 *
742 			 * if MTU on the route is 0, we need to fix the MTU.
743 			 * this case happens with path MTU discovery timeouts.
744 			 */
745 			 mtu = ifmtu;
746 			 if ((ro_pmtu->ro_rt->rt_rmx.rmx_locks & RTV_MTU) == 0)
747 				 ro_pmtu->ro_rt->rt_rmx.rmx_mtu = mtu; /* XXX */
748 		}
749 	} else {
750 		mtu = nd_ifinfo[ifp->if_index].linkmtu;
751 	}
752 
753 	/* Fake scoped addresses */
754 	if ((ifp->if_flags & IFF_LOOPBACK) != 0) {
755 		/*
756 		 * If source or destination address is a scoped address, and
757 		 * the packet is going to be sent to a loopback interface,
758 		 * we should keep the original interface.
759 		 */
760 
761 		/*
762 		 * XXX: this is a very experimental and temporary solution.
763 		 * We eventually have sockaddr_in6 and use the sin6_scope_id
764 		 * field of the structure here.
765 		 * We rely on the consistency between two scope zone ids
766 		 * of source add destination, which should already be assured
767 		 * Larger scopes than link will be supported in the near
768 		 * future.
769 		 */
770 		origifp = NULL;
771 		if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_src))
772 			origifp = ifindex2ifnet[ntohs(ip6->ip6_src.s6_addr16[1])];
773 		else if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_dst))
774 			origifp = ifindex2ifnet[ntohs(ip6->ip6_dst.s6_addr16[1])];
775 		/*
776 		 * XXX: origifp can be NULL even in those two cases above.
777 		 * For example, if we remove the (only) link-local address
778 		 * from the loopback interface, and try to send a link-local
779 		 * address without link-id information.  Then the source
780 		 * address is ::1, and the destination address is the
781 		 * link-local address with its s6_addr16[1] being zero.
782 		 * What is worse, if the packet goes to the loopback interface
783 		 * by a default rejected route, the null pointer would be
784 		 * passed to looutput, and the kernel would hang.
785 		 * The following last resort would prevent such disaster.
786 		 */
787 		if (origifp == NULL)
788 			origifp = ifp;
789 	}
790 	else
791 		origifp = ifp;
792 	if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_src))
793 		ip6->ip6_src.s6_addr16[1] = 0;
794 	if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_dst))
795 		ip6->ip6_dst.s6_addr16[1] = 0;
796 
797 	/*
798 	 * If the outgoing packet contains a hop-by-hop options header,
799 	 * it must be examined and processed even by the source node.
800 	 * (RFC 2460, section 4.)
801 	 */
802 	if (exthdrs.ip6e_hbh) {
803 		struct ip6_hbh *hbh = mtod(exthdrs.ip6e_hbh, struct ip6_hbh *);
804 		u_int32_t dummy1; /* XXX unused */
805 		u_int32_t dummy2; /* XXX unused */
806 
807 		/*
808 		 *  XXX: if we have to send an ICMPv6 error to the sender,
809 		 *       we need the M_LOOP flag since icmp6_error() expects
810 		 *       the IPv6 and the hop-by-hop options header are
811 		 *       continuous unless the flag is set.
812 		 */
813 		m->m_flags |= M_LOOP;
814 		m->m_pkthdr.rcvif = ifp;
815 		if (ip6_process_hopopts(m,
816 					(u_int8_t *)(hbh + 1),
817 					((hbh->ip6h_len + 1) << 3) -
818 					sizeof(struct ip6_hbh),
819 					&dummy1, &dummy2) < 0) {
820 			/* m was already freed at this point */
821 			error = EINVAL;/* better error? */
822 			goto done;
823 		}
824 		m->m_flags &= ~M_LOOP; /* XXX */
825 		m->m_pkthdr.rcvif = NULL;
826 	}
827 
828 #ifdef PFIL_HOOKS
829 	/*
830 	 * Run through list of hooks for output packets.
831 	 */
832 	if ((error = pfil_run_hooks(&inet6_pfil_hook, &m, ifp,
833 				    PFIL_OUT)) != 0)
834 		goto done;
835 	if (m == NULL)
836 		goto done;
837 	ip6 = mtod(m, struct ip6_hdr *);
838 #endif /* PFIL_HOOKS */
839 	/*
840 	 * Send the packet to the outgoing interface.
841 	 * If necessary, do IPv6 fragmentation before sending.
842 	 */
843 	tlen = m->m_pkthdr.len;
844 	if (tlen <= mtu
845 #ifdef notyet
846 	    /*
847 	     * On any link that cannot convey a 1280-octet packet in one piece,
848 	     * link-specific fragmentation and reassembly must be provided at
849 	     * a layer below IPv6. [RFC 2460, sec.5]
850 	     * Thus if the interface has ability of link-level fragmentation,
851 	     * we can just send the packet even if the packet size is
852 	     * larger than the link's MTU.
853 	     * XXX: IFF_FRAGMENTABLE (or such) flag has not been defined yet...
854 	     */
855 
856 	    || ifp->if_flags & IFF_FRAGMENTABLE
857 #endif
858 	    )
859 	{
860 #ifdef IFA_STATS
861 		struct in6_ifaddr *ia6;
862 		ip6 = mtod(m, struct ip6_hdr *);
863 		ia6 = in6_ifawithifp(ifp, &ip6->ip6_src);
864 		if (ia6) {
865 			ia6->ia_ifa.ifa_data.ifad_outbytes +=
866 				m->m_pkthdr.len;
867 		}
868 #endif
869 #ifdef IPSEC
870 		/* clean ipsec history once it goes out of the node */
871 		ipsec_delaux(m);
872 #endif
873 		error = nd6_output(ifp, origifp, m, dst, ro->ro_rt);
874 		goto done;
875 	} else if (mtu < IPV6_MMTU) {
876 		/*
877 		 * note that path MTU is never less than IPV6_MMTU
878 		 * (see icmp6_input).
879 		 */
880 		error = EMSGSIZE;
881 		in6_ifstat_inc(ifp, ifs6_out_fragfail);
882 		goto bad;
883 	} else if (ip6->ip6_plen == 0) { /* jumbo payload cannot be fragmented */
884 		error = EMSGSIZE;
885 		in6_ifstat_inc(ifp, ifs6_out_fragfail);
886 		goto bad;
887 	} else {
888 		struct mbuf **mnext, *m_frgpart;
889 		struct ip6_frag *ip6f;
890 		u_int32_t id = htonl(ip6_id++);
891 		u_char nextproto;
892 
893 		/*
894 		 * Too large for the destination or interface;
895 		 * fragment if possible.
896 		 * Must be able to put at least 8 bytes per fragment.
897 		 */
898 		hlen = unfragpartlen;
899 		if (mtu > IPV6_MAXPACKET)
900 			mtu = IPV6_MAXPACKET;
901 		len = (mtu - hlen - sizeof(struct ip6_frag)) & ~7;
902 		if (len < 8) {
903 			error = EMSGSIZE;
904 			in6_ifstat_inc(ifp, ifs6_out_fragfail);
905 			goto bad;
906 		}
907 
908 		mnext = &m->m_nextpkt;
909 
910 		/*
911 		 * Change the next header field of the last header in the
912 		 * unfragmentable part.
913 		 */
914 		if (exthdrs.ip6e_rthdr) {
915 			nextproto = *mtod(exthdrs.ip6e_rthdr, u_char *);
916 			*mtod(exthdrs.ip6e_rthdr, u_char *) = IPPROTO_FRAGMENT;
917 		} else if (exthdrs.ip6e_dest1) {
918 			nextproto = *mtod(exthdrs.ip6e_dest1, u_char *);
919 			*mtod(exthdrs.ip6e_dest1, u_char *) = IPPROTO_FRAGMENT;
920 		} else if (exthdrs.ip6e_hbh) {
921 			nextproto = *mtod(exthdrs.ip6e_hbh, u_char *);
922 			*mtod(exthdrs.ip6e_hbh, u_char *) = IPPROTO_FRAGMENT;
923 		} else {
924 			nextproto = ip6->ip6_nxt;
925 			ip6->ip6_nxt = IPPROTO_FRAGMENT;
926 		}
927 
928 		/*
929 		 * Loop through length of segment after first fragment,
930 		 * make new header and copy data of each part and link onto chain.
931 		 */
932 		m0 = m;
933 		for (off = hlen; off < tlen; off += len) {
934 			MGETHDR(m, M_DONTWAIT, MT_HEADER);
935 			if (!m) {
936 				error = ENOBUFS;
937 				ip6stat.ip6s_odropped++;
938 				goto sendorfree;
939 			}
940 			m->m_flags = m0->m_flags & M_COPYFLAGS;
941 			*mnext = m;
942 			mnext = &m->m_nextpkt;
943 			m->m_data += max_linkhdr;
944 			mhip6 = mtod(m, struct ip6_hdr *);
945 			*mhip6 = *ip6;
946 			m->m_len = sizeof(*mhip6);
947  			error = ip6_insertfraghdr(m0, m, hlen, &ip6f);
948  			if (error) {
949 				ip6stat.ip6s_odropped++;
950 				goto sendorfree;
951 			}
952 			ip6f->ip6f_offlg = htons((u_short)((off - hlen) & ~7));
953 			if (off + len >= tlen)
954 				len = tlen - off;
955 			else
956 				ip6f->ip6f_offlg |= IP6F_MORE_FRAG;
957 			mhip6->ip6_plen = htons((u_short)(len + hlen +
958 							  sizeof(*ip6f) -
959 							  sizeof(struct ip6_hdr)));
960 			if ((m_frgpart = m_copy(m0, off, len)) == 0) {
961 				error = ENOBUFS;
962 				ip6stat.ip6s_odropped++;
963 				goto sendorfree;
964 			}
965 			m_cat(m, m_frgpart);
966 			m->m_pkthdr.len = len + hlen + sizeof(*ip6f);
967 			m->m_pkthdr.rcvif = (struct ifnet *)0;
968 			ip6f->ip6f_reserved = 0;
969 			ip6f->ip6f_ident = id;
970 			ip6f->ip6f_nxt = nextproto;
971 			ip6stat.ip6s_ofragments++;
972 			in6_ifstat_inc(ifp, ifs6_out_fragcreat);
973 		}
974 
975 		in6_ifstat_inc(ifp, ifs6_out_fragok);
976 	}
977 
978 	/*
979 	 * Remove leading garbages.
980 	 */
981 sendorfree:
982 	m = m0->m_nextpkt;
983 	m0->m_nextpkt = 0;
984 	m_freem(m0);
985 	for (m0 = m; m; m = m0) {
986 		m0 = m->m_nextpkt;
987 		m->m_nextpkt = 0;
988 		if (error == 0) {
989 #ifdef IFA_STATS
990 			struct in6_ifaddr *ia6;
991 			ip6 = mtod(m, struct ip6_hdr *);
992 			ia6 = in6_ifawithifp(ifp, &ip6->ip6_src);
993 			if (ia6) {
994 				ia6->ia_ifa.ifa_data.ifad_outbytes +=
995 					m->m_pkthdr.len;
996 			}
997 #endif
998 #ifdef IPSEC
999 			/* clean ipsec history once it goes out of the node */
1000 			ipsec_delaux(m);
1001 #endif
1002 			error = nd6_output(ifp, origifp, m, dst, ro->ro_rt);
1003 		} else
1004 			m_freem(m);
1005 	}
1006 
1007 	if (error == 0)
1008 		ip6stat.ip6s_fragmented++;
1009 
1010 done:
1011 	if (ro == &ip6route && ro->ro_rt) { /* brace necessary for RTFREE */
1012 		RTFREE(ro->ro_rt);
1013 	} else if (ro_pmtu == &ip6route && ro_pmtu->ro_rt) {
1014 		RTFREE(ro_pmtu->ro_rt);
1015 	}
1016 
1017 #ifdef IPSEC
1018 	if (sp != NULL)
1019 		key_freesp(sp);
1020 #endif /* IPSEC */
1021 
1022 	return(error);
1023 
1024 freehdrs:
1025 	m_freem(exthdrs.ip6e_hbh);	/* m_freem will check if mbuf is 0 */
1026 	m_freem(exthdrs.ip6e_dest1);
1027 	m_freem(exthdrs.ip6e_rthdr);
1028 	m_freem(exthdrs.ip6e_dest2);
1029 	/* fall through */
1030 bad:
1031 	m_freem(m);
1032 	goto done;
1033 }
1034 
1035 static int
1036 ip6_copyexthdr(mp, hdr, hlen)
1037 	struct mbuf **mp;
1038 	caddr_t hdr;
1039 	int hlen;
1040 {
1041 	struct mbuf *m;
1042 
1043 	if (hlen > MCLBYTES)
1044 		return(ENOBUFS); /* XXX */
1045 
1046 	MGET(m, M_DONTWAIT, MT_DATA);
1047 	if (!m)
1048 		return(ENOBUFS);
1049 
1050 	if (hlen > MLEN) {
1051 		MCLGET(m, M_DONTWAIT);
1052 		if ((m->m_flags & M_EXT) == 0) {
1053 			m_free(m);
1054 			return(ENOBUFS);
1055 		}
1056 	}
1057 	m->m_len = hlen;
1058 	if (hdr)
1059 		bcopy(hdr, mtod(m, caddr_t), hlen);
1060 
1061 	*mp = m;
1062 	return(0);
1063 }
1064 
1065 /*
1066  * Insert jumbo payload option.
1067  */
1068 static int
1069 ip6_insert_jumboopt(exthdrs, plen)
1070 	struct ip6_exthdrs *exthdrs;
1071 	u_int32_t plen;
1072 {
1073 	struct mbuf *mopt;
1074 	u_char *optbuf;
1075 	u_int32_t v;
1076 
1077 #define JUMBOOPTLEN	8	/* length of jumbo payload option and padding */
1078 
1079 	/*
1080 	 * If there is no hop-by-hop options header, allocate new one.
1081 	 * If there is one but it doesn't have enough space to store the
1082 	 * jumbo payload option, allocate a cluster to store the whole options.
1083 	 * Otherwise, use it to store the options.
1084 	 */
1085 	if (exthdrs->ip6e_hbh == 0) {
1086 		MGET(mopt, M_DONTWAIT, MT_DATA);
1087 		if (mopt == 0)
1088 			return(ENOBUFS);
1089 		mopt->m_len = JUMBOOPTLEN;
1090 		optbuf = mtod(mopt, u_char *);
1091 		optbuf[1] = 0;	/* = ((JUMBOOPTLEN) >> 3) - 1 */
1092 		exthdrs->ip6e_hbh = mopt;
1093 	} else {
1094 		struct ip6_hbh *hbh;
1095 
1096 		mopt = exthdrs->ip6e_hbh;
1097 		if (M_TRAILINGSPACE(mopt) < JUMBOOPTLEN) {
1098 			/*
1099 			 * XXX assumption:
1100 			 * - exthdrs->ip6e_hbh is not referenced from places
1101 			 *   other than exthdrs.
1102 			 * - exthdrs->ip6e_hbh is not an mbuf chain.
1103 			 */
1104 			int oldoptlen = mopt->m_len;
1105 			struct mbuf *n;
1106 
1107 			/*
1108 			 * XXX: give up if the whole (new) hbh header does
1109 			 * not fit even in an mbuf cluster.
1110 			 */
1111 			if (oldoptlen + JUMBOOPTLEN > MCLBYTES)
1112 				return(ENOBUFS);
1113 
1114 			/*
1115 			 * As a consequence, we must always prepare a cluster
1116 			 * at this point.
1117 			 */
1118 			MGET(n, M_DONTWAIT, MT_DATA);
1119 			if (n) {
1120 				MCLGET(n, M_DONTWAIT);
1121 				if ((n->m_flags & M_EXT) == 0) {
1122 					m_freem(n);
1123 					n = NULL;
1124 				}
1125 			}
1126 			if (!n)
1127 				return(ENOBUFS);
1128 			n->m_len = oldoptlen + JUMBOOPTLEN;
1129 			bcopy(mtod(mopt, caddr_t), mtod(n, caddr_t),
1130 			      oldoptlen);
1131 			optbuf = mtod(n, caddr_t) + oldoptlen;
1132 			m_freem(mopt);
1133 			mopt = exthdrs->ip6e_hbh = n;
1134 		} else {
1135 			optbuf = mtod(mopt, u_char *) + mopt->m_len;
1136 			mopt->m_len += JUMBOOPTLEN;
1137 		}
1138 		optbuf[0] = IP6OPT_PADN;
1139 		optbuf[1] = 1;
1140 
1141 		/*
1142 		 * Adjust the header length according to the pad and
1143 		 * the jumbo payload option.
1144 		 */
1145 		hbh = mtod(mopt, struct ip6_hbh *);
1146 		hbh->ip6h_len += (JUMBOOPTLEN >> 3);
1147 	}
1148 
1149 	/* fill in the option. */
1150 	optbuf[2] = IP6OPT_JUMBO;
1151 	optbuf[3] = 4;
1152 	v = (u_int32_t)htonl(plen + JUMBOOPTLEN);
1153 	bcopy(&v, &optbuf[4], sizeof(u_int32_t));
1154 
1155 	/* finally, adjust the packet header length */
1156 	exthdrs->ip6e_ip6->m_pkthdr.len += JUMBOOPTLEN;
1157 
1158 	return(0);
1159 #undef JUMBOOPTLEN
1160 }
1161 
1162 /*
1163  * Insert fragment header and copy unfragmentable header portions.
1164  */
1165 static int
1166 ip6_insertfraghdr(m0, m, hlen, frghdrp)
1167 	struct mbuf *m0, *m;
1168 	int hlen;
1169 	struct ip6_frag **frghdrp;
1170 {
1171 	struct mbuf *n, *mlast;
1172 
1173 	if (hlen > sizeof(struct ip6_hdr)) {
1174 		n = m_copym(m0, sizeof(struct ip6_hdr),
1175 			    hlen - sizeof(struct ip6_hdr), M_DONTWAIT);
1176 		if (n == 0)
1177 			return(ENOBUFS);
1178 		m->m_next = n;
1179 	} else
1180 		n = m;
1181 
1182 	/* Search for the last mbuf of unfragmentable part. */
1183 	for (mlast = n; mlast->m_next; mlast = mlast->m_next)
1184 		;
1185 
1186 	if ((mlast->m_flags & M_EXT) == 0 &&
1187 	    M_TRAILINGSPACE(mlast) >= sizeof(struct ip6_frag)) {
1188 		/* use the trailing space of the last mbuf for the fragment hdr */
1189 		*frghdrp =
1190 			(struct ip6_frag *)(mtod(mlast, caddr_t) + mlast->m_len);
1191 		mlast->m_len += sizeof(struct ip6_frag);
1192 		m->m_pkthdr.len += sizeof(struct ip6_frag);
1193 	} else {
1194 		/* allocate a new mbuf for the fragment header */
1195 		struct mbuf *mfrg;
1196 
1197 		MGET(mfrg, M_DONTWAIT, MT_DATA);
1198 		if (mfrg == 0)
1199 			return(ENOBUFS);
1200 		mfrg->m_len = sizeof(struct ip6_frag);
1201 		*frghdrp = mtod(mfrg, struct ip6_frag *);
1202 		mlast->m_next = mfrg;
1203 	}
1204 
1205 	return(0);
1206 }
1207 
1208 /*
1209  * IP6 socket option processing.
1210  */
1211 int
1212 ip6_ctloutput(op, so, level, optname, mp)
1213 	int op;
1214 	struct socket *so;
1215 	int level, optname;
1216 	struct mbuf **mp;
1217 {
1218 	struct in6pcb *in6p = sotoin6pcb(so);
1219 	struct mbuf *m = *mp;
1220 	int optval = 0;
1221 	int error = 0;
1222 	struct proc *p = curproc;	/* XXX */
1223 
1224 	if (level == IPPROTO_IPV6) {
1225 		switch (op) {
1226 
1227 		case PRCO_SETOPT:
1228 			switch (optname) {
1229 			case IPV6_PKTOPTIONS:
1230 				/* m is freed in ip6_pcbopts */
1231 				return(ip6_pcbopts(&in6p->in6p_outputopts,
1232 						   m, so));
1233 			case IPV6_HOPOPTS:
1234 			case IPV6_DSTOPTS:
1235 				if (p == 0 || suser(p->p_ucred, &p->p_acflag)) {
1236 					error = EPERM;
1237 					break;
1238 				}
1239 				/* fall through */
1240 			case IPV6_UNICAST_HOPS:
1241 			case IPV6_RECVOPTS:
1242 			case IPV6_RECVRETOPTS:
1243 			case IPV6_RECVDSTADDR:
1244 			case IPV6_PKTINFO:
1245 			case IPV6_HOPLIMIT:
1246 			case IPV6_RTHDR:
1247 			case IPV6_CHECKSUM:
1248 			case IPV6_FAITH:
1249 			case IPV6_V6ONLY:
1250 				if (!m || m->m_len != sizeof(int)) {
1251 					error = EINVAL;
1252 					break;
1253 				}
1254 				optval = *mtod(m, int *);
1255 				switch (optname) {
1256 
1257 				case IPV6_UNICAST_HOPS:
1258 					if (optval < -1 || optval >= 256)
1259 						error = EINVAL;
1260 					else {
1261 						/* -1 = kernel default */
1262 						in6p->in6p_hops = optval;
1263 					}
1264 					break;
1265 #define OPTSET(bit) \
1266 if (optval) \
1267 	in6p->in6p_flags |= bit; \
1268 else \
1269 	in6p->in6p_flags &= ~bit;
1270 
1271 				case IPV6_RECVOPTS:
1272 					OPTSET(IN6P_RECVOPTS);
1273 					break;
1274 
1275 				case IPV6_RECVRETOPTS:
1276 					OPTSET(IN6P_RECVRETOPTS);
1277 					break;
1278 
1279 				case IPV6_RECVDSTADDR:
1280 					OPTSET(IN6P_RECVDSTADDR);
1281 					break;
1282 
1283 				case IPV6_PKTINFO:
1284 					OPTSET(IN6P_PKTINFO);
1285 					break;
1286 
1287 				case IPV6_HOPLIMIT:
1288 					OPTSET(IN6P_HOPLIMIT);
1289 					break;
1290 
1291 				case IPV6_HOPOPTS:
1292 					OPTSET(IN6P_HOPOPTS);
1293 					break;
1294 
1295 				case IPV6_DSTOPTS:
1296 					OPTSET(IN6P_DSTOPTS);
1297 					break;
1298 
1299 				case IPV6_RTHDR:
1300 					OPTSET(IN6P_RTHDR);
1301 					break;
1302 
1303 				case IPV6_CHECKSUM:
1304 					in6p->in6p_cksum = optval;
1305 					break;
1306 
1307 				case IPV6_FAITH:
1308 					OPTSET(IN6P_FAITH);
1309 					break;
1310 
1311 				case IPV6_V6ONLY:
1312 					/*
1313 					 * make setsockopt(IPV6_V6ONLY)
1314 					 * available only prior to bind(2).
1315 					 * see ipng mailing list, Jun 22 2001.
1316 					 */
1317 					if (in6p->in6p_lport ||
1318 					    !IN6_IS_ADDR_UNSPECIFIED(&in6p->in6p_laddr))
1319 					{
1320 						error = EINVAL;
1321 						break;
1322 					}
1323 #ifdef INET6_BINDV6ONLY
1324 					if (!optval)
1325 						error = EINVAL;
1326 #else
1327 					OPTSET(IN6P_IPV6_V6ONLY);
1328 #endif
1329 					break;
1330 				}
1331 				break;
1332 #undef OPTSET
1333 
1334 			case IPV6_MULTICAST_IF:
1335 			case IPV6_MULTICAST_HOPS:
1336 			case IPV6_MULTICAST_LOOP:
1337 			case IPV6_JOIN_GROUP:
1338 			case IPV6_LEAVE_GROUP:
1339 				error =	ip6_setmoptions(optname, &in6p->in6p_moptions, m);
1340 				break;
1341 
1342 			case IPV6_PORTRANGE:
1343 				optval = *mtod(m, int *);
1344 
1345 				switch (optval) {
1346 				case IPV6_PORTRANGE_DEFAULT:
1347 					in6p->in6p_flags &= ~(IN6P_LOWPORT);
1348 					in6p->in6p_flags &= ~(IN6P_HIGHPORT);
1349 					break;
1350 
1351 				case IPV6_PORTRANGE_HIGH:
1352 					in6p->in6p_flags &= ~(IN6P_LOWPORT);
1353 					in6p->in6p_flags |= IN6P_HIGHPORT;
1354 					break;
1355 
1356 				case IPV6_PORTRANGE_LOW:
1357 					in6p->in6p_flags &= ~(IN6P_HIGHPORT);
1358 					in6p->in6p_flags |= IN6P_LOWPORT;
1359 					break;
1360 
1361 				default:
1362 					error = EINVAL;
1363 					break;
1364 				}
1365 				break;
1366 
1367 #ifdef IPSEC
1368 			case IPV6_IPSEC_POLICY:
1369 			    {
1370 				caddr_t req = NULL;
1371 				size_t len = 0;
1372 
1373 				int priv = 0;
1374 				if (p == 0 || suser(p->p_ucred, &p->p_acflag))
1375 					priv = 0;
1376 				else
1377 					priv = 1;
1378 				if (m) {
1379 					req = mtod(m, caddr_t);
1380 					len = m->m_len;
1381 				}
1382 				error = ipsec6_set_policy(in6p,
1383 				                   optname, req, len, priv);
1384 			    }
1385 				break;
1386 #endif /* IPSEC */
1387 
1388 			default:
1389 				error = ENOPROTOOPT;
1390 				break;
1391 			}
1392 			if (m)
1393 				(void)m_free(m);
1394 			break;
1395 
1396 		case PRCO_GETOPT:
1397 			switch (optname) {
1398 
1399 			case IPV6_OPTIONS:
1400 			case IPV6_RETOPTS:
1401 #if 0
1402 				*mp = m = m_get(M_WAIT, MT_SOOPTS);
1403 				if (in6p->in6p_options) {
1404 					m->m_len = in6p->in6p_options->m_len;
1405 					bcopy(mtod(in6p->in6p_options, caddr_t),
1406 					      mtod(m, caddr_t),
1407 					      (unsigned)m->m_len);
1408 				} else
1409 					m->m_len = 0;
1410 				break;
1411 #else
1412 				error = ENOPROTOOPT;
1413 				break;
1414 #endif
1415 
1416 			case IPV6_PKTOPTIONS:
1417 				if (in6p->in6p_options) {
1418 					*mp = m_copym(in6p->in6p_options, 0,
1419 						      M_COPYALL, M_WAIT);
1420 				} else {
1421 					*mp = m_get(M_WAIT, MT_SOOPTS);
1422 					(*mp)->m_len = 0;
1423 				}
1424 				break;
1425 
1426 			case IPV6_HOPOPTS:
1427 			case IPV6_DSTOPTS:
1428 				if (p == 0 || suser(p->p_ucred, &p->p_acflag)) {
1429 					error = EPERM;
1430 					break;
1431 				}
1432 				/* fall through */
1433 			case IPV6_UNICAST_HOPS:
1434 			case IPV6_RECVOPTS:
1435 			case IPV6_RECVRETOPTS:
1436 			case IPV6_RECVDSTADDR:
1437 			case IPV6_PORTRANGE:
1438 			case IPV6_PKTINFO:
1439 			case IPV6_HOPLIMIT:
1440 			case IPV6_RTHDR:
1441 			case IPV6_CHECKSUM:
1442 			case IPV6_FAITH:
1443 			case IPV6_V6ONLY:
1444 				*mp = m = m_get(M_WAIT, MT_SOOPTS);
1445 				m->m_len = sizeof(int);
1446 				switch (optname) {
1447 
1448 				case IPV6_UNICAST_HOPS:
1449 					optval = in6p->in6p_hops;
1450 					break;
1451 
1452 #define OPTBIT(bit) (in6p->in6p_flags & bit ? 1 : 0)
1453 
1454 				case IPV6_RECVOPTS:
1455 					optval = OPTBIT(IN6P_RECVOPTS);
1456 					break;
1457 
1458 				case IPV6_RECVRETOPTS:
1459 					optval = OPTBIT(IN6P_RECVRETOPTS);
1460 					break;
1461 
1462 				case IPV6_RECVDSTADDR:
1463 					optval = OPTBIT(IN6P_RECVDSTADDR);
1464 					break;
1465 
1466 				case IPV6_PORTRANGE:
1467 				    {
1468 					int flags;
1469 					flags = in6p->in6p_flags;
1470 					if (flags & IN6P_HIGHPORT)
1471 						optval = IPV6_PORTRANGE_HIGH;
1472 					else if (flags & IN6P_LOWPORT)
1473 						optval = IPV6_PORTRANGE_LOW;
1474 					else
1475 						optval = 0;
1476 					break;
1477 				    }
1478 
1479 				case IPV6_PKTINFO:
1480 					optval = OPTBIT(IN6P_PKTINFO);
1481 					break;
1482 
1483 				case IPV6_HOPLIMIT:
1484 					optval = OPTBIT(IN6P_HOPLIMIT);
1485 					break;
1486 
1487 				case IPV6_HOPOPTS:
1488 					optval = OPTBIT(IN6P_HOPOPTS);
1489 					break;
1490 
1491 				case IPV6_DSTOPTS:
1492 					optval = OPTBIT(IN6P_DSTOPTS);
1493 					break;
1494 
1495 				case IPV6_RTHDR:
1496 					optval = OPTBIT(IN6P_RTHDR);
1497 					break;
1498 
1499 				case IPV6_CHECKSUM:
1500 					optval = in6p->in6p_cksum;
1501 					break;
1502 
1503 				case IPV6_FAITH:
1504 					optval = OPTBIT(IN6P_FAITH);
1505 					break;
1506 
1507 				case IPV6_V6ONLY:
1508 					optval = OPTBIT(IN6P_IPV6_V6ONLY);
1509 					break;
1510 				}
1511 				*mtod(m, int *) = optval;
1512 				break;
1513 
1514 			case IPV6_MULTICAST_IF:
1515 			case IPV6_MULTICAST_HOPS:
1516 			case IPV6_MULTICAST_LOOP:
1517 			case IPV6_JOIN_GROUP:
1518 			case IPV6_LEAVE_GROUP:
1519 				error = ip6_getmoptions(optname, in6p->in6p_moptions, mp);
1520 				break;
1521 
1522 #ifdef IPSEC
1523 			case IPV6_IPSEC_POLICY:
1524 			{
1525 				caddr_t req = NULL;
1526 				size_t len = 0;
1527 
1528 				if (m) {
1529 					req = mtod(m, caddr_t);
1530 					len = m->m_len;
1531 				}
1532 				error = ipsec6_get_policy(in6p, req, len, mp);
1533 				break;
1534 			}
1535 #endif /* IPSEC */
1536 
1537 			default:
1538 				error = ENOPROTOOPT;
1539 				break;
1540 			}
1541 			break;
1542 		}
1543 	} else {
1544 		error = EINVAL;
1545 		if (op == PRCO_SETOPT && *mp)
1546 			(void)m_free(*mp);
1547 	}
1548 	return(error);
1549 }
1550 
1551 /*
1552  * Set up IP6 options in pcb for insertion in output packets.
1553  * Store in mbuf with pointer in pcbopt, adding pseudo-option
1554  * with destination address if source routed.
1555  */
1556 static int
1557 ip6_pcbopts(pktopt, m, so)
1558 	struct ip6_pktopts **pktopt;
1559 	struct mbuf *m;
1560 	struct socket *so;
1561 {
1562 	struct ip6_pktopts *opt = *pktopt;
1563 	int error = 0;
1564 	struct proc *p = curproc;	/* XXX */
1565 	int priv = 0;
1566 
1567 	/* turn off any old options. */
1568 	if (opt) {
1569 		if (opt->ip6po_m)
1570 			(void)m_free(opt->ip6po_m);
1571 	} else
1572 		opt = malloc(sizeof(*opt), M_IP6OPT, M_WAITOK);
1573 	*pktopt = 0;
1574 
1575 	if (!m || m->m_len == 0) {
1576 		/*
1577 		 * Only turning off any previous options.
1578 		 */
1579 		if (opt)
1580 			free(opt, M_IP6OPT);
1581 		if (m)
1582 			(void)m_free(m);
1583 		return(0);
1584 	}
1585 
1586 	/*  set options specified by user. */
1587 	if (p && !suser(p->p_ucred, &p->p_acflag))
1588 		priv = 1;
1589 	if ((error = ip6_setpktoptions(m, opt, priv)) != 0) {
1590 		(void)m_free(m);
1591 		return(error);
1592 	}
1593 	*pktopt = opt;
1594 	return(0);
1595 }
1596 
1597 /*
1598  * Set the IP6 multicast options in response to user setsockopt().
1599  */
1600 static int
1601 ip6_setmoptions(optname, im6op, m)
1602 	int optname;
1603 	struct ip6_moptions **im6op;
1604 	struct mbuf *m;
1605 {
1606 	int error = 0;
1607 	u_int loop, ifindex;
1608 	struct ipv6_mreq *mreq;
1609 	struct ifnet *ifp;
1610 	struct ip6_moptions *im6o = *im6op;
1611 	struct route_in6 ro;
1612 	struct sockaddr_in6 *dst;
1613 	struct in6_multi_mship *imm;
1614 	struct proc *p = curproc;	/* XXX */
1615 
1616 	if (im6o == NULL) {
1617 		/*
1618 		 * No multicast option buffer attached to the pcb;
1619 		 * allocate one and initialize to default values.
1620 		 */
1621 		im6o = (struct ip6_moptions *)
1622 			malloc(sizeof(*im6o), M_IPMOPTS, M_WAITOK);
1623 
1624 		if (im6o == NULL)
1625 			return(ENOBUFS);
1626 		*im6op = im6o;
1627 		im6o->im6o_multicast_ifp = NULL;
1628 		im6o->im6o_multicast_hlim = ip6_defmcasthlim;
1629 		im6o->im6o_multicast_loop = IPV6_DEFAULT_MULTICAST_LOOP;
1630 		LIST_INIT(&im6o->im6o_memberships);
1631 	}
1632 
1633 	switch (optname) {
1634 
1635 	case IPV6_MULTICAST_IF:
1636 		/*
1637 		 * Select the interface for outgoing multicast packets.
1638 		 */
1639 		if (m == NULL || m->m_len != sizeof(u_int)) {
1640 			error = EINVAL;
1641 			break;
1642 		}
1643 		bcopy(mtod(m, u_int *), &ifindex, sizeof(ifindex));
1644 		if (ifindex < 0 || if_index < ifindex) {
1645 			error = ENXIO;	/* XXX EINVAL? */
1646 			break;
1647 		}
1648 		ifp = ifindex2ifnet[ifindex];
1649 		if (ifp == NULL || (ifp->if_flags & IFF_MULTICAST) == 0) {
1650 			error = EADDRNOTAVAIL;
1651 			break;
1652 		}
1653 		im6o->im6o_multicast_ifp = ifp;
1654 		break;
1655 
1656 	case IPV6_MULTICAST_HOPS:
1657 	    {
1658 		/*
1659 		 * Set the IP6 hoplimit for outgoing multicast packets.
1660 		 */
1661 		int optval;
1662 		if (m == NULL || m->m_len != sizeof(int)) {
1663 			error = EINVAL;
1664 			break;
1665 		}
1666 		bcopy(mtod(m, u_int *), &optval, sizeof(optval));
1667 		if (optval < -1 || optval >= 256)
1668 			error = EINVAL;
1669 		else if (optval == -1)
1670 			im6o->im6o_multicast_hlim = ip6_defmcasthlim;
1671 		else
1672 			im6o->im6o_multicast_hlim = optval;
1673 		break;
1674 	    }
1675 
1676 	case IPV6_MULTICAST_LOOP:
1677 		/*
1678 		 * Set the loopback flag for outgoing multicast packets.
1679 		 * Must be zero or one.
1680 		 */
1681 		if (m == NULL || m->m_len != sizeof(u_int)) {
1682 			error = EINVAL;
1683 			break;
1684 		}
1685 		bcopy(mtod(m, u_int *), &loop, sizeof(loop));
1686 		if (loop > 1) {
1687 			error = EINVAL;
1688 			break;
1689 		}
1690 		im6o->im6o_multicast_loop = loop;
1691 		break;
1692 
1693 	case IPV6_JOIN_GROUP:
1694 		/*
1695 		 * Add a multicast group membership.
1696 		 * Group must be a valid IP6 multicast address.
1697 		 */
1698 		if (m == NULL || m->m_len != sizeof(struct ipv6_mreq)) {
1699 			error = EINVAL;
1700 			break;
1701 		}
1702 		mreq = mtod(m, struct ipv6_mreq *);
1703 		if (IN6_IS_ADDR_UNSPECIFIED(&mreq->ipv6mr_multiaddr)) {
1704 			/*
1705 			 * We use the unspecified address to specify to accept
1706 			 * all multicast addresses. Only super user is allowed
1707 			 * to do this.
1708 			 */
1709 			if (suser(p->p_ucred, &p->p_acflag))
1710 			{
1711 				error = EACCES;
1712 				break;
1713 			}
1714 		} else if (!IN6_IS_ADDR_MULTICAST(&mreq->ipv6mr_multiaddr)) {
1715 			error = EINVAL;
1716 			break;
1717 		}
1718 
1719 		/*
1720 		 * If the interface is specified, validate it.
1721 		 */
1722 		if (mreq->ipv6mr_interface < 0
1723 		 || if_index < mreq->ipv6mr_interface) {
1724 			error = ENXIO;	/* XXX EINVAL? */
1725 			break;
1726 		}
1727 		/*
1728 		 * If no interface was explicitly specified, choose an
1729 		 * appropriate one according to the given multicast address.
1730 		 */
1731 		if (mreq->ipv6mr_interface == 0) {
1732 			/*
1733 			 * If the multicast address is in node-local scope,
1734 			 * the interface should be a loopback interface.
1735 			 * Otherwise, look up the routing table for the
1736 			 * address, and choose the outgoing interface.
1737 			 *   XXX: is it a good approach?
1738 			 */
1739 			if (IN6_IS_ADDR_MC_NODELOCAL(&mreq->ipv6mr_multiaddr)) {
1740 				ifp = &loif[0];
1741 			} else {
1742 				ro.ro_rt = NULL;
1743 				dst = (struct sockaddr_in6 *)&ro.ro_dst;
1744 				bzero(dst, sizeof(*dst));
1745 				dst->sin6_len = sizeof(struct sockaddr_in6);
1746 				dst->sin6_family = AF_INET6;
1747 				dst->sin6_addr = mreq->ipv6mr_multiaddr;
1748 				rtalloc((struct route *)&ro);
1749 				if (ro.ro_rt == NULL) {
1750 					error = EADDRNOTAVAIL;
1751 					break;
1752 				}
1753 				ifp = ro.ro_rt->rt_ifp;
1754 				rtfree(ro.ro_rt);
1755 			}
1756 		} else
1757 			ifp = ifindex2ifnet[mreq->ipv6mr_interface];
1758 
1759 		/*
1760 		 * See if we found an interface, and confirm that it
1761 		 * supports multicast
1762 		 */
1763 		if (ifp == NULL || (ifp->if_flags & IFF_MULTICAST) == 0) {
1764 			error = EADDRNOTAVAIL;
1765 			break;
1766 		}
1767 		/*
1768 		 * Put interface index into the multicast address,
1769 		 * if the address has link-local scope.
1770 		 */
1771 		if (IN6_IS_ADDR_MC_LINKLOCAL(&mreq->ipv6mr_multiaddr)) {
1772 			mreq->ipv6mr_multiaddr.s6_addr16[1]
1773 				= htons(mreq->ipv6mr_interface);
1774 		}
1775 		/*
1776 		 * See if the membership already exists.
1777 		 */
1778 		for (imm = im6o->im6o_memberships.lh_first;
1779 		     imm != NULL; imm = imm->i6mm_chain.le_next)
1780 			if (imm->i6mm_maddr->in6m_ifp == ifp &&
1781 			    IN6_ARE_ADDR_EQUAL(&imm->i6mm_maddr->in6m_addr,
1782 					       &mreq->ipv6mr_multiaddr))
1783 				break;
1784 		if (imm != NULL) {
1785 			error = EADDRINUSE;
1786 			break;
1787 		}
1788 		/*
1789 		 * Everything looks good; add a new record to the multicast
1790 		 * address list for the given interface.
1791 		 */
1792 		imm = malloc(sizeof(*imm), M_IPMADDR, M_WAITOK);
1793 		if (imm == NULL) {
1794 			error = ENOBUFS;
1795 			break;
1796 		}
1797 		if ((imm->i6mm_maddr =
1798 		     in6_addmulti(&mreq->ipv6mr_multiaddr, ifp, &error)) == NULL) {
1799 			free(imm, M_IPMADDR);
1800 			break;
1801 		}
1802 		LIST_INSERT_HEAD(&im6o->im6o_memberships, imm, i6mm_chain);
1803 		break;
1804 
1805 	case IPV6_LEAVE_GROUP:
1806 		/*
1807 		 * Drop a multicast group membership.
1808 		 * Group must be a valid IP6 multicast address.
1809 		 */
1810 		if (m == NULL || m->m_len != sizeof(struct ipv6_mreq)) {
1811 			error = EINVAL;
1812 			break;
1813 		}
1814 		mreq = mtod(m, struct ipv6_mreq *);
1815 		if (IN6_IS_ADDR_UNSPECIFIED(&mreq->ipv6mr_multiaddr)) {
1816 			if (suser(p->p_ucred, &p->p_acflag))
1817 			{
1818 				error = EACCES;
1819 				break;
1820 			}
1821 		} else if (!IN6_IS_ADDR_MULTICAST(&mreq->ipv6mr_multiaddr)) {
1822 			error = EINVAL;
1823 			break;
1824 		}
1825 		/*
1826 		 * If an interface address was specified, get a pointer
1827 		 * to its ifnet structure.
1828 		 */
1829 		if (mreq->ipv6mr_interface < 0
1830 		 || if_index < mreq->ipv6mr_interface) {
1831 			error = ENXIO;	/* XXX EINVAL? */
1832 			break;
1833 		}
1834 		ifp = ifindex2ifnet[mreq->ipv6mr_interface];
1835 		/*
1836 		 * Put interface index into the multicast address,
1837 		 * if the address has link-local scope.
1838 		 */
1839 		if (IN6_IS_ADDR_MC_LINKLOCAL(&mreq->ipv6mr_multiaddr)) {
1840 			mreq->ipv6mr_multiaddr.s6_addr16[1]
1841 				= htons(mreq->ipv6mr_interface);
1842 		}
1843 		/*
1844 		 * Find the membership in the membership list.
1845 		 */
1846 		for (imm = im6o->im6o_memberships.lh_first;
1847 		     imm != NULL; imm = imm->i6mm_chain.le_next) {
1848 			if ((ifp == NULL ||
1849 			     imm->i6mm_maddr->in6m_ifp == ifp) &&
1850 			    IN6_ARE_ADDR_EQUAL(&imm->i6mm_maddr->in6m_addr,
1851 					       &mreq->ipv6mr_multiaddr))
1852 				break;
1853 		}
1854 		if (imm == NULL) {
1855 			/* Unable to resolve interface */
1856 			error = EADDRNOTAVAIL;
1857 			break;
1858 		}
1859 		/*
1860 		 * Give up the multicast address record to which the
1861 		 * membership points.
1862 		 */
1863 		LIST_REMOVE(imm, i6mm_chain);
1864 		in6_delmulti(imm->i6mm_maddr);
1865 		free(imm, M_IPMADDR);
1866 		break;
1867 
1868 	default:
1869 		error = EOPNOTSUPP;
1870 		break;
1871 	}
1872 
1873 	/*
1874 	 * If all options have default values, no need to keep the mbuf.
1875 	 */
1876 	if (im6o->im6o_multicast_ifp == NULL &&
1877 	    im6o->im6o_multicast_hlim == ip6_defmcasthlim &&
1878 	    im6o->im6o_multicast_loop == IPV6_DEFAULT_MULTICAST_LOOP &&
1879 	    im6o->im6o_memberships.lh_first == NULL) {
1880 		free(*im6op, M_IPMOPTS);
1881 		*im6op = NULL;
1882 	}
1883 
1884 	return(error);
1885 }
1886 
1887 /*
1888  * Return the IP6 multicast options in response to user getsockopt().
1889  */
1890 static int
1891 ip6_getmoptions(optname, im6o, mp)
1892 	int optname;
1893 	struct ip6_moptions *im6o;
1894 	struct mbuf **mp;
1895 {
1896 	u_int *hlim, *loop, *ifindex;
1897 
1898 	*mp = m_get(M_WAIT, MT_SOOPTS);
1899 
1900 	switch (optname) {
1901 
1902 	case IPV6_MULTICAST_IF:
1903 		ifindex = mtod(*mp, u_int *);
1904 		(*mp)->m_len = sizeof(u_int);
1905 		if (im6o == NULL || im6o->im6o_multicast_ifp == NULL)
1906 			*ifindex = 0;
1907 		else
1908 			*ifindex = im6o->im6o_multicast_ifp->if_index;
1909 		return(0);
1910 
1911 	case IPV6_MULTICAST_HOPS:
1912 		hlim = mtod(*mp, u_int *);
1913 		(*mp)->m_len = sizeof(u_int);
1914 		if (im6o == NULL)
1915 			*hlim = ip6_defmcasthlim;
1916 		else
1917 			*hlim = im6o->im6o_multicast_hlim;
1918 		return(0);
1919 
1920 	case IPV6_MULTICAST_LOOP:
1921 		loop = mtod(*mp, u_int *);
1922 		(*mp)->m_len = sizeof(u_int);
1923 		if (im6o == NULL)
1924 			*loop = ip6_defmcasthlim;
1925 		else
1926 			*loop = im6o->im6o_multicast_loop;
1927 		return(0);
1928 
1929 	default:
1930 		return(EOPNOTSUPP);
1931 	}
1932 }
1933 
1934 /*
1935  * Discard the IP6 multicast options.
1936  */
1937 void
1938 ip6_freemoptions(im6o)
1939 	struct ip6_moptions *im6o;
1940 {
1941 	struct in6_multi_mship *imm;
1942 
1943 	if (im6o == NULL)
1944 		return;
1945 
1946 	while ((imm = im6o->im6o_memberships.lh_first) != NULL) {
1947 		LIST_REMOVE(imm, i6mm_chain);
1948 		if (imm->i6mm_maddr)
1949 			in6_delmulti(imm->i6mm_maddr);
1950 		free(imm, M_IPMADDR);
1951 	}
1952 	free(im6o, M_IPMOPTS);
1953 }
1954 
1955 /*
1956  * Set IPv6 outgoing packet options based on advanced API.
1957  */
1958 int
1959 ip6_setpktoptions(control, opt, priv)
1960 	struct mbuf *control;
1961 	struct ip6_pktopts *opt;
1962 	int priv;
1963 {
1964 	struct cmsghdr *cm = 0;
1965 
1966 	if (control == 0 || opt == 0)
1967 		return(EINVAL);
1968 
1969 	bzero(opt, sizeof(*opt));
1970 	opt->ip6po_hlim = -1; /* -1 means to use default hop limit */
1971 
1972 	/*
1973 	 * XXX: Currently, we assume all the optional information is stored
1974 	 * in a single mbuf.
1975 	 */
1976 	if (control->m_next)
1977 		return(EINVAL);
1978 
1979 	opt->ip6po_m = control;
1980 
1981 	for (; control->m_len; control->m_data += CMSG_ALIGN(cm->cmsg_len),
1982 		     control->m_len -= CMSG_ALIGN(cm->cmsg_len)) {
1983 		cm = mtod(control, struct cmsghdr *);
1984 		if (cm->cmsg_len == 0 || cm->cmsg_len > control->m_len)
1985 			return(EINVAL);
1986 		if (cm->cmsg_level != IPPROTO_IPV6)
1987 			continue;
1988 
1989 		switch (cm->cmsg_type) {
1990 		case IPV6_PKTINFO:
1991 			if (cm->cmsg_len != CMSG_LEN(sizeof(struct in6_pktinfo)))
1992 				return(EINVAL);
1993 			opt->ip6po_pktinfo = (struct in6_pktinfo *)CMSG_DATA(cm);
1994 			if (opt->ip6po_pktinfo->ipi6_ifindex &&
1995 			    IN6_IS_ADDR_LINKLOCAL(&opt->ip6po_pktinfo->ipi6_addr))
1996 				opt->ip6po_pktinfo->ipi6_addr.s6_addr16[1] =
1997 					htons(opt->ip6po_pktinfo->ipi6_ifindex);
1998 
1999 			if (opt->ip6po_pktinfo->ipi6_ifindex > if_index
2000 			 || opt->ip6po_pktinfo->ipi6_ifindex < 0) {
2001 				return(ENXIO);
2002 			}
2003 
2004 			/*
2005 			 * Check if the requested source address is indeed a
2006 			 * unicast address assigned to the node, and can be
2007 			 * used as the packet's source address.
2008 			 */
2009 			if (!IN6_IS_ADDR_UNSPECIFIED(&opt->ip6po_pktinfo->ipi6_addr)) {
2010 				struct ifaddr *ia;
2011 				struct in6_ifaddr *ia6;
2012 				struct sockaddr_in6 sin6;
2013 
2014 				bzero(&sin6, sizeof(sin6));
2015 				sin6.sin6_len = sizeof(sin6);
2016 				sin6.sin6_family = AF_INET6;
2017 				sin6.sin6_addr =
2018 					opt->ip6po_pktinfo->ipi6_addr;
2019 				ia = ifa_ifwithaddr(sin6tosa(&sin6));
2020 				if (ia == NULL ||
2021 				    (opt->ip6po_pktinfo->ipi6_ifindex &&
2022 				     (ia->ifa_ifp->if_index !=
2023 				      opt->ip6po_pktinfo->ipi6_ifindex))) {
2024 					return(EADDRNOTAVAIL);
2025 				}
2026 				ia6 = (struct in6_ifaddr *)ia;
2027 				if ((ia6->ia6_flags & (IN6_IFF_ANYCAST|IN6_IFF_NOTREADY)) != 0) {
2028 					return(EADDRNOTAVAIL);
2029 				}
2030 
2031 				/*
2032 				 * Check if the requested source address is
2033 				 * indeed a unicast address assigned to the
2034 				 * node.
2035 				 */
2036 				if (IN6_IS_ADDR_MULTICAST(&opt->ip6po_pktinfo->ipi6_addr))
2037 					return(EADDRNOTAVAIL);
2038 			}
2039 			break;
2040 
2041 		case IPV6_HOPLIMIT:
2042 			if (cm->cmsg_len != CMSG_LEN(sizeof(int)))
2043 				return(EINVAL);
2044 
2045 			bcopy(CMSG_DATA(cm), &opt->ip6po_hlim,
2046 			    sizeof(opt->ip6po_hlim));
2047 			if (opt->ip6po_hlim < -1 || opt->ip6po_hlim > 255)
2048 				return(EINVAL);
2049 			break;
2050 
2051 		case IPV6_NEXTHOP:
2052 			if (!priv)
2053 				return(EPERM);
2054 
2055 			if (cm->cmsg_len < sizeof(u_char) ||
2056 			    /* check if cmsg_len is large enough for sa_len */
2057 			    cm->cmsg_len < CMSG_LEN(*CMSG_DATA(cm)))
2058 				return(EINVAL);
2059 
2060 			opt->ip6po_nexthop = (struct sockaddr *)CMSG_DATA(cm);
2061 
2062 			break;
2063 
2064 		case IPV6_HOPOPTS:
2065 			if (cm->cmsg_len < CMSG_LEN(sizeof(struct ip6_hbh)))
2066 				return(EINVAL);
2067 			opt->ip6po_hbh = (struct ip6_hbh *)CMSG_DATA(cm);
2068 			if (cm->cmsg_len !=
2069 			    CMSG_LEN((opt->ip6po_hbh->ip6h_len + 1) << 3))
2070 				return(EINVAL);
2071 			break;
2072 
2073 		case IPV6_DSTOPTS:
2074 			if (cm->cmsg_len < CMSG_LEN(sizeof(struct ip6_dest)))
2075 				return(EINVAL);
2076 
2077 			/*
2078 			 * If there is no routing header yet, the destination
2079 			 * options header should be put on the 1st part.
2080 			 * Otherwise, the header should be on the 2nd part.
2081 			 * (See RFC 2460, section 4.1)
2082 			 */
2083 			if (opt->ip6po_rthdr == NULL) {
2084 				opt->ip6po_dest1 =
2085 					(struct ip6_dest *)CMSG_DATA(cm);
2086 				if (cm->cmsg_len !=
2087 				    CMSG_LEN((opt->ip6po_dest1->ip6d_len + 1)
2088 					     << 3))
2089 					return(EINVAL);
2090 			}
2091 			else {
2092 				opt->ip6po_dest2 =
2093 					(struct ip6_dest *)CMSG_DATA(cm);
2094 				if (cm->cmsg_len !=
2095 				    CMSG_LEN((opt->ip6po_dest2->ip6d_len + 1)
2096 					     << 3))
2097 					return(EINVAL);
2098 			}
2099 			break;
2100 
2101 		case IPV6_RTHDR:
2102 			if (cm->cmsg_len < CMSG_LEN(sizeof(struct ip6_rthdr)))
2103 				return(EINVAL);
2104 			opt->ip6po_rthdr = (struct ip6_rthdr *)CMSG_DATA(cm);
2105 			if (cm->cmsg_len !=
2106 			    CMSG_LEN((opt->ip6po_rthdr->ip6r_len + 1) << 3))
2107 				return(EINVAL);
2108 			switch (opt->ip6po_rthdr->ip6r_type) {
2109 			case IPV6_RTHDR_TYPE_0:
2110 				if (opt->ip6po_rthdr->ip6r_segleft == 0)
2111 					return(EINVAL);
2112 				break;
2113 			default:
2114 				return(EINVAL);
2115 			}
2116 			break;
2117 
2118 		default:
2119 			return(ENOPROTOOPT);
2120 		}
2121 	}
2122 
2123 	return(0);
2124 }
2125 
2126 /*
2127  * Routine called from ip6_output() to loop back a copy of an IP6 multicast
2128  * packet to the input queue of a specified interface.  Note that this
2129  * calls the output routine of the loopback "driver", but with an interface
2130  * pointer that might NOT be &loif -- easier than replicating that code here.
2131  */
2132 void
2133 ip6_mloopback(ifp, m, dst)
2134 	struct ifnet *ifp;
2135 	struct mbuf *m;
2136 	struct sockaddr_in6 *dst;
2137 {
2138 	struct mbuf *copym;
2139 	struct ip6_hdr *ip6;
2140 
2141 	copym = m_copy(m, 0, M_COPYALL);
2142 	if (copym == NULL)
2143 		return;
2144 
2145 	/*
2146 	 * Make sure to deep-copy IPv6 header portion in case the data
2147 	 * is in an mbuf cluster, so that we can safely override the IPv6
2148 	 * header portion later.
2149 	 */
2150 	if ((copym->m_flags & M_EXT) != 0 ||
2151 	    copym->m_len < sizeof(struct ip6_hdr)) {
2152 		copym = m_pullup(copym, sizeof(struct ip6_hdr));
2153 		if (copym == NULL)
2154 			return;
2155 	}
2156 
2157 #ifdef DIAGNOSTIC
2158 	if (copym->m_len < sizeof(*ip6)) {
2159 		m_freem(copym);
2160 		return;
2161 	}
2162 #endif
2163 
2164 	ip6 = mtod(copym, struct ip6_hdr *);
2165 	if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_src))
2166 		ip6->ip6_src.s6_addr16[1] = 0;
2167 	if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_dst))
2168 		ip6->ip6_dst.s6_addr16[1] = 0;
2169 
2170 	(void)looutput(ifp, copym, (struct sockaddr *)dst, NULL);
2171 }
2172 
2173 /*
2174  * Chop IPv6 header off from the payload.
2175  */
2176 static int
2177 ip6_splithdr(m, exthdrs)
2178 	struct mbuf *m;
2179 	struct ip6_exthdrs *exthdrs;
2180 {
2181 	struct mbuf *mh;
2182 	struct ip6_hdr *ip6;
2183 
2184 	ip6 = mtod(m, struct ip6_hdr *);
2185 	if (m->m_len > sizeof(*ip6)) {
2186 		MGETHDR(mh, M_DONTWAIT, MT_HEADER);
2187 		if (mh == 0) {
2188 			m_freem(m);
2189 			return ENOBUFS;
2190 		}
2191 		M_COPY_PKTHDR(mh, m);
2192 		MH_ALIGN(mh, sizeof(*ip6));
2193 		m->m_flags &= ~M_PKTHDR;
2194 		m->m_len -= sizeof(*ip6);
2195 		m->m_data += sizeof(*ip6);
2196 		mh->m_next = m;
2197 		m = mh;
2198 		m->m_len = sizeof(*ip6);
2199 		bcopy((caddr_t)ip6, mtod(m, caddr_t), sizeof(*ip6));
2200 	}
2201 	exthdrs->ip6e_ip6 = m;
2202 	return 0;
2203 }
2204 
2205 /*
2206  * Compute IPv6 extension header length.
2207  */
2208 int
2209 ip6_optlen(in6p)
2210 	struct in6pcb *in6p;
2211 {
2212 	int len;
2213 
2214 	if (!in6p->in6p_outputopts)
2215 		return 0;
2216 
2217 	len = 0;
2218 #define elen(x) \
2219     (((struct ip6_ext *)(x)) ? (((struct ip6_ext *)(x))->ip6e_len + 1) << 3 : 0)
2220 
2221 	len += elen(in6p->in6p_outputopts->ip6po_hbh);
2222 	len += elen(in6p->in6p_outputopts->ip6po_dest1);
2223 	len += elen(in6p->in6p_outputopts->ip6po_rthdr);
2224 	len += elen(in6p->in6p_outputopts->ip6po_dest2);
2225 	return len;
2226 #undef elen
2227 }
2228