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