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