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