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