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