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