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