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