xref: /freebsd/sys/netinet6/ip6_output.c (revision cec50dea12481dc578c0805c887ab2097e1c06c5)
1 /*	$FreeBSD$	*/
2 /*	$KAME: ip6_output.c,v 1.279 2002/01/26 06:12:30 jinmei Exp $	*/
3 
4 /*
5  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the project nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32 
33 /*
34  * Copyright (c) 1982, 1986, 1988, 1990, 1993
35  *	The Regents of the University of California.  All rights reserved.
36  *
37  * Redistribution and use in source and binary forms, with or without
38  * modification, are permitted provided that the following conditions
39  * are met:
40  * 1. Redistributions of source code must retain the above copyright
41  *    notice, this list of conditions and the following disclaimer.
42  * 2. Redistributions in binary form must reproduce the above copyright
43  *    notice, this list of conditions and the following disclaimer in the
44  *    documentation and/or other materials provided with the distribution.
45  * 4. Neither the name of the University nor the names of its contributors
46  *    may be used to endorse or promote products derived from this software
47  *    without specific prior written permission.
48  *
49  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
50  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
51  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
52  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
53  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
54  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
55  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
56  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
57  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
58  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
59  * SUCH DAMAGE.
60  *
61  *	@(#)ip_output.c	8.3 (Berkeley) 1/21/94
62  */
63 
64 #include "opt_ip6fw.h"
65 #include "opt_inet.h"
66 #include "opt_inet6.h"
67 #include "opt_ipsec.h"
68 
69 #include <sys/param.h>
70 #include <sys/malloc.h>
71 #include <sys/mbuf.h>
72 #include <sys/proc.h>
73 #include <sys/errno.h>
74 #include <sys/protosw.h>
75 #include <sys/socket.h>
76 #include <sys/socketvar.h>
77 #include <sys/systm.h>
78 #include <sys/kernel.h>
79 
80 #include <net/if.h>
81 #include <net/route.h>
82 #include <net/pfil.h>
83 
84 #include <netinet/in.h>
85 #include <netinet/in_var.h>
86 #include <netinet6/in6_var.h>
87 #include <netinet/ip6.h>
88 #include <netinet/icmp6.h>
89 #include <netinet6/ip6_var.h>
90 #include <netinet/in_pcb.h>
91 #include <netinet/tcp_var.h>
92 #include <netinet6/nd6.h>
93 
94 #ifdef IPSEC
95 #include <netinet6/ipsec.h>
96 #ifdef INET6
97 #include <netinet6/ipsec6.h>
98 #endif
99 #include <netkey/key.h>
100 #endif /* IPSEC */
101 
102 #ifdef FAST_IPSEC
103 #include <netipsec/ipsec.h>
104 #include <netipsec/ipsec6.h>
105 #include <netipsec/key.h>
106 #endif /* FAST_IPSEC */
107 
108 #include <netinet6/ip6_fw.h>
109 
110 #include <net/net_osdep.h>
111 
112 #include <netinet6/ip6protosw.h>
113 
114 static MALLOC_DEFINE(M_IPMOPTS, "ip6_moptions", "internet multicast options");
115 
116 struct ip6_exthdrs {
117 	struct mbuf *ip6e_ip6;
118 	struct mbuf *ip6e_hbh;
119 	struct mbuf *ip6e_dest1;
120 	struct mbuf *ip6e_rthdr;
121 	struct mbuf *ip6e_dest2;
122 };
123 
124 static int ip6_pcbopt __P((int, u_char *, int, struct ip6_pktopts **,
125 			   int, int));
126 static int ip6_pcbopts __P((struct ip6_pktopts **, struct mbuf *,
127 	struct socket *, struct sockopt *));
128 static int ip6_getpcbopt __P((struct ip6_pktopts *, int, struct sockopt *));
129 static int ip6_setpktoption __P((int, u_char *, int, struct ip6_pktopts *, int,
130 	int, int, int));
131 
132 static int ip6_setmoptions __P((int, struct ip6_moptions **, struct mbuf *));
133 static int ip6_getmoptions __P((int, struct ip6_moptions *, struct mbuf **));
134 static int ip6_copyexthdr __P((struct mbuf **, caddr_t, int));
135 static int ip6_insertfraghdr __P((struct mbuf *, struct mbuf *, int,
136 	struct ip6_frag **));
137 static int ip6_insert_jumboopt __P((struct ip6_exthdrs *, u_int32_t));
138 static int ip6_splithdr __P((struct mbuf *, struct ip6_exthdrs *));
139 static int ip6_getpmtu __P((struct route_in6 *, struct route_in6 *,
140 	struct ifnet *, struct in6_addr *, u_long *, int *));
141 
142 
143 /*
144  * IP6 output. The packet in mbuf chain m contains a skeletal IP6
145  * header (with pri, len, nxt, hlim, src, dst).
146  * This function may modify ver and hlim only.
147  * The mbuf chain containing the packet will be freed.
148  * The mbuf opt, if present, will not be freed.
149  *
150  * type of "mtu": rt_rmx.rmx_mtu is u_long, ifnet.ifr_mtu is int, and
151  * nd_ifinfo.linkmtu is u_int32_t.  so we use u_long to hold largest one,
152  * which is rt_rmx.rmx_mtu.
153  */
154 int
155 ip6_output(m0, opt, ro, flags, im6o, ifpp, inp)
156 	struct mbuf *m0;
157 	struct ip6_pktopts *opt;
158 	struct route_in6 *ro;
159 	int flags;
160 	struct ip6_moptions *im6o;
161 	struct ifnet **ifpp;		/* XXX: just for statistics */
162 	struct inpcb *inp;
163 {
164 	struct ip6_hdr *ip6, *mhip6;
165 	struct ifnet *ifp, *origifp;
166 	struct mbuf *m = m0;
167 	int hlen, tlen, len, off;
168 	struct route_in6 ip6route;
169 	struct sockaddr_in6 *dst;
170 	int error = 0;
171 	struct in6_ifaddr *ia = NULL;
172 	u_long mtu;
173 	int alwaysfrag, dontfrag;
174 	u_int32_t optlen = 0, plen = 0, unfragpartlen = 0;
175 	struct ip6_exthdrs exthdrs;
176 	struct in6_addr finaldst;
177 	struct route_in6 *ro_pmtu = NULL;
178 	int hdrsplit = 0;
179 	int needipsec = 0;
180 #if defined(IPSEC) || defined(FAST_IPSEC)
181 	int needipsectun = 0;
182 	struct secpolicy *sp = NULL;
183 #endif /*IPSEC || FAST_IPSEC*/
184 
185 	ip6 = mtod(m, struct ip6_hdr *);
186 	finaldst = ip6->ip6_dst;
187 
188 #define MAKE_EXTHDR(hp, mp)						\
189     do {								\
190 	if (hp) {							\
191 		struct ip6_ext *eh = (struct ip6_ext *)(hp);		\
192 		error = ip6_copyexthdr((mp), (caddr_t)(hp),		\
193 		    ((eh)->ip6e_len + 1) << 3);				\
194 		if (error)						\
195 			goto freehdrs;					\
196 	}								\
197     } while (/*CONSTCOND*/ 0)
198 
199 	bzero(&exthdrs, sizeof(exthdrs));
200 
201 	if (opt) {
202 		/* Hop-by-Hop options header */
203 		MAKE_EXTHDR(opt->ip6po_hbh, &exthdrs.ip6e_hbh);
204 		/* Destination options header(1st part) */
205 		if (opt->ip6po_rthdr) {
206 			/*
207 			 * Destination options header(1st part)
208 			 * This only makes sence with a routing header.
209 			 * See Section 9.2 of RFC 3542.
210 			 * Disabling this part just for MIP6 convenience is
211 			 * a bad idea.  We need to think carefully about a
212 			 * way to make the advanced API coexist with MIP6
213 			 * options, which might automatically be inserted in
214 			 * the kernel.
215 			 */
216 			MAKE_EXTHDR(opt->ip6po_dest1, &exthdrs.ip6e_dest1);
217 		}
218 		/* Routing header */
219 		MAKE_EXTHDR(opt->ip6po_rthdr, &exthdrs.ip6e_rthdr);
220 		/* Destination options header(2nd part) */
221 		MAKE_EXTHDR(opt->ip6po_dest2, &exthdrs.ip6e_dest2);
222 	}
223 
224 #ifdef IPSEC
225 	/* get a security policy for this packet */
226 	if (inp == NULL)
227 		sp = ipsec6_getpolicybyaddr(m, IPSEC_DIR_OUTBOUND, 0, &error);
228 	else
229 		sp = ipsec6_getpolicybypcb(m, IPSEC_DIR_OUTBOUND, inp, &error);
230 
231 	if (sp == NULL) {
232 		ipsec6stat.out_inval++;
233 		goto freehdrs;
234 	}
235 
236 	error = 0;
237 
238 	/* check policy */
239 	switch (sp->policy) {
240 	case IPSEC_POLICY_DISCARD:
241 		/*
242 		 * This packet is just discarded.
243 		 */
244 		ipsec6stat.out_polvio++;
245 		goto freehdrs;
246 
247 	case IPSEC_POLICY_BYPASS:
248 	case IPSEC_POLICY_NONE:
249 		/* no need to do IPsec. */
250 		needipsec = 0;
251 		break;
252 
253 	case IPSEC_POLICY_IPSEC:
254 		if (sp->req == NULL) {
255 			/* acquire a policy */
256 			error = key_spdacquire(sp);
257 			goto freehdrs;
258 		}
259 		needipsec = 1;
260 		break;
261 
262 	case IPSEC_POLICY_ENTRUST:
263 	default:
264 		printf("ip6_output: Invalid policy found. %d\n", sp->policy);
265 	}
266 #endif /* IPSEC */
267 #ifdef FAST_IPSEC
268 	/* get a security policy for this packet */
269 	if (inp == NULL)
270 		sp = ipsec_getpolicybyaddr(m, IPSEC_DIR_OUTBOUND, 0, &error);
271 	else
272 		sp = ipsec_getpolicybysock(m, IPSEC_DIR_OUTBOUND, inp, &error);
273 
274 	if (sp == NULL) {
275 		newipsecstat.ips_out_inval++;
276 		goto freehdrs;
277 	}
278 
279 	error = 0;
280 
281 	/* check policy */
282 	switch (sp->policy) {
283 	case IPSEC_POLICY_DISCARD:
284 		/*
285 		 * This packet is just discarded.
286 		 */
287 		newipsecstat.ips_out_polvio++;
288 		goto freehdrs;
289 
290 	case IPSEC_POLICY_BYPASS:
291 	case IPSEC_POLICY_NONE:
292 		/* no need to do IPsec. */
293 		needipsec = 0;
294 		break;
295 
296 	case IPSEC_POLICY_IPSEC:
297 		if (sp->req == NULL) {
298 			/* acquire a policy */
299 			error = key_spdacquire(sp);
300 			goto freehdrs;
301 		}
302 		needipsec = 1;
303 		break;
304 
305 	case IPSEC_POLICY_ENTRUST:
306 	default:
307 		printf("ip6_output: Invalid policy found. %d\n", sp->policy);
308 	}
309 #endif /* FAST_IPSEC */
310 
311 	/*
312 	 * Calculate the total length of the extension header chain.
313 	 * Keep the length of the unfragmentable part for fragmentation.
314 	 */
315 	optlen = 0;
316 	if (exthdrs.ip6e_hbh) optlen += exthdrs.ip6e_hbh->m_len;
317 	if (exthdrs.ip6e_dest1) optlen += exthdrs.ip6e_dest1->m_len;
318 	if (exthdrs.ip6e_rthdr) optlen += exthdrs.ip6e_rthdr->m_len;
319 	unfragpartlen = optlen + sizeof(struct ip6_hdr);
320 	/* NOTE: we don't add AH/ESP length here. do that later. */
321 	if (exthdrs.ip6e_dest2) optlen += exthdrs.ip6e_dest2->m_len;
322 
323 	/*
324 	 * If we need IPsec, or there is at least one extension header,
325 	 * separate IP6 header from the payload.
326 	 */
327 	if ((needipsec || optlen) && !hdrsplit) {
328 		if ((error = ip6_splithdr(m, &exthdrs)) != 0) {
329 			m = NULL;
330 			goto freehdrs;
331 		}
332 		m = exthdrs.ip6e_ip6;
333 		hdrsplit++;
334 	}
335 
336 	/* adjust pointer */
337 	ip6 = mtod(m, struct ip6_hdr *);
338 
339 	/* adjust mbuf packet header length */
340 	m->m_pkthdr.len += optlen;
341 	plen = m->m_pkthdr.len - sizeof(*ip6);
342 
343 	/* If this is a jumbo payload, insert a jumbo payload option. */
344 	if (plen > IPV6_MAXPACKET) {
345 		if (!hdrsplit) {
346 			if ((error = ip6_splithdr(m, &exthdrs)) != 0) {
347 				m = NULL;
348 				goto freehdrs;
349 			}
350 			m = exthdrs.ip6e_ip6;
351 			hdrsplit++;
352 		}
353 		/* adjust pointer */
354 		ip6 = mtod(m, struct ip6_hdr *);
355 		if ((error = ip6_insert_jumboopt(&exthdrs, plen)) != 0)
356 			goto freehdrs;
357 		ip6->ip6_plen = 0;
358 	} else
359 		ip6->ip6_plen = htons(plen);
360 
361 	/*
362 	 * Concatenate headers and fill in next header fields.
363 	 * Here we have, on "m"
364 	 *	IPv6 payload
365 	 * and we insert headers accordingly.  Finally, we should be getting:
366 	 *	IPv6 hbh dest1 rthdr ah* [esp* dest2 payload]
367 	 *
368 	 * during the header composing process, "m" points to IPv6 header.
369 	 * "mprev" points to an extension header prior to esp.
370 	 */
371 	{
372 		u_char *nexthdrp = &ip6->ip6_nxt;
373 		struct mbuf *mprev = m;
374 
375 		/*
376 		 * we treat dest2 specially.  this makes IPsec processing
377 		 * much easier.  the goal here is to make mprev point the
378 		 * mbuf prior to dest2.
379 		 *
380 		 * result: IPv6 dest2 payload
381 		 * m and mprev will point to IPv6 header.
382 		 */
383 		if (exthdrs.ip6e_dest2) {
384 			if (!hdrsplit)
385 				panic("assumption failed: hdr not split");
386 			exthdrs.ip6e_dest2->m_next = m->m_next;
387 			m->m_next = exthdrs.ip6e_dest2;
388 			*mtod(exthdrs.ip6e_dest2, u_char *) = ip6->ip6_nxt;
389 			ip6->ip6_nxt = IPPROTO_DSTOPTS;
390 		}
391 
392 #define MAKE_CHAIN(m, mp, p, i)\
393     do {\
394 	if (m) {\
395 		if (!hdrsplit) \
396 			panic("assumption failed: hdr not split"); \
397 		*mtod((m), u_char *) = *(p);\
398 		*(p) = (i);\
399 		p = mtod((m), u_char *);\
400 		(m)->m_next = (mp)->m_next;\
401 		(mp)->m_next = (m);\
402 		(mp) = (m);\
403 	}\
404     } while (/*CONSTCOND*/ 0)
405 		/*
406 		 * result: IPv6 hbh dest1 rthdr dest2 payload
407 		 * m will point to IPv6 header.  mprev will point to the
408 		 * extension header prior to dest2 (rthdr in the above case).
409 		 */
410 		MAKE_CHAIN(exthdrs.ip6e_hbh, mprev, nexthdrp, IPPROTO_HOPOPTS);
411 		MAKE_CHAIN(exthdrs.ip6e_dest1, mprev, nexthdrp,
412 		    IPPROTO_DSTOPTS);
413 		MAKE_CHAIN(exthdrs.ip6e_rthdr, mprev, nexthdrp,
414 		    IPPROTO_ROUTING);
415 
416 #if defined(IPSEC) || defined(FAST_IPSEC)
417 		if (!needipsec)
418 			goto skip_ipsec2;
419 
420 		/*
421 		 * pointers after IPsec headers are not valid any more.
422 		 * other pointers need a great care too.
423 		 * (IPsec routines should not mangle mbufs prior to AH/ESP)
424 		 */
425 		exthdrs.ip6e_dest2 = NULL;
426 
427 	    {
428 		struct ip6_rthdr *rh = NULL;
429 		int segleft_org = 0;
430 		struct ipsec_output_state state;
431 
432 		if (exthdrs.ip6e_rthdr) {
433 			rh = mtod(exthdrs.ip6e_rthdr, struct ip6_rthdr *);
434 			segleft_org = rh->ip6r_segleft;
435 			rh->ip6r_segleft = 0;
436 		}
437 
438 		bzero(&state, sizeof(state));
439 		state.m = m;
440 		error = ipsec6_output_trans(&state, nexthdrp, mprev, sp, flags,
441 		    &needipsectun);
442 		m = state.m;
443 		if (error) {
444 			/* mbuf is already reclaimed in ipsec6_output_trans. */
445 			m = NULL;
446 			switch (error) {
447 			case EHOSTUNREACH:
448 			case ENETUNREACH:
449 			case EMSGSIZE:
450 			case ENOBUFS:
451 			case ENOMEM:
452 				break;
453 			default:
454 				printf("ip6_output (ipsec): error code %d\n", error);
455 				/* FALLTHROUGH */
456 			case ENOENT:
457 				/* don't show these error codes to the user */
458 				error = 0;
459 				break;
460 			}
461 			goto bad;
462 		}
463 		if (exthdrs.ip6e_rthdr) {
464 			/* ah6_output doesn't modify mbuf chain */
465 			rh->ip6r_segleft = segleft_org;
466 		}
467 	    }
468 skip_ipsec2:;
469 #endif
470 	}
471 
472 	/*
473 	 * If there is a routing header, replace the destination address field
474 	 * with the first hop of the routing header.
475 	 */
476 	if (exthdrs.ip6e_rthdr) {
477 		struct ip6_rthdr *rh =
478 			(struct ip6_rthdr *)(mtod(exthdrs.ip6e_rthdr,
479 						  struct ip6_rthdr *));
480 		struct ip6_rthdr0 *rh0;
481 		struct in6_addr *addrs;
482 
483 		switch (rh->ip6r_type) {
484 		case IPV6_RTHDR_TYPE_0:
485 			 rh0 = (struct ip6_rthdr0 *)rh;
486 			 addrs = (struct in6_addr *)(rh0 + 1);
487 
488 			 ip6->ip6_dst = *addrs;
489 			 bcopy((caddr_t)(addrs + 1), (caddr_t)addrs,
490 			       sizeof(struct in6_addr)*(rh0->ip6r0_segleft - 1)
491 				 );
492 			 *(addrs + rh0->ip6r0_segleft - 1) = finaldst;
493 			 break;
494 		default:	/* is it possible? */
495 			 error = EINVAL;
496 			 goto bad;
497 		}
498 	}
499 
500 	/* Source address validation */
501 	if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src) &&
502 	    (flags & IPV6_DADOUTPUT) == 0) {
503 		error = EOPNOTSUPP;
504 		ip6stat.ip6s_badscope++;
505 		goto bad;
506 	}
507 	if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_src)) {
508 		error = EOPNOTSUPP;
509 		ip6stat.ip6s_badscope++;
510 		goto bad;
511 	}
512 
513 	ip6stat.ip6s_localout++;
514 
515 	/*
516 	 * Route packet.
517 	 */
518 	if (ro == 0) {
519 		ro = &ip6route;
520 		bzero((caddr_t)ro, sizeof(*ro));
521 	}
522 	ro_pmtu = ro;
523 	if (opt && opt->ip6po_rthdr)
524 		ro = &opt->ip6po_route;
525 	dst = (struct sockaddr_in6 *)&ro->ro_dst;
526 
527 	/*
528 	 * If there is a cached route,
529 	 * check that it is to the same destination
530 	 * and is still up. If not, free it and try again.
531 	 */
532 	if (ro->ro_rt && ((ro->ro_rt->rt_flags & RTF_UP) == 0 ||
533 			 dst->sin6_family != AF_INET6 ||
534 			 !IN6_ARE_ADDR_EQUAL(&dst->sin6_addr, &ip6->ip6_dst))) {
535 		RTFREE(ro->ro_rt);
536 		ro->ro_rt = (struct rtentry *)0;
537 	}
538 	if (ro->ro_rt == 0) {
539 		bzero(dst, sizeof(*dst));
540 		dst->sin6_family = AF_INET6;
541 		dst->sin6_len = sizeof(struct sockaddr_in6);
542 		dst->sin6_addr = ip6->ip6_dst;
543 	}
544 
545  	/*
546 	 * if specified, try to fill in the traffic class field.
547 	 * do not override if a non-zero value is already set.
548 	 * we check the diffserv field and the ecn field separately.
549 	 */
550 	if (opt && opt->ip6po_tclass >= 0) {
551 		int mask = 0;
552 
553 		if ((ip6->ip6_flow & htonl(0xfc << 20)) == 0)
554 			mask |= 0xfc;
555 		if ((ip6->ip6_flow & htonl(0x03 << 20)) == 0)
556 			mask |= 0x03;
557 		if (mask != 0)
558 			ip6->ip6_flow |= htonl((opt->ip6po_tclass & mask) << 20);
559 	}
560 
561 	/* fill in or override the hop limit field, if necessary. */
562 	if (opt && opt->ip6po_hlim != -1)
563 		ip6->ip6_hlim = opt->ip6po_hlim & 0xff;
564 	else if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
565 		if (im6o != NULL)
566 			ip6->ip6_hlim = im6o->im6o_multicast_hlim;
567 		else
568 			ip6->ip6_hlim = ip6_defmcasthlim;
569 	}
570 
571 #if defined(IPSEC) || defined(FAST_IPSEC)
572 	if (needipsec && needipsectun) {
573 		struct ipsec_output_state state;
574 
575 		/*
576 		 * All the extension headers will become inaccessible
577 		 * (since they can be encrypted).
578 		 * Don't panic, we need no more updates to extension headers
579 		 * on inner IPv6 packet (since they are now encapsulated).
580 		 *
581 		 * IPv6 [ESP|AH] IPv6 [extension headers] payload
582 		 */
583 		bzero(&exthdrs, sizeof(exthdrs));
584 		exthdrs.ip6e_ip6 = m;
585 
586 		bzero(&state, sizeof(state));
587 		state.m = m;
588 		state.ro = (struct route *)ro;
589 		state.dst = (struct sockaddr *)dst;
590 
591 		error = ipsec6_output_tunnel(&state, sp, flags);
592 
593 		m = state.m;
594 		ro = (struct route_in6 *)state.ro;
595 		dst = (struct sockaddr_in6 *)state.dst;
596 		if (error) {
597 			/* mbuf is already reclaimed in ipsec6_output_tunnel. */
598 			m0 = m = NULL;
599 			m = NULL;
600 			switch (error) {
601 			case EHOSTUNREACH:
602 			case ENETUNREACH:
603 			case EMSGSIZE:
604 			case ENOBUFS:
605 			case ENOMEM:
606 				break;
607 			default:
608 				printf("ip6_output (ipsec): error code %d\n", error);
609 				/* FALLTHROUGH */
610 			case ENOENT:
611 				/* don't show these error codes to the user */
612 				error = 0;
613 				break;
614 			}
615 			goto bad;
616 		}
617 
618 		exthdrs.ip6e_ip6 = m;
619 	}
620 #endif /* IPSEC */
621 
622 	if (!IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
623 		/* Unicast */
624 
625 #define ifatoia6(ifa)	((struct in6_ifaddr *)(ifa))
626 #define sin6tosa(sin6)	((struct sockaddr *)(sin6))
627 		/* xxx
628 		 * interface selection comes here
629 		 * if an interface is specified from an upper layer,
630 		 * ifp must point it.
631 		 */
632 		if (ro->ro_rt == 0) {
633 			/*
634 			 * non-bsdi always clone routes, if parent is
635 			 * PRF_CLONING.
636 			 */
637 			rtalloc((struct route *)ro);
638 		}
639 		if (ro->ro_rt == 0) {
640 			ip6stat.ip6s_noroute++;
641 			error = EHOSTUNREACH;
642 			/* XXX in6_ifstat_inc(ifp, ifs6_out_discard); */
643 			goto bad;
644 		}
645 		/* XXX rt not locked */
646 		ia = ifatoia6(ro->ro_rt->rt_ifa);
647 		ifp = ro->ro_rt->rt_ifp;
648 		ro->ro_rt->rt_rmx.rmx_pksent++;
649 		if (ro->ro_rt->rt_flags & RTF_GATEWAY)
650 			dst = (struct sockaddr_in6 *)ro->ro_rt->rt_gateway;
651 		m->m_flags &= ~(M_BCAST | M_MCAST);	/* just in case */
652 
653 		in6_ifstat_inc(ifp, ifs6_out_request);
654 
655 		/*
656 		 * Check if the outgoing interface conflicts with
657 		 * the interface specified by ifi6_ifindex (if specified).
658 		 * Note that loopback interface is always okay.
659 		 * (this may happen when we are sending a packet to one of
660 		 *  our own addresses.)
661 		 */
662 		if (opt && opt->ip6po_pktinfo
663 		 && opt->ip6po_pktinfo->ipi6_ifindex) {
664 			if (!(ifp->if_flags & IFF_LOOPBACK)
665 			 && ifp->if_index != opt->ip6po_pktinfo->ipi6_ifindex) {
666 				ip6stat.ip6s_noroute++;
667 				in6_ifstat_inc(ifp, ifs6_out_discard);
668 				error = EHOSTUNREACH;
669 				goto bad;
670 			}
671 		}
672 
673 		if (opt && opt->ip6po_hlim != -1)
674 			ip6->ip6_hlim = opt->ip6po_hlim & 0xff;
675 	} else {
676 		/* Multicast */
677 		struct	in6_multi *in6m;
678 
679 		m->m_flags = (m->m_flags & ~M_BCAST) | M_MCAST;
680 
681 		/*
682 		 * See if the caller provided any multicast options
683 		 */
684 		ifp = NULL;
685 		if (im6o != NULL) {
686 			ip6->ip6_hlim = im6o->im6o_multicast_hlim;
687 			if (im6o->im6o_multicast_ifp != NULL)
688 				ifp = im6o->im6o_multicast_ifp;
689 		} else
690 			ip6->ip6_hlim = ip6_defmcasthlim;
691 
692 		/*
693 		 * See if the caller provided the outgoing interface
694 		 * as an ancillary data.
695 		 * Boundary check for ifindex is assumed to be already done.
696 		 */
697 		if (opt && opt->ip6po_pktinfo && opt->ip6po_pktinfo->ipi6_ifindex)
698 			ifp = ifnet_byindex(opt->ip6po_pktinfo->ipi6_ifindex);
699 
700 		/*
701 		 * If the destination is a node-local scope multicast,
702 		 * the packet should be loop-backed only.
703 		 */
704 		if (IN6_IS_ADDR_MC_INTFACELOCAL(&ip6->ip6_dst)) {
705 			/*
706 			 * If the outgoing interface is already specified,
707 			 * it should be a loopback interface.
708 			 */
709 			if (ifp && (ifp->if_flags & IFF_LOOPBACK) == 0) {
710 				ip6stat.ip6s_badscope++;
711 				error = ENETUNREACH; /* XXX: better error? */
712 				/* XXX correct ifp? */
713 				in6_ifstat_inc(ifp, ifs6_out_discard);
714 				goto bad;
715 			} else {
716 				ifp = &loif[0];
717 			}
718 		}
719 
720 		if (opt && opt->ip6po_hlim != -1)
721 			ip6->ip6_hlim = opt->ip6po_hlim & 0xff;
722 
723 		/*
724 		 * If caller did not provide an interface lookup a
725 		 * default in the routing table.  This is either a
726 		 * default for the speicfied group (i.e. a host
727 		 * route), or a multicast default (a route for the
728 		 * ``net'' ff00::/8).
729 		 */
730 		if (ifp == NULL) {
731 			if (ro->ro_rt == 0)
732 				ro->ro_rt = rtalloc1((struct sockaddr *)
733 						&ro->ro_dst, 0, 0UL);
734 			else
735 				RT_LOCK(ro->ro_rt);
736 			if (ro->ro_rt == 0) {
737 				ip6stat.ip6s_noroute++;
738 				error = EHOSTUNREACH;
739 				/* XXX in6_ifstat_inc(ifp, ifs6_out_discard) */
740 				goto bad;
741 			}
742 			ia = ifatoia6(ro->ro_rt->rt_ifa);
743 			ifp = ro->ro_rt->rt_ifp;
744 			ro->ro_rt->rt_rmx.rmx_pksent++;
745 			RT_UNLOCK(ro->ro_rt);
746 		}
747 
748 		if ((flags & IPV6_FORWARDING) == 0)
749 			in6_ifstat_inc(ifp, ifs6_out_request);
750 		in6_ifstat_inc(ifp, ifs6_out_mcast);
751 
752 		/*
753 		 * Confirm that the outgoing interface supports multicast.
754 		 */
755 		if ((ifp->if_flags & IFF_MULTICAST) == 0) {
756 			ip6stat.ip6s_noroute++;
757 			in6_ifstat_inc(ifp, ifs6_out_discard);
758 			error = ENETUNREACH;
759 			goto bad;
760 		}
761 		IN6_LOOKUP_MULTI(ip6->ip6_dst, ifp, in6m);
762 		if (in6m != NULL &&
763 		   (im6o == NULL || im6o->im6o_multicast_loop)) {
764 			/*
765 			 * If we belong to the destination multicast group
766 			 * on the outgoing interface, and the caller did not
767 			 * forbid loopback, loop back a copy.
768 			 */
769 			ip6_mloopback(ifp, m, dst);
770 		} else {
771 			/*
772 			 * If we are acting as a multicast router, perform
773 			 * multicast forwarding as if the packet had just
774 			 * arrived on the interface to which we are about
775 			 * to send.  The multicast forwarding function
776 			 * recursively calls this function, using the
777 			 * IPV6_FORWARDING flag to prevent infinite recursion.
778 			 *
779 			 * Multicasts that are looped back by ip6_mloopback(),
780 			 * above, will be forwarded by the ip6_input() routine,
781 			 * if necessary.
782 			 */
783 			if (ip6_mrouter && (flags & IPV6_FORWARDING) == 0) {
784 				if (ip6_mforward(ip6, ifp, m) != 0) {
785 					m_freem(m);
786 					goto done;
787 				}
788 			}
789 		}
790 		/*
791 		 * Multicasts with a hoplimit of zero may be looped back,
792 		 * above, but must not be transmitted on a network.
793 		 * Also, multicasts addressed to the loopback interface
794 		 * are not sent -- the above call to ip6_mloopback() will
795 		 * loop back a copy if this host actually belongs to the
796 		 * destination group on the loopback interface.
797 		 */
798 		if (ip6->ip6_hlim == 0 || (ifp->if_flags & IFF_LOOPBACK) ||
799 		    IN6_IS_ADDR_MC_INTFACELOCAL(&ip6->ip6_dst)) {
800 			m_freem(m);
801 			goto done;
802 		}
803 	}
804 
805 	/*
806 	 * Fill the outgoing inteface to tell the upper layer
807 	 * to increment per-interface statistics.
808 	 */
809 	if (ifpp)
810 		*ifpp = ifp;
811 
812 	/* Determine path MTU. */
813 	if ((error = ip6_getpmtu(ro_pmtu, ro, ifp, &finaldst, &mtu,
814 	    &alwaysfrag)) != 0)
815 		goto bad;
816 
817 	/*
818 	 * The caller of this function may specify to use the minimum MTU
819 	 * in some cases.
820 	 * An advanced API option (IPV6_USE_MIN_MTU) can also override MTU
821 	 * setting.  The logic is a bit complicated; by default, unicast
822 	 * packets will follow path MTU while multicast packets will be sent at
823 	 * the minimum MTU.  If IP6PO_MINMTU_ALL is specified, all packets
824 	 * including unicast ones will be sent at the minimum MTU.  Multicast
825 	 * packets will always be sent at the minimum MTU unless
826 	 * IP6PO_MINMTU_DISABLE is explicitly specified.
827 	 * See RFC 3542 for more details.
828 	 */
829 	if (mtu > IPV6_MMTU) {
830 		if ((flags & IPV6_MINMTU))
831 			mtu = IPV6_MMTU;
832 		else if (opt && opt->ip6po_minmtu == IP6PO_MINMTU_ALL)
833 			mtu = IPV6_MMTU;
834 		else if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) &&
835 			 (opt == NULL ||
836 			  opt->ip6po_minmtu != IP6PO_MINMTU_DISABLE)) {
837 			mtu = IPV6_MMTU;
838 		}
839 	}
840 
841 	/* Fake scoped addresses */
842 	if ((ifp->if_flags & IFF_LOOPBACK) != 0) {
843 		/*
844 		 * If source or destination address is a scoped address, and
845 		 * the packet is going to be sent to a loopback interface,
846 		 * we should keep the original interface.
847 		 */
848 
849 		/*
850 		 * XXX: this is a very experimental and temporary solution.
851 		 * We eventually have sockaddr_in6 and use the sin6_scope_id
852 		 * field of the structure here.
853 		 * We rely on the consistency between two scope zone ids
854 		 * of source and destination, which should already be assured.
855 		 * Larger scopes than link will be supported in the future.
856 		 */
857 		origifp = NULL;
858 		if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_src))
859 			origifp = ifnet_byindex(ntohs(ip6->ip6_src.s6_addr16[1]));
860 		else if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_dst))
861 			origifp = ifnet_byindex(ntohs(ip6->ip6_dst.s6_addr16[1]));
862 		/*
863 		 * XXX: origifp can be NULL even in those two cases above.
864 		 * For example, if we remove the (only) link-local address
865 		 * from the loopback interface, and try to send a link-local
866 		 * address without link-id information.  Then the source
867 		 * address is ::1, and the destination address is the
868 		 * link-local address with its s6_addr16[1] being zero.
869 		 * What is worse, if the packet goes to the loopback interface
870 		 * by a default rejected route, the null pointer would be
871 		 * passed to looutput, and the kernel would hang.
872 		 * The following last resort would prevent such disaster.
873 		 */
874 		if (origifp == NULL)
875 			origifp = ifp;
876 	}
877 	else
878 		origifp = ifp;
879 	/*
880 	 * clear embedded scope identifiers if necessary.
881 	 * in6_clearscope will touch the addresses only when necessary.
882 	 */
883 	in6_clearscope(&ip6->ip6_src);
884 	in6_clearscope(&ip6->ip6_dst);
885 
886 	/*
887 	 * Check with the firewall...
888 	 */
889 	if (ip6_fw_enable && ip6_fw_chk_ptr) {
890 		u_short port = 0;
891 		m->m_pkthdr.rcvif = NULL;	/* XXX */
892 		/* If ipfw says divert, we have to just drop packet */
893 		if ((*ip6_fw_chk_ptr)(&ip6, ifp, &port, &m)) {
894 			m_freem(m);
895 			goto done;
896 		}
897 		if (!m) {
898 			error = EACCES;
899 			goto done;
900 		}
901 	}
902 
903 	/*
904 	 * If the outgoing packet contains a hop-by-hop options header,
905 	 * it must be examined and processed even by the source node.
906 	 * (RFC 2460, section 4.)
907 	 */
908 	if (exthdrs.ip6e_hbh) {
909 		struct ip6_hbh *hbh = mtod(exthdrs.ip6e_hbh, struct ip6_hbh *);
910 		u_int32_t dummy1; /* XXX unused */
911 		u_int32_t dummy2; /* XXX unused */
912 
913 #ifdef DIAGNOSTIC
914 		if ((hbh->ip6h_len + 1) << 3 > exthdrs.ip6e_hbh->m_len)
915 			panic("ip6e_hbh is not continuous");
916 #endif
917 		/*
918 		 *  XXX: if we have to send an ICMPv6 error to the sender,
919 		 *       we need the M_LOOP flag since icmp6_error() expects
920 		 *       the IPv6 and the hop-by-hop options header are
921 		 *       continuous unless the flag is set.
922 		 */
923 		m->m_flags |= M_LOOP;
924 		m->m_pkthdr.rcvif = ifp;
925 		if (ip6_process_hopopts(m, (u_int8_t *)(hbh + 1),
926 		    ((hbh->ip6h_len + 1) << 3) - sizeof(struct ip6_hbh),
927 		    &dummy1, &dummy2) < 0) {
928 			/* m was already freed at this point */
929 			error = EINVAL;/* better error? */
930 			goto done;
931 		}
932 		m->m_flags &= ~M_LOOP; /* XXX */
933 		m->m_pkthdr.rcvif = NULL;
934 	}
935 
936 	/* Jump over all PFIL processing if hooks are not active. */
937 	if (inet6_pfil_hook.ph_busy_count == -1)
938 		goto passout;
939 
940 	/* Run through list of hooks for output packets. */
941 	error = pfil_run_hooks(&inet6_pfil_hook, &m, ifp, PFIL_OUT);
942 	if (error != 0 || m == NULL)
943 		goto done;
944 	ip6 = mtod(m, struct ip6_hdr *);
945 
946 passout:
947 	/*
948 	 * Send the packet to the outgoing interface.
949 	 * If necessary, do IPv6 fragmentation before sending.
950 	 *
951 	 * the logic here is rather complex:
952 	 * 1: normal case (dontfrag == 0, alwaysfrag == 0)
953 	 * 1-a:	send as is if tlen <= path mtu
954 	 * 1-b:	fragment if tlen > path mtu
955 	 *
956 	 * 2: if user asks us not to fragment (dontfrag == 1)
957 	 * 2-a:	send as is if tlen <= interface mtu
958 	 * 2-b:	error if tlen > interface mtu
959 	 *
960 	 * 3: if we always need to attach fragment header (alwaysfrag == 1)
961 	 *	always fragment
962 	 *
963 	 * 4: if dontfrag == 1 && alwaysfrag == 1
964 	 *	error, as we cannot handle this conflicting request
965 	 */
966 	tlen = m->m_pkthdr.len;
967 
968 	if (opt && (opt->ip6po_flags & IP6PO_DONTFRAG))
969 		dontfrag = 1;
970 	else
971 		dontfrag = 0;
972 	if (dontfrag && alwaysfrag) {	/* case 4 */
973 		/* conflicting request - can't transmit */
974 		error = EMSGSIZE;
975 		goto bad;
976 	}
977 	if (dontfrag && tlen > IN6_LINKMTU(ifp)) {	/* case 2-b */
978 		/*
979 		 * Even if the DONTFRAG option is specified, we cannot send the
980 		 * packet when the data length is larger than the MTU of the
981 		 * outgoing interface.
982 		 * Notify the error by sending IPV6_PATHMTU ancillary data as
983 		 * well as returning an error code (the latter is not described
984 		 * in the API spec.)
985 		 */
986 		u_int32_t mtu32;
987 		struct ip6ctlparam ip6cp;
988 
989 		mtu32 = (u_int32_t)mtu;
990 		bzero(&ip6cp, sizeof(ip6cp));
991 		ip6cp.ip6c_cmdarg = (void *)&mtu32;
992 		pfctlinput2(PRC_MSGSIZE, (struct sockaddr *)&ro_pmtu->ro_dst,
993 		    (void *)&ip6cp);
994 
995 		error = EMSGSIZE;
996 		goto bad;
997 	}
998 
999 	/*
1000 	 * transmit packet without fragmentation
1001 	 */
1002 	if (dontfrag || (!alwaysfrag && tlen <= mtu)) {	/* case 1-a and 2-a */
1003 		struct in6_ifaddr *ia6;
1004 
1005 		ip6 = mtod(m, struct ip6_hdr *);
1006 		ia6 = in6_ifawithifp(ifp, &ip6->ip6_src);
1007 		if (ia6) {
1008 			/* Record statistics for this interface address. */
1009 			ia6->ia_ifa.if_opackets++;
1010 			ia6->ia_ifa.if_obytes += m->m_pkthdr.len;
1011 		}
1012 #ifdef IPSEC
1013 		/* clean ipsec history once it goes out of the node */
1014 		ipsec_delaux(m);
1015 #endif
1016 		error = nd6_output(ifp, origifp, m, dst, ro->ro_rt);
1017 		goto done;
1018 	}
1019 
1020 	/*
1021 	 * try to fragment the packet.  case 1-b and 3
1022 	 */
1023 	if (mtu < IPV6_MMTU) {
1024 		/* path MTU cannot be less than IPV6_MMTU */
1025 		error = EMSGSIZE;
1026 		in6_ifstat_inc(ifp, ifs6_out_fragfail);
1027 		goto bad;
1028 	} else if (ip6->ip6_plen == 0) {
1029 		/* jumbo payload cannot be fragmented */
1030 		error = EMSGSIZE;
1031 		in6_ifstat_inc(ifp, ifs6_out_fragfail);
1032 		goto bad;
1033 	} else {
1034 		struct mbuf **mnext, *m_frgpart;
1035 		struct ip6_frag *ip6f;
1036 		u_int32_t id = htonl(ip6_randomid());
1037 		u_char nextproto;
1038 		struct ip6ctlparam ip6cp;
1039 		u_int32_t mtu32;
1040 		int qslots = ifp->if_snd.ifq_maxlen - ifp->if_snd.ifq_len;
1041 
1042 		/*
1043 		 * Too large for the destination or interface;
1044 		 * fragment if possible.
1045 		 * Must be able to put at least 8 bytes per fragment.
1046 		 */
1047 		hlen = unfragpartlen;
1048 		if (mtu > IPV6_MAXPACKET)
1049 			mtu = IPV6_MAXPACKET;
1050 
1051 		/* Notify a proper path MTU to applications. */
1052 		mtu32 = (u_int32_t)mtu;
1053 		bzero(&ip6cp, sizeof(ip6cp));
1054 		ip6cp.ip6c_cmdarg = (void *)&mtu32;
1055 		pfctlinput2(PRC_MSGSIZE, (struct sockaddr *)&ro_pmtu->ro_dst,
1056 		    (void *)&ip6cp);
1057 
1058 		len = (mtu - hlen - sizeof(struct ip6_frag)) & ~7;
1059 		if (len < 8) {
1060 			error = EMSGSIZE;
1061 			in6_ifstat_inc(ifp, ifs6_out_fragfail);
1062 			goto bad;
1063 		}
1064 
1065 		/*
1066 		 * Verify that we have any chance at all of being able to queue
1067 		 *      the packet or packet fragments
1068 		 */
1069 		if (qslots <= 0 || ((u_int)qslots * (mtu - hlen)
1070 		    < tlen  /* - hlen */)) {
1071 			error = ENOBUFS;
1072 			ip6stat.ip6s_odropped++;
1073 			goto bad;
1074 		}
1075 
1076 		mnext = &m->m_nextpkt;
1077 
1078 		/*
1079 		 * Change the next header field of the last header in the
1080 		 * unfragmentable part.
1081 		 */
1082 		if (exthdrs.ip6e_rthdr) {
1083 			nextproto = *mtod(exthdrs.ip6e_rthdr, u_char *);
1084 			*mtod(exthdrs.ip6e_rthdr, u_char *) = IPPROTO_FRAGMENT;
1085 		} else if (exthdrs.ip6e_dest1) {
1086 			nextproto = *mtod(exthdrs.ip6e_dest1, u_char *);
1087 			*mtod(exthdrs.ip6e_dest1, u_char *) = IPPROTO_FRAGMENT;
1088 		} else if (exthdrs.ip6e_hbh) {
1089 			nextproto = *mtod(exthdrs.ip6e_hbh, u_char *);
1090 			*mtod(exthdrs.ip6e_hbh, u_char *) = IPPROTO_FRAGMENT;
1091 		} else {
1092 			nextproto = ip6->ip6_nxt;
1093 			ip6->ip6_nxt = IPPROTO_FRAGMENT;
1094 		}
1095 
1096 		/*
1097 		 * Loop through length of segment after first fragment,
1098 		 * make new header and copy data of each part and link onto
1099 		 * chain.
1100 		 */
1101 		m0 = m;
1102 		for (off = hlen; off < tlen; off += len) {
1103 			MGETHDR(m, M_DONTWAIT, MT_HEADER);
1104 			if (!m) {
1105 				error = ENOBUFS;
1106 				ip6stat.ip6s_odropped++;
1107 				goto sendorfree;
1108 			}
1109 			m->m_pkthdr.rcvif = NULL;
1110 			m->m_flags = m0->m_flags & M_COPYFLAGS;
1111 			*mnext = m;
1112 			mnext = &m->m_nextpkt;
1113 			m->m_data += max_linkhdr;
1114 			mhip6 = mtod(m, struct ip6_hdr *);
1115 			*mhip6 = *ip6;
1116 			m->m_len = sizeof(*mhip6);
1117 			error = ip6_insertfraghdr(m0, m, hlen, &ip6f);
1118 			if (error) {
1119 				ip6stat.ip6s_odropped++;
1120 				goto sendorfree;
1121 			}
1122 			ip6f->ip6f_offlg = htons((u_short)((off - hlen) & ~7));
1123 			if (off + len >= tlen)
1124 				len = tlen - off;
1125 			else
1126 				ip6f->ip6f_offlg |= IP6F_MORE_FRAG;
1127 			mhip6->ip6_plen = htons((u_short)(len + hlen +
1128 			    sizeof(*ip6f) - sizeof(struct ip6_hdr)));
1129 			if ((m_frgpart = m_copy(m0, off, len)) == 0) {
1130 				error = ENOBUFS;
1131 				ip6stat.ip6s_odropped++;
1132 				goto sendorfree;
1133 			}
1134 			m_cat(m, m_frgpart);
1135 			m->m_pkthdr.len = len + hlen + sizeof(*ip6f);
1136 			m->m_pkthdr.rcvif = (struct ifnet *)0;
1137 			ip6f->ip6f_reserved = 0;
1138 			ip6f->ip6f_ident = id;
1139 			ip6f->ip6f_nxt = nextproto;
1140 			ip6stat.ip6s_ofragments++;
1141 			in6_ifstat_inc(ifp, ifs6_out_fragcreat);
1142 		}
1143 
1144 		in6_ifstat_inc(ifp, ifs6_out_fragok);
1145 	}
1146 
1147 	/*
1148 	 * Remove leading garbages.
1149 	 */
1150 sendorfree:
1151 	m = m0->m_nextpkt;
1152 	m0->m_nextpkt = 0;
1153 	m_freem(m0);
1154 	for (m0 = m; m; m = m0) {
1155 		m0 = m->m_nextpkt;
1156 		m->m_nextpkt = 0;
1157 		if (error == 0) {
1158  			/* Record statistics for this interface address. */
1159  			if (ia) {
1160  				ia->ia_ifa.if_opackets++;
1161  				ia->ia_ifa.if_obytes += m->m_pkthdr.len;
1162  			}
1163 #ifdef IPSEC
1164 			/* clean ipsec history once it goes out of the node */
1165 			ipsec_delaux(m);
1166 #endif
1167 			error = nd6_output(ifp, origifp, m, dst, ro->ro_rt);
1168 		} else
1169 			m_freem(m);
1170 	}
1171 
1172 	if (error == 0)
1173 		ip6stat.ip6s_fragmented++;
1174 
1175 done:
1176 	if (ro == &ip6route && ro->ro_rt) { /* brace necessary for RTFREE */
1177 		RTFREE(ro->ro_rt);
1178 	} else if (ro_pmtu == &ip6route && ro_pmtu->ro_rt) {
1179 		RTFREE(ro_pmtu->ro_rt);
1180 	}
1181 
1182 #ifdef IPSEC
1183 	if (sp != NULL)
1184 		key_freesp(sp);
1185 #endif /* IPSEC */
1186 #ifdef FAST_IPSEC
1187 	if (sp != NULL)
1188 		KEY_FREESP(&sp);
1189 #endif /* FAST_IPSEC */
1190 
1191 	return (error);
1192 
1193 freehdrs:
1194 	m_freem(exthdrs.ip6e_hbh);	/* m_freem will check if mbuf is 0 */
1195 	m_freem(exthdrs.ip6e_dest1);
1196 	m_freem(exthdrs.ip6e_rthdr);
1197 	m_freem(exthdrs.ip6e_dest2);
1198 	/* FALLTHROUGH */
1199 bad:
1200 	m_freem(m);
1201 	goto done;
1202 }
1203 
1204 static int
1205 ip6_copyexthdr(mp, hdr, hlen)
1206 	struct mbuf **mp;
1207 	caddr_t hdr;
1208 	int hlen;
1209 {
1210 	struct mbuf *m;
1211 
1212 	if (hlen > MCLBYTES)
1213 		return (ENOBUFS); /* XXX */
1214 
1215 	MGET(m, M_DONTWAIT, MT_DATA);
1216 	if (!m)
1217 		return (ENOBUFS);
1218 
1219 	if (hlen > MLEN) {
1220 		MCLGET(m, M_DONTWAIT);
1221 		if ((m->m_flags & M_EXT) == 0) {
1222 			m_free(m);
1223 			return (ENOBUFS);
1224 		}
1225 	}
1226 	m->m_len = hlen;
1227 	if (hdr)
1228 		bcopy(hdr, mtod(m, caddr_t), hlen);
1229 
1230 	*mp = m;
1231 	return (0);
1232 }
1233 
1234 /*
1235  * Insert jumbo payload option.
1236  */
1237 static int
1238 ip6_insert_jumboopt(exthdrs, plen)
1239 	struct ip6_exthdrs *exthdrs;
1240 	u_int32_t plen;
1241 {
1242 	struct mbuf *mopt;
1243 	u_char *optbuf;
1244 	u_int32_t v;
1245 
1246 #define JUMBOOPTLEN	8	/* length of jumbo payload option and padding */
1247 
1248 	/*
1249 	 * If there is no hop-by-hop options header, allocate new one.
1250 	 * If there is one but it doesn't have enough space to store the
1251 	 * jumbo payload option, allocate a cluster to store the whole options.
1252 	 * Otherwise, use it to store the options.
1253 	 */
1254 	if (exthdrs->ip6e_hbh == 0) {
1255 		MGET(mopt, M_DONTWAIT, MT_DATA);
1256 		if (mopt == 0)
1257 			return (ENOBUFS);
1258 		mopt->m_len = JUMBOOPTLEN;
1259 		optbuf = mtod(mopt, u_char *);
1260 		optbuf[1] = 0;	/* = ((JUMBOOPTLEN) >> 3) - 1 */
1261 		exthdrs->ip6e_hbh = mopt;
1262 	} else {
1263 		struct ip6_hbh *hbh;
1264 
1265 		mopt = exthdrs->ip6e_hbh;
1266 		if (M_TRAILINGSPACE(mopt) < JUMBOOPTLEN) {
1267 			/*
1268 			 * XXX assumption:
1269 			 * - exthdrs->ip6e_hbh is not referenced from places
1270 			 *   other than exthdrs.
1271 			 * - exthdrs->ip6e_hbh is not an mbuf chain.
1272 			 */
1273 			int oldoptlen = mopt->m_len;
1274 			struct mbuf *n;
1275 
1276 			/*
1277 			 * XXX: give up if the whole (new) hbh header does
1278 			 * not fit even in an mbuf cluster.
1279 			 */
1280 			if (oldoptlen + JUMBOOPTLEN > MCLBYTES)
1281 				return (ENOBUFS);
1282 
1283 			/*
1284 			 * As a consequence, we must always prepare a cluster
1285 			 * at this point.
1286 			 */
1287 			MGET(n, M_DONTWAIT, MT_DATA);
1288 			if (n) {
1289 				MCLGET(n, M_DONTWAIT);
1290 				if ((n->m_flags & M_EXT) == 0) {
1291 					m_freem(n);
1292 					n = NULL;
1293 				}
1294 			}
1295 			if (!n)
1296 				return (ENOBUFS);
1297 			n->m_len = oldoptlen + JUMBOOPTLEN;
1298 			bcopy(mtod(mopt, caddr_t), mtod(n, caddr_t),
1299 			    oldoptlen);
1300 			optbuf = mtod(n, caddr_t) + oldoptlen;
1301 			m_freem(mopt);
1302 			mopt = exthdrs->ip6e_hbh = n;
1303 		} else {
1304 			optbuf = mtod(mopt, u_char *) + mopt->m_len;
1305 			mopt->m_len += JUMBOOPTLEN;
1306 		}
1307 		optbuf[0] = IP6OPT_PADN;
1308 		optbuf[1] = 1;
1309 
1310 		/*
1311 		 * Adjust the header length according to the pad and
1312 		 * the jumbo payload option.
1313 		 */
1314 		hbh = mtod(mopt, struct ip6_hbh *);
1315 		hbh->ip6h_len += (JUMBOOPTLEN >> 3);
1316 	}
1317 
1318 	/* fill in the option. */
1319 	optbuf[2] = IP6OPT_JUMBO;
1320 	optbuf[3] = 4;
1321 	v = (u_int32_t)htonl(plen + JUMBOOPTLEN);
1322 	bcopy(&v, &optbuf[4], sizeof(u_int32_t));
1323 
1324 	/* finally, adjust the packet header length */
1325 	exthdrs->ip6e_ip6->m_pkthdr.len += JUMBOOPTLEN;
1326 
1327 	return (0);
1328 #undef JUMBOOPTLEN
1329 }
1330 
1331 /*
1332  * Insert fragment header and copy unfragmentable header portions.
1333  */
1334 static int
1335 ip6_insertfraghdr(m0, m, hlen, frghdrp)
1336 	struct mbuf *m0, *m;
1337 	int hlen;
1338 	struct ip6_frag **frghdrp;
1339 {
1340 	struct mbuf *n, *mlast;
1341 
1342 	if (hlen > sizeof(struct ip6_hdr)) {
1343 		n = m_copym(m0, sizeof(struct ip6_hdr),
1344 		    hlen - sizeof(struct ip6_hdr), M_DONTWAIT);
1345 		if (n == 0)
1346 			return (ENOBUFS);
1347 		m->m_next = n;
1348 	} else
1349 		n = m;
1350 
1351 	/* Search for the last mbuf of unfragmentable part. */
1352 	for (mlast = n; mlast->m_next; mlast = mlast->m_next)
1353 		;
1354 
1355 	if ((mlast->m_flags & M_EXT) == 0 &&
1356 	    M_TRAILINGSPACE(mlast) >= sizeof(struct ip6_frag)) {
1357 		/* use the trailing space of the last mbuf for the fragment hdr */
1358 		*frghdrp = (struct ip6_frag *)(mtod(mlast, caddr_t) +
1359 		    mlast->m_len);
1360 		mlast->m_len += sizeof(struct ip6_frag);
1361 		m->m_pkthdr.len += sizeof(struct ip6_frag);
1362 	} else {
1363 		/* allocate a new mbuf for the fragment header */
1364 		struct mbuf *mfrg;
1365 
1366 		MGET(mfrg, M_DONTWAIT, MT_DATA);
1367 		if (mfrg == 0)
1368 			return (ENOBUFS);
1369 		mfrg->m_len = sizeof(struct ip6_frag);
1370 		*frghdrp = mtod(mfrg, struct ip6_frag *);
1371 		mlast->m_next = mfrg;
1372 	}
1373 
1374 	return (0);
1375 }
1376 
1377 static int
1378 ip6_getpmtu(ro_pmtu, ro, ifp, dst, mtup, alwaysfragp)
1379 	struct route_in6 *ro_pmtu, *ro;
1380 	struct ifnet *ifp;
1381 	struct in6_addr *dst;
1382 	u_long *mtup;
1383 	int *alwaysfragp;
1384 {
1385 	u_int32_t mtu = 0;
1386 	int alwaysfrag = 0;
1387 	int error = 0;
1388 
1389 	if (ro_pmtu != ro) {
1390 		/* The first hop and the final destination may differ. */
1391 		struct sockaddr_in6 *sa6_dst =
1392 		    (struct sockaddr_in6 *)&ro_pmtu->ro_dst;
1393 		if (ro_pmtu->ro_rt &&
1394 		    ((ro_pmtu->ro_rt->rt_flags & RTF_UP) == 0 ||
1395 		     !IN6_ARE_ADDR_EQUAL(&sa6_dst->sin6_addr, dst))) {
1396 			RTFREE(ro_pmtu->ro_rt);
1397 			ro_pmtu->ro_rt = (struct rtentry *)NULL;
1398 		}
1399 		if (ro_pmtu->ro_rt == NULL) {
1400 			bzero(sa6_dst, sizeof(*sa6_dst));
1401 			sa6_dst->sin6_family = AF_INET6;
1402 			sa6_dst->sin6_len = sizeof(struct sockaddr_in6);
1403 			sa6_dst->sin6_addr = *dst;
1404 
1405 			rtalloc((struct route *)ro_pmtu);
1406 		}
1407 	}
1408 	if (ro_pmtu->ro_rt) {
1409 		u_int32_t ifmtu;
1410 		struct in_conninfo inc;
1411 
1412 		bzero(&inc, sizeof(inc));
1413 		inc.inc_flags = 1; /* IPv6 */
1414 		inc.inc6_faddr = *dst;
1415 
1416 		if (ifp == NULL)
1417 			ifp = ro_pmtu->ro_rt->rt_ifp;
1418 		ifmtu = IN6_LINKMTU(ifp);
1419 		mtu = tcp_hc_getmtu(&inc);
1420 		if (mtu)
1421 			mtu = min(mtu, ro_pmtu->ro_rt->rt_rmx.rmx_mtu);
1422 		else
1423 			mtu = ro_pmtu->ro_rt->rt_rmx.rmx_mtu;
1424 		if (mtu == 0)
1425 			mtu = ifmtu;
1426 		else if (mtu < IPV6_MMTU) {
1427 			/*
1428 			 * RFC2460 section 5, last paragraph:
1429 			 * if we record ICMPv6 too big message with
1430 			 * mtu < IPV6_MMTU, transmit packets sized IPV6_MMTU
1431 			 * or smaller, with framgent header attached.
1432 			 * (fragment header is needed regardless from the
1433 			 * packet size, for translators to identify packets)
1434 			 */
1435 			alwaysfrag = 1;
1436 			mtu = IPV6_MMTU;
1437 		} else if (mtu > ifmtu) {
1438 			/*
1439 			 * The MTU on the route is larger than the MTU on
1440 			 * the interface!  This shouldn't happen, unless the
1441 			 * MTU of the interface has been changed after the
1442 			 * interface was brought up.  Change the MTU in the
1443 			 * route to match the interface MTU (as long as the
1444 			 * field isn't locked).
1445 			 */
1446 			mtu = ifmtu;
1447 			ro_pmtu->ro_rt->rt_rmx.rmx_mtu = mtu;
1448 		}
1449 	} else if (ifp) {
1450 		mtu = IN6_LINKMTU(ifp);
1451 	} else
1452 		error = EHOSTUNREACH; /* XXX */
1453 
1454 	*mtup = mtu;
1455 	if (alwaysfragp)
1456 		*alwaysfragp = alwaysfrag;
1457 	return (error);
1458 }
1459 
1460 /*
1461  * IP6 socket option processing.
1462  */
1463 int
1464 ip6_ctloutput(so, sopt)
1465 	struct socket *so;
1466 	struct sockopt *sopt;
1467 {
1468 	int privileged, optdatalen, uproto;
1469 	void *optdata;
1470 	struct inpcb *in6p = sotoinpcb(so);
1471 	int error, optval;
1472 	int level, op, optname;
1473 	int optlen;
1474 	struct thread *td;
1475 
1476 	if (sopt) {
1477 		level = sopt->sopt_level;
1478 		op = sopt->sopt_dir;
1479 		optname = sopt->sopt_name;
1480 		optlen = sopt->sopt_valsize;
1481 		td = sopt->sopt_td;
1482 	} else {
1483 		panic("ip6_ctloutput: arg soopt is NULL");
1484 	}
1485 	error = optval = 0;
1486 
1487 	privileged = (td == 0 || suser(td)) ? 0 : 1;
1488 	uproto = (int)so->so_proto->pr_protocol;
1489 
1490 	if (level == IPPROTO_IPV6) {
1491 		switch (op) {
1492 
1493 		case SOPT_SET:
1494 			switch (optname) {
1495 			case IPV6_2292PKTOPTIONS:
1496 #ifdef IPV6_PKTOPTIONS
1497 			case IPV6_PKTOPTIONS:
1498 #endif
1499 			{
1500 				struct mbuf *m;
1501 
1502 				error = soopt_getm(sopt, &m); /* XXX */
1503 				if (error != 0)
1504 					break;
1505 				error = soopt_mcopyin(sopt, m); /* XXX */
1506 				if (error != 0)
1507 					break;
1508 				error = ip6_pcbopts(&in6p->in6p_outputopts,
1509 						    m, so, sopt);
1510 				m_freem(m); /* XXX */
1511 				break;
1512 			}
1513 
1514 			/*
1515 			 * Use of some Hop-by-Hop options or some
1516 			 * Destination options, might require special
1517 			 * privilege.  That is, normal applications
1518 			 * (without special privilege) might be forbidden
1519 			 * from setting certain options in outgoing packets,
1520 			 * and might never see certain options in received
1521 			 * packets. [RFC 2292 Section 6]
1522 			 * KAME specific note:
1523 			 *  KAME prevents non-privileged users from sending or
1524 			 *  receiving ANY hbh/dst options in order to avoid
1525 			 *  overhead of parsing options in the kernel.
1526 			 */
1527 			case IPV6_RECVHOPOPTS:
1528 			case IPV6_RECVDSTOPTS:
1529 			case IPV6_RECVRTHDRDSTOPTS:
1530 				if (!privileged) {
1531 					error = EPERM;
1532 					break;
1533 				}
1534 				/* FALLTHROUGH */
1535 			case IPV6_UNICAST_HOPS:
1536 			case IPV6_HOPLIMIT:
1537 			case IPV6_FAITH:
1538 
1539 			case IPV6_RECVPKTINFO:
1540 			case IPV6_RECVHOPLIMIT:
1541 			case IPV6_RECVRTHDR:
1542 			case IPV6_RECVPATHMTU:
1543 			case IPV6_RECVTCLASS:
1544 			case IPV6_V6ONLY:
1545 			case IPV6_AUTOFLOWLABEL:
1546 				if (optlen != sizeof(int)) {
1547 					error = EINVAL;
1548 					break;
1549 				}
1550 				error = sooptcopyin(sopt, &optval,
1551 					sizeof optval, sizeof optval);
1552 				if (error)
1553 					break;
1554 				switch (optname) {
1555 
1556 				case IPV6_UNICAST_HOPS:
1557 					if (optval < -1 || optval >= 256)
1558 						error = EINVAL;
1559 					else {
1560 						/* -1 = kernel default */
1561 						in6p->in6p_hops = optval;
1562 						if ((in6p->in6p_vflag &
1563 						     INP_IPV4) != 0)
1564 							in6p->inp_ip_ttl = optval;
1565 					}
1566 					break;
1567 #define OPTSET(bit) \
1568 do { \
1569 	if (optval) \
1570 		in6p->in6p_flags |= (bit); \
1571 	else \
1572 		in6p->in6p_flags &= ~(bit); \
1573 } while (/*CONSTCOND*/ 0)
1574 #define OPTSET2292(bit) \
1575 do { \
1576 	in6p->in6p_flags |= IN6P_RFC2292; \
1577 	if (optval) \
1578 		in6p->in6p_flags |= (bit); \
1579 	else \
1580 		in6p->in6p_flags &= ~(bit); \
1581 } while (/*CONSTCOND*/ 0)
1582 #define OPTBIT(bit) (in6p->in6p_flags & (bit) ? 1 : 0)
1583 
1584 				case IPV6_RECVPKTINFO:
1585 					/* cannot mix with RFC2292 */
1586 					if (OPTBIT(IN6P_RFC2292)) {
1587 						error = EINVAL;
1588 						break;
1589 					}
1590 					OPTSET(IN6P_PKTINFO);
1591 					break;
1592 
1593 				case IPV6_HOPLIMIT:
1594 				{
1595 					struct ip6_pktopts **optp;
1596 
1597 					/* cannot mix with RFC2292 */
1598 					if (OPTBIT(IN6P_RFC2292)) {
1599 						error = EINVAL;
1600 						break;
1601 					}
1602 					optp = &in6p->in6p_outputopts;
1603 					error = ip6_pcbopt(IPV6_HOPLIMIT,
1604 							   (u_char *)&optval,
1605 							   sizeof(optval),
1606 							   optp,
1607 							   privileged, uproto);
1608 					break;
1609 				}
1610 
1611 				case IPV6_RECVHOPLIMIT:
1612 					/* cannot mix with RFC2292 */
1613 					if (OPTBIT(IN6P_RFC2292)) {
1614 						error = EINVAL;
1615 						break;
1616 					}
1617 					OPTSET(IN6P_HOPLIMIT);
1618 					break;
1619 
1620 				case IPV6_RECVHOPOPTS:
1621 					/* cannot mix with RFC2292 */
1622 					if (OPTBIT(IN6P_RFC2292)) {
1623 						error = EINVAL;
1624 						break;
1625 					}
1626 					OPTSET(IN6P_HOPOPTS);
1627 					break;
1628 
1629 				case IPV6_RECVDSTOPTS:
1630 					/* cannot mix with RFC2292 */
1631 					if (OPTBIT(IN6P_RFC2292)) {
1632 						error = EINVAL;
1633 						break;
1634 					}
1635 					OPTSET(IN6P_DSTOPTS);
1636 					break;
1637 
1638 				case IPV6_RECVRTHDRDSTOPTS:
1639 					/* cannot mix with RFC2292 */
1640 					if (OPTBIT(IN6P_RFC2292)) {
1641 						error = EINVAL;
1642 						break;
1643 					}
1644 					OPTSET(IN6P_RTHDRDSTOPTS);
1645 					break;
1646 
1647 				case IPV6_RECVRTHDR:
1648 					/* cannot mix with RFC2292 */
1649 					if (OPTBIT(IN6P_RFC2292)) {
1650 						error = EINVAL;
1651 						break;
1652 					}
1653 					OPTSET(IN6P_RTHDR);
1654 					break;
1655 
1656 				case IPV6_FAITH:
1657 					OPTSET(IN6P_FAITH);
1658 					break;
1659 
1660 				case IPV6_RECVPATHMTU:
1661 					/*
1662 					 * We ignore this option for TCP
1663 					 * sockets.
1664 					 * (rfc2292bis leaves this case
1665 					 * unspecified.)
1666 					 */
1667 					if (uproto != IPPROTO_TCP)
1668 						OPTSET(IN6P_MTU);
1669 					break;
1670 
1671 				case IPV6_V6ONLY:
1672 					/*
1673 					 * make setsockopt(IPV6_V6ONLY)
1674 					 * available only prior to bind(2).
1675 					 * see ipng mailing list, Jun 22 2001.
1676 					 */
1677 					if (in6p->in6p_lport ||
1678 					    !IN6_IS_ADDR_UNSPECIFIED(&in6p->in6p_laddr)) {
1679 						error = EINVAL;
1680 						break;
1681 					}
1682 					OPTSET(IN6P_IPV6_V6ONLY);
1683 					if (optval)
1684 						in6p->in6p_vflag &= ~INP_IPV4;
1685 					else
1686 						in6p->in6p_vflag |= INP_IPV4;
1687 					break;
1688 				case IPV6_RECVTCLASS:
1689 					/* cannot mix with RFC2292 XXX */
1690 					if (OPTBIT(IN6P_RFC2292)) {
1691 						error = EINVAL;
1692 						break;
1693 					}
1694 					OPTSET(IN6P_TCLASS);
1695 					break;
1696 				case IPV6_AUTOFLOWLABEL:
1697 					OPTSET(IN6P_AUTOFLOWLABEL);
1698 					break;
1699 
1700 				}
1701 				break;
1702 
1703 			case IPV6_TCLASS:
1704 			case IPV6_DONTFRAG:
1705 			case IPV6_USE_MIN_MTU:
1706 			case IPV6_PREFER_TEMPADDR:
1707 				if (optlen != sizeof(optval)) {
1708 					error = EINVAL;
1709 					break;
1710 				}
1711 				error = sooptcopyin(sopt, &optval,
1712 					sizeof optval, sizeof optval);
1713 				if (error)
1714 					break;
1715 				{
1716 					struct ip6_pktopts **optp;
1717 					optp = &in6p->in6p_outputopts;
1718 					error = ip6_pcbopt(optname,
1719 							   (u_char *)&optval,
1720 							   sizeof(optval),
1721 							   optp,
1722 							   privileged, uproto);
1723 					break;
1724 				}
1725 
1726 			case IPV6_2292PKTINFO:
1727 			case IPV6_2292HOPLIMIT:
1728 			case IPV6_2292HOPOPTS:
1729 			case IPV6_2292DSTOPTS:
1730 			case IPV6_2292RTHDR:
1731 				/* RFC 2292 */
1732 				if (optlen != sizeof(int)) {
1733 					error = EINVAL;
1734 					break;
1735 				}
1736 				error = sooptcopyin(sopt, &optval,
1737 					sizeof optval, sizeof optval);
1738 				if (error)
1739 					break;
1740 				switch (optname) {
1741 				case IPV6_2292PKTINFO:
1742 					OPTSET2292(IN6P_PKTINFO);
1743 					break;
1744 				case IPV6_2292HOPLIMIT:
1745 					OPTSET2292(IN6P_HOPLIMIT);
1746 					break;
1747 				case IPV6_2292HOPOPTS:
1748 					/*
1749 					 * Check super-user privilege.
1750 					 * See comments for IPV6_RECVHOPOPTS.
1751 					 */
1752 					if (!privileged)
1753 						return (EPERM);
1754 					OPTSET2292(IN6P_HOPOPTS);
1755 					break;
1756 				case IPV6_2292DSTOPTS:
1757 					if (!privileged)
1758 						return (EPERM);
1759 					OPTSET2292(IN6P_DSTOPTS|IN6P_RTHDRDSTOPTS); /* XXX */
1760 					break;
1761 				case IPV6_2292RTHDR:
1762 					OPTSET2292(IN6P_RTHDR);
1763 					break;
1764 				}
1765 				break;
1766 			case IPV6_PKTINFO:
1767 			case IPV6_HOPOPTS:
1768 			case IPV6_RTHDR:
1769 			case IPV6_DSTOPTS:
1770 			case IPV6_RTHDRDSTOPTS:
1771 			case IPV6_NEXTHOP:
1772 			{
1773 				/* new advanced API (2292bis) */
1774 				u_char *optbuf;
1775 				int optlen;
1776 				struct ip6_pktopts **optp;
1777 
1778 				/* cannot mix with RFC2292 */
1779 				if (OPTBIT(IN6P_RFC2292)) {
1780 					error = EINVAL;
1781 					break;
1782 				}
1783 
1784 				switch (optname) {
1785 				case IPV6_HOPOPTS:
1786 				case IPV6_DSTOPTS:
1787 				case IPV6_RTHDRDSTOPTS:
1788 				case IPV6_NEXTHOP:
1789 					if (!privileged)
1790 						error = EPERM;
1791 					break;
1792 				}
1793 				if (error)
1794 					break;
1795 
1796 				switch (optname) {
1797 				case IPV6_PKTINFO:
1798 					optlen = sizeof(struct in6_pktinfo);
1799 					break;
1800 				case IPV6_NEXTHOP:
1801 					optlen = SOCK_MAXADDRLEN;
1802 					break;
1803 				default:
1804 					optlen = IPV6_MAXOPTHDR;
1805 					break;
1806 				}
1807 				if (sopt->sopt_valsize > optlen) {
1808 					error = EINVAL;
1809 					break;
1810 				}
1811 
1812 				optlen = sopt->sopt_valsize;
1813 				optbuf = malloc(optlen, M_TEMP, M_WAITOK);
1814 				error = sooptcopyin(sopt, optbuf, optlen,
1815 				    optlen);
1816 				if (error) {
1817 					free(optbuf, M_TEMP);
1818 					break;
1819 				}
1820 
1821 				optp = &in6p->in6p_outputopts;
1822 				error = ip6_pcbopt(optname,
1823 						   optbuf, optlen,
1824 						   optp, privileged, uproto);
1825 				free(optbuf, M_TEMP);
1826 				break;
1827 			}
1828 #undef OPTSET
1829 
1830 			case IPV6_MULTICAST_IF:
1831 			case IPV6_MULTICAST_HOPS:
1832 			case IPV6_MULTICAST_LOOP:
1833 			case IPV6_JOIN_GROUP:
1834 			case IPV6_LEAVE_GROUP:
1835 			    {
1836 				if (sopt->sopt_valsize > MLEN) {
1837 					error = EMSGSIZE;
1838 					break;
1839 				}
1840 				/* XXX */
1841 			    }
1842 			    /* FALLTHROUGH */
1843 			    {
1844 				struct mbuf *m;
1845 
1846 				if (sopt->sopt_valsize > MCLBYTES) {
1847 					error = EMSGSIZE;
1848 					break;
1849 				}
1850 				/* XXX */
1851 				MGET(m, sopt->sopt_td ? M_WAIT : M_DONTWAIT, MT_HEADER);
1852 				if (m == 0) {
1853 					error = ENOBUFS;
1854 					break;
1855 				}
1856 				if (sopt->sopt_valsize > MLEN) {
1857 					MCLGET(m, sopt->sopt_td ? M_WAIT : M_DONTWAIT);
1858 					if ((m->m_flags & M_EXT) == 0) {
1859 						m_free(m);
1860 						error = ENOBUFS;
1861 						break;
1862 					}
1863 				}
1864 				m->m_len = sopt->sopt_valsize;
1865 				error = sooptcopyin(sopt, mtod(m, char *),
1866 						    m->m_len, m->m_len);
1867 				if (error) {
1868 					(void)m_free(m);
1869 					break;
1870 				}
1871 				error =	ip6_setmoptions(sopt->sopt_name,
1872 							&in6p->in6p_moptions,
1873 							m);
1874 				(void)m_free(m);
1875 			    }
1876 				break;
1877 
1878 			case IPV6_PORTRANGE:
1879 				error = sooptcopyin(sopt, &optval,
1880 				    sizeof optval, sizeof optval);
1881 				if (error)
1882 					break;
1883 
1884 				switch (optval) {
1885 				case IPV6_PORTRANGE_DEFAULT:
1886 					in6p->in6p_flags &= ~(IN6P_LOWPORT);
1887 					in6p->in6p_flags &= ~(IN6P_HIGHPORT);
1888 					break;
1889 
1890 				case IPV6_PORTRANGE_HIGH:
1891 					in6p->in6p_flags &= ~(IN6P_LOWPORT);
1892 					in6p->in6p_flags |= IN6P_HIGHPORT;
1893 					break;
1894 
1895 				case IPV6_PORTRANGE_LOW:
1896 					in6p->in6p_flags &= ~(IN6P_HIGHPORT);
1897 					in6p->in6p_flags |= IN6P_LOWPORT;
1898 					break;
1899 
1900 				default:
1901 					error = EINVAL;
1902 					break;
1903 				}
1904 				break;
1905 
1906 #if defined(IPSEC) || defined(FAST_IPSEC)
1907 			case IPV6_IPSEC_POLICY:
1908 			    {
1909 				caddr_t req = NULL;
1910 				size_t len = 0;
1911 				struct mbuf *m;
1912 
1913 				if ((error = soopt_getm(sopt, &m)) != 0) /* XXX */
1914 					break;
1915 				if ((error = soopt_mcopyin(sopt, m)) != 0) /* XXX */
1916 					break;
1917 				if (m) {
1918 					req = mtod(m, caddr_t);
1919 					len = m->m_len;
1920 				}
1921 				error = ipsec6_set_policy(in6p, optname, req,
1922 							  len, privileged);
1923 				m_freem(m);
1924 			    }
1925 				break;
1926 #endif /* KAME IPSEC */
1927 
1928 			case IPV6_FW_ADD:
1929 			case IPV6_FW_DEL:
1930 			case IPV6_FW_FLUSH:
1931 			case IPV6_FW_ZERO:
1932 			    {
1933 				struct mbuf *m;
1934 				struct mbuf **mp = &m;
1935 
1936 				if (ip6_fw_ctl_ptr == NULL)
1937 					return EINVAL;
1938 				/* XXX */
1939 				if ((error = soopt_getm(sopt, &m)) != 0)
1940 					break;
1941 				/* XXX */
1942 				if ((error = soopt_mcopyin(sopt, m)) != 0)
1943 					break;
1944 				error = (*ip6_fw_ctl_ptr)(optname, mp);
1945 				m = *mp;
1946 			    }
1947 				break;
1948 
1949 			default:
1950 				error = ENOPROTOOPT;
1951 				break;
1952 			}
1953 			break;
1954 
1955 		case SOPT_GET:
1956 			switch (optname) {
1957 
1958 			case IPV6_2292PKTOPTIONS:
1959 #ifdef IPV6_PKTOPTIONS
1960 			case IPV6_PKTOPTIONS:
1961 #endif
1962 				/*
1963 				 * RFC3542 (effectively) deprecated the
1964 				 * semantics of the 2292-style pktoptions.
1965 				 * Since it was not reliable in nature (i.e.,
1966 				 * applications had to expect the lack of some
1967 				 * information after all), it would make sense
1968 				 * to simplify this part by always returning
1969 				 * empty data.
1970 				 */
1971 				sopt->sopt_valsize = 0;
1972 				break;
1973 
1974 			case IPV6_RECVHOPOPTS:
1975 			case IPV6_RECVDSTOPTS:
1976 			case IPV6_RECVRTHDRDSTOPTS:
1977 			case IPV6_UNICAST_HOPS:
1978 			case IPV6_RECVPKTINFO:
1979 			case IPV6_RECVHOPLIMIT:
1980 			case IPV6_RECVRTHDR:
1981 			case IPV6_RECVPATHMTU:
1982 
1983 			case IPV6_FAITH:
1984 			case IPV6_V6ONLY:
1985 			case IPV6_PORTRANGE:
1986 			case IPV6_RECVTCLASS:
1987 			case IPV6_AUTOFLOWLABEL:
1988 				switch (optname) {
1989 
1990 				case IPV6_RECVHOPOPTS:
1991 					optval = OPTBIT(IN6P_HOPOPTS);
1992 					break;
1993 
1994 				case IPV6_RECVDSTOPTS:
1995 					optval = OPTBIT(IN6P_DSTOPTS);
1996 					break;
1997 
1998 				case IPV6_RECVRTHDRDSTOPTS:
1999 					optval = OPTBIT(IN6P_RTHDRDSTOPTS);
2000 					break;
2001 
2002 				case IPV6_UNICAST_HOPS:
2003 					optval = in6p->in6p_hops;
2004 					break;
2005 
2006 				case IPV6_RECVPKTINFO:
2007 					optval = OPTBIT(IN6P_PKTINFO);
2008 					break;
2009 
2010 				case IPV6_RECVHOPLIMIT:
2011 					optval = OPTBIT(IN6P_HOPLIMIT);
2012 					break;
2013 
2014 				case IPV6_RECVRTHDR:
2015 					optval = OPTBIT(IN6P_RTHDR);
2016 					break;
2017 
2018 				case IPV6_RECVPATHMTU:
2019 					optval = OPTBIT(IN6P_MTU);
2020 					break;
2021 
2022 				case IPV6_FAITH:
2023 					optval = OPTBIT(IN6P_FAITH);
2024 					break;
2025 
2026 				case IPV6_V6ONLY:
2027 					optval = OPTBIT(IN6P_IPV6_V6ONLY);
2028 					break;
2029 
2030 				case IPV6_PORTRANGE:
2031 				    {
2032 					int flags;
2033 					flags = in6p->in6p_flags;
2034 					if (flags & IN6P_HIGHPORT)
2035 						optval = IPV6_PORTRANGE_HIGH;
2036 					else if (flags & IN6P_LOWPORT)
2037 						optval = IPV6_PORTRANGE_LOW;
2038 					else
2039 						optval = 0;
2040 					break;
2041 				    }
2042 				case IPV6_RECVTCLASS:
2043 					optval = OPTBIT(IN6P_TCLASS);
2044 					break;
2045 
2046 				case IPV6_AUTOFLOWLABEL:
2047 					optval = OPTBIT(IN6P_AUTOFLOWLABEL);
2048 					break;
2049 				}
2050 				if (error)
2051 					break;
2052 				error = sooptcopyout(sopt, &optval,
2053 					sizeof optval);
2054 				break;
2055 
2056 			case IPV6_PATHMTU:
2057 			{
2058 				u_long pmtu = 0;
2059 				struct ip6_mtuinfo mtuinfo;
2060 				struct route_in6 sro;
2061 
2062 				bzero(&sro, sizeof(sro));
2063 
2064 				if (!(so->so_state & SS_ISCONNECTED))
2065 					return (ENOTCONN);
2066 				/*
2067 				 * XXX: we dot not consider the case of source
2068 				 * routing, or optional information to specify
2069 				 * the outgoing interface.
2070 				 */
2071 				error = ip6_getpmtu(&sro, NULL, NULL,
2072 				    &in6p->in6p_faddr, &pmtu, NULL);
2073 				if (sro.ro_rt)
2074 					RTFREE(sro.ro_rt);
2075 				if (error)
2076 					break;
2077 				if (pmtu > IPV6_MAXPACKET)
2078 					pmtu = IPV6_MAXPACKET;
2079 
2080 				bzero(&mtuinfo, sizeof(mtuinfo));
2081 				mtuinfo.ip6m_mtu = (u_int32_t)pmtu;
2082 				optdata = (void *)&mtuinfo;
2083 				optdatalen = sizeof(mtuinfo);
2084 				error = sooptcopyout(sopt, optdata,
2085 				    optdatalen);
2086 				break;
2087 			}
2088 
2089 			case IPV6_2292PKTINFO:
2090 			case IPV6_2292HOPLIMIT:
2091 			case IPV6_2292HOPOPTS:
2092 			case IPV6_2292RTHDR:
2093 			case IPV6_2292DSTOPTS:
2094 				switch (optname) {
2095 				case IPV6_2292PKTINFO:
2096 					optval = OPTBIT(IN6P_PKTINFO);
2097 					break;
2098 				case IPV6_2292HOPLIMIT:
2099 					optval = OPTBIT(IN6P_HOPLIMIT);
2100 					break;
2101 				case IPV6_2292HOPOPTS:
2102 					optval = OPTBIT(IN6P_HOPOPTS);
2103 					break;
2104 				case IPV6_2292RTHDR:
2105 					optval = OPTBIT(IN6P_RTHDR);
2106 					break;
2107 				case IPV6_2292DSTOPTS:
2108 					optval = OPTBIT(IN6P_DSTOPTS|IN6P_RTHDRDSTOPTS);
2109 					break;
2110 				}
2111 				error = sooptcopyout(sopt, &optval,
2112 				    sizeof optval);
2113 				break;
2114 			case IPV6_PKTINFO:
2115 			case IPV6_HOPOPTS:
2116 			case IPV6_RTHDR:
2117 			case IPV6_DSTOPTS:
2118 			case IPV6_RTHDRDSTOPTS:
2119 			case IPV6_NEXTHOP:
2120 			case IPV6_TCLASS:
2121 			case IPV6_DONTFRAG:
2122 			case IPV6_USE_MIN_MTU:
2123 			case IPV6_PREFER_TEMPADDR:
2124 				error = ip6_getpcbopt(in6p->in6p_outputopts,
2125 				    optname, sopt);
2126 				break;
2127 
2128 			case IPV6_MULTICAST_IF:
2129 			case IPV6_MULTICAST_HOPS:
2130 			case IPV6_MULTICAST_LOOP:
2131 			case IPV6_JOIN_GROUP:
2132 			case IPV6_LEAVE_GROUP:
2133 			    {
2134 				struct mbuf *m;
2135 				error = ip6_getmoptions(sopt->sopt_name,
2136 				    in6p->in6p_moptions, &m);
2137 				if (error == 0)
2138 					error = sooptcopyout(sopt,
2139 					    mtod(m, char *), m->m_len);
2140 				m_freem(m);
2141 			    }
2142 				break;
2143 
2144 #if defined(IPSEC) || defined(FAST_IPSEC)
2145 			case IPV6_IPSEC_POLICY:
2146 			  {
2147 				caddr_t req = NULL;
2148 				size_t len = 0;
2149 				struct mbuf *m = NULL;
2150 				struct mbuf **mp = &m;
2151 				size_t ovalsize = sopt->sopt_valsize;
2152 				caddr_t oval = (caddr_t)sopt->sopt_val;
2153 
2154 				error = soopt_getm(sopt, &m); /* XXX */
2155 				if (error != 0)
2156 					break;
2157 				error = soopt_mcopyin(sopt, m); /* XXX */
2158 				if (error != 0)
2159 					break;
2160 				sopt->sopt_valsize = ovalsize;
2161 				sopt->sopt_val = oval;
2162 				if (m) {
2163 					req = mtod(m, caddr_t);
2164 					len = m->m_len;
2165 				}
2166 				error = ipsec6_get_policy(in6p, req, len, mp);
2167 				if (error == 0)
2168 					error = soopt_mcopyout(sopt, m); /* XXX */
2169 				if (error == 0 && m)
2170 					m_freem(m);
2171 				break;
2172 			  }
2173 #endif /* KAME IPSEC */
2174 
2175 			case IPV6_FW_GET:
2176 			  {
2177 				struct mbuf *m;
2178 				struct mbuf **mp = &m;
2179 
2180 				if (ip6_fw_ctl_ptr == NULL)
2181 			        {
2182 					return EINVAL;
2183 				}
2184 				error = (*ip6_fw_ctl_ptr)(optname, mp);
2185 				if (error == 0)
2186 					error = soopt_mcopyout(sopt, m); /* XXX */
2187 				if (error == 0 && m)
2188 					m_freem(m);
2189 			  }
2190 				break;
2191 
2192 			default:
2193 				error = ENOPROTOOPT;
2194 				break;
2195 			}
2196 			break;
2197 		}
2198 	} else {		/* level != IPPROTO_IPV6 */
2199 		error = EINVAL;
2200 	}
2201 	return (error);
2202 }
2203 
2204 int
2205 ip6_raw_ctloutput(so, sopt)
2206 	struct socket *so;
2207 	struct sockopt *sopt;
2208 {
2209 	int error = 0, optval, optlen;
2210 	const int icmp6off = offsetof(struct icmp6_hdr, icmp6_cksum);
2211 	struct in6pcb *in6p = sotoin6pcb(so);
2212 	int level, op, optname;
2213 
2214 	if (sopt) {
2215 		level = sopt->sopt_level;
2216 		op = sopt->sopt_dir;
2217 		optname = sopt->sopt_name;
2218 		optlen = sopt->sopt_valsize;
2219 	} else
2220 		panic("ip6_raw_ctloutput: arg soopt is NULL");
2221 
2222 	if (level != IPPROTO_IPV6) {
2223 		return (EINVAL);
2224 	}
2225 
2226 	switch (optname) {
2227 	case IPV6_CHECKSUM:
2228 		/*
2229 		 * For ICMPv6 sockets, no modification allowed for checksum
2230 		 * offset, permit "no change" values to help existing apps.
2231 		 *
2232 		 * XXX 2292bis says: "An attempt to set IPV6_CHECKSUM
2233 		 * for an ICMPv6 socket will fail."
2234 		 * The current behavior does not meet 2292bis.
2235 		 */
2236 		switch (op) {
2237 		case SOPT_SET:
2238 			if (optlen != sizeof(int)) {
2239 				error = EINVAL;
2240 				break;
2241 			}
2242 			error = sooptcopyin(sopt, &optval, sizeof(optval),
2243 					    sizeof(optval));
2244 			if (error)
2245 				break;
2246 			if ((optval % 2) != 0) {
2247 				/* the API assumes even offset values */
2248 				error = EINVAL;
2249 			} else if (so->so_proto->pr_protocol ==
2250 			    IPPROTO_ICMPV6) {
2251 				if (optval != icmp6off)
2252 					error = EINVAL;
2253 			} else
2254 				in6p->in6p_cksum = optval;
2255 			break;
2256 
2257 		case SOPT_GET:
2258 			if (so->so_proto->pr_protocol == IPPROTO_ICMPV6)
2259 				optval = icmp6off;
2260 			else
2261 				optval = in6p->in6p_cksum;
2262 
2263 			error = sooptcopyout(sopt, &optval, sizeof(optval));
2264 			break;
2265 
2266 		default:
2267 			error = EINVAL;
2268 			break;
2269 		}
2270 		break;
2271 
2272 	default:
2273 		error = ENOPROTOOPT;
2274 		break;
2275 	}
2276 
2277 	return (error);
2278 }
2279 
2280 /*
2281  * Set up IP6 options in pcb for insertion in output packets or
2282  * specifying behavior of outgoing packets.
2283  */
2284 static int
2285 ip6_pcbopts(pktopt, m, so, sopt)
2286 	struct ip6_pktopts **pktopt;
2287 	struct mbuf *m;
2288 	struct socket *so;
2289 	struct sockopt *sopt;
2290 {
2291 	struct ip6_pktopts *opt = *pktopt;
2292 	int error = 0;
2293 	struct thread *td = sopt->sopt_td;
2294 	int priv = 0;
2295 
2296 	/* turn off any old options. */
2297 	if (opt) {
2298 #ifdef DIAGNOSTIC
2299 		if (opt->ip6po_pktinfo || opt->ip6po_nexthop ||
2300 		    opt->ip6po_hbh || opt->ip6po_dest1 || opt->ip6po_dest2 ||
2301 		    opt->ip6po_rhinfo.ip6po_rhi_rthdr)
2302 			printf("ip6_pcbopts: all specified options are cleared.\n");
2303 #endif
2304 		ip6_clearpktopts(opt, -1);
2305 	} else
2306 		opt = malloc(sizeof(*opt), M_IP6OPT, M_WAITOK);
2307 	*pktopt = NULL;
2308 
2309 	if (!m || m->m_len == 0) {
2310 		/*
2311 		 * Only turning off any previous options, regardless of
2312 		 * whether the opt is just created or given.
2313 		 */
2314 		free(opt, M_IP6OPT);
2315 		return (0);
2316 	}
2317 
2318 	/*  set options specified by user. */
2319 	if (td && !suser(td))
2320 		priv = 1;
2321 	if ((error = ip6_setpktoptions(m, opt, NULL, priv, 1,
2322 	    so->so_proto->pr_protocol)) != 0) {
2323 		ip6_clearpktopts(opt, -1); /* XXX: discard all options */
2324 		free(opt, M_IP6OPT);
2325 		return (error);
2326 	}
2327 	*pktopt = opt;
2328 	return (0);
2329 }
2330 
2331 /*
2332  * initialize ip6_pktopts.  beware that there are non-zero default values in
2333  * the struct.
2334  */
2335 void
2336 init_ip6pktopts(opt)
2337 	struct ip6_pktopts *opt;
2338 {
2339 
2340 	bzero(opt, sizeof(*opt));
2341 	opt->ip6po_hlim = -1;	/* -1 means default hop limit */
2342 	opt->ip6po_tclass = -1;	/* -1 means default traffic class */
2343 	opt->ip6po_minmtu = IP6PO_MINMTU_MCASTONLY;
2344 	opt->ip6po_prefer_tempaddr = IP6PO_TEMPADDR_SYSTEM;
2345 }
2346 
2347 static int
2348 ip6_pcbopt(optname, buf, len, pktopt, priv, uproto)
2349 	int optname, len, priv;
2350 	u_char *buf;
2351 	struct ip6_pktopts **pktopt;
2352 	int uproto;
2353 {
2354 	struct ip6_pktopts *opt;
2355 
2356 	if (*pktopt == NULL) {
2357 		*pktopt = malloc(sizeof(struct ip6_pktopts), M_IP6OPT,
2358 		    M_WAITOK);
2359 		init_ip6pktopts(*pktopt);
2360 		(*pktopt)->needfree = 1;
2361 	}
2362 	opt = *pktopt;
2363 
2364 	return (ip6_setpktoption(optname, buf, len, opt, priv, 1, 0, uproto));
2365 }
2366 
2367 static int
2368 ip6_getpcbopt(pktopt, optname, sopt)
2369 	struct ip6_pktopts *pktopt;
2370 	struct sockopt *sopt;
2371 	int optname;
2372 {
2373 	void *optdata = NULL;
2374 	int optdatalen = 0;
2375 	struct ip6_ext *ip6e;
2376 	int error = 0;
2377 	struct in6_pktinfo null_pktinfo;
2378 	int deftclass = 0, on;
2379 	int defminmtu = IP6PO_MINMTU_MCASTONLY;
2380 	int defpreftemp = IP6PO_TEMPADDR_SYSTEM;
2381 
2382 	switch (optname) {
2383 	case IPV6_PKTINFO:
2384 		if (pktopt && pktopt->ip6po_pktinfo)
2385 			optdata = (void *)pktopt->ip6po_pktinfo;
2386 		else {
2387 			/* XXX: we don't have to do this every time... */
2388 			bzero(&null_pktinfo, sizeof(null_pktinfo));
2389 			optdata = (void *)&null_pktinfo;
2390 		}
2391 		optdatalen = sizeof(struct in6_pktinfo);
2392 		break;
2393 	case IPV6_TCLASS:
2394 		if (pktopt && pktopt->ip6po_tclass >= 0)
2395 			optdata = (void *)&pktopt->ip6po_tclass;
2396 		else
2397 			optdata = (void *)&deftclass;
2398 		optdatalen = sizeof(int);
2399 		break;
2400 	case IPV6_HOPOPTS:
2401 		if (pktopt && pktopt->ip6po_hbh) {
2402 			optdata = (void *)pktopt->ip6po_hbh;
2403 			ip6e = (struct ip6_ext *)pktopt->ip6po_hbh;
2404 			optdatalen = (ip6e->ip6e_len + 1) << 3;
2405 		}
2406 		break;
2407 	case IPV6_RTHDR:
2408 		if (pktopt && pktopt->ip6po_rthdr) {
2409 			optdata = (void *)pktopt->ip6po_rthdr;
2410 			ip6e = (struct ip6_ext *)pktopt->ip6po_rthdr;
2411 			optdatalen = (ip6e->ip6e_len + 1) << 3;
2412 		}
2413 		break;
2414 	case IPV6_RTHDRDSTOPTS:
2415 		if (pktopt && pktopt->ip6po_dest1) {
2416 			optdata = (void *)pktopt->ip6po_dest1;
2417 			ip6e = (struct ip6_ext *)pktopt->ip6po_dest1;
2418 			optdatalen = (ip6e->ip6e_len + 1) << 3;
2419 		}
2420 		break;
2421 	case IPV6_DSTOPTS:
2422 		if (pktopt && pktopt->ip6po_dest2) {
2423 			optdata = (void *)pktopt->ip6po_dest2;
2424 			ip6e = (struct ip6_ext *)pktopt->ip6po_dest2;
2425 			optdatalen = (ip6e->ip6e_len + 1) << 3;
2426 		}
2427 		break;
2428 	case IPV6_NEXTHOP:
2429 		if (pktopt && pktopt->ip6po_nexthop) {
2430 			optdata = (void *)pktopt->ip6po_nexthop;
2431 			optdatalen = pktopt->ip6po_nexthop->sa_len;
2432 		}
2433 		break;
2434 	case IPV6_USE_MIN_MTU:
2435 		if (pktopt)
2436 			optdata = (void *)&pktopt->ip6po_minmtu;
2437 		else
2438 			optdata = (void *)&defminmtu;
2439 		optdatalen = sizeof(int);
2440 		break;
2441 	case IPV6_DONTFRAG:
2442 		if (pktopt && ((pktopt->ip6po_flags) & IP6PO_DONTFRAG))
2443 			on = 1;
2444 		else
2445 			on = 0;
2446 		optdata = (void *)&on;
2447 		optdatalen = sizeof(on);
2448 		break;
2449 	case IPV6_PREFER_TEMPADDR:
2450 		if (pktopt)
2451 			optdata = (void *)&pktopt->ip6po_prefer_tempaddr;
2452 		else
2453 			optdata = (void *)&defpreftemp;
2454 		optdatalen = sizeof(int);
2455 		break;
2456 	default:		/* should not happen */
2457 #ifdef DIAGNOSTIC
2458 		panic("ip6_getpcbopt: unexpected option\n");
2459 #endif
2460 		return (ENOPROTOOPT);
2461 	}
2462 
2463 	error = sooptcopyout(sopt, optdata, optdatalen);
2464 
2465 	return (error);
2466 }
2467 
2468 void
2469 ip6_clearpktopts(pktopt, optname)
2470 	struct ip6_pktopts *pktopt;
2471 	int optname;
2472 {
2473 	int needfree;
2474 
2475 	if (pktopt == NULL)
2476 		return;
2477 
2478 	needfree = pktopt->needfree;
2479 
2480 	if (optname == -1 || optname == IPV6_PKTINFO) {
2481 		if (needfree && pktopt->ip6po_pktinfo)
2482 			free(pktopt->ip6po_pktinfo, M_IP6OPT);
2483 		pktopt->ip6po_pktinfo = NULL;
2484 	}
2485 	if (optname == -1 || optname == IPV6_HOPLIMIT)
2486 		pktopt->ip6po_hlim = -1;
2487 	if (optname == -1 || optname == IPV6_TCLASS)
2488 		pktopt->ip6po_tclass = -1;
2489 	if (optname == -1 || optname == IPV6_NEXTHOP) {
2490 		if (pktopt->ip6po_nextroute.ro_rt) {
2491 			RTFREE(pktopt->ip6po_nextroute.ro_rt);
2492 			pktopt->ip6po_nextroute.ro_rt = NULL;
2493 		}
2494 		if (needfree && pktopt->ip6po_nexthop)
2495 			free(pktopt->ip6po_nexthop, M_IP6OPT);
2496 		pktopt->ip6po_nexthop = NULL;
2497 	}
2498 	if (optname == -1 || optname == IPV6_HOPOPTS) {
2499 		if (needfree && pktopt->ip6po_hbh)
2500 			free(pktopt->ip6po_hbh, M_IP6OPT);
2501 		pktopt->ip6po_hbh = NULL;
2502 	}
2503 	if (optname == -1 || optname == IPV6_RTHDRDSTOPTS) {
2504 		if (needfree && pktopt->ip6po_dest1)
2505 			free(pktopt->ip6po_dest1, M_IP6OPT);
2506 		pktopt->ip6po_dest1 = NULL;
2507 	}
2508 	if (optname == -1 || optname == IPV6_RTHDR) {
2509 		if (needfree && pktopt->ip6po_rhinfo.ip6po_rhi_rthdr)
2510 			free(pktopt->ip6po_rhinfo.ip6po_rhi_rthdr, M_IP6OPT);
2511 		pktopt->ip6po_rhinfo.ip6po_rhi_rthdr = NULL;
2512 		if (pktopt->ip6po_route.ro_rt) {
2513 			RTFREE(pktopt->ip6po_route.ro_rt);
2514 			pktopt->ip6po_route.ro_rt = NULL;
2515 		}
2516 	}
2517 	if (optname == -1 || optname == IPV6_DSTOPTS) {
2518 		if (needfree && pktopt->ip6po_dest2)
2519 			free(pktopt->ip6po_dest2, M_IP6OPT);
2520 		pktopt->ip6po_dest2 = NULL;
2521 	}
2522 }
2523 
2524 #define PKTOPT_EXTHDRCPY(type) \
2525 do {\
2526 	if (src->type) {\
2527 		int hlen = (((struct ip6_ext *)src->type)->ip6e_len + 1) << 3;\
2528 		dst->type = malloc(hlen, M_IP6OPT, canwait);\
2529 		if (dst->type == NULL && canwait == M_NOWAIT)\
2530 			goto bad;\
2531 		bcopy(src->type, dst->type, hlen);\
2532 	}\
2533 } while (/*CONSTCOND*/ 0)
2534 
2535 struct ip6_pktopts *
2536 ip6_copypktopts(src, canwait)
2537 	struct ip6_pktopts *src;
2538 	int canwait;
2539 {
2540 	struct ip6_pktopts *dst;
2541 
2542 	if (src == NULL) {
2543 		printf("ip6_clearpktopts: invalid argument\n");
2544 		return (NULL);
2545 	}
2546 
2547 	dst = malloc(sizeof(*dst), M_IP6OPT, canwait);
2548 	if (dst == NULL && canwait == M_NOWAIT)
2549 		return (NULL);
2550 	bzero(dst, sizeof(*dst));
2551 	dst->needfree = 1;
2552 
2553 	dst->ip6po_hlim = src->ip6po_hlim;
2554 	dst->ip6po_tclass = src->ip6po_tclass;
2555 	dst->ip6po_flags = src->ip6po_flags;
2556 	if (src->ip6po_pktinfo) {
2557 		dst->ip6po_pktinfo = malloc(sizeof(*dst->ip6po_pktinfo),
2558 		    M_IP6OPT, canwait);
2559 		if (dst->ip6po_pktinfo == NULL && canwait == M_NOWAIT)
2560 			goto bad;
2561 		*dst->ip6po_pktinfo = *src->ip6po_pktinfo;
2562 	}
2563 	if (src->ip6po_nexthop) {
2564 		dst->ip6po_nexthop = malloc(src->ip6po_nexthop->sa_len,
2565 		    M_IP6OPT, canwait);
2566 		if (dst->ip6po_nexthop == NULL && canwait == M_NOWAIT)
2567 			goto bad;
2568 		bcopy(src->ip6po_nexthop, dst->ip6po_nexthop,
2569 		    src->ip6po_nexthop->sa_len);
2570 	}
2571 	PKTOPT_EXTHDRCPY(ip6po_hbh);
2572 	PKTOPT_EXTHDRCPY(ip6po_dest1);
2573 	PKTOPT_EXTHDRCPY(ip6po_dest2);
2574 	PKTOPT_EXTHDRCPY(ip6po_rthdr); /* not copy the cached route */
2575 	return (dst);
2576 
2577   bad:
2578 	if (dst->ip6po_pktinfo) free(dst->ip6po_pktinfo, M_IP6OPT);
2579 	if (dst->ip6po_nexthop) free(dst->ip6po_nexthop, M_IP6OPT);
2580 	if (dst->ip6po_hbh) free(dst->ip6po_hbh, M_IP6OPT);
2581 	if (dst->ip6po_dest1) free(dst->ip6po_dest1, M_IP6OPT);
2582 	if (dst->ip6po_dest2) free(dst->ip6po_dest2, M_IP6OPT);
2583 	if (dst->ip6po_rthdr) free(dst->ip6po_rthdr, M_IP6OPT);
2584 	free(dst, M_IP6OPT);
2585 	return (NULL);
2586 }
2587 #undef PKTOPT_EXTHDRCPY
2588 
2589 void
2590 ip6_freepcbopts(pktopt)
2591 	struct ip6_pktopts *pktopt;
2592 {
2593 	if (pktopt == NULL)
2594 		return;
2595 
2596 	ip6_clearpktopts(pktopt, -1);
2597 
2598 	free(pktopt, M_IP6OPT);
2599 }
2600 
2601 /*
2602  * Set the IP6 multicast options in response to user setsockopt().
2603  */
2604 static int
2605 ip6_setmoptions(optname, im6op, m)
2606 	int optname;
2607 	struct ip6_moptions **im6op;
2608 	struct mbuf *m;
2609 {
2610 	int error = 0;
2611 	u_int loop, ifindex;
2612 	struct ipv6_mreq *mreq;
2613 	struct ifnet *ifp;
2614 	struct ip6_moptions *im6o = *im6op;
2615 	struct route_in6 ro;
2616 	struct sockaddr_in6 *dst;
2617 	struct in6_multi_mship *imm;
2618 	struct thread *td = curthread;
2619 
2620 	if (im6o == NULL) {
2621 		/*
2622 		 * No multicast option buffer attached to the pcb;
2623 		 * allocate one and initialize to default values.
2624 		 */
2625 		im6o = (struct ip6_moptions *)
2626 			malloc(sizeof(*im6o), M_IPMOPTS, M_WAITOK);
2627 
2628 		if (im6o == NULL)
2629 			return (ENOBUFS);
2630 		*im6op = im6o;
2631 		im6o->im6o_multicast_ifp = NULL;
2632 		im6o->im6o_multicast_hlim = ip6_defmcasthlim;
2633 		im6o->im6o_multicast_loop = IPV6_DEFAULT_MULTICAST_LOOP;
2634 		LIST_INIT(&im6o->im6o_memberships);
2635 	}
2636 
2637 	switch (optname) {
2638 
2639 	case IPV6_MULTICAST_IF:
2640 		/*
2641 		 * Select the interface for outgoing multicast packets.
2642 		 */
2643 		if (m == NULL || m->m_len != sizeof(u_int)) {
2644 			error = EINVAL;
2645 			break;
2646 		}
2647 		bcopy(mtod(m, u_int *), &ifindex, sizeof(ifindex));
2648 		if (ifindex < 0 || if_index < ifindex) {
2649 			error = ENXIO;	/* XXX EINVAL? */
2650 			break;
2651 		}
2652 		ifp = ifnet_byindex(ifindex);
2653 		if (ifp == NULL || (ifp->if_flags & IFF_MULTICAST) == 0) {
2654 			error = EADDRNOTAVAIL;
2655 			break;
2656 		}
2657 		im6o->im6o_multicast_ifp = ifp;
2658 		break;
2659 
2660 	case IPV6_MULTICAST_HOPS:
2661 	    {
2662 		/*
2663 		 * Set the IP6 hoplimit for outgoing multicast packets.
2664 		 */
2665 		int optval;
2666 		if (m == NULL || m->m_len != sizeof(int)) {
2667 			error = EINVAL;
2668 			break;
2669 		}
2670 		bcopy(mtod(m, u_int *), &optval, sizeof(optval));
2671 		if (optval < -1 || optval >= 256)
2672 			error = EINVAL;
2673 		else if (optval == -1)
2674 			im6o->im6o_multicast_hlim = ip6_defmcasthlim;
2675 		else
2676 			im6o->im6o_multicast_hlim = optval;
2677 		break;
2678 	    }
2679 
2680 	case IPV6_MULTICAST_LOOP:
2681 		/*
2682 		 * Set the loopback flag for outgoing multicast packets.
2683 		 * Must be zero or one.
2684 		 */
2685 		if (m == NULL || m->m_len != sizeof(u_int)) {
2686 			error = EINVAL;
2687 			break;
2688 		}
2689 		bcopy(mtod(m, u_int *), &loop, sizeof(loop));
2690 		if (loop > 1) {
2691 			error = EINVAL;
2692 			break;
2693 		}
2694 		im6o->im6o_multicast_loop = loop;
2695 		break;
2696 
2697 	case IPV6_JOIN_GROUP:
2698 		/*
2699 		 * Add a multicast group membership.
2700 		 * Group must be a valid IP6 multicast address.
2701 		 */
2702 		if (m == NULL || m->m_len != sizeof(struct ipv6_mreq)) {
2703 			error = EINVAL;
2704 			break;
2705 		}
2706 		mreq = mtod(m, struct ipv6_mreq *);
2707 		if (IN6_IS_ADDR_UNSPECIFIED(&mreq->ipv6mr_multiaddr)) {
2708 			/*
2709 			 * We use the unspecified address to specify to accept
2710 			 * all multicast addresses. Only super user is allowed
2711 			 * to do this.
2712 			 */
2713 			if (suser(td)) {
2714 				error = EACCES;
2715 				break;
2716 			}
2717 		} else if (!IN6_IS_ADDR_MULTICAST(&mreq->ipv6mr_multiaddr)) {
2718 			error = EINVAL;
2719 			break;
2720 		}
2721 
2722 		/*
2723 		 * If the interface is specified, validate it.
2724 		 */
2725 		if (mreq->ipv6mr_interface < 0 ||
2726 		    if_index < mreq->ipv6mr_interface) {
2727 			error = ENXIO;	/* XXX EINVAL? */
2728 			break;
2729 		}
2730 		/*
2731 		 * If no interface was explicitly specified, choose an
2732 		 * appropriate one according to the given multicast address.
2733 		 */
2734 		if (mreq->ipv6mr_interface == 0) {
2735 			/*
2736 			 * If the multicast address is in node-local scope,
2737 			 * the interface should be a loopback interface.
2738 			 * Otherwise, look up the routing table for the
2739 			 * address, and choose the outgoing interface.
2740 			 *   XXX: is it a good approach?
2741 			 */
2742 			if (IN6_IS_ADDR_MC_INTFACELOCAL(&mreq->ipv6mr_multiaddr)) {
2743 				ifp = &loif[0];
2744 			} else {
2745 				ro.ro_rt = NULL;
2746 				dst = (struct sockaddr_in6 *)&ro.ro_dst;
2747 				bzero(dst, sizeof(*dst));
2748 				dst->sin6_len = sizeof(struct sockaddr_in6);
2749 				dst->sin6_family = AF_INET6;
2750 				dst->sin6_addr = mreq->ipv6mr_multiaddr;
2751 				rtalloc((struct route *)&ro);
2752 				if (ro.ro_rt == NULL) {
2753 					error = EADDRNOTAVAIL;
2754 					break;
2755 				}
2756 				ifp = ro.ro_rt->rt_ifp;
2757 				RTFREE(ro.ro_rt);
2758 			}
2759 		} else
2760 			ifp = ifnet_byindex(mreq->ipv6mr_interface);
2761 
2762 		/*
2763 		 * See if we found an interface, and confirm that it
2764 		 * supports multicast
2765 		 */
2766 		if (ifp == NULL || (ifp->if_flags & IFF_MULTICAST) == 0) {
2767 			error = EADDRNOTAVAIL;
2768 			break;
2769 		}
2770 		/*
2771 		 * Put interface index into the multicast address,
2772 		 * if the address has link-local scope.
2773 		 */
2774 		if (IN6_IS_ADDR_MC_LINKLOCAL(&mreq->ipv6mr_multiaddr)) {
2775 			mreq->ipv6mr_multiaddr.s6_addr16[1] =
2776 			    htons(ifp->if_index);
2777 		}
2778 		/*
2779 		 * See if the membership already exists.
2780 		 */
2781 		for (imm = im6o->im6o_memberships.lh_first;
2782 		     imm != NULL; imm = imm->i6mm_chain.le_next)
2783 			if (imm->i6mm_maddr->in6m_ifp == ifp &&
2784 			    IN6_ARE_ADDR_EQUAL(&imm->i6mm_maddr->in6m_addr,
2785 					       &mreq->ipv6mr_multiaddr))
2786 				break;
2787 		if (imm != NULL) {
2788 			error = EADDRINUSE;
2789 			break;
2790 		}
2791 		/*
2792 		 * Everything looks good; add a new record to the multicast
2793 		 * address list for the given interface.
2794 		 */
2795 		imm = malloc(sizeof(*imm), M_IPMADDR, M_WAITOK);
2796 		if (imm == NULL) {
2797 			error = ENOBUFS;
2798 			break;
2799 		}
2800 		if ((imm->i6mm_maddr =
2801 		     in6_addmulti(&mreq->ipv6mr_multiaddr, ifp, &error)) == NULL) {
2802 			free(imm, M_IPMADDR);
2803 			break;
2804 		}
2805 		LIST_INSERT_HEAD(&im6o->im6o_memberships, imm, i6mm_chain);
2806 		break;
2807 
2808 	case IPV6_LEAVE_GROUP:
2809 		/*
2810 		 * Drop a multicast group membership.
2811 		 * Group must be a valid IP6 multicast address.
2812 		 */
2813 		if (m == NULL || m->m_len != sizeof(struct ipv6_mreq)) {
2814 			error = EINVAL;
2815 			break;
2816 		}
2817 		mreq = mtod(m, struct ipv6_mreq *);
2818 		if (IN6_IS_ADDR_UNSPECIFIED(&mreq->ipv6mr_multiaddr)) {
2819 			if (suser(td)) {
2820 				error = EACCES;
2821 				break;
2822 			}
2823 		} else if (!IN6_IS_ADDR_MULTICAST(&mreq->ipv6mr_multiaddr)) {
2824 			error = EINVAL;
2825 			break;
2826 		}
2827 		/*
2828 		 * If an interface address was specified, get a pointer
2829 		 * to its ifnet structure.
2830 		 */
2831 		if (mreq->ipv6mr_interface < 0
2832 		 || if_index < mreq->ipv6mr_interface) {
2833 			error = ENXIO;	/* XXX EINVAL? */
2834 			break;
2835 		}
2836 		ifp = ifnet_byindex(mreq->ipv6mr_interface);
2837 		/*
2838 		 * Put interface index into the multicast address,
2839 		 * if the address has link-local scope.
2840 		 */
2841 		if (IN6_IS_ADDR_MC_LINKLOCAL(&mreq->ipv6mr_multiaddr)) {
2842 			mreq->ipv6mr_multiaddr.s6_addr16[1]
2843 				= htons(mreq->ipv6mr_interface);
2844 		}
2845 
2846 		/*
2847 		 * Find the membership in the membership list.
2848 		 */
2849 		for (imm = im6o->im6o_memberships.lh_first;
2850 		     imm != NULL; imm = imm->i6mm_chain.le_next) {
2851 			if ((ifp == NULL || imm->i6mm_maddr->in6m_ifp == ifp) &&
2852 			    IN6_ARE_ADDR_EQUAL(&imm->i6mm_maddr->in6m_addr,
2853 			    &mreq->ipv6mr_multiaddr))
2854 				break;
2855 		}
2856 		if (imm == NULL) {
2857 			/* Unable to resolve interface */
2858 			error = EADDRNOTAVAIL;
2859 			break;
2860 		}
2861 		/*
2862 		 * Give up the multicast address record to which the
2863 		 * membership points.
2864 		 */
2865 		LIST_REMOVE(imm, i6mm_chain);
2866 		in6_delmulti(imm->i6mm_maddr);
2867 		free(imm, M_IPMADDR);
2868 		break;
2869 
2870 	default:
2871 		error = EOPNOTSUPP;
2872 		break;
2873 	}
2874 
2875 	/*
2876 	 * If all options have default values, no need to keep the mbuf.
2877 	 */
2878 	if (im6o->im6o_multicast_ifp == NULL &&
2879 	    im6o->im6o_multicast_hlim == ip6_defmcasthlim &&
2880 	    im6o->im6o_multicast_loop == IPV6_DEFAULT_MULTICAST_LOOP &&
2881 	    im6o->im6o_memberships.lh_first == NULL) {
2882 		free(*im6op, M_IPMOPTS);
2883 		*im6op = NULL;
2884 	}
2885 
2886 	return (error);
2887 }
2888 
2889 /*
2890  * Return the IP6 multicast options in response to user getsockopt().
2891  */
2892 static int
2893 ip6_getmoptions(optname, im6o, mp)
2894 	int optname;
2895 	struct ip6_moptions *im6o;
2896 	struct mbuf **mp;
2897 {
2898 	u_int *hlim, *loop, *ifindex;
2899 
2900 	*mp = m_get(M_TRYWAIT, MT_HEADER);		/* XXX */
2901 
2902 	switch (optname) {
2903 
2904 	case IPV6_MULTICAST_IF:
2905 		ifindex = mtod(*mp, u_int *);
2906 		(*mp)->m_len = sizeof(u_int);
2907 		if (im6o == NULL || im6o->im6o_multicast_ifp == NULL)
2908 			*ifindex = 0;
2909 		else
2910 			*ifindex = im6o->im6o_multicast_ifp->if_index;
2911 		return (0);
2912 
2913 	case IPV6_MULTICAST_HOPS:
2914 		hlim = mtod(*mp, u_int *);
2915 		(*mp)->m_len = sizeof(u_int);
2916 		if (im6o == NULL)
2917 			*hlim = ip6_defmcasthlim;
2918 		else
2919 			*hlim = im6o->im6o_multicast_hlim;
2920 		return (0);
2921 
2922 	case IPV6_MULTICAST_LOOP:
2923 		loop = mtod(*mp, u_int *);
2924 		(*mp)->m_len = sizeof(u_int);
2925 		if (im6o == NULL)
2926 			*loop = ip6_defmcasthlim;
2927 		else
2928 			*loop = im6o->im6o_multicast_loop;
2929 		return (0);
2930 
2931 	default:
2932 		return (EOPNOTSUPP);
2933 	}
2934 }
2935 
2936 /*
2937  * Discard the IP6 multicast options.
2938  */
2939 void
2940 ip6_freemoptions(im6o)
2941 	struct ip6_moptions *im6o;
2942 {
2943 	struct in6_multi_mship *imm;
2944 
2945 	if (im6o == NULL)
2946 		return;
2947 
2948 	while ((imm = im6o->im6o_memberships.lh_first) != NULL) {
2949 		LIST_REMOVE(imm, i6mm_chain);
2950 		if (imm->i6mm_maddr)
2951 			in6_delmulti(imm->i6mm_maddr);
2952 		free(imm, M_IPMADDR);
2953 	}
2954 	free(im6o, M_IPMOPTS);
2955 }
2956 
2957 /*
2958  * Set IPv6 outgoing packet options based on advanced API.
2959  */
2960 int
2961 ip6_setpktoptions(control, opt, stickyopt, priv, needcopy, uproto)
2962 	struct mbuf *control;
2963 	struct ip6_pktopts *opt, *stickyopt;
2964 	int priv, needcopy, uproto;
2965 {
2966 	struct cmsghdr *cm = 0;
2967 
2968 	if (control == 0 || opt == 0)
2969 		return (EINVAL);
2970 
2971 	if (stickyopt) {
2972 		/*
2973 		 * If stickyopt is provided, make a local copy of the options
2974 		 * for this particular packet, then override them by ancillary
2975 		 * objects.
2976 		 * XXX: need to gain a reference for the cached route of the
2977 		 * next hop in case of the overriding.
2978 		 */
2979 		*opt = *stickyopt;
2980 		if (opt->ip6po_nextroute.ro_rt) {
2981 			RT_LOCK(opt->ip6po_nextroute.ro_rt);
2982 			RT_ADDREF(opt->ip6po_nextroute.ro_rt);
2983 			RT_UNLOCK(opt->ip6po_nextroute.ro_rt);
2984 		}
2985 	} else
2986 		init_ip6pktopts(opt);
2987 	opt->needfree = needcopy;
2988 
2989 	/*
2990 	 * XXX: Currently, we assume all the optional information is stored
2991 	 * in a single mbuf.
2992 	 */
2993 	if (control->m_next)
2994 		return (EINVAL);
2995 
2996 	for (; control->m_len; control->m_data += CMSG_ALIGN(cm->cmsg_len),
2997 	    control->m_len -= CMSG_ALIGN(cm->cmsg_len)) {
2998 		int error;
2999 
3000 		if (control->m_len < CMSG_LEN(0))
3001 			return (EINVAL);
3002 
3003 		cm = mtod(control, struct cmsghdr *);
3004 		if (cm->cmsg_len == 0 || cm->cmsg_len > control->m_len)
3005 			return (EINVAL);
3006 		if (cm->cmsg_level != IPPROTO_IPV6)
3007 			continue;
3008 
3009 		error = ip6_setpktoption(cm->cmsg_type, CMSG_DATA(cm),
3010 		    cm->cmsg_len - CMSG_LEN(0), opt, priv, needcopy, 1, uproto);
3011 		if (error)
3012 			return (error);
3013 	}
3014 
3015 	return (0);
3016 }
3017 
3018 /*
3019  * Set a particular packet option, as a sticky option or an ancillary data
3020  * item.  "len" can be 0 only when it's a sticky option.
3021  * We have 4 cases of combination of "sticky" and "cmsg":
3022  * "sticky=0, cmsg=0": impossible
3023  * "sticky=0, cmsg=1": RFC2292 or rfc2292bis ancillary data
3024  * "sticky=1, cmsg=0": rfc2292bis socket option
3025  * "sticky=1, cmsg=1": RFC2292 socket option
3026  */
3027 static int
3028 ip6_setpktoption(optname, buf, len, opt, priv, sticky, cmsg, uproto)
3029 	int optname, len, priv, sticky, cmsg, uproto;
3030 	u_char *buf;
3031 	struct ip6_pktopts *opt;
3032 {
3033 	int minmtupolicy, preftemp;
3034 
3035 	if (!sticky && !cmsg) {
3036 #ifdef DIAGNOSTIC
3037 		printf("ip6_setpktoption: impossible case\n");
3038 #endif
3039 		return (EINVAL);
3040 	}
3041 
3042 	/*
3043 	 * IPV6_2292xxx is for backward compatibility to RFC2292, and should
3044 	 * not be specified in the context of rfc2292bis.  Conversely,
3045 	 * rfc2292bis types should not be specified in the context of RFC2292.
3046 	 */
3047 	if (!cmsg) {
3048 		switch (optname) {
3049 		case IPV6_2292PKTINFO:
3050 		case IPV6_2292HOPLIMIT:
3051 		case IPV6_2292NEXTHOP:
3052 		case IPV6_2292HOPOPTS:
3053 		case IPV6_2292DSTOPTS:
3054 		case IPV6_2292RTHDR:
3055 		case IPV6_2292PKTOPTIONS:
3056 			return (ENOPROTOOPT);
3057 		}
3058 	}
3059 	if (sticky && cmsg) {
3060 		switch (optname) {
3061 		case IPV6_PKTINFO:
3062 		case IPV6_HOPLIMIT:
3063 		case IPV6_NEXTHOP:
3064 		case IPV6_HOPOPTS:
3065 		case IPV6_DSTOPTS:
3066 		case IPV6_RTHDRDSTOPTS:
3067 		case IPV6_RTHDR:
3068 		case IPV6_USE_MIN_MTU:
3069 		case IPV6_DONTFRAG:
3070 		case IPV6_TCLASS:
3071 		case IPV6_PREFER_TEMPADDR: /* XXX: not an rfc2292bis option */
3072 			return (ENOPROTOOPT);
3073 		}
3074 	}
3075 
3076 	switch (optname) {
3077 	case IPV6_2292PKTINFO:
3078 	case IPV6_PKTINFO:
3079 	{
3080 		struct ifnet *ifp = NULL;
3081 		struct in6_pktinfo *pktinfo;
3082 
3083 		if (len != sizeof(struct in6_pktinfo))
3084 			return (EINVAL);
3085 
3086 		pktinfo = (struct in6_pktinfo *)buf;
3087 
3088 		/*
3089 		 * An application can clear any sticky IPV6_PKTINFO option by
3090 		 * doing a "regular" setsockopt with ipi6_addr being
3091 		 * in6addr_any and ipi6_ifindex being zero.
3092 		 * [RFC 3542, Section 6]
3093 		 */
3094 		if (optname == IPV6_PKTINFO && opt->ip6po_pktinfo &&
3095 		    pktinfo->ipi6_ifindex == 0 &&
3096 		    IN6_IS_ADDR_UNSPECIFIED(&pktinfo->ipi6_addr)) {
3097 			ip6_clearpktopts(opt, optname);
3098 			break;
3099 		}
3100 
3101 		if (uproto == IPPROTO_TCP && optname == IPV6_PKTINFO &&
3102 		    sticky && !IN6_IS_ADDR_UNSPECIFIED(&pktinfo->ipi6_addr)) {
3103 			return (EINVAL);
3104 		}
3105 
3106 		/* validate the interface index if specified. */
3107 		if (pktinfo->ipi6_ifindex > if_index ||
3108 		    pktinfo->ipi6_ifindex < 0) {
3109 			 return (ENXIO);
3110 		}
3111 		if (pktinfo->ipi6_ifindex) {
3112 			ifp = ifnet_byindex(pktinfo->ipi6_ifindex);
3113 			if (ifp == NULL)
3114 				return (ENXIO);
3115 		}
3116 
3117 		/*
3118 		 * We store the address anyway, and let in6_selectsrc()
3119 		 * validate the specified address.  This is because ipi6_addr
3120 		 * may not have enough information about its scope zone, and
3121 		 * we may need additional information (such as outgoing
3122 		 * interface or the scope zone of a destination address) to
3123 		 * disambiguate the scope.
3124 		 * XXX: the delay of the validation may confuse the
3125 		 * application when it is used as a sticky option.
3126 		 */
3127 		if (sticky) {
3128 			if (opt->ip6po_pktinfo == NULL) {
3129 				opt->ip6po_pktinfo = malloc(sizeof(*pktinfo),
3130 				    M_IP6OPT, M_WAITOK);
3131 			}
3132 			bcopy(pktinfo, opt->ip6po_pktinfo, sizeof(*pktinfo));
3133 		} else
3134 			opt->ip6po_pktinfo = pktinfo;
3135 		break;
3136 	}
3137 
3138 	case IPV6_2292HOPLIMIT:
3139 	case IPV6_HOPLIMIT:
3140 	{
3141 		int *hlimp;
3142 
3143 		/*
3144 		 * RFC 3542 deprecated the usage of sticky IPV6_HOPLIMIT
3145 		 * to simplify the ordering among hoplimit options.
3146 		 */
3147 		if (optname == IPV6_HOPLIMIT && sticky)
3148 			return (ENOPROTOOPT);
3149 
3150 		if (len != sizeof(int))
3151 			return (EINVAL);
3152 		hlimp = (int *)buf;
3153 		if (*hlimp < -1 || *hlimp > 255)
3154 			return (EINVAL);
3155 
3156 		opt->ip6po_hlim = *hlimp;
3157 		break;
3158 	}
3159 
3160 	case IPV6_TCLASS:
3161 	{
3162 		int tclass;
3163 
3164 		if (len != sizeof(int))
3165 			return (EINVAL);
3166 		tclass = *(int *)buf;
3167 		if (tclass < -1 || tclass > 255)
3168 			return (EINVAL);
3169 
3170 		opt->ip6po_tclass = tclass;
3171 		break;
3172 	}
3173 
3174 	case IPV6_2292NEXTHOP:
3175 	case IPV6_NEXTHOP:
3176 		if (!priv)
3177 			return (EPERM);
3178 
3179 		if (len == 0) {	/* just remove the option */
3180 			ip6_clearpktopts(opt, IPV6_NEXTHOP);
3181 			break;
3182 		}
3183 
3184 		/* check if cmsg_len is large enough for sa_len */
3185 		if (len < sizeof(struct sockaddr) || len < *buf)
3186 			return (EINVAL);
3187 
3188 		switch (((struct sockaddr *)buf)->sa_family) {
3189 		case AF_INET6:
3190 		{
3191 			struct sockaddr_in6 *sa6 = (struct sockaddr_in6 *)buf;
3192 #if 0
3193 			int error;
3194 #endif
3195 
3196 			if (sa6->sin6_len != sizeof(struct sockaddr_in6))
3197 				return (EINVAL);
3198 
3199 			if (IN6_IS_ADDR_UNSPECIFIED(&sa6->sin6_addr) ||
3200 			    IN6_IS_ADDR_MULTICAST(&sa6->sin6_addr)) {
3201 				return (EINVAL);
3202 			}
3203 #if 0
3204 			if ((error = scope6_check_id(sa6, ip6_use_defzone))
3205 			    != 0) {
3206 				return (error);
3207 			}
3208 #endif
3209 			sa6->sin6_scope_id = 0; /* XXX */
3210 			break;
3211 		}
3212 		case AF_LINK:	/* should eventually be supported */
3213 		default:
3214 			return (EAFNOSUPPORT);
3215 		}
3216 
3217 		/* turn off the previous option, then set the new option. */
3218 		ip6_clearpktopts(opt, IPV6_NEXTHOP);
3219 		if (sticky) {
3220 			opt->ip6po_nexthop = malloc(*buf, M_IP6OPT, M_WAITOK);
3221 			bcopy(buf, opt->ip6po_nexthop, *buf);
3222 		} else
3223 			opt->ip6po_nexthop = (struct sockaddr *)buf;
3224 		break;
3225 
3226 	case IPV6_2292HOPOPTS:
3227 	case IPV6_HOPOPTS:
3228 	{
3229 		struct ip6_hbh *hbh;
3230 		int hbhlen;
3231 
3232 		/*
3233 		 * XXX: We don't allow a non-privileged user to set ANY HbH
3234 		 * options, since per-option restriction has too much
3235 		 * overhead.
3236 		 */
3237 		if (!priv)
3238 			return (EPERM);
3239 
3240 		if (len == 0) {
3241 			ip6_clearpktopts(opt, IPV6_HOPOPTS);
3242 			break;	/* just remove the option */
3243 		}
3244 
3245 		/* message length validation */
3246 		if (len < sizeof(struct ip6_hbh))
3247 			return (EINVAL);
3248 		hbh = (struct ip6_hbh *)buf;
3249 		hbhlen = (hbh->ip6h_len + 1) << 3;
3250 		if (len != hbhlen)
3251 			return (EINVAL);
3252 
3253 		/* turn off the previous option, then set the new option. */
3254 		ip6_clearpktopts(opt, IPV6_HOPOPTS);
3255 		if (sticky) {
3256 			opt->ip6po_hbh = malloc(hbhlen, M_IP6OPT, M_WAITOK);
3257 			bcopy(hbh, opt->ip6po_hbh, hbhlen);
3258 		} else
3259 			opt->ip6po_hbh = hbh;
3260 
3261 		break;
3262 	}
3263 
3264 	case IPV6_2292DSTOPTS:
3265 	case IPV6_DSTOPTS:
3266 	case IPV6_RTHDRDSTOPTS:
3267 	{
3268 		struct ip6_dest *dest, **newdest = NULL;
3269 		int destlen;
3270 
3271 		if (!priv)	/* XXX: see the comment for IPV6_HOPOPTS */
3272 			return (EPERM);
3273 
3274 		if (len == 0) {
3275 			ip6_clearpktopts(opt, optname);
3276 			break;	/* just remove the option */
3277 		}
3278 
3279 		/* message length validation */
3280 		if (len < sizeof(struct ip6_dest))
3281 			return (EINVAL);
3282 		dest = (struct ip6_dest *)buf;
3283 		destlen = (dest->ip6d_len + 1) << 3;
3284 		if (len != destlen)
3285 			return (EINVAL);
3286 
3287 		/*
3288 		 * Determine the position that the destination options header
3289 		 * should be inserted; before or after the routing header.
3290 		 */
3291 		switch (optname) {
3292 		case IPV6_2292DSTOPTS:
3293 			/*
3294 			 * The old advacned API is ambiguous on this point.
3295 			 * Our approach is to determine the position based
3296 			 * according to the existence of a routing header.
3297 			 * Note, however, that this depends on the order of the
3298 			 * extension headers in the ancillary data; the 1st
3299 			 * part of the destination options header must appear
3300 			 * before the routing header in the ancillary data,
3301 			 * too.
3302 			 * RFC2292bis solved the ambiguity by introducing
3303 			 * separate ancillary data or option types.
3304 			 */
3305 			if (opt->ip6po_rthdr == NULL)
3306 				newdest = &opt->ip6po_dest1;
3307 			else
3308 				newdest = &opt->ip6po_dest2;
3309 			break;
3310 		case IPV6_RTHDRDSTOPTS:
3311 			newdest = &opt->ip6po_dest1;
3312 			break;
3313 		case IPV6_DSTOPTS:
3314 			newdest = &opt->ip6po_dest2;
3315 			break;
3316 		}
3317 
3318 		/* turn off the previous option, then set the new option. */
3319 		ip6_clearpktopts(opt, optname);
3320 		if (sticky) {
3321 			*newdest = malloc(destlen, M_IP6OPT, M_WAITOK);
3322 			bcopy(dest, *newdest, destlen);
3323 		} else
3324 			*newdest = dest;
3325 
3326 		break;
3327 	}
3328 
3329 	case IPV6_2292RTHDR:
3330 	case IPV6_RTHDR:
3331 	{
3332 		struct ip6_rthdr *rth;
3333 		int rthlen;
3334 
3335 		if (len == 0) {
3336 			ip6_clearpktopts(opt, IPV6_RTHDR);
3337 			break;	/* just remove the option */
3338 		}
3339 
3340 		/* message length validation */
3341 		if (len < sizeof(struct ip6_rthdr))
3342 			return (EINVAL);
3343 		rth = (struct ip6_rthdr *)buf;
3344 		rthlen = (rth->ip6r_len + 1) << 3;
3345 		if (len != rthlen)
3346 			return (EINVAL);
3347 
3348 		switch (rth->ip6r_type) {
3349 		case IPV6_RTHDR_TYPE_0:
3350 			if (rth->ip6r_len == 0)	/* must contain one addr */
3351 				return (EINVAL);
3352 			if (rth->ip6r_len % 2) /* length must be even */
3353 				return (EINVAL);
3354 			if (rth->ip6r_len / 2 != rth->ip6r_segleft)
3355 				return (EINVAL);
3356 			break;
3357 		default:
3358 			return (EINVAL);	/* not supported */
3359 		}
3360 
3361 		/* turn off the previous option */
3362 		ip6_clearpktopts(opt, IPV6_RTHDR);
3363 		if (sticky) {
3364 			opt->ip6po_rthdr = malloc(rthlen, M_IP6OPT, M_WAITOK);
3365 			bcopy(rth, opt->ip6po_rthdr, rthlen);
3366 		} else
3367 			opt->ip6po_rthdr = rth;
3368 
3369 		break;
3370 	}
3371 
3372 	case IPV6_USE_MIN_MTU:
3373 		if (len != sizeof(int))
3374 			return (EINVAL);
3375 		minmtupolicy = *(int *)buf;
3376 		if (minmtupolicy != IP6PO_MINMTU_MCASTONLY &&
3377 		    minmtupolicy != IP6PO_MINMTU_DISABLE &&
3378 		    minmtupolicy != IP6PO_MINMTU_ALL) {
3379 			return (EINVAL);
3380 		}
3381 		opt->ip6po_minmtu = minmtupolicy;
3382 		break;
3383 
3384 	case IPV6_DONTFRAG:
3385 		if (len != sizeof(int))
3386 			return (EINVAL);
3387 
3388 		if (uproto == IPPROTO_TCP || *(int *)buf == 0) {
3389 			/*
3390 			 * we ignore this option for TCP sockets.
3391 			 * (rfc2292bis leaves this case unspecified.)
3392 			 */
3393 			opt->ip6po_flags &= ~IP6PO_DONTFRAG;
3394 		} else
3395 			opt->ip6po_flags |= IP6PO_DONTFRAG;
3396 		break;
3397 
3398 	case IPV6_PREFER_TEMPADDR:
3399 		if (len != sizeof(int))
3400 			return (EINVAL);
3401 		preftemp = *(int *)buf;
3402 		if (preftemp != IP6PO_TEMPADDR_SYSTEM &&
3403 		    preftemp != IP6PO_TEMPADDR_NOTPREFER &&
3404 		    preftemp != IP6PO_TEMPADDR_PREFER) {
3405 			return (EINVAL);
3406 		}
3407 		opt->ip6po_prefer_tempaddr = preftemp;
3408 		break;
3409 
3410 	default:
3411 		return (ENOPROTOOPT);
3412 	} /* end of switch */
3413 
3414 	return (0);
3415 }
3416 
3417 /*
3418  * Routine called from ip6_output() to loop back a copy of an IP6 multicast
3419  * packet to the input queue of a specified interface.  Note that this
3420  * calls the output routine of the loopback "driver", but with an interface
3421  * pointer that might NOT be &loif -- easier than replicating that code here.
3422  */
3423 void
3424 ip6_mloopback(ifp, m, dst)
3425 	struct ifnet *ifp;
3426 	struct mbuf *m;
3427 	struct sockaddr_in6 *dst;
3428 {
3429 	struct mbuf *copym;
3430 	struct ip6_hdr *ip6;
3431 
3432 	copym = m_copy(m, 0, M_COPYALL);
3433 	if (copym == NULL)
3434 		return;
3435 
3436 	/*
3437 	 * Make sure to deep-copy IPv6 header portion in case the data
3438 	 * is in an mbuf cluster, so that we can safely override the IPv6
3439 	 * header portion later.
3440 	 */
3441 	if ((copym->m_flags & M_EXT) != 0 ||
3442 	    copym->m_len < sizeof(struct ip6_hdr)) {
3443 		copym = m_pullup(copym, sizeof(struct ip6_hdr));
3444 		if (copym == NULL)
3445 			return;
3446 	}
3447 
3448 #ifdef DIAGNOSTIC
3449 	if (copym->m_len < sizeof(*ip6)) {
3450 		m_freem(copym);
3451 		return;
3452 	}
3453 #endif
3454 
3455 	ip6 = mtod(copym, struct ip6_hdr *);
3456 	/*
3457 	 * clear embedded scope identifiers if necessary.
3458 	 * in6_clearscope will touch the addresses only when necessary.
3459 	 */
3460 	in6_clearscope(&ip6->ip6_src);
3461 	in6_clearscope(&ip6->ip6_dst);
3462 
3463 	(void)if_simloop(ifp, copym, dst->sin6_family, 0);
3464 }
3465 
3466 /*
3467  * Chop IPv6 header off from the payload.
3468  */
3469 static int
3470 ip6_splithdr(m, exthdrs)
3471 	struct mbuf *m;
3472 	struct ip6_exthdrs *exthdrs;
3473 {
3474 	struct mbuf *mh;
3475 	struct ip6_hdr *ip6;
3476 
3477 	ip6 = mtod(m, struct ip6_hdr *);
3478 	if (m->m_len > sizeof(*ip6)) {
3479 		MGETHDR(mh, M_DONTWAIT, MT_HEADER);
3480 		if (mh == 0) {
3481 			m_freem(m);
3482 			return ENOBUFS;
3483 		}
3484 		M_MOVE_PKTHDR(mh, m);
3485 		MH_ALIGN(mh, sizeof(*ip6));
3486 		m->m_len -= sizeof(*ip6);
3487 		m->m_data += sizeof(*ip6);
3488 		mh->m_next = m;
3489 		m = mh;
3490 		m->m_len = sizeof(*ip6);
3491 		bcopy((caddr_t)ip6, mtod(m, caddr_t), sizeof(*ip6));
3492 	}
3493 	exthdrs->ip6e_ip6 = m;
3494 	return 0;
3495 }
3496 
3497 /*
3498  * Compute IPv6 extension header length.
3499  */
3500 int
3501 ip6_optlen(in6p)
3502 	struct in6pcb *in6p;
3503 {
3504 	int len;
3505 
3506 	if (!in6p->in6p_outputopts)
3507 		return 0;
3508 
3509 	len = 0;
3510 #define elen(x) \
3511     (((struct ip6_ext *)(x)) ? (((struct ip6_ext *)(x))->ip6e_len + 1) << 3 : 0)
3512 
3513 	len += elen(in6p->in6p_outputopts->ip6po_hbh);
3514 	if (in6p->in6p_outputopts->ip6po_rthdr)
3515 		/* dest1 is valid with rthdr only */
3516 		len += elen(in6p->in6p_outputopts->ip6po_dest1);
3517 	len += elen(in6p->in6p_outputopts->ip6po_rthdr);
3518 	len += elen(in6p->in6p_outputopts->ip6po_dest2);
3519 	return len;
3520 #undef elen
3521 }
3522