xref: /openbsd-src/sys/netinet6/ip6_output.c (revision 5054e3e78af0749a9bb00ba9a024b3ee2d90290f)
1 /*	$OpenBSD: ip6_output.c,v 1.108 2009/10/28 21:03:17 deraadt 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 				*mp = m = m_get(M_WAIT, MT_SOOPTS);
1918 #ifndef IPSEC
1919 				m->m_len = sizeof(int);
1920 				*mtod(m, int *) = IPSEC_LEVEL_NONE;
1921 #else
1922 				m->m_len = sizeof(int);
1923 				switch (optname) {
1924 				case IPV6_AUTH_LEVEL:
1925 					optval = inp->inp_seclevel[SL_AUTH];
1926 					break;
1927 
1928 				case IPV6_ESP_TRANS_LEVEL:
1929 					optval =
1930 					    inp->inp_seclevel[SL_ESP_TRANS];
1931 					break;
1932 
1933 				case IPV6_ESP_NETWORK_LEVEL:
1934 					optval =
1935 					    inp->inp_seclevel[SL_ESP_NETWORK];
1936 					break;
1937 
1938 				case IPV6_IPCOMP_LEVEL:
1939 					optval = inp->inp_seclevel[SL_IPCOMP];
1940 					break;
1941 				}
1942 				*mtod(m, int *) = optval;
1943 #endif
1944 				break;
1945 
1946 			default:
1947 				error = ENOPROTOOPT;
1948 				break;
1949 			}
1950 			break;
1951 		}
1952 	} else {
1953 		error = EINVAL;
1954 		if (op == PRCO_SETOPT && *mp)
1955 			(void)m_free(*mp);
1956 	}
1957 	return (error);
1958 }
1959 
1960 int
1961 ip6_raw_ctloutput(int op, struct socket *so, int level, int optname,
1962 	struct mbuf **mp)
1963 {
1964 	int error = 0, optval, optlen;
1965 	const int icmp6off = offsetof(struct icmp6_hdr, icmp6_cksum);
1966 	struct inpcb *inp = sotoinpcb(so);
1967 	struct mbuf *m = *mp;
1968 
1969 	optlen = m ? m->m_len : 0;
1970 
1971 	if (level != IPPROTO_IPV6) {
1972 		if (op == PRCO_SETOPT && *mp)
1973 			(void)m_free(*mp);
1974 		return (EINVAL);
1975 	}
1976 
1977 	switch (optname) {
1978 	case IPV6_CHECKSUM:
1979 		/*
1980 		 * For ICMPv6 sockets, no modification allowed for checksum
1981 		 * offset, permit "no change" values to help existing apps.
1982 		 *
1983 		 * RFC3542 says: "An attempt to set IPV6_CHECKSUM
1984 		 * for an ICMPv6 socket will fail."
1985 		 * The current behavior does not meet RFC3542.
1986 		 */
1987 		switch (op) {
1988 		case PRCO_SETOPT:
1989 			if (optlen != sizeof(int)) {
1990 				error = EINVAL;
1991 				break;
1992 			}
1993 			optval = *mtod(m, int *);
1994 			if ((optval % 2) != 0) {
1995 				/* the API assumes even offset values */
1996 				error = EINVAL;
1997 			} else if (so->so_proto->pr_protocol == IPPROTO_ICMPV6) {
1998 				if (optval != icmp6off)
1999 					error = EINVAL;
2000 			} else
2001 				inp->in6p_cksum = optval;
2002 			break;
2003 
2004 		case PRCO_GETOPT:
2005 			if (so->so_proto->pr_protocol == IPPROTO_ICMPV6)
2006 				optval = icmp6off;
2007 			else
2008 				optval = inp->in6p_cksum;
2009 
2010 			*mp = m = m_get(M_WAIT, MT_SOOPTS);
2011 			m->m_len = sizeof(int);
2012 			*mtod(m, int *) = optval;
2013 			break;
2014 
2015 		default:
2016 			error = EINVAL;
2017 			break;
2018 		}
2019 		break;
2020 
2021 	default:
2022 		error = ENOPROTOOPT;
2023 		break;
2024 	}
2025 
2026 	if (op == PRCO_SETOPT && m)
2027 		(void)m_free(m);
2028 
2029 	return (error);
2030 }
2031 
2032 /*
2033  * Set up IP6 options in pcb for insertion in output packets.
2034  * Store in mbuf with pointer in pcbopt, adding pseudo-option
2035  * with destination address if source routed.
2036  */
2037 static int
2038 ip6_pcbopts(struct ip6_pktopts **pktopt, struct mbuf *m, struct socket *so)
2039 {
2040 	struct ip6_pktopts *opt = *pktopt;
2041 	int error = 0;
2042 	struct proc *p = curproc;	/* XXX */
2043 	int priv = 0;
2044 
2045 	/* turn off any old options. */
2046 	if (opt)
2047 		ip6_clearpktopts(opt, -1);
2048 	else
2049 		opt = malloc(sizeof(*opt), M_IP6OPT, M_WAITOK);
2050 	*pktopt = 0;
2051 
2052 	if (!m || m->m_len == 0) {
2053 		/*
2054 		 * Only turning off any previous options, regardless of
2055 		 * whether the opt is just created or given.
2056 		 */
2057 		free(opt, M_IP6OPT);
2058 		return (0);
2059 	}
2060 
2061 	/*  set options specified by user. */
2062 	if (p && !suser(p, 0))
2063 		priv = 1;
2064 	if ((error = ip6_setpktopts(m, opt, NULL, priv,
2065 	    so->so_proto->pr_protocol)) != 0) {
2066 		ip6_clearpktopts(opt, -1);	/* XXX discard all options */
2067 		free(opt, M_IP6OPT);
2068 		return (error);
2069 	}
2070 	*pktopt = opt;
2071 	return (0);
2072 }
2073 
2074 /*
2075  * initialize ip6_pktopts.  beware that there are non-zero default values in
2076  * the struct.
2077  */
2078 void
2079 ip6_initpktopts(struct ip6_pktopts *opt)
2080 {
2081 
2082 	bzero(opt, sizeof(*opt));
2083 	opt->ip6po_hlim = -1;	/* -1 means default hop limit */
2084 	opt->ip6po_tclass = -1;	/* -1 means default traffic class */
2085 	opt->ip6po_minmtu = IP6PO_MINMTU_MCASTONLY;
2086 }
2087 
2088 #define sin6tosa(sin6)	((struct sockaddr *)(sin6)) /* XXX */
2089 static int
2090 ip6_pcbopt(int optname, u_char *buf, int len, struct ip6_pktopts **pktopt,
2091 	int priv, int uproto)
2092 {
2093 	struct ip6_pktopts *opt;
2094 
2095 	if (*pktopt == NULL) {
2096 		*pktopt = malloc(sizeof(struct ip6_pktopts), M_IP6OPT,
2097 		    M_WAITOK);
2098 		ip6_initpktopts(*pktopt);
2099 	}
2100 	opt = *pktopt;
2101 
2102 	return (ip6_setpktopt(optname, buf, len, opt, priv, 1, 0, uproto));
2103 }
2104 
2105 static int
2106 ip6_getpcbopt(struct ip6_pktopts *pktopt, int optname, struct mbuf **mp)
2107 {
2108 	void *optdata = NULL;
2109 	int optdatalen = 0;
2110 	struct ip6_ext *ip6e;
2111 	int error = 0;
2112 	struct in6_pktinfo null_pktinfo;
2113 	int deftclass = 0, on;
2114 	int defminmtu = IP6PO_MINMTU_MCASTONLY;
2115 	struct mbuf *m;
2116 
2117 	switch (optname) {
2118 	case IPV6_PKTINFO:
2119 		if (pktopt && pktopt->ip6po_pktinfo)
2120 			optdata = (void *)pktopt->ip6po_pktinfo;
2121 		else {
2122 			/* XXX: we don't have to do this every time... */
2123 			bzero(&null_pktinfo, sizeof(null_pktinfo));
2124 			optdata = (void *)&null_pktinfo;
2125 		}
2126 		optdatalen = sizeof(struct in6_pktinfo);
2127 		break;
2128 	case IPV6_TCLASS:
2129 		if (pktopt && pktopt->ip6po_tclass >= 0)
2130 			optdata = (void *)&pktopt->ip6po_tclass;
2131 		else
2132 			optdata = (void *)&deftclass;
2133 		optdatalen = sizeof(int);
2134 		break;
2135 	case IPV6_HOPOPTS:
2136 		if (pktopt && pktopt->ip6po_hbh) {
2137 			optdata = (void *)pktopt->ip6po_hbh;
2138 			ip6e = (struct ip6_ext *)pktopt->ip6po_hbh;
2139 			optdatalen = (ip6e->ip6e_len + 1) << 3;
2140 		}
2141 		break;
2142 	case IPV6_RTHDR:
2143 		if (pktopt && pktopt->ip6po_rthdr) {
2144 			optdata = (void *)pktopt->ip6po_rthdr;
2145 			ip6e = (struct ip6_ext *)pktopt->ip6po_rthdr;
2146 			optdatalen = (ip6e->ip6e_len + 1) << 3;
2147 		}
2148 		break;
2149 	case IPV6_RTHDRDSTOPTS:
2150 		if (pktopt && pktopt->ip6po_dest1) {
2151 			optdata = (void *)pktopt->ip6po_dest1;
2152 			ip6e = (struct ip6_ext *)pktopt->ip6po_dest1;
2153 			optdatalen = (ip6e->ip6e_len + 1) << 3;
2154 		}
2155 		break;
2156 	case IPV6_DSTOPTS:
2157 		if (pktopt && pktopt->ip6po_dest2) {
2158 			optdata = (void *)pktopt->ip6po_dest2;
2159 			ip6e = (struct ip6_ext *)pktopt->ip6po_dest2;
2160 			optdatalen = (ip6e->ip6e_len + 1) << 3;
2161 		}
2162 		break;
2163 	case IPV6_NEXTHOP:
2164 		if (pktopt && pktopt->ip6po_nexthop) {
2165 			optdata = (void *)pktopt->ip6po_nexthop;
2166 			optdatalen = pktopt->ip6po_nexthop->sa_len;
2167 		}
2168 		break;
2169 	case IPV6_USE_MIN_MTU:
2170 		if (pktopt)
2171 			optdata = (void *)&pktopt->ip6po_minmtu;
2172 		else
2173 			optdata = (void *)&defminmtu;
2174 		optdatalen = sizeof(int);
2175 		break;
2176 	case IPV6_DONTFRAG:
2177 		if (pktopt && ((pktopt->ip6po_flags) & IP6PO_DONTFRAG))
2178 			on = 1;
2179 		else
2180 			on = 0;
2181 		optdata = (void *)&on;
2182 		optdatalen = sizeof(on);
2183 		break;
2184 	default:		/* should not happen */
2185 #ifdef DIAGNOSTIC
2186 		panic("ip6_getpcbopt: unexpected option\n");
2187 #endif
2188 		return (ENOPROTOOPT);
2189 	}
2190 
2191 	if (optdatalen > MCLBYTES)
2192 		return (EMSGSIZE); /* XXX */
2193 	*mp = m = m_get(M_WAIT, MT_SOOPTS);
2194 	if (optdatalen > MLEN)
2195 		MCLGET(m, M_WAIT);
2196 	m->m_len = optdatalen;
2197 	if (optdatalen)
2198 		bcopy(optdata, mtod(m, void *), optdatalen);
2199 
2200 	return (error);
2201 }
2202 
2203 void
2204 ip6_clearpktopts(struct ip6_pktopts *pktopt, int optname)
2205 {
2206 	if (optname == -1 || optname == IPV6_PKTINFO) {
2207 		if (pktopt->ip6po_pktinfo)
2208 			free(pktopt->ip6po_pktinfo, M_IP6OPT);
2209 		pktopt->ip6po_pktinfo = NULL;
2210 	}
2211 	if (optname == -1 || optname == IPV6_HOPLIMIT)
2212 		pktopt->ip6po_hlim = -1;
2213 	if (optname == -1 || optname == IPV6_TCLASS)
2214 		pktopt->ip6po_tclass = -1;
2215 	if (optname == -1 || optname == IPV6_NEXTHOP) {
2216 		if (pktopt->ip6po_nextroute.ro_rt) {
2217 			RTFREE(pktopt->ip6po_nextroute.ro_rt);
2218 			pktopt->ip6po_nextroute.ro_rt = NULL;
2219 		}
2220 		if (pktopt->ip6po_nexthop)
2221 			free(pktopt->ip6po_nexthop, M_IP6OPT);
2222 		pktopt->ip6po_nexthop = NULL;
2223 	}
2224 	if (optname == -1 || optname == IPV6_HOPOPTS) {
2225 		if (pktopt->ip6po_hbh)
2226 			free(pktopt->ip6po_hbh, M_IP6OPT);
2227 		pktopt->ip6po_hbh = NULL;
2228 	}
2229 	if (optname == -1 || optname == IPV6_RTHDRDSTOPTS) {
2230 		if (pktopt->ip6po_dest1)
2231 			free(pktopt->ip6po_dest1, M_IP6OPT);
2232 		pktopt->ip6po_dest1 = NULL;
2233 	}
2234 	if (optname == -1 || optname == IPV6_RTHDR) {
2235 		if (pktopt->ip6po_rhinfo.ip6po_rhi_rthdr)
2236 			free(pktopt->ip6po_rhinfo.ip6po_rhi_rthdr, M_IP6OPT);
2237 		pktopt->ip6po_rhinfo.ip6po_rhi_rthdr = NULL;
2238 		if (pktopt->ip6po_route.ro_rt) {
2239 			RTFREE(pktopt->ip6po_route.ro_rt);
2240 			pktopt->ip6po_route.ro_rt = NULL;
2241 		}
2242 	}
2243 	if (optname == -1 || optname == IPV6_DSTOPTS) {
2244 		if (pktopt->ip6po_dest2)
2245 			free(pktopt->ip6po_dest2, M_IP6OPT);
2246 		pktopt->ip6po_dest2 = NULL;
2247 	}
2248 }
2249 
2250 #define PKTOPT_EXTHDRCPY(type) \
2251 do {\
2252 	if (src->type) {\
2253 		int hlen = (((struct ip6_ext *)src->type)->ip6e_len + 1) << 3;\
2254 		dst->type = malloc(hlen, M_IP6OPT, canwait);\
2255 		if (dst->type == NULL && canwait == M_NOWAIT)\
2256 			goto bad;\
2257 		bcopy(src->type, dst->type, hlen);\
2258 	}\
2259 } while (/*CONSTCOND*/ 0)
2260 
2261 static int
2262 copypktopts(struct ip6_pktopts *dst, struct ip6_pktopts *src, int canwait)
2263 {
2264 	dst->ip6po_hlim = src->ip6po_hlim;
2265 	dst->ip6po_tclass = src->ip6po_tclass;
2266 	dst->ip6po_flags = src->ip6po_flags;
2267 	if (src->ip6po_pktinfo) {
2268 		dst->ip6po_pktinfo = malloc(sizeof(*dst->ip6po_pktinfo),
2269 		    M_IP6OPT, canwait);
2270 		if (dst->ip6po_pktinfo == NULL && canwait == M_NOWAIT)
2271 			goto bad;
2272 		*dst->ip6po_pktinfo = *src->ip6po_pktinfo;
2273 	}
2274 	if (src->ip6po_nexthop) {
2275 		dst->ip6po_nexthop = malloc(src->ip6po_nexthop->sa_len,
2276 		    M_IP6OPT, canwait);
2277 		if (dst->ip6po_nexthop == NULL && canwait == M_NOWAIT)
2278 			goto bad;
2279 		bcopy(src->ip6po_nexthop, dst->ip6po_nexthop,
2280 		    src->ip6po_nexthop->sa_len);
2281 	}
2282 	PKTOPT_EXTHDRCPY(ip6po_hbh);
2283 	PKTOPT_EXTHDRCPY(ip6po_dest1);
2284 	PKTOPT_EXTHDRCPY(ip6po_dest2);
2285 	PKTOPT_EXTHDRCPY(ip6po_rthdr); /* not copy the cached route */
2286 	return (0);
2287 
2288   bad:
2289 	ip6_clearpktopts(dst, -1);
2290 	return (ENOBUFS);
2291 }
2292 #undef PKTOPT_EXTHDRCPY
2293 
2294 void
2295 ip6_freepcbopts(struct ip6_pktopts *pktopt)
2296 {
2297 	if (pktopt == NULL)
2298 		return;
2299 
2300 	ip6_clearpktopts(pktopt, -1);
2301 
2302 	free(pktopt, M_IP6OPT);
2303 }
2304 
2305 /*
2306  * Set the IP6 multicast options in response to user setsockopt().
2307  */
2308 static int
2309 ip6_setmoptions(int optname, struct ip6_moptions **im6op, struct mbuf *m)
2310 {
2311 	int error = 0;
2312 	u_int loop, ifindex;
2313 	struct ipv6_mreq *mreq;
2314 	struct ifnet *ifp;
2315 	struct ip6_moptions *im6o = *im6op;
2316 	struct route_in6 ro;
2317 	struct sockaddr_in6 *dst;
2318 	struct in6_multi_mship *imm;
2319 	struct proc *p = curproc;	/* XXX */
2320 
2321 	if (im6o == NULL) {
2322 		/*
2323 		 * No multicast option buffer attached to the pcb;
2324 		 * allocate one and initialize to default values.
2325 		 */
2326 		im6o = (struct ip6_moptions *)
2327 			malloc(sizeof(*im6o), M_IPMOPTS, M_WAITOK);
2328 
2329 		if (im6o == NULL)
2330 			return (ENOBUFS);
2331 		*im6op = im6o;
2332 		im6o->im6o_multicast_ifp = NULL;
2333 		im6o->im6o_multicast_hlim = ip6_defmcasthlim;
2334 		im6o->im6o_multicast_loop = IPV6_DEFAULT_MULTICAST_LOOP;
2335 		LIST_INIT(&im6o->im6o_memberships);
2336 	}
2337 
2338 	switch (optname) {
2339 
2340 	case IPV6_MULTICAST_IF:
2341 		/*
2342 		 * Select the interface for outgoing multicast packets.
2343 		 */
2344 		if (m == NULL || m->m_len != sizeof(u_int)) {
2345 			error = EINVAL;
2346 			break;
2347 		}
2348 		bcopy(mtod(m, u_int *), &ifindex, sizeof(ifindex));
2349 		if (ifindex == 0)
2350 			ifp = NULL;
2351 		else {
2352 			if (ifindex < 0 || if_indexlim <= ifindex ||
2353 			    !ifindex2ifnet[ifindex]) {
2354 				error = ENXIO;	/* XXX EINVAL? */
2355 				break;
2356 			}
2357 			ifp = ifindex2ifnet[ifindex];
2358 			if (ifp == NULL ||
2359 			    (ifp->if_flags & IFF_MULTICAST) == 0) {
2360 				error = EADDRNOTAVAIL;
2361 				break;
2362 			}
2363 		}
2364 		im6o->im6o_multicast_ifp = ifp;
2365 		break;
2366 
2367 	case IPV6_MULTICAST_HOPS:
2368 	    {
2369 		/*
2370 		 * Set the IP6 hoplimit for outgoing multicast packets.
2371 		 */
2372 		int optval;
2373 		if (m == NULL || m->m_len != sizeof(int)) {
2374 			error = EINVAL;
2375 			break;
2376 		}
2377 		bcopy(mtod(m, u_int *), &optval, sizeof(optval));
2378 		if (optval < -1 || optval >= 256)
2379 			error = EINVAL;
2380 		else if (optval == -1)
2381 			im6o->im6o_multicast_hlim = ip6_defmcasthlim;
2382 		else
2383 			im6o->im6o_multicast_hlim = optval;
2384 		break;
2385 	    }
2386 
2387 	case IPV6_MULTICAST_LOOP:
2388 		/*
2389 		 * Set the loopback flag for outgoing multicast packets.
2390 		 * Must be zero or one.
2391 		 */
2392 		if (m == NULL || m->m_len != sizeof(u_int)) {
2393 			error = EINVAL;
2394 			break;
2395 		}
2396 		bcopy(mtod(m, u_int *), &loop, sizeof(loop));
2397 		if (loop > 1) {
2398 			error = EINVAL;
2399 			break;
2400 		}
2401 		im6o->im6o_multicast_loop = loop;
2402 		break;
2403 
2404 	case IPV6_JOIN_GROUP:
2405 		/*
2406 		 * Add a multicast group membership.
2407 		 * Group must be a valid IP6 multicast address.
2408 		 */
2409 		if (m == NULL || m->m_len != sizeof(struct ipv6_mreq)) {
2410 			error = EINVAL;
2411 			break;
2412 		}
2413 		mreq = mtod(m, struct ipv6_mreq *);
2414 		if (IN6_IS_ADDR_UNSPECIFIED(&mreq->ipv6mr_multiaddr)) {
2415 			/*
2416 			 * We use the unspecified address to specify to accept
2417 			 * all multicast addresses. Only super user is allowed
2418 			 * to do this.
2419 			 */
2420 			if (suser(p, 0))
2421 			{
2422 				error = EACCES;
2423 				break;
2424 			}
2425 		} else if (!IN6_IS_ADDR_MULTICAST(&mreq->ipv6mr_multiaddr)) {
2426 			error = EINVAL;
2427 			break;
2428 		}
2429 
2430 		/*
2431 		 * If no interface was explicitly specified, choose an
2432 		 * appropriate one according to the given multicast address.
2433 		 */
2434 		if (mreq->ipv6mr_interface == 0) {
2435 			/*
2436 			 * Look up the routing table for the
2437 			 * address, and choose the outgoing interface.
2438 			 *   XXX: is it a good approach?
2439 			 */
2440 			ro.ro_rt = NULL;
2441 			dst = (struct sockaddr_in6 *)&ro.ro_dst;
2442 			bzero(dst, sizeof(*dst));
2443 			dst->sin6_len = sizeof(struct sockaddr_in6);
2444 			dst->sin6_family = AF_INET6;
2445 			dst->sin6_addr = mreq->ipv6mr_multiaddr;
2446 			rtalloc((struct route *)&ro);
2447 			if (ro.ro_rt == NULL) {
2448 				error = EADDRNOTAVAIL;
2449 				break;
2450 			}
2451 			ifp = ro.ro_rt->rt_ifp;
2452 			rtfree(ro.ro_rt);
2453 		} else {
2454 			/*
2455 			 * If the interface is specified, validate it.
2456 			 */
2457 			if (mreq->ipv6mr_interface < 0 ||
2458 			    if_indexlim <= mreq->ipv6mr_interface ||
2459 			    !ifindex2ifnet[mreq->ipv6mr_interface]) {
2460 				error = ENXIO;	/* XXX EINVAL? */
2461 				break;
2462 			}
2463 			ifp = ifindex2ifnet[mreq->ipv6mr_interface];
2464 		}
2465 
2466 		/*
2467 		 * See if we found an interface, and confirm that it
2468 		 * supports multicast
2469 		 */
2470 		if (ifp == NULL || (ifp->if_flags & IFF_MULTICAST) == 0) {
2471 			error = EADDRNOTAVAIL;
2472 			break;
2473 		}
2474 		/*
2475 		 * Put interface index into the multicast address,
2476 		 * if the address has link/interface-local scope.
2477 		 */
2478 		if (IN6_IS_SCOPE_EMBED(&mreq->ipv6mr_multiaddr)) {
2479 			mreq->ipv6mr_multiaddr.s6_addr16[1] =
2480 			    htons(ifp->if_index);
2481 		}
2482 		/*
2483 		 * See if the membership already exists.
2484 		 */
2485 		LIST_FOREACH(imm, &im6o->im6o_memberships, i6mm_chain)
2486 			if (imm->i6mm_maddr->in6m_ifp == ifp &&
2487 			    IN6_ARE_ADDR_EQUAL(&imm->i6mm_maddr->in6m_addr,
2488 			    &mreq->ipv6mr_multiaddr))
2489 				break;
2490 		if (imm != NULL) {
2491 			error = EADDRINUSE;
2492 			break;
2493 		}
2494 		/*
2495 		 * Everything looks good; add a new record to the multicast
2496 		 * address list for the given interface.
2497 		 */
2498 		imm = in6_joingroup(ifp, &mreq->ipv6mr_multiaddr, &error);
2499 		if (!imm)
2500 			break;
2501 		LIST_INSERT_HEAD(&im6o->im6o_memberships, imm, i6mm_chain);
2502 		break;
2503 
2504 	case IPV6_LEAVE_GROUP:
2505 		/*
2506 		 * Drop a multicast group membership.
2507 		 * Group must be a valid IP6 multicast address.
2508 		 */
2509 		if (m == NULL || m->m_len != sizeof(struct ipv6_mreq)) {
2510 			error = EINVAL;
2511 			break;
2512 		}
2513 		mreq = mtod(m, struct ipv6_mreq *);
2514 		if (IN6_IS_ADDR_UNSPECIFIED(&mreq->ipv6mr_multiaddr)) {
2515 			if (suser(p, 0))
2516 			{
2517 				error = EACCES;
2518 				break;
2519 			}
2520 		} else if (!IN6_IS_ADDR_MULTICAST(&mreq->ipv6mr_multiaddr)) {
2521 			error = EINVAL;
2522 			break;
2523 		}
2524 		/*
2525 		 * If an interface address was specified, get a pointer
2526 		 * to its ifnet structure.
2527 		 */
2528 		if (mreq->ipv6mr_interface == 0)
2529 			ifp = NULL;
2530 		else {
2531 			if (mreq->ipv6mr_interface < 0 ||
2532 			    if_indexlim <= mreq->ipv6mr_interface ||
2533 			    !ifindex2ifnet[mreq->ipv6mr_interface]) {
2534 				error = ENXIO;	/* XXX EINVAL? */
2535 				break;
2536 			}
2537 			ifp = ifindex2ifnet[mreq->ipv6mr_interface];
2538 		}
2539 
2540 		/*
2541 		 * Put interface index into the multicast address,
2542 		 * if the address has link-local scope.
2543 		 */
2544 		if (IN6_IS_ADDR_MC_LINKLOCAL(&mreq->ipv6mr_multiaddr)) {
2545 			mreq->ipv6mr_multiaddr.s6_addr16[1] =
2546 			    htons(mreq->ipv6mr_interface);
2547 		}
2548 		/*
2549 		 * Find the membership in the membership list.
2550 		 */
2551 		LIST_FOREACH(imm, &im6o->im6o_memberships, i6mm_chain) {
2552 			if ((ifp == NULL || imm->i6mm_maddr->in6m_ifp == ifp) &&
2553 			    IN6_ARE_ADDR_EQUAL(&imm->i6mm_maddr->in6m_addr,
2554 			    &mreq->ipv6mr_multiaddr))
2555 				break;
2556 		}
2557 		if (imm == NULL) {
2558 			/* Unable to resolve interface */
2559 			error = EADDRNOTAVAIL;
2560 			break;
2561 		}
2562 		/*
2563 		 * Give up the multicast address record to which the
2564 		 * membership points.
2565 		 */
2566 		LIST_REMOVE(imm, i6mm_chain);
2567 		in6_leavegroup(imm);
2568 		break;
2569 
2570 	default:
2571 		error = EOPNOTSUPP;
2572 		break;
2573 	}
2574 
2575 	/*
2576 	 * If all options have default values, no need to keep the option
2577 	 * structure.
2578 	 */
2579 	if (im6o->im6o_multicast_ifp == NULL &&
2580 	    im6o->im6o_multicast_hlim == ip6_defmcasthlim &&
2581 	    im6o->im6o_multicast_loop == IPV6_DEFAULT_MULTICAST_LOOP &&
2582 	    LIST_EMPTY(&im6o->im6o_memberships)) {
2583 		free(*im6op, M_IPMOPTS);
2584 		*im6op = NULL;
2585 	}
2586 
2587 	return (error);
2588 }
2589 
2590 /*
2591  * Return the IP6 multicast options in response to user getsockopt().
2592  */
2593 static int
2594 ip6_getmoptions(int optname, struct ip6_moptions *im6o, struct mbuf **mp)
2595 {
2596 	u_int *hlim, *loop, *ifindex;
2597 
2598 	*mp = m_get(M_WAIT, MT_SOOPTS);
2599 
2600 	switch (optname) {
2601 
2602 	case IPV6_MULTICAST_IF:
2603 		ifindex = mtod(*mp, u_int *);
2604 		(*mp)->m_len = sizeof(u_int);
2605 		if (im6o == NULL || im6o->im6o_multicast_ifp == NULL)
2606 			*ifindex = 0;
2607 		else
2608 			*ifindex = im6o->im6o_multicast_ifp->if_index;
2609 		return (0);
2610 
2611 	case IPV6_MULTICAST_HOPS:
2612 		hlim = mtod(*mp, u_int *);
2613 		(*mp)->m_len = sizeof(u_int);
2614 		if (im6o == NULL)
2615 			*hlim = ip6_defmcasthlim;
2616 		else
2617 			*hlim = im6o->im6o_multicast_hlim;
2618 		return (0);
2619 
2620 	case IPV6_MULTICAST_LOOP:
2621 		loop = mtod(*mp, u_int *);
2622 		(*mp)->m_len = sizeof(u_int);
2623 		if (im6o == NULL)
2624 			*loop = ip6_defmcasthlim;
2625 		else
2626 			*loop = im6o->im6o_multicast_loop;
2627 		return (0);
2628 
2629 	default:
2630 		return (EOPNOTSUPP);
2631 	}
2632 }
2633 
2634 /*
2635  * Discard the IP6 multicast options.
2636  */
2637 void
2638 ip6_freemoptions(struct ip6_moptions *im6o)
2639 {
2640 	struct in6_multi_mship *imm;
2641 
2642 	if (im6o == NULL)
2643 		return;
2644 
2645 	while (!LIST_EMPTY(&im6o->im6o_memberships)) {
2646 		imm = LIST_FIRST(&im6o->im6o_memberships);
2647 		LIST_REMOVE(imm, i6mm_chain);
2648 		in6_leavegroup(imm);
2649 	}
2650 	free(im6o, M_IPMOPTS);
2651 }
2652 
2653 /*
2654  * Set IPv6 outgoing packet options based on advanced API.
2655  */
2656 int
2657 ip6_setpktopts(struct mbuf *control, struct ip6_pktopts *opt,
2658 	struct ip6_pktopts *stickyopt, int priv, int uproto)
2659 {
2660 	u_int clen;
2661 	struct cmsghdr *cm = 0;
2662 	caddr_t cmsgs;
2663 	int error;
2664 
2665 	if (control == NULL || opt == NULL)
2666 		return (EINVAL);
2667 
2668 	ip6_initpktopts(opt);
2669 	if (stickyopt) {
2670 		int error;
2671 
2672 		/*
2673 		 * If stickyopt is provided, make a local copy of the options
2674 		 * for this particular packet, then override them by ancillary
2675 		 * objects.
2676 		 * XXX: copypktopts() does not copy the cached route to a next
2677 		 * hop (if any).  This is not very good in terms of efficiency,
2678 		 * but we can allow this since this option should be rarely
2679 		 * used.
2680 		 */
2681 		if ((error = copypktopts(opt, stickyopt, M_NOWAIT)) != 0)
2682 			return (error);
2683 	}
2684 
2685 	/*
2686 	 * XXX: Currently, we assume all the optional information is stored
2687 	 * in a single mbuf.
2688 	 */
2689 	if (control->m_next)
2690 		return (EINVAL);
2691 
2692 	clen = control->m_len;
2693 	cmsgs = mtod(control, caddr_t);
2694 	do {
2695 		if (clen < CMSG_LEN(0))
2696 			return (EINVAL);
2697 		cm = (struct cmsghdr *)cmsgs;
2698 		if (cm->cmsg_len < CMSG_LEN(0) ||
2699 		    CMSG_ALIGN(cm->cmsg_len) > clen)
2700 			return (EINVAL);
2701 		if (cm->cmsg_level == IPPROTO_IPV6) {
2702 			error = ip6_setpktopt(cm->cmsg_type, CMSG_DATA(cm),
2703 			    cm->cmsg_len - CMSG_LEN(0), opt, priv, 0, 1, uproto);
2704 			if (error)
2705 				return (error);
2706 		}
2707 
2708 		clen -= CMSG_ALIGN(cm->cmsg_len);
2709 		cmsgs += CMSG_ALIGN(cm->cmsg_len);
2710 	} while (clen);
2711 
2712 	return (0);
2713 }
2714 
2715 /*
2716  * Set a particular packet option, as a sticky option or an ancillary data
2717  * item.  "len" can be 0 only when it's a sticky option.
2718  * We have 4 cases of combination of "sticky" and "cmsg":
2719  * "sticky=0, cmsg=0": impossible
2720  * "sticky=0, cmsg=1": RFC2292 or RFC3542 ancillary data
2721  * "sticky=1, cmsg=0": RFC3542 socket option
2722  * "sticky=1, cmsg=1": RFC2292 socket option
2723  */
2724 static int
2725 ip6_setpktopt(int optname, u_char *buf, int len, struct ip6_pktopts *opt,
2726 	int priv, int sticky, int cmsg, int uproto)
2727 {
2728 	int minmtupolicy;
2729 
2730 	if (!sticky && !cmsg) {
2731 #ifdef DIAGNOSTIC
2732 		printf("ip6_setpktopt: impossible case\n");
2733 #endif
2734 		return (EINVAL);
2735 	}
2736 
2737 	/*
2738 	 * IPV6_2292xxx is for backward compatibility to RFC2292, and should
2739 	 * not be specified in the context of RFC3542.  Conversely,
2740 	 * RFC3542 types should not be specified in the context of RFC2292.
2741 	 */
2742 	if (!cmsg) {
2743 		switch (optname) {
2744 		case IPV6_2292PKTINFO:
2745 		case IPV6_2292HOPLIMIT:
2746 		case IPV6_2292NEXTHOP:
2747 		case IPV6_2292HOPOPTS:
2748 		case IPV6_2292DSTOPTS:
2749 		case IPV6_2292RTHDR:
2750 		case IPV6_2292PKTOPTIONS:
2751 			return (ENOPROTOOPT);
2752 		}
2753 	}
2754 	if (sticky && cmsg) {
2755 		switch (optname) {
2756 		case IPV6_PKTINFO:
2757 		case IPV6_HOPLIMIT:
2758 		case IPV6_NEXTHOP:
2759 		case IPV6_HOPOPTS:
2760 		case IPV6_DSTOPTS:
2761 		case IPV6_RTHDRDSTOPTS:
2762 		case IPV6_RTHDR:
2763 		case IPV6_USE_MIN_MTU:
2764 		case IPV6_DONTFRAG:
2765 		case IPV6_TCLASS:
2766 			return (ENOPROTOOPT);
2767 		}
2768 	}
2769 
2770 	switch (optname) {
2771 	case IPV6_2292PKTINFO:
2772 	case IPV6_PKTINFO:
2773 	{
2774 		struct ifnet *ifp = NULL;
2775 		struct in6_pktinfo *pktinfo;
2776 
2777 		if (len != sizeof(struct in6_pktinfo))
2778 			return (EINVAL);
2779 
2780 		pktinfo = (struct in6_pktinfo *)buf;
2781 
2782 		/*
2783 		 * An application can clear any sticky IPV6_PKTINFO option by
2784 		 * doing a "regular" setsockopt with ipi6_addr being
2785 		 * in6addr_any and ipi6_ifindex being zero.
2786 		 * [RFC 3542, Section 6]
2787 		 */
2788 		if (optname == IPV6_PKTINFO && opt->ip6po_pktinfo &&
2789 		    pktinfo->ipi6_ifindex == 0 &&
2790 		    IN6_IS_ADDR_UNSPECIFIED(&pktinfo->ipi6_addr)) {
2791 			ip6_clearpktopts(opt, optname);
2792 			break;
2793 		}
2794 
2795 		if (uproto == IPPROTO_TCP && optname == IPV6_PKTINFO &&
2796 		    sticky && !IN6_IS_ADDR_UNSPECIFIED(&pktinfo->ipi6_addr)) {
2797 			return (EINVAL);
2798 		}
2799 
2800 		/* validate the interface index if specified. */
2801 		if (pktinfo->ipi6_ifindex >= if_indexlim ||
2802 		    pktinfo->ipi6_ifindex < 0) {
2803 			 return (ENXIO);
2804 		}
2805 		if (pktinfo->ipi6_ifindex) {
2806 			ifp = ifindex2ifnet[pktinfo->ipi6_ifindex];
2807 			if (ifp == NULL)
2808 				return (ENXIO);
2809 		}
2810 
2811 		/*
2812 		 * We store the address anyway, and let in6_selectsrc()
2813 		 * validate the specified address.  This is because ipi6_addr
2814 		 * may not have enough information about its scope zone, and
2815 		 * we may need additional information (such as outgoing
2816 		 * interface or the scope zone of a destination address) to
2817 		 * disambiguate the scope.
2818 		 * XXX: the delay of the validation may confuse the
2819 		 * application when it is used as a sticky option.
2820 		 */
2821 		if (opt->ip6po_pktinfo == NULL) {
2822 			opt->ip6po_pktinfo = malloc(sizeof(*pktinfo),
2823 			    M_IP6OPT, M_NOWAIT);
2824 			if (opt->ip6po_pktinfo == NULL)
2825 				return (ENOBUFS);
2826 		}
2827 		bcopy(pktinfo, opt->ip6po_pktinfo, sizeof(*pktinfo));
2828 		break;
2829 	}
2830 
2831 	case IPV6_2292HOPLIMIT:
2832 	case IPV6_HOPLIMIT:
2833 	{
2834 		int *hlimp;
2835 
2836 		/*
2837 		 * RFC 3542 deprecated the usage of sticky IPV6_HOPLIMIT
2838 		 * to simplify the ordering among hoplimit options.
2839 		 */
2840 		if (optname == IPV6_HOPLIMIT && sticky)
2841 			return (ENOPROTOOPT);
2842 
2843 		if (len != sizeof(int))
2844 			return (EINVAL);
2845 		hlimp = (int *)buf;
2846 		if (*hlimp < -1 || *hlimp > 255)
2847 			return (EINVAL);
2848 
2849 		opt->ip6po_hlim = *hlimp;
2850 		break;
2851 	}
2852 
2853 	case IPV6_TCLASS:
2854 	{
2855 		int tclass;
2856 
2857 		if (len != sizeof(int))
2858 			return (EINVAL);
2859 		tclass = *(int *)buf;
2860 		if (tclass < -1 || tclass > 255)
2861 			return (EINVAL);
2862 
2863 		opt->ip6po_tclass = tclass;
2864 		break;
2865 	}
2866 
2867 	case IPV6_2292NEXTHOP:
2868 	case IPV6_NEXTHOP:
2869 		if (!priv)
2870 			return (EPERM);
2871 
2872 		if (len == 0) {	/* just remove the option */
2873 			ip6_clearpktopts(opt, IPV6_NEXTHOP);
2874 			break;
2875 		}
2876 
2877 		/* check if cmsg_len is large enough for sa_len */
2878 		if (len < sizeof(struct sockaddr) || len < *buf)
2879 			return (EINVAL);
2880 
2881 		switch (((struct sockaddr *)buf)->sa_family) {
2882 		case AF_INET6:
2883 		{
2884 			struct sockaddr_in6 *sa6 = (struct sockaddr_in6 *)buf;
2885 
2886 			if (sa6->sin6_len != sizeof(struct sockaddr_in6))
2887 				return (EINVAL);
2888 
2889 			if (IN6_IS_ADDR_UNSPECIFIED(&sa6->sin6_addr) ||
2890 			    IN6_IS_ADDR_MULTICAST(&sa6->sin6_addr)) {
2891 				return (EINVAL);
2892 			}
2893 			if (IN6_IS_SCOPE_EMBED(&sa6->sin6_addr)) {
2894 				if (sa6->sin6_scope_id < 0 ||
2895 				    if_indexlim <= sa6->sin6_scope_id ||
2896 				    !ifindex2ifnet[sa6->sin6_scope_id])
2897 					return (EINVAL);
2898 				sa6->sin6_addr.s6_addr16[1] =
2899 				    htonl(sa6->sin6_scope_id);
2900 			} else if (sa6->sin6_scope_id)
2901 				return (EINVAL);
2902 			break;
2903 		}
2904 		case AF_LINK:	/* eventually be supported? */
2905 		default:
2906 			return (EAFNOSUPPORT);
2907 		}
2908 
2909 		/* turn off the previous option, then set the new option. */
2910 		ip6_clearpktopts(opt, IPV6_NEXTHOP);
2911 		opt->ip6po_nexthop = malloc(*buf, M_IP6OPT, M_NOWAIT);
2912 		if (opt->ip6po_nexthop == NULL)
2913 			return (ENOBUFS);
2914 		bcopy(buf, opt->ip6po_nexthop, *buf);
2915 		break;
2916 
2917 	case IPV6_2292HOPOPTS:
2918 	case IPV6_HOPOPTS:
2919 	{
2920 		struct ip6_hbh *hbh;
2921 		int hbhlen;
2922 
2923 		/*
2924 		 * XXX: We don't allow a non-privileged user to set ANY HbH
2925 		 * options, since per-option restriction has too much
2926 		 * overhead.
2927 		 */
2928 		if (!priv)
2929 			return (EPERM);
2930 
2931 		if (len == 0) {
2932 			ip6_clearpktopts(opt, IPV6_HOPOPTS);
2933 			break;	/* just remove the option */
2934 		}
2935 
2936 		/* message length validation */
2937 		if (len < sizeof(struct ip6_hbh))
2938 			return (EINVAL);
2939 		hbh = (struct ip6_hbh *)buf;
2940 		hbhlen = (hbh->ip6h_len + 1) << 3;
2941 		if (len != hbhlen)
2942 			return (EINVAL);
2943 
2944 		/* turn off the previous option, then set the new option. */
2945 		ip6_clearpktopts(opt, IPV6_HOPOPTS);
2946 		opt->ip6po_hbh = malloc(hbhlen, M_IP6OPT, M_NOWAIT);
2947 		if (opt->ip6po_hbh == NULL)
2948 			return (ENOBUFS);
2949 		bcopy(hbh, opt->ip6po_hbh, hbhlen);
2950 
2951 		break;
2952 	}
2953 
2954 	case IPV6_2292DSTOPTS:
2955 	case IPV6_DSTOPTS:
2956 	case IPV6_RTHDRDSTOPTS:
2957 	{
2958 		struct ip6_dest *dest, **newdest = NULL;
2959 		int destlen;
2960 
2961 		if (!priv)	/* XXX: see the comment for IPV6_HOPOPTS */
2962 			return (EPERM);
2963 
2964 		if (len == 0) {
2965 			ip6_clearpktopts(opt, optname);
2966 			break;	/* just remove the option */
2967 		}
2968 
2969 		/* message length validation */
2970 		if (len < sizeof(struct ip6_dest))
2971 			return (EINVAL);
2972 		dest = (struct ip6_dest *)buf;
2973 		destlen = (dest->ip6d_len + 1) << 3;
2974 		if (len != destlen)
2975 			return (EINVAL);
2976 		/*
2977 		 * Determine the position that the destination options header
2978 		 * should be inserted; before or after the routing header.
2979 		 */
2980 		switch (optname) {
2981 		case IPV6_2292DSTOPTS:
2982 			/*
2983 			 * The old advanced API is ambiguous on this point.
2984 			 * Our approach is to determine the position based
2985 			 * according to the existence of a routing header.
2986 			 * Note, however, that this depends on the order of the
2987 			 * extension headers in the ancillary data; the 1st
2988 			 * part of the destination options header must appear
2989 			 * before the routing header in the ancillary data,
2990 			 * too.
2991 			 * RFC3542 solved the ambiguity by introducing
2992 			 * separate ancillary data or option types.
2993 			 */
2994 			if (opt->ip6po_rthdr == NULL)
2995 				newdest = &opt->ip6po_dest1;
2996 			else
2997 				newdest = &opt->ip6po_dest2;
2998 			break;
2999 		case IPV6_RTHDRDSTOPTS:
3000 			newdest = &opt->ip6po_dest1;
3001 			break;
3002 		case IPV6_DSTOPTS:
3003 			newdest = &opt->ip6po_dest2;
3004 			break;
3005 		}
3006 
3007 		/* turn off the previous option, then set the new option. */
3008 		ip6_clearpktopts(opt, optname);
3009 		*newdest = malloc(destlen, M_IP6OPT, M_NOWAIT);
3010 		if (*newdest == NULL)
3011 			return (ENOBUFS);
3012 		bcopy(dest, *newdest, destlen);
3013 
3014 		break;
3015 	}
3016 
3017 	case IPV6_2292RTHDR:
3018 	case IPV6_RTHDR:
3019 	{
3020 		struct ip6_rthdr *rth;
3021 		int rthlen;
3022 
3023 		if (len == 0) {
3024 			ip6_clearpktopts(opt, IPV6_RTHDR);
3025 			break;	/* just remove the option */
3026 		}
3027 
3028 		/* message length validation */
3029 		if (len < sizeof(struct ip6_rthdr))
3030 			return (EINVAL);
3031 		rth = (struct ip6_rthdr *)buf;
3032 		rthlen = (rth->ip6r_len + 1) << 3;
3033 		if (len != rthlen)
3034 			return (EINVAL);
3035 
3036 		switch (rth->ip6r_type) {
3037 		case IPV6_RTHDR_TYPE_0:
3038 			if (rth->ip6r_len == 0)	/* must contain one addr */
3039 				return (EINVAL);
3040 			if (rth->ip6r_len % 2) /* length must be even */
3041 				return (EINVAL);
3042 			if (rth->ip6r_len / 2 != rth->ip6r_segleft)
3043 				return (EINVAL);
3044 			break;
3045 		default:
3046 			return (EINVAL);	/* not supported */
3047 		}
3048 		/* turn off the previous option */
3049 		ip6_clearpktopts(opt, IPV6_RTHDR);
3050 		opt->ip6po_rthdr = malloc(rthlen, M_IP6OPT, M_NOWAIT);
3051 		if (opt->ip6po_rthdr == NULL)
3052 			return (ENOBUFS);
3053 		bcopy(rth, opt->ip6po_rthdr, rthlen);
3054 		break;
3055 	}
3056 
3057 	case IPV6_USE_MIN_MTU:
3058 		if (len != sizeof(int))
3059 			return (EINVAL);
3060 		minmtupolicy = *(int *)buf;
3061 		if (minmtupolicy != IP6PO_MINMTU_MCASTONLY &&
3062 		    minmtupolicy != IP6PO_MINMTU_DISABLE &&
3063 		    minmtupolicy != IP6PO_MINMTU_ALL) {
3064 			return (EINVAL);
3065 		}
3066 		opt->ip6po_minmtu = minmtupolicy;
3067 		break;
3068 
3069 	case IPV6_DONTFRAG:
3070 		if (len != sizeof(int))
3071 			return (EINVAL);
3072 
3073 		if (uproto == IPPROTO_TCP || *(int *)buf == 0) {
3074 			/*
3075 			 * we ignore this option for TCP sockets.
3076 			 * (RFC3542 leaves this case unspecified.)
3077 			 */
3078 			opt->ip6po_flags &= ~IP6PO_DONTFRAG;
3079 		} else
3080 			opt->ip6po_flags |= IP6PO_DONTFRAG;
3081 		break;
3082 
3083 	default:
3084 		return (ENOPROTOOPT);
3085 	} /* end of switch */
3086 
3087 	return (0);
3088 }
3089 
3090 /*
3091  * Routine called from ip6_output() to loop back a copy of an IP6 multicast
3092  * packet to the input queue of a specified interface.  Note that this
3093  * calls the output routine of the loopback "driver", but with an interface
3094  * pointer that might NOT be lo0ifp -- easier than replicating that code here.
3095  */
3096 void
3097 ip6_mloopback(struct ifnet *ifp, struct mbuf *m, struct sockaddr_in6 *dst)
3098 {
3099 	struct mbuf *copym;
3100 	struct ip6_hdr *ip6;
3101 
3102 	/*
3103 	 * Duplicate the packet.
3104 	 */
3105 	copym = m_copy(m, 0, M_COPYALL);
3106 	if (copym == NULL)
3107 		return;
3108 
3109 	/*
3110 	 * Make sure to deep-copy IPv6 header portion in case the data
3111 	 * is in an mbuf cluster, so that we can safely override the IPv6
3112 	 * header portion later.
3113 	 */
3114 	if ((copym->m_flags & M_EXT) != 0 ||
3115 	    copym->m_len < sizeof(struct ip6_hdr)) {
3116 		copym = m_pullup(copym, sizeof(struct ip6_hdr));
3117 		if (copym == NULL)
3118 			return;
3119 	}
3120 
3121 #ifdef DIAGNOSTIC
3122 	if (copym->m_len < sizeof(*ip6)) {
3123 		m_freem(copym);
3124 		return;
3125 	}
3126 #endif
3127 
3128 	ip6 = mtod(copym, struct ip6_hdr *);
3129 	if (IN6_IS_SCOPE_EMBED(&ip6->ip6_src))
3130 		ip6->ip6_src.s6_addr16[1] = 0;
3131 	if (IN6_IS_SCOPE_EMBED(&ip6->ip6_dst))
3132 		ip6->ip6_dst.s6_addr16[1] = 0;
3133 
3134 	(void)looutput(ifp, copym, (struct sockaddr *)dst, NULL);
3135 }
3136 
3137 /*
3138  * Chop IPv6 header off from the payload.
3139  */
3140 static int
3141 ip6_splithdr(struct mbuf *m, struct ip6_exthdrs *exthdrs)
3142 {
3143 	struct mbuf *mh;
3144 	struct ip6_hdr *ip6;
3145 
3146 	ip6 = mtod(m, struct ip6_hdr *);
3147 	if (m->m_len > sizeof(*ip6)) {
3148 		MGETHDR(mh, M_DONTWAIT, MT_HEADER);
3149 		if (mh == 0) {
3150 			m_freem(m);
3151 			return ENOBUFS;
3152 		}
3153 		M_MOVE_PKTHDR(mh, m);
3154 		MH_ALIGN(mh, sizeof(*ip6));
3155 		m->m_len -= sizeof(*ip6);
3156 		m->m_data += sizeof(*ip6);
3157 		mh->m_next = m;
3158 		m = mh;
3159 		m->m_len = sizeof(*ip6);
3160 		bcopy((caddr_t)ip6, mtod(m, caddr_t), sizeof(*ip6));
3161 	}
3162 	exthdrs->ip6e_ip6 = m;
3163 	return 0;
3164 }
3165 
3166 /*
3167  * Compute IPv6 extension header length.
3168  */
3169 int
3170 ip6_optlen(struct inpcb *inp)
3171 {
3172 	int len;
3173 
3174 	if (!inp->inp_outputopts6)
3175 		return 0;
3176 
3177 	len = 0;
3178 #define elen(x) \
3179     (((struct ip6_ext *)(x)) ? (((struct ip6_ext *)(x))->ip6e_len + 1) << 3 : 0)
3180 
3181 	len += elen(inp->inp_outputopts6->ip6po_hbh);
3182 	len += elen(inp->inp_outputopts6->ip6po_dest1);
3183 	len += elen(inp->inp_outputopts6->ip6po_rthdr);
3184 	len += elen(inp->inp_outputopts6->ip6po_dest2);
3185 	return len;
3186 #undef elen
3187 }
3188 
3189 u_int32_t
3190 ip6_randomid(void)
3191 {
3192 	return idgen32(&ip6_id_ctx);
3193 }
3194 
3195 void
3196 ip6_randomid_init(void)
3197 {
3198 	idgen32_init(&ip6_id_ctx);
3199 }
3200