xref: /netbsd-src/sys/netinet6/ip6_output.c (revision eb961d0e02b7a46a9acfa877b02df48df6637278)
1 /*	$NetBSD: ip6_output.c,v 1.95 2006/03/05 23:47:08 rpaulo 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 <sys/cdefs.h>
65 __KERNEL_RCSID(0, "$NetBSD: ip6_output.c,v 1.95 2006/03/05 23:47:08 rpaulo Exp $");
66 
67 #include "opt_inet.h"
68 #include "opt_ipsec.h"
69 #include "opt_pfil_hooks.h"
70 
71 #include <sys/param.h>
72 #include <sys/malloc.h>
73 #include <sys/mbuf.h>
74 #include <sys/errno.h>
75 #include <sys/protosw.h>
76 #include <sys/socket.h>
77 #include <sys/socketvar.h>
78 #include <sys/systm.h>
79 #include <sys/proc.h>
80 
81 #include <net/if.h>
82 #include <net/route.h>
83 #ifdef PFIL_HOOKS
84 #include <net/pfil.h>
85 #endif
86 
87 #include <netinet/in.h>
88 #include <netinet/in_var.h>
89 #include <netinet/ip6.h>
90 #include <netinet/icmp6.h>
91 #include <netinet/in_offload.h>
92 #include <netinet6/ip6_var.h>
93 #include <netinet6/in6_pcb.h>
94 #include <netinet6/nd6.h>
95 #include <netinet6/ip6protosw.h>
96 #include <netinet6/scope6_var.h>
97 
98 #ifdef IPSEC
99 #include <netinet6/ipsec.h>
100 #include <netkey/key.h>
101 #endif /* IPSEC */
102 
103 #include <net/net_osdep.h>
104 
105 #ifdef PFIL_HOOKS
106 extern struct pfil_head inet6_pfil_hook;	/* XXX */
107 #endif
108 
109 struct ip6_exthdrs {
110 	struct mbuf *ip6e_ip6;
111 	struct mbuf *ip6e_hbh;
112 	struct mbuf *ip6e_dest1;
113 	struct mbuf *ip6e_rthdr;
114 	struct mbuf *ip6e_dest2;
115 };
116 
117 static int ip6_pcbopts __P((struct ip6_pktopts **, struct mbuf *,
118 	struct socket *));
119 static int ip6_setmoptions __P((int, struct ip6_moptions **, struct mbuf *));
120 static int ip6_getmoptions __P((int, struct ip6_moptions *, struct mbuf **));
121 static int ip6_copyexthdr __P((struct mbuf **, caddr_t, int));
122 static int ip6_insertfraghdr __P((struct mbuf *, struct mbuf *, int,
123 	struct ip6_frag **));
124 static int ip6_insert_jumboopt __P((struct ip6_exthdrs *, u_int32_t));
125 static int ip6_splithdr __P((struct mbuf *, struct ip6_exthdrs *));
126 static int ip6_getpmtu __P((struct route_in6 *, struct route_in6 *,
127 	struct ifnet *, struct in6_addr *, u_long *, int *));
128 
129 #define	IN6_NEED_CHECKSUM(ifp, csum_flags) \
130 	(__predict_true(((ifp)->if_flags & IFF_LOOPBACK) == 0 || \
131 	(((csum_flags) & M_CSUM_UDPv6) != 0 && udp_do_loopback_cksum) || \
132 	(((csum_flags) & M_CSUM_TCPv6) != 0 && tcp_do_loopback_cksum)))
133 
134 /*
135  * IP6 output. The packet in mbuf chain m contains a skeletal IP6
136  * header (with pri, len, nxt, hlim, src, dst).
137  * This function may modify ver and hlim only.
138  * The mbuf chain containing the packet will be freed.
139  * The mbuf opt, if present, will not be freed.
140  *
141  * type of "mtu": rt_rmx.rmx_mtu is u_long, ifnet.ifr_mtu is int, and
142  * nd_ifinfo.linkmtu is u_int32_t.  so we use u_long to hold largest one,
143  * which is rt_rmx.rmx_mtu.
144  */
145 int
146 ip6_output(m0, opt, ro, flags, im6o, so, ifpp)
147 	struct mbuf *m0;
148 	struct ip6_pktopts *opt;
149 	struct route_in6 *ro;
150 	int flags;
151 	struct ip6_moptions *im6o;
152 	struct socket *so;
153 	struct ifnet **ifpp;		/* XXX: just for statistics */
154 {
155 	struct ip6_hdr *ip6, *mhip6;
156 	struct ifnet *ifp, *origifp;
157 	struct mbuf *m = m0;
158 	int hlen, tlen, len, off;
159 	struct route_in6 ip6route;
160 	struct rtentry *rt = NULL;
161 	struct sockaddr_in6 *dst, src_sa, dst_sa;
162 	int error = 0;
163 	struct in6_ifaddr *ia = NULL;
164 	u_long mtu;
165 	int alwaysfrag, dontfrag;
166 	u_int32_t optlen = 0, plen = 0, unfragpartlen = 0;
167 	struct ip6_exthdrs exthdrs;
168 	struct in6_addr finaldst, src0, dst0;
169 	u_int32_t zone;
170 	struct route_in6 *ro_pmtu = NULL;
171 	int hdrsplit = 0;
172 	int needipsec = 0;
173 #ifdef IPSEC
174 	int needipsectun = 0;
175 	struct secpolicy *sp = NULL;
176 
177 	ip6 = mtod(m, struct ip6_hdr *);
178 #endif /* IPSEC */
179 
180 	M_CSUM_DATA_IPv6_HL_SET(m->m_pkthdr.csum_data, sizeof(struct ip6_hdr));
181 
182 #define MAKE_EXTHDR(hp, mp)						\
183     do {								\
184 	if (hp) {							\
185 		struct ip6_ext *eh = (struct ip6_ext *)(hp);		\
186 		error = ip6_copyexthdr((mp), (caddr_t)(hp), 		\
187 		    ((eh)->ip6e_len + 1) << 3);				\
188 		if (error)						\
189 			goto freehdrs;					\
190 	}								\
191     } while (/*CONSTCOND*/ 0)
192 
193 	bzero(&exthdrs, sizeof(exthdrs));
194 	if (opt) {
195 		/* Hop-by-Hop options header */
196 		MAKE_EXTHDR(opt->ip6po_hbh, &exthdrs.ip6e_hbh);
197 		/* Destination options header(1st part) */
198 		MAKE_EXTHDR(opt->ip6po_dest1, &exthdrs.ip6e_dest1);
199 		/* Routing header */
200 		MAKE_EXTHDR(opt->ip6po_rthdr, &exthdrs.ip6e_rthdr);
201 		/* Destination options header(2nd part) */
202 		MAKE_EXTHDR(opt->ip6po_dest2, &exthdrs.ip6e_dest2);
203 	}
204 
205 #ifdef IPSEC
206 	if ((flags & IPV6_FORWARDING) != 0) {
207 		needipsec = 0;
208 		goto skippolicycheck;
209 	}
210 
211 	/* get a security policy for this packet */
212 	if (so == NULL)
213 		sp = ipsec6_getpolicybyaddr(m, IPSEC_DIR_OUTBOUND, 0, &error);
214 	else {
215 		if (IPSEC_PCB_SKIP_IPSEC(sotoinpcb_hdr(so)->inph_sp,
216 					 IPSEC_DIR_OUTBOUND)) {
217 			needipsec = 0;
218 			goto skippolicycheck;
219 		}
220 		sp = ipsec6_getpolicybysock(m, IPSEC_DIR_OUTBOUND, so, &error);
221 	}
222 
223 	if (sp == NULL) {
224 		ipsec6stat.out_inval++;
225 		goto freehdrs;
226 	}
227 
228 	error = 0;
229 
230 	/* check policy */
231 	switch (sp->policy) {
232 	case IPSEC_POLICY_DISCARD:
233 		/*
234 		 * This packet is just discarded.
235 		 */
236 		ipsec6stat.out_polvio++;
237 		goto freehdrs;
238 
239 	case IPSEC_POLICY_BYPASS:
240 	case IPSEC_POLICY_NONE:
241 		/* no need to do IPsec. */
242 		needipsec = 0;
243 		break;
244 
245 	case IPSEC_POLICY_IPSEC:
246 		if (sp->req == NULL) {
247 			/* XXX should be panic ? */
248 			printf("ip6_output: No IPsec request specified.\n");
249 			error = EINVAL;
250 			goto freehdrs;
251 		}
252 		needipsec = 1;
253 		break;
254 
255 	case IPSEC_POLICY_ENTRUST:
256 	default:
257 		printf("ip6_output: Invalid policy found. %d\n", sp->policy);
258 	}
259 
260   skippolicycheck:;
261 #endif /* IPSEC */
262 
263 	if (needipsec &&
264 	    (m->m_pkthdr.csum_flags & (M_CSUM_UDPv6|M_CSUM_TCPv6)) != 0) {
265 		in6_delayed_cksum(m);
266 		m->m_pkthdr.csum_flags &= ~(M_CSUM_UDPv6|M_CSUM_TCPv6);
267 	}
268 
269 	/*
270 	 * Calculate the total length of the extension header chain.
271 	 * Keep the length of the unfragmentable part for fragmentation.
272 	 */
273 	optlen = 0;
274 	if (exthdrs.ip6e_hbh) optlen += exthdrs.ip6e_hbh->m_len;
275 	if (exthdrs.ip6e_dest1) optlen += exthdrs.ip6e_dest1->m_len;
276 	if (exthdrs.ip6e_rthdr) optlen += exthdrs.ip6e_rthdr->m_len;
277 	unfragpartlen = optlen + sizeof(struct ip6_hdr);
278 	/* NOTE: we don't add AH/ESP length here. do that later. */
279 	if (exthdrs.ip6e_dest2) optlen += exthdrs.ip6e_dest2->m_len;
280 
281 	/*
282 	 * If we need IPsec, or there is at least one extension header,
283 	 * separate IP6 header from the payload.
284 	 */
285 	if ((needipsec || optlen) && !hdrsplit) {
286 		if ((error = ip6_splithdr(m, &exthdrs)) != 0) {
287 			m = NULL;
288 			goto freehdrs;
289 		}
290 		m = exthdrs.ip6e_ip6;
291 		hdrsplit++;
292 	}
293 
294 	/* adjust pointer */
295 	ip6 = mtod(m, struct ip6_hdr *);
296 
297 	/* adjust mbuf packet header length */
298 	m->m_pkthdr.len += optlen;
299 	plen = m->m_pkthdr.len - sizeof(*ip6);
300 
301 	/* If this is a jumbo payload, insert a jumbo payload option. */
302 	if (plen > IPV6_MAXPACKET) {
303 		if (!hdrsplit) {
304 			if ((error = ip6_splithdr(m, &exthdrs)) != 0) {
305 				m = NULL;
306 				goto freehdrs;
307 			}
308 			m = exthdrs.ip6e_ip6;
309 			hdrsplit++;
310 		}
311 		/* adjust pointer */
312 		ip6 = mtod(m, struct ip6_hdr *);
313 		if ((error = ip6_insert_jumboopt(&exthdrs, plen)) != 0)
314 			goto freehdrs;
315 		optlen += 8; /* XXX JUMBOOPTLEN */
316 		ip6->ip6_plen = 0;
317 	} else
318 		ip6->ip6_plen = htons(plen);
319 
320 	/*
321 	 * Concatenate headers and fill in next header fields.
322 	 * Here we have, on "m"
323 	 *	IPv6 payload
324 	 * and we insert headers accordingly.  Finally, we should be getting:
325 	 *	IPv6 hbh dest1 rthdr ah* [esp* dest2 payload]
326 	 *
327 	 * during the header composing process, "m" points to IPv6 header.
328 	 * "mprev" points to an extension header prior to esp.
329 	 */
330 	{
331 		u_char *nexthdrp = &ip6->ip6_nxt;
332 		struct mbuf *mprev = m;
333 
334 		/*
335 		 * we treat dest2 specially.  this makes IPsec processing
336 		 * much easier.  the goal here is to make mprev point the
337 		 * mbuf prior to dest2.
338 		 *
339 		 * result: IPv6 dest2 payload
340 		 * m and mprev will point to IPv6 header.
341 		 */
342 		if (exthdrs.ip6e_dest2) {
343 			if (!hdrsplit)
344 				panic("assumption failed: hdr not split");
345 			exthdrs.ip6e_dest2->m_next = m->m_next;
346 			m->m_next = exthdrs.ip6e_dest2;
347 			*mtod(exthdrs.ip6e_dest2, u_char *) = ip6->ip6_nxt;
348 			ip6->ip6_nxt = IPPROTO_DSTOPTS;
349 		}
350 
351 #define MAKE_CHAIN(m, mp, p, i)\
352     do {\
353 	if (m) {\
354 		if (!hdrsplit) \
355 			panic("assumption failed: hdr not split"); \
356 		*mtod((m), u_char *) = *(p);\
357 		*(p) = (i);\
358 		p = mtod((m), u_char *);\
359 		(m)->m_next = (mp)->m_next;\
360 		(mp)->m_next = (m);\
361 		(mp) = (m);\
362 	}\
363     } while (/*CONSTCOND*/ 0)
364 		/*
365 		 * result: IPv6 hbh dest1 rthdr dest2 payload
366 		 * m will point to IPv6 header.  mprev will point to the
367 		 * extension header prior to dest2 (rthdr in the above case).
368 		 */
369 		MAKE_CHAIN(exthdrs.ip6e_hbh, mprev, nexthdrp, IPPROTO_HOPOPTS);
370 		MAKE_CHAIN(exthdrs.ip6e_dest1, mprev, nexthdrp,
371 		    IPPROTO_DSTOPTS);
372 		MAKE_CHAIN(exthdrs.ip6e_rthdr, mprev, nexthdrp,
373 		    IPPROTO_ROUTING);
374 
375 		M_CSUM_DATA_IPv6_HL_SET(m->m_pkthdr.csum_data,
376 		    sizeof(struct ip6_hdr) + optlen);
377 
378 #ifdef IPSEC
379 		if (!needipsec)
380 			goto skip_ipsec2;
381 
382 		/*
383 		 * pointers after IPsec headers are not valid any more.
384 		 * other pointers need a great care too.
385 		 * (IPsec routines should not mangle mbufs prior to AH/ESP)
386 		 */
387 		exthdrs.ip6e_dest2 = NULL;
388 
389 	    {
390 		struct ip6_rthdr *rh = NULL;
391 		int segleft_org = 0;
392 		struct ipsec_output_state state;
393 
394 		if (exthdrs.ip6e_rthdr) {
395 			rh = mtod(exthdrs.ip6e_rthdr, struct ip6_rthdr *);
396 			segleft_org = rh->ip6r_segleft;
397 			rh->ip6r_segleft = 0;
398 		}
399 
400 		bzero(&state, sizeof(state));
401 		state.m = m;
402 		error = ipsec6_output_trans(&state, nexthdrp, mprev, sp, flags,
403 		    &needipsectun);
404 		m = state.m;
405 		if (error) {
406 			/* mbuf is already reclaimed in ipsec6_output_trans. */
407 			m = NULL;
408 			switch (error) {
409 			case EHOSTUNREACH:
410 			case ENETUNREACH:
411 			case EMSGSIZE:
412 			case ENOBUFS:
413 			case ENOMEM:
414 				break;
415 			default:
416 				printf("ip6_output (ipsec): error code %d\n", error);
417 				/* FALLTHROUGH */
418 			case ENOENT:
419 				/* don't show these error codes to the user */
420 				error = 0;
421 				break;
422 			}
423 			goto bad;
424 		}
425 		if (exthdrs.ip6e_rthdr) {
426 			/* ah6_output doesn't modify mbuf chain */
427 			rh->ip6r_segleft = segleft_org;
428 		}
429 	    }
430 skip_ipsec2:;
431 #endif
432 	}
433 
434 	/*
435 	 * If there is a routing header, replace destination address field
436 	 * with the first hop of the routing header.
437 	 */
438 	if (exthdrs.ip6e_rthdr) {
439 		struct ip6_rthdr *rh;
440 		struct ip6_rthdr0 *rh0;
441 		struct in6_addr *addr;
442 		struct sockaddr_in6 sa;
443 
444 		rh = (struct ip6_rthdr *)(mtod(exthdrs.ip6e_rthdr,
445 		    struct ip6_rthdr *));
446 		finaldst = ip6->ip6_dst;
447 		switch (rh->ip6r_type) {
448 		case IPV6_RTHDR_TYPE_0:
449 			 rh0 = (struct ip6_rthdr0 *)rh;
450 			 addr = (struct in6_addr *)(rh0 + 1);
451 
452 			 /*
453 			  * construct a sockaddr_in6 form of
454 			  * the first hop.
455 			  *
456 			  * XXX: we may not have enough
457 			  * information about its scope zone;
458 			  * there is no standard API to pass
459 			  * the information from the
460 			  * application.
461 			  */
462 			 bzero(&sa, sizeof(sa));
463 			 sa.sin6_family = AF_INET6;
464 			 sa.sin6_len = sizeof(sa);
465 			 sa.sin6_addr = addr[0];
466 			 if ((error = sa6_embedscope(&sa,
467 			     ip6_use_defzone)) != 0) {
468 				 goto bad;
469 			 }
470 			 ip6->ip6_dst = sa.sin6_addr;
471 			 (void)memmove(&addr[0], &addr[1],
472 			     sizeof(struct in6_addr) *
473 			     (rh0->ip6r0_segleft - 1));
474 			 addr[rh0->ip6r0_segleft - 1] = finaldst;
475 			 /* XXX */
476 			 in6_clearscope(addr + rh0->ip6r0_segleft - 1);
477 			 break;
478 		default:	/* is it possible? */
479 			 error = EINVAL;
480 			 goto bad;
481 		}
482 	}
483 
484 	/* Source address validation */
485 	if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src) &&
486 	    (flags & IPV6_UNSPECSRC) == 0) {
487 		error = EOPNOTSUPP;
488 		ip6stat.ip6s_badscope++;
489 		goto bad;
490 	}
491 	if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_src)) {
492 		error = EOPNOTSUPP;
493 		ip6stat.ip6s_badscope++;
494 		goto bad;
495 	}
496 
497 	ip6stat.ip6s_localout++;
498 
499 	/*
500 	 * Route packet.
501 	 */
502 	/* initialize cached route */
503 	if (ro == 0) {
504 		ro = &ip6route;
505 		bzero((caddr_t)ro, sizeof(*ro));
506 	}
507 	ro_pmtu = ro;
508 	if (opt && opt->ip6po_rthdr)
509 		ro = &opt->ip6po_route;
510 	dst = (struct sockaddr_in6 *)&ro->ro_dst;
511 
512 #ifdef notyet	     /* this will be available with the RFC3542 support */
513  	/*
514 	 * if specified, try to fill in the traffic class field.
515 	 * do not override if a non-zero value is already set.
516 	 * we check the diffserv field and the ecn field separately.
517 	 */
518 	if (opt && opt->ip6po_tclass >= 0) {
519 		int mask = 0;
520 
521 		if ((ip6->ip6_flow & htonl(0xfc << 20)) == 0)
522 			mask |= 0xfc;
523 		if ((ip6->ip6_flow & htonl(0x03 << 20)) == 0)
524 			mask |= 0x03;
525 		if (mask != 0)
526 			ip6->ip6_flow |= htonl((opt->ip6po_tclass & mask) << 20);
527 	}
528 #endif
529 
530 	/* fill in or override the hop limit field, if necessary. */
531 	if (opt && opt->ip6po_hlim != -1)
532 		ip6->ip6_hlim = opt->ip6po_hlim & 0xff;
533 	else if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
534 		if (im6o != NULL)
535 			ip6->ip6_hlim = im6o->im6o_multicast_hlim;
536 		else
537 			ip6->ip6_hlim = ip6_defmcasthlim;
538 	}
539 
540 #ifdef IPSEC
541 	if (needipsec && needipsectun) {
542 		struct ipsec_output_state state;
543 
544 		/*
545 		 * All the extension headers will become inaccessible
546 		 * (since they can be encrypted).
547 		 * Don't panic, we need no more updates to extension headers
548 		 * on inner IPv6 packet (since they are now encapsulated).
549 		 *
550 		 * IPv6 [ESP|AH] IPv6 [extension headers] payload
551 		 */
552 		bzero(&exthdrs, sizeof(exthdrs));
553 		exthdrs.ip6e_ip6 = m;
554 
555 		bzero(&state, sizeof(state));
556 		state.m = m;
557 		state.ro = (struct route *)ro;
558 		state.dst = (struct sockaddr *)dst;
559 
560 		error = ipsec6_output_tunnel(&state, sp, flags);
561 
562 		m = state.m;
563 		ro_pmtu = ro = (struct route_in6 *)state.ro;
564 		dst = (struct sockaddr_in6 *)state.dst;
565 		if (error) {
566 			/* mbuf is already reclaimed in ipsec6_output_tunnel. */
567 			m0 = m = NULL;
568 			m = NULL;
569 			switch (error) {
570 			case EHOSTUNREACH:
571 			case ENETUNREACH:
572 			case EMSGSIZE:
573 			case ENOBUFS:
574 			case ENOMEM:
575 				break;
576 			default:
577 				printf("ip6_output (ipsec): error code %d\n", error);
578 				/* FALLTHROUGH */
579 			case ENOENT:
580 				/* don't show these error codes to the user */
581 				error = 0;
582 				break;
583 			}
584 			goto bad;
585 		}
586 
587 		exthdrs.ip6e_ip6 = m;
588 	}
589 #endif /* IPSEC */
590 
591 	/* adjust pointer */
592 	ip6 = mtod(m, struct ip6_hdr *);
593 
594 	bzero(&dst_sa, sizeof(dst_sa));
595 	dst_sa.sin6_family = AF_INET6;
596 	dst_sa.sin6_len = sizeof(dst_sa);
597 	dst_sa.sin6_addr = ip6->ip6_dst;
598 	if ((error = in6_selectroute(&dst_sa, opt, im6o, ro, &ifp, &rt, 0))
599 	    != 0) {
600 		switch (error) {
601 		case EHOSTUNREACH:
602 			ip6stat.ip6s_noroute++;
603 			break;
604 		case EADDRNOTAVAIL:
605 		default:
606 			break; /* XXX statistics? */
607 		}
608 		if (ifp != NULL)
609 			in6_ifstat_inc(ifp, ifs6_out_discard);
610 		goto bad;
611 	}
612 	if (rt == NULL) {
613 		/*
614 		 * If in6_selectroute() does not return a route entry,
615 		 * dst may not have been updated.
616 		 */
617 		*dst = dst_sa;	/* XXX */
618 	}
619 
620 	/*
621 	 * then rt (for unicast) and ifp must be non-NULL valid values.
622 	 */
623 	if ((flags & IPV6_FORWARDING) == 0) {
624 		/* XXX: the FORWARDING flag can be set for mrouting. */
625 		in6_ifstat_inc(ifp, ifs6_out_request);
626 	}
627 	if (rt != NULL) {
628 		ia = (struct in6_ifaddr *)(rt->rt_ifa);
629 		rt->rt_use++;
630 	}
631 
632 	/*
633 	 * The outgoing interface must be in the zone of source and
634 	 * destination addresses.  We should use ia_ifp to support the
635 	 * case of sending packets to an address of our own.
636 	 */
637 	if (ia != NULL && ia->ia_ifp)
638 		origifp = ia->ia_ifp;
639 	else
640 		origifp = ifp;
641 
642 	src0 = ip6->ip6_src;
643 	if (in6_setscope(&src0, origifp, &zone))
644 		goto badscope;
645 	bzero(&src_sa, sizeof(src_sa));
646 	src_sa.sin6_family = AF_INET6;
647 	src_sa.sin6_len = sizeof(src_sa);
648 	src_sa.sin6_addr = ip6->ip6_src;
649 	if (sa6_recoverscope(&src_sa) || zone != src_sa.sin6_scope_id)
650 		goto badscope;
651 
652 	dst0 = ip6->ip6_dst;
653 	if (in6_setscope(&dst0, origifp, &zone))
654 		goto badscope;
655 	/* re-initialize to be sure */
656 	bzero(&dst_sa, sizeof(dst_sa));
657 	dst_sa.sin6_family = AF_INET6;
658 	dst_sa.sin6_len = sizeof(dst_sa);
659 	dst_sa.sin6_addr = ip6->ip6_dst;
660 	if (sa6_recoverscope(&dst_sa) || zone != dst_sa.sin6_scope_id)
661 		goto badscope;
662 
663 	/* scope check is done. */
664 	goto routefound;
665 
666   badscope:
667 	ip6stat.ip6s_badscope++;
668 	in6_ifstat_inc(origifp, ifs6_out_discard);
669 	if (error == 0)
670 		error = EHOSTUNREACH; /* XXX */
671 	goto bad;
672 
673   routefound:
674 	if (rt && !IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
675 #ifdef notyet	     /* this will be available with the RFC3542 support */
676 		if (opt && opt->ip6po_nextroute.ro_rt) {
677 			/*
678 			 * The nexthop is explicitly specified by the
679 			 * application.  We assume the next hop is an IPv6
680 			 * address.
681 			 */
682 			dst = (struct sockaddr_in6 *)opt->ip6po_nexthop;
683 		} else
684 #endif
685 			if ((rt->rt_flags & RTF_GATEWAY))
686 				dst = (struct sockaddr_in6 *)rt->rt_gateway;
687 	}
688 
689 	/*
690 	 * XXXXXX: original code follows:
691 	 */
692 	if (!IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst))
693 		m->m_flags &= ~(M_BCAST | M_MCAST);	/* just in case */
694 	else {
695 		struct	in6_multi *in6m;
696 
697 		m->m_flags = (m->m_flags & ~M_BCAST) | M_MCAST;
698 
699 		in6_ifstat_inc(ifp, ifs6_out_mcast);
700 
701 		/*
702 		 * Confirm that the outgoing interface supports multicast.
703 		 */
704 		if (!(ifp->if_flags & IFF_MULTICAST)) {
705 			ip6stat.ip6s_noroute++;
706 			in6_ifstat_inc(ifp, ifs6_out_discard);
707 			error = ENETUNREACH;
708 			goto bad;
709 		}
710 
711 		IN6_LOOKUP_MULTI(ip6->ip6_dst, ifp, in6m);
712 		if (in6m != NULL &&
713 		   (im6o == NULL || im6o->im6o_multicast_loop)) {
714 			/*
715 			 * If we belong to the destination multicast group
716 			 * on the outgoing interface, and the caller did not
717 			 * forbid loopback, loop back a copy.
718 			 */
719 			ip6_mloopback(ifp, m, dst);
720 		} else {
721 			/*
722 			 * If we are acting as a multicast router, perform
723 			 * multicast forwarding as if the packet had just
724 			 * arrived on the interface to which we are about
725 			 * to send.  The multicast forwarding function
726 			 * recursively calls this function, using the
727 			 * IPV6_FORWARDING flag to prevent infinite recursion.
728 			 *
729 			 * Multicasts that are looped back by ip6_mloopback(),
730 			 * above, will be forwarded by the ip6_input() routine,
731 			 * if necessary.
732 			 */
733 			if (ip6_mrouter && (flags & IPV6_FORWARDING) == 0) {
734 				if (ip6_mforward(ip6, ifp, m) != 0) {
735 					m_freem(m);
736 					goto done;
737 				}
738 			}
739 		}
740 		/*
741 		 * Multicasts with a hoplimit of zero may be looped back,
742 		 * above, but must not be transmitted on a network.
743 		 * Also, multicasts addressed to the loopback interface
744 		 * are not sent -- the above call to ip6_mloopback() will
745 		 * loop back a copy if this host actually belongs to the
746 		 * destination group on the loopback interface.
747 		 */
748 		if (ip6->ip6_hlim == 0 || (ifp->if_flags & IFF_LOOPBACK) ||
749 		    IN6_IS_ADDR_MC_INTFACELOCAL(&ip6->ip6_dst)) {
750 			m_freem(m);
751 			goto done;
752 		}
753 	}
754 
755 	/*
756 	 * Fill the outgoing inteface to tell the upper layer
757 	 * to increment per-interface statistics.
758 	 */
759 	if (ifpp)
760 		*ifpp = ifp;
761 
762 	/* Determine path MTU. */
763 	if ((error = ip6_getpmtu(ro_pmtu, ro, ifp, &finaldst, &mtu,
764 	    &alwaysfrag)) != 0)
765 		goto bad;
766 #ifdef IPSEC
767 	if (needipsectun)
768 		mtu = IPV6_MMTU;
769 #endif
770 
771 	/*
772 	 * The caller of this function may specify to use the minimum MTU
773 	 * in some cases.
774 	 */
775 	if (mtu > IPV6_MMTU) {
776 		if ((flags & IPV6_MINMTU))
777 			mtu = IPV6_MMTU;
778 	}
779 
780 	/*
781 	 * clear embedded scope identifiers if necessary.
782 	 * in6_clearscope will touch the addresses only when necessary.
783 	 */
784 	in6_clearscope(&ip6->ip6_src);
785 	in6_clearscope(&ip6->ip6_dst);
786 
787 	/*
788 	 * If the outgoing packet contains a hop-by-hop options header,
789 	 * it must be examined and processed even by the source node.
790 	 * (RFC 2460, section 4.)
791 	 */
792 	if (exthdrs.ip6e_hbh) {
793 		struct ip6_hbh *hbh = mtod(exthdrs.ip6e_hbh, struct ip6_hbh *);
794 		u_int32_t dummy1; /* XXX unused */
795 		u_int32_t dummy2; /* XXX unused */
796 
797 		/*
798 		 *  XXX: if we have to send an ICMPv6 error to the sender,
799 		 *       we need the M_LOOP flag since icmp6_error() expects
800 		 *       the IPv6 and the hop-by-hop options header are
801 		 *       continuous unless the flag is set.
802 		 */
803 		m->m_flags |= M_LOOP;
804 		m->m_pkthdr.rcvif = ifp;
805 		if (ip6_process_hopopts(m, (u_int8_t *)(hbh + 1),
806 		    ((hbh->ip6h_len + 1) << 3) - sizeof(struct ip6_hbh),
807 		    &dummy1, &dummy2) < 0) {
808 			/* m was already freed at this point */
809 			error = EINVAL;/* better error? */
810 			goto done;
811 		}
812 		m->m_flags &= ~M_LOOP; /* XXX */
813 		m->m_pkthdr.rcvif = NULL;
814 	}
815 
816 #ifdef PFIL_HOOKS
817 	/*
818 	 * Run through list of hooks for output packets.
819 	 */
820 	if ((error = pfil_run_hooks(&inet6_pfil_hook, &m, ifp, PFIL_OUT)) != 0)
821 		goto done;
822 	if (m == NULL)
823 		goto done;
824 	ip6 = mtod(m, struct ip6_hdr *);
825 #endif /* PFIL_HOOKS */
826 	/*
827 	 * Send the packet to the outgoing interface.
828 	 * If necessary, do IPv6 fragmentation before sending.
829 	 *
830 	 * the logic here is rather complex:
831 	 * 1: normal case (dontfrag == 0, alwaysfrag == 0)
832 	 * 1-a:	send as is if tlen <= path mtu
833 	 * 1-b:	fragment if tlen > path mtu
834 	 *
835 	 * 2: if user asks us not to fragment (dontfrag == 1)
836 	 * 2-a:	send as is if tlen <= interface mtu
837 	 * 2-b:	error if tlen > interface mtu
838 	 *
839 	 * 3: if we always need to attach fragment header (alwaysfrag == 1)
840 	 *	always fragment
841 	 *
842 	 * 4: if dontfrag == 1 && alwaysfrag == 1
843 	 *	error, as we cannot handle this conflicting request
844 	 */
845 	tlen = m->m_pkthdr.len;
846 
847 	dontfrag = 0;
848 	if (dontfrag && alwaysfrag) {	/* case 4 */
849 		/* conflicting request - can't transmit */
850 		error = EMSGSIZE;
851 		goto bad;
852 	}
853 	if (dontfrag && tlen > IN6_LINKMTU(ifp)) {	/* case 2-b */
854 		/*
855 		 * Even if the DONTFRAG option is specified, we cannot send the
856 		 * packet when the data length is larger than the MTU of the
857 		 * outgoing interface.
858 		 * Notify the error by sending IPV6_PATHMTU ancillary data as
859 		 * well as returning an error code (the latter is not described
860 		 * in the API spec.)
861 		 */
862 		u_int32_t mtu32;
863 		struct ip6ctlparam ip6cp;
864 
865 		mtu32 = (u_int32_t)mtu;
866 		bzero(&ip6cp, sizeof(ip6cp));
867 		ip6cp.ip6c_cmdarg = (void *)&mtu32;
868 		pfctlinput2(PRC_MSGSIZE, (struct sockaddr *)&ro_pmtu->ro_dst,
869 		    (void *)&ip6cp);
870 
871 		error = EMSGSIZE;
872 		goto bad;
873 	}
874 
875 	/*
876 	 * transmit packet without fragmentation
877 	 */
878 	if (dontfrag || (!alwaysfrag && tlen <= mtu)) {	/* case 1-a and 2-a */
879 		struct in6_ifaddr *ia6;
880 		int sw_csum;
881 
882 		ip6 = mtod(m, struct ip6_hdr *);
883 		ia6 = in6_ifawithifp(ifp, &ip6->ip6_src);
884 		if (ia6) {
885 			/* Record statistics for this interface address. */
886 			ia6->ia_ifa.ifa_data.ifad_outbytes += m->m_pkthdr.len;
887 		}
888 #ifdef IPSEC
889 		/* clean ipsec history once it goes out of the node */
890 		ipsec_delaux(m);
891 #endif
892 
893 		sw_csum = m->m_pkthdr.csum_flags & ~ifp->if_csum_flags_tx;
894 		if ((sw_csum & (M_CSUM_UDPv6|M_CSUM_TCPv6)) != 0) {
895 			if (IN6_NEED_CHECKSUM(ifp,
896 			    sw_csum & (M_CSUM_UDPv6|M_CSUM_TCPv6))) {
897 				in6_delayed_cksum(m);
898 			}
899 			m->m_pkthdr.csum_flags &= ~(M_CSUM_UDPv6|M_CSUM_TCPv6);
900 		}
901 
902 		error = nd6_output(ifp, origifp, m, dst, ro->ro_rt);
903 		goto done;
904 	}
905 
906 	/*
907 	 * try to fragment the packet.  case 1-b and 3
908 	 */
909 	if (mtu < IPV6_MMTU) {
910 		/* path MTU cannot be less than IPV6_MMTU */
911 		error = EMSGSIZE;
912 		in6_ifstat_inc(ifp, ifs6_out_fragfail);
913 		goto bad;
914 	} else if (ip6->ip6_plen == 0) {
915 		/* jumbo payload cannot be fragmented */
916 		error = EMSGSIZE;
917 		in6_ifstat_inc(ifp, ifs6_out_fragfail);
918 		goto bad;
919 	} else {
920 		struct mbuf **mnext, *m_frgpart;
921 		struct ip6_frag *ip6f;
922 		u_int32_t id = htonl(ip6_randomid());
923 		u_char nextproto;
924 		struct ip6ctlparam ip6cp;
925 		u_int32_t mtu32;
926 
927 		/*
928 		 * Too large for the destination or interface;
929 		 * fragment if possible.
930 		 * Must be able to put at least 8 bytes per fragment.
931 		 */
932 		hlen = unfragpartlen;
933 		if (mtu > IPV6_MAXPACKET)
934 			mtu = IPV6_MAXPACKET;
935 
936 		/* Notify a proper path MTU to applications. */
937 		mtu32 = (u_int32_t)mtu;
938 		bzero(&ip6cp, sizeof(ip6cp));
939 		ip6cp.ip6c_cmdarg = (void *)&mtu32;
940 		pfctlinput2(PRC_MSGSIZE, (struct sockaddr *)&ro_pmtu->ro_dst,
941 		    (void *)&ip6cp);
942 
943 		len = (mtu - hlen - sizeof(struct ip6_frag)) & ~7;
944 		if (len < 8) {
945 			error = EMSGSIZE;
946 			in6_ifstat_inc(ifp, ifs6_out_fragfail);
947 			goto bad;
948 		}
949 
950 		mnext = &m->m_nextpkt;
951 
952 		/*
953 		 * Change the next header field of the last header in the
954 		 * unfragmentable part.
955 		 */
956 		if (exthdrs.ip6e_rthdr) {
957 			nextproto = *mtod(exthdrs.ip6e_rthdr, u_char *);
958 			*mtod(exthdrs.ip6e_rthdr, u_char *) = IPPROTO_FRAGMENT;
959 		} else if (exthdrs.ip6e_dest1) {
960 			nextproto = *mtod(exthdrs.ip6e_dest1, u_char *);
961 			*mtod(exthdrs.ip6e_dest1, u_char *) = IPPROTO_FRAGMENT;
962 		} else if (exthdrs.ip6e_hbh) {
963 			nextproto = *mtod(exthdrs.ip6e_hbh, u_char *);
964 			*mtod(exthdrs.ip6e_hbh, u_char *) = IPPROTO_FRAGMENT;
965 		} else {
966 			nextproto = ip6->ip6_nxt;
967 			ip6->ip6_nxt = IPPROTO_FRAGMENT;
968 		}
969 
970 		if ((m->m_pkthdr.csum_flags & (M_CSUM_UDPv6|M_CSUM_TCPv6))
971 		    != 0) {
972 			if (IN6_NEED_CHECKSUM(ifp,
973 			    m->m_pkthdr.csum_flags &
974 			    (M_CSUM_UDPv6|M_CSUM_TCPv6))) {
975 				in6_delayed_cksum(m);
976 			}
977 			m->m_pkthdr.csum_flags &= ~(M_CSUM_UDPv6|M_CSUM_TCPv6);
978 		}
979 
980 		/*
981 		 * Loop through length of segment after first fragment,
982 		 * make new header and copy data of each part and link onto
983 		 * chain.
984 		 */
985 		m0 = m;
986 		for (off = hlen; off < tlen; off += len) {
987 			struct mbuf *mlast;
988 
989 			MGETHDR(m, M_DONTWAIT, MT_HEADER);
990 			if (!m) {
991 				error = ENOBUFS;
992 				ip6stat.ip6s_odropped++;
993 				goto sendorfree;
994 			}
995 			m->m_pkthdr.rcvif = NULL;
996 			m->m_flags = m0->m_flags & M_COPYFLAGS;
997 			*mnext = m;
998 			mnext = &m->m_nextpkt;
999 			m->m_data += max_linkhdr;
1000 			mhip6 = mtod(m, struct ip6_hdr *);
1001 			*mhip6 = *ip6;
1002 			m->m_len = sizeof(*mhip6);
1003 			error = ip6_insertfraghdr(m0, m, hlen, &ip6f);
1004 			if (error) {
1005 				ip6stat.ip6s_odropped++;
1006 				goto sendorfree;
1007 			}
1008 			ip6f->ip6f_offlg = htons((u_int16_t)((off - hlen) & ~7));
1009 			if (off + len >= tlen)
1010 				len = tlen - off;
1011 			else
1012 				ip6f->ip6f_offlg |= IP6F_MORE_FRAG;
1013 			mhip6->ip6_plen = htons((u_int16_t)(len + hlen +
1014 			    sizeof(*ip6f) - sizeof(struct ip6_hdr)));
1015 			if ((m_frgpart = m_copy(m0, off, len)) == 0) {
1016 				error = ENOBUFS;
1017 				ip6stat.ip6s_odropped++;
1018 				goto sendorfree;
1019 			}
1020 			for (mlast = m; mlast->m_next; mlast = mlast->m_next)
1021 				;
1022 			mlast->m_next = m_frgpart;
1023 			m->m_pkthdr.len = len + hlen + sizeof(*ip6f);
1024 			m->m_pkthdr.rcvif = (struct ifnet *)0;
1025 			ip6f->ip6f_reserved = 0;
1026 			ip6f->ip6f_ident = id;
1027 			ip6f->ip6f_nxt = nextproto;
1028 			ip6stat.ip6s_ofragments++;
1029 			in6_ifstat_inc(ifp, ifs6_out_fragcreat);
1030 		}
1031 
1032 		in6_ifstat_inc(ifp, ifs6_out_fragok);
1033 	}
1034 
1035 	/*
1036 	 * Remove leading garbages.
1037 	 */
1038 sendorfree:
1039 	m = m0->m_nextpkt;
1040 	m0->m_nextpkt = 0;
1041 	m_freem(m0);
1042 	for (m0 = m; m; m = m0) {
1043 		m0 = m->m_nextpkt;
1044 		m->m_nextpkt = 0;
1045 		if (error == 0) {
1046 			struct in6_ifaddr *ia6;
1047 			ip6 = mtod(m, struct ip6_hdr *);
1048 			ia6 = in6_ifawithifp(ifp, &ip6->ip6_src);
1049 			if (ia6) {
1050 				/*
1051 				 * Record statistics for this interface
1052 				 * address.
1053 				 */
1054 				ia6->ia_ifa.ifa_data.ifad_outbytes +=
1055 				    m->m_pkthdr.len;
1056 			}
1057 #ifdef IPSEC
1058 			/* clean ipsec history once it goes out of the node */
1059 			ipsec_delaux(m);
1060 #endif
1061 			error = nd6_output(ifp, origifp, m, dst, ro->ro_rt);
1062 		} else
1063 			m_freem(m);
1064 	}
1065 
1066 	if (error == 0)
1067 		ip6stat.ip6s_fragmented++;
1068 
1069 done:
1070 	if (ro == &ip6route && ro->ro_rt) { /* brace necessary for RTFREE */
1071 		RTFREE(ro->ro_rt);
1072 	} else if (ro_pmtu == &ip6route && ro_pmtu->ro_rt) {
1073 		RTFREE(ro_pmtu->ro_rt);
1074 	}
1075 
1076 #ifdef IPSEC
1077 	if (sp != NULL)
1078 		key_freesp(sp);
1079 #endif /* IPSEC */
1080 
1081 	return (error);
1082 
1083 freehdrs:
1084 	m_freem(exthdrs.ip6e_hbh);	/* m_freem will check if mbuf is 0 */
1085 	m_freem(exthdrs.ip6e_dest1);
1086 	m_freem(exthdrs.ip6e_rthdr);
1087 	m_freem(exthdrs.ip6e_dest2);
1088 	/* FALLTHROUGH */
1089 bad:
1090 	m_freem(m);
1091 	goto done;
1092 }
1093 
1094 static int
1095 ip6_copyexthdr(mp, hdr, hlen)
1096 	struct mbuf **mp;
1097 	caddr_t hdr;
1098 	int hlen;
1099 {
1100 	struct mbuf *m;
1101 
1102 	if (hlen > MCLBYTES)
1103 		return (ENOBUFS); /* XXX */
1104 
1105 	MGET(m, M_DONTWAIT, MT_DATA);
1106 	if (!m)
1107 		return (ENOBUFS);
1108 
1109 	if (hlen > MLEN) {
1110 		MCLGET(m, M_DONTWAIT);
1111 		if ((m->m_flags & M_EXT) == 0) {
1112 			m_free(m);
1113 			return (ENOBUFS);
1114 		}
1115 	}
1116 	m->m_len = hlen;
1117 	if (hdr)
1118 		bcopy(hdr, mtod(m, caddr_t), hlen);
1119 
1120 	*mp = m;
1121 	return (0);
1122 }
1123 
1124 /*
1125  * Process a delayed payload checksum calculation.
1126  */
1127 void
1128 in6_delayed_cksum(struct mbuf *m)
1129 {
1130 	uint16_t csum, offset;
1131 
1132 	KASSERT((m->m_pkthdr.csum_flags & (M_CSUM_UDPv6|M_CSUM_TCPv6)) != 0);
1133 	KASSERT((~m->m_pkthdr.csum_flags & (M_CSUM_UDPv6|M_CSUM_TCPv6)) != 0);
1134 	KASSERT((m->m_pkthdr.csum_flags
1135 	    & (M_CSUM_UDPv4|M_CSUM_TCPv4|M_CSUM_TSOv4)) == 0);
1136 
1137 	offset = M_CSUM_DATA_IPv6_HL(m->m_pkthdr.csum_data);
1138 	csum = in6_cksum(m, 0, offset, m->m_pkthdr.len - offset);
1139 	if (csum == 0 && (m->m_pkthdr.csum_flags & M_CSUM_UDPv6) != 0) {
1140 		csum = 0xffff;
1141 	}
1142 
1143 	offset += M_CSUM_DATA_IPv6_OFFSET(m->m_pkthdr.csum_data);
1144 	if ((offset + sizeof(csum)) > m->m_len) {
1145 		m_copyback(m, offset, sizeof(csum), &csum);
1146 	} else {
1147 		*(uint16_t *)(mtod(m, caddr_t) + offset) = csum;
1148 	}
1149 }
1150 
1151 /*
1152  * Insert jumbo payload option.
1153  */
1154 static int
1155 ip6_insert_jumboopt(exthdrs, plen)
1156 	struct ip6_exthdrs *exthdrs;
1157 	u_int32_t plen;
1158 {
1159 	struct mbuf *mopt;
1160 	u_int8_t *optbuf;
1161 	u_int32_t v;
1162 
1163 #define JUMBOOPTLEN	8	/* length of jumbo payload option and padding */
1164 
1165 	/*
1166 	 * If there is no hop-by-hop options header, allocate new one.
1167 	 * If there is one but it doesn't have enough space to store the
1168 	 * jumbo payload option, allocate a cluster to store the whole options.
1169 	 * Otherwise, use it to store the options.
1170 	 */
1171 	if (exthdrs->ip6e_hbh == 0) {
1172 		MGET(mopt, M_DONTWAIT, MT_DATA);
1173 		if (mopt == 0)
1174 			return (ENOBUFS);
1175 		mopt->m_len = JUMBOOPTLEN;
1176 		optbuf = mtod(mopt, u_int8_t *);
1177 		optbuf[1] = 0;	/* = ((JUMBOOPTLEN) >> 3) - 1 */
1178 		exthdrs->ip6e_hbh = mopt;
1179 	} else {
1180 		struct ip6_hbh *hbh;
1181 
1182 		mopt = exthdrs->ip6e_hbh;
1183 		if (M_TRAILINGSPACE(mopt) < JUMBOOPTLEN) {
1184 			/*
1185 			 * XXX assumption:
1186 			 * - exthdrs->ip6e_hbh is not referenced from places
1187 			 *   other than exthdrs.
1188 			 * - exthdrs->ip6e_hbh is not an mbuf chain.
1189 			 */
1190 			int oldoptlen = mopt->m_len;
1191 			struct mbuf *n;
1192 
1193 			/*
1194 			 * XXX: give up if the whole (new) hbh header does
1195 			 * not fit even in an mbuf cluster.
1196 			 */
1197 			if (oldoptlen + JUMBOOPTLEN > MCLBYTES)
1198 				return (ENOBUFS);
1199 
1200 			/*
1201 			 * As a consequence, we must always prepare a cluster
1202 			 * at this point.
1203 			 */
1204 			MGET(n, M_DONTWAIT, MT_DATA);
1205 			if (n) {
1206 				MCLGET(n, M_DONTWAIT);
1207 				if ((n->m_flags & M_EXT) == 0) {
1208 					m_freem(n);
1209 					n = NULL;
1210 				}
1211 			}
1212 			if (!n)
1213 				return (ENOBUFS);
1214 			n->m_len = oldoptlen + JUMBOOPTLEN;
1215 			bcopy(mtod(mopt, caddr_t), mtod(n, caddr_t),
1216 			    oldoptlen);
1217 			optbuf = mtod(n, u_int8_t *) + oldoptlen;
1218 			m_freem(mopt);
1219 			mopt = exthdrs->ip6e_hbh = n;
1220 		} else {
1221 			optbuf = mtod(mopt, u_int8_t *) + mopt->m_len;
1222 			mopt->m_len += JUMBOOPTLEN;
1223 		}
1224 		optbuf[0] = IP6OPT_PADN;
1225 		optbuf[1] = 0;
1226 
1227 		/*
1228 		 * Adjust the header length according to the pad and
1229 		 * the jumbo payload option.
1230 		 */
1231 		hbh = mtod(mopt, struct ip6_hbh *);
1232 		hbh->ip6h_len += (JUMBOOPTLEN >> 3);
1233 	}
1234 
1235 	/* fill in the option. */
1236 	optbuf[2] = IP6OPT_JUMBO;
1237 	optbuf[3] = 4;
1238 	v = (u_int32_t)htonl(plen + JUMBOOPTLEN);
1239 	bcopy(&v, &optbuf[4], sizeof(u_int32_t));
1240 
1241 	/* finally, adjust the packet header length */
1242 	exthdrs->ip6e_ip6->m_pkthdr.len += JUMBOOPTLEN;
1243 
1244 	return (0);
1245 #undef JUMBOOPTLEN
1246 }
1247 
1248 /*
1249  * Insert fragment header and copy unfragmentable header portions.
1250  */
1251 static int
1252 ip6_insertfraghdr(m0, m, hlen, frghdrp)
1253 	struct mbuf *m0, *m;
1254 	int hlen;
1255 	struct ip6_frag **frghdrp;
1256 {
1257 	struct mbuf *n, *mlast;
1258 
1259 	if (hlen > sizeof(struct ip6_hdr)) {
1260 		n = m_copym(m0, sizeof(struct ip6_hdr),
1261 		    hlen - sizeof(struct ip6_hdr), M_DONTWAIT);
1262 		if (n == 0)
1263 			return (ENOBUFS);
1264 		m->m_next = n;
1265 	} else
1266 		n = m;
1267 
1268 	/* Search for the last mbuf of unfragmentable part. */
1269 	for (mlast = n; mlast->m_next; mlast = mlast->m_next)
1270 		;
1271 
1272 	if ((mlast->m_flags & M_EXT) == 0 &&
1273 	    M_TRAILINGSPACE(mlast) >= sizeof(struct ip6_frag)) {
1274 		/* use the trailing space of the last mbuf for the fragment hdr */
1275 		*frghdrp = (struct ip6_frag *)(mtod(mlast, caddr_t) +
1276 		    mlast->m_len);
1277 		mlast->m_len += sizeof(struct ip6_frag);
1278 		m->m_pkthdr.len += sizeof(struct ip6_frag);
1279 	} else {
1280 		/* allocate a new mbuf for the fragment header */
1281 		struct mbuf *mfrg;
1282 
1283 		MGET(mfrg, M_DONTWAIT, MT_DATA);
1284 		if (mfrg == 0)
1285 			return (ENOBUFS);
1286 		mfrg->m_len = sizeof(struct ip6_frag);
1287 		*frghdrp = mtod(mfrg, struct ip6_frag *);
1288 		mlast->m_next = mfrg;
1289 	}
1290 
1291 	return (0);
1292 }
1293 
1294 static int
1295 ip6_getpmtu(ro_pmtu, ro, ifp, dst, mtup, alwaysfragp)
1296 	struct route_in6 *ro_pmtu, *ro;
1297 	struct ifnet *ifp;
1298 	struct in6_addr *dst;
1299 	u_long *mtup;
1300 	int *alwaysfragp;
1301 {
1302 	u_int32_t mtu = 0;
1303 	int alwaysfrag = 0;
1304 	int error = 0;
1305 
1306 	if (ro_pmtu != ro) {
1307 		/* The first hop and the final destination may differ. */
1308 		struct sockaddr_in6 *sa6_dst =
1309 		    (struct sockaddr_in6 *)&ro_pmtu->ro_dst;
1310 		if (ro_pmtu->ro_rt &&
1311 		    ((ro_pmtu->ro_rt->rt_flags & RTF_UP) == 0 ||
1312 		      !IN6_ARE_ADDR_EQUAL(&sa6_dst->sin6_addr, dst))) {
1313 			RTFREE(ro_pmtu->ro_rt);
1314 			ro_pmtu->ro_rt = (struct rtentry *)NULL;
1315 		}
1316 		if (ro_pmtu->ro_rt == NULL) {
1317 			bzero(sa6_dst, sizeof(*sa6_dst)); /* for safety */
1318 			sa6_dst->sin6_family = AF_INET6;
1319 			sa6_dst->sin6_len = sizeof(struct sockaddr_in6);
1320 			sa6_dst->sin6_addr = *dst;
1321 
1322 			rtalloc((struct route *)ro_pmtu);
1323 		}
1324 	}
1325 	if (ro_pmtu->ro_rt) {
1326 		u_int32_t ifmtu;
1327 
1328 		if (ifp == NULL)
1329 			ifp = ro_pmtu->ro_rt->rt_ifp;
1330 		ifmtu = IN6_LINKMTU(ifp);
1331 		mtu = ro_pmtu->ro_rt->rt_rmx.rmx_mtu;
1332 		if (mtu == 0)
1333 			mtu = ifmtu;
1334 		else if (mtu < IPV6_MMTU) {
1335 			/*
1336 			 * RFC2460 section 5, last paragraph:
1337 			 * if we record ICMPv6 too big message with
1338 			 * mtu < IPV6_MMTU, transmit packets sized IPV6_MMTU
1339 			 * or smaller, with fragment header attached.
1340 			 * (fragment header is needed regardless from the
1341 			 * packet size, for translators to identify packets)
1342 			 */
1343 			alwaysfrag = 1;
1344 			mtu = IPV6_MMTU;
1345 		} else if (mtu > ifmtu) {
1346 			/*
1347 			 * The MTU on the route is larger than the MTU on
1348 			 * the interface!  This shouldn't happen, unless the
1349 			 * MTU of the interface has been changed after the
1350 			 * interface was brought up.  Change the MTU in the
1351 			 * route to match the interface MTU (as long as the
1352 			 * field isn't locked).
1353 			 */
1354 			mtu = ifmtu;
1355 			if (!(ro_pmtu->ro_rt->rt_rmx.rmx_locks & RTV_MTU))
1356 				ro_pmtu->ro_rt->rt_rmx.rmx_mtu = mtu;
1357 		}
1358 	} else if (ifp) {
1359 		mtu = IN6_LINKMTU(ifp);
1360 	} else
1361 		error = EHOSTUNREACH; /* XXX */
1362 
1363 	*mtup = mtu;
1364 	if (alwaysfragp)
1365 		*alwaysfragp = alwaysfrag;
1366 	return (error);
1367 }
1368 
1369 /*
1370  * IP6 socket option processing.
1371  */
1372 int
1373 ip6_ctloutput(op, so, level, optname, mp)
1374 	int op;
1375 	struct socket *so;
1376 	int level, optname;
1377 	struct mbuf **mp;
1378 {
1379 	struct in6pcb *in6p = sotoin6pcb(so);
1380 	struct mbuf *m = *mp;
1381 	int optval = 0;
1382 	int error = 0;
1383 	struct proc *p = curproc;	/* XXX */
1384 
1385 	if (level == IPPROTO_IPV6) {
1386 		switch (op) {
1387 		case PRCO_SETOPT:
1388 			switch (optname) {
1389 			case IPV6_PKTOPTIONS:
1390 				/* m is freed in ip6_pcbopts */
1391 				return (ip6_pcbopts(&in6p->in6p_outputopts,
1392 				    m, so));
1393 			case IPV6_HOPOPTS:
1394 			case IPV6_DSTOPTS:
1395 				if (p == 0 || suser(p->p_ucred, &p->p_acflag)) {
1396 					error = EPERM;
1397 					break;
1398 				}
1399 				/* FALLTHROUGH */
1400 			case IPV6_UNICAST_HOPS:
1401 			case IPV6_RECVOPTS:
1402 			case IPV6_RECVRETOPTS:
1403 			case IPV6_RECVDSTADDR:
1404 			case IPV6_PKTINFO:
1405 			case IPV6_HOPLIMIT:
1406 			case IPV6_RTHDR:
1407 			case IPV6_FAITH:
1408 			case IPV6_V6ONLY:
1409 			case IPV6_USE_MIN_MTU:
1410 				if (!m || m->m_len != sizeof(int)) {
1411 					error = EINVAL;
1412 					break;
1413 				}
1414 				optval = *mtod(m, int *);
1415 				switch (optname) {
1416 
1417 				case IPV6_UNICAST_HOPS:
1418 					if (optval < -1 || optval >= 256)
1419 						error = EINVAL;
1420 					else {
1421 						/* -1 = kernel default */
1422 						in6p->in6p_hops = optval;
1423 					}
1424 					break;
1425 #define OPTSET(bit) \
1426 do { \
1427 	if (optval) \
1428 		in6p->in6p_flags |= (bit); \
1429 	else \
1430 		in6p->in6p_flags &= ~(bit); \
1431 } while (/*CONSTCOND*/ 0)
1432 
1433 				case IPV6_RECVOPTS:
1434 					OPTSET(IN6P_RECVOPTS);
1435 					break;
1436 
1437 				case IPV6_RECVRETOPTS:
1438 					OPTSET(IN6P_RECVRETOPTS);
1439 					break;
1440 
1441 				case IPV6_RECVDSTADDR:
1442 					OPTSET(IN6P_RECVDSTADDR);
1443 					break;
1444 
1445 				case IPV6_PKTINFO:
1446 					OPTSET(IN6P_PKTINFO);
1447 					break;
1448 
1449 				case IPV6_HOPLIMIT:
1450 					OPTSET(IN6P_HOPLIMIT);
1451 					break;
1452 
1453 				case IPV6_HOPOPTS:
1454 					OPTSET(IN6P_HOPOPTS);
1455 					break;
1456 
1457 				case IPV6_DSTOPTS:
1458 					OPTSET(IN6P_DSTOPTS);
1459 					break;
1460 
1461 				case IPV6_RTHDR:
1462 					OPTSET(IN6P_RTHDR);
1463 					break;
1464 
1465 				case IPV6_FAITH:
1466 					OPTSET(IN6P_FAITH);
1467 					break;
1468 
1469 				case IPV6_USE_MIN_MTU:
1470 					OPTSET(IN6P_MINMTU);
1471 					break;
1472 
1473 				case IPV6_V6ONLY:
1474 					/*
1475 					 * make setsockopt(IPV6_V6ONLY)
1476 					 * available only prior to bind(2).
1477 					 * see ipng mailing list, Jun 22 2001.
1478 					 */
1479 					if (in6p->in6p_lport ||
1480 					    !IN6_IS_ADDR_UNSPECIFIED(&in6p->in6p_laddr)) {
1481 						error = EINVAL;
1482 						break;
1483 					}
1484 #ifdef INET6_BINDV6ONLY
1485 					if (!optval)
1486 						error = EINVAL;
1487 #else
1488 					OPTSET(IN6P_IPV6_V6ONLY);
1489 #endif
1490 					break;
1491 				}
1492 				break;
1493 #undef OPTSET
1494 
1495 			case IPV6_MULTICAST_IF:
1496 			case IPV6_MULTICAST_HOPS:
1497 			case IPV6_MULTICAST_LOOP:
1498 			case IPV6_JOIN_GROUP:
1499 			case IPV6_LEAVE_GROUP:
1500 				error =	ip6_setmoptions(optname,
1501 				    &in6p->in6p_moptions, m);
1502 				break;
1503 
1504 			case IPV6_PORTRANGE:
1505 				optval = *mtod(m, int *);
1506 
1507 				switch (optval) {
1508 				case IPV6_PORTRANGE_DEFAULT:
1509 					in6p->in6p_flags &= ~(IN6P_LOWPORT);
1510 					in6p->in6p_flags &= ~(IN6P_HIGHPORT);
1511 					break;
1512 
1513 				case IPV6_PORTRANGE_HIGH:
1514 					in6p->in6p_flags &= ~(IN6P_LOWPORT);
1515 					in6p->in6p_flags |= IN6P_HIGHPORT;
1516 					break;
1517 
1518 				case IPV6_PORTRANGE_LOW:
1519 					in6p->in6p_flags &= ~(IN6P_HIGHPORT);
1520 					in6p->in6p_flags |= IN6P_LOWPORT;
1521 					break;
1522 
1523 				default:
1524 					error = EINVAL;
1525 					break;
1526 				}
1527 				break;
1528 
1529 #ifdef IPSEC
1530 			case IPV6_IPSEC_POLICY:
1531 			    {
1532 				caddr_t req = NULL;
1533 				size_t len = 0;
1534 
1535 				int priv = 0;
1536 				if (p == 0 || suser(p->p_ucred, &p->p_acflag))
1537 					priv = 0;
1538 				else
1539 					priv = 1;
1540 				if (m) {
1541 					req = mtod(m, caddr_t);
1542 					len = m->m_len;
1543 				}
1544 				error = ipsec6_set_policy(in6p,
1545 				                   optname, req, len, priv);
1546 			    }
1547 				break;
1548 #endif /* IPSEC */
1549 
1550 			default:
1551 				error = ENOPROTOOPT;
1552 				break;
1553 			}
1554 			if (m)
1555 				(void)m_free(m);
1556 			break;
1557 
1558 		case PRCO_GETOPT:
1559 			switch (optname) {
1560 
1561 			case IPV6_OPTIONS:
1562 			case IPV6_RETOPTS:
1563 				error = ENOPROTOOPT;
1564 				break;
1565 
1566 			case IPV6_PKTOPTIONS:
1567 				if (in6p->in6p_options) {
1568 					*mp = m_copym(in6p->in6p_options, 0,
1569 					    M_COPYALL, M_WAIT);
1570 				} else {
1571 					*mp = m_get(M_WAIT, MT_SOOPTS);
1572 					(*mp)->m_len = 0;
1573 				}
1574 				break;
1575 
1576 			case IPV6_HOPOPTS:
1577 			case IPV6_DSTOPTS:
1578 				if (p == 0 || suser(p->p_ucred, &p->p_acflag)) {
1579 					error = EPERM;
1580 					break;
1581 				}
1582 				/* FALLTHROUGH */
1583 			case IPV6_UNICAST_HOPS:
1584 			case IPV6_RECVOPTS:
1585 			case IPV6_RECVRETOPTS:
1586 			case IPV6_RECVDSTADDR:
1587 			case IPV6_PORTRANGE:
1588 			case IPV6_PKTINFO:
1589 			case IPV6_HOPLIMIT:
1590 			case IPV6_RTHDR:
1591 			case IPV6_FAITH:
1592 			case IPV6_V6ONLY:
1593 			case IPV6_USE_MIN_MTU:
1594 				*mp = m = m_get(M_WAIT, MT_SOOPTS);
1595 				m->m_len = sizeof(int);
1596 				switch (optname) {
1597 
1598 				case IPV6_UNICAST_HOPS:
1599 					optval = in6p->in6p_hops;
1600 					break;
1601 
1602 #define OPTBIT(bit) (in6p->in6p_flags & bit ? 1 : 0)
1603 
1604 				case IPV6_RECVOPTS:
1605 					optval = OPTBIT(IN6P_RECVOPTS);
1606 					break;
1607 
1608 				case IPV6_RECVRETOPTS:
1609 					optval = OPTBIT(IN6P_RECVRETOPTS);
1610 					break;
1611 
1612 				case IPV6_RECVDSTADDR:
1613 					optval = OPTBIT(IN6P_RECVDSTADDR);
1614 					break;
1615 
1616 				case IPV6_PORTRANGE:
1617 				    {
1618 					int flags;
1619 					flags = in6p->in6p_flags;
1620 					if (flags & IN6P_HIGHPORT)
1621 						optval = IPV6_PORTRANGE_HIGH;
1622 					else if (flags & IN6P_LOWPORT)
1623 						optval = IPV6_PORTRANGE_LOW;
1624 					else
1625 						optval = 0;
1626 					break;
1627 				    }
1628 
1629 				case IPV6_PKTINFO:
1630 					optval = OPTBIT(IN6P_PKTINFO);
1631 					break;
1632 
1633 				case IPV6_HOPLIMIT:
1634 					optval = OPTBIT(IN6P_HOPLIMIT);
1635 					break;
1636 
1637 				case IPV6_HOPOPTS:
1638 					optval = OPTBIT(IN6P_HOPOPTS);
1639 					break;
1640 
1641 				case IPV6_DSTOPTS:
1642 					optval = OPTBIT(IN6P_DSTOPTS);
1643 					break;
1644 
1645 				case IPV6_RTHDR:
1646 					optval = OPTBIT(IN6P_RTHDR);
1647 					break;
1648 
1649 				case IPV6_FAITH:
1650 					optval = OPTBIT(IN6P_FAITH);
1651 					break;
1652 
1653 				case IPV6_V6ONLY:
1654 					optval = OPTBIT(IN6P_IPV6_V6ONLY);
1655 					break;
1656 
1657 				case IPV6_USE_MIN_MTU:
1658 					optval = OPTBIT(IN6P_MINMTU);
1659 					break;
1660 				}
1661 				*mtod(m, int *) = optval;
1662 				break;
1663 
1664 			case IPV6_MULTICAST_IF:
1665 			case IPV6_MULTICAST_HOPS:
1666 			case IPV6_MULTICAST_LOOP:
1667 			case IPV6_JOIN_GROUP:
1668 			case IPV6_LEAVE_GROUP:
1669 				error = ip6_getmoptions(optname, in6p->in6p_moptions, mp);
1670 				break;
1671 
1672 #if 0	/* defined(IPSEC) */
1673 			/* XXX: code broken */
1674 			case IPV6_IPSEC_POLICY:
1675 			{
1676 				caddr_t req = NULL;
1677 				size_t len = 0;
1678 
1679 				if (m) {
1680 					req = mtod(m, caddr_t);
1681 					len = m->m_len;
1682 				}
1683 				error = ipsec6_get_policy(in6p, req, len, mp);
1684 				break;
1685 			}
1686 #endif /* IPSEC */
1687 
1688 			default:
1689 				error = ENOPROTOOPT;
1690 				break;
1691 			}
1692 			break;
1693 		}
1694 	} else {
1695 		error = EINVAL;
1696 		if (op == PRCO_SETOPT && *mp)
1697 			(void)m_free(*mp);
1698 	}
1699 	return (error);
1700 }
1701 
1702 int
1703 ip6_raw_ctloutput(op, so, level, optname, mp)
1704 	int op;
1705 	struct socket *so;
1706 	int level, optname;
1707 	struct mbuf **mp;
1708 {
1709 	int error = 0, optval, optlen;
1710 	const int icmp6off = offsetof(struct icmp6_hdr, icmp6_cksum);
1711 	struct in6pcb *in6p = sotoin6pcb(so);
1712 	struct mbuf *m = *mp;
1713 
1714 	optlen = m ? m->m_len : 0;
1715 
1716 	if (level != IPPROTO_IPV6) {
1717 		if (op == PRCO_SETOPT && *mp)
1718 			(void)m_free(*mp);
1719 		return (EINVAL);
1720 	}
1721 
1722 	switch (optname) {
1723 	case IPV6_CHECKSUM:
1724 		/*
1725 		 * For ICMPv6 sockets, no modification allowed for checksum
1726 		 * offset, permit "no change" values to help existing apps.
1727 		 *
1728 		 * XXX 2292bis says: "An attempt to set IPV6_CHECKSUM
1729 		 * for an ICMPv6 socket will fail."
1730 		 * The current behavior does not meet 2292bis.
1731 		 */
1732 		switch (op) {
1733 		case PRCO_SETOPT:
1734 			if (optlen != sizeof(int)) {
1735 				error = EINVAL;
1736 				break;
1737 			}
1738 			optval = *mtod(m, int *);
1739 			if ((optval % 2) != 0) {
1740 				/* the API assumes even offset values */
1741 				error = EINVAL;
1742 			} else if (so->so_proto->pr_protocol ==
1743 			    IPPROTO_ICMPV6) {
1744 				if (optval != icmp6off)
1745 					error = EINVAL;
1746 			} else
1747 				in6p->in6p_cksum = optval;
1748 			break;
1749 
1750 		case PRCO_GETOPT:
1751 			if (so->so_proto->pr_protocol == IPPROTO_ICMPV6)
1752 				optval = icmp6off;
1753 			else
1754 				optval = in6p->in6p_cksum;
1755 
1756 			*mp = m = m_get(M_WAIT, MT_SOOPTS);
1757 			m->m_len = sizeof(int);
1758 			*mtod(m, int *) = optval;
1759 			break;
1760 
1761 		default:
1762 			error = EINVAL;
1763 			break;
1764 		}
1765 		break;
1766 
1767 	default:
1768 		error = ENOPROTOOPT;
1769 		break;
1770 	}
1771 
1772 	if (op == PRCO_SETOPT && m)
1773 		(void)m_free(m);
1774 
1775 	return (error);
1776 }
1777 
1778 /*
1779  * Set up IP6 options in pcb for insertion in output packets.
1780  * Store in mbuf with pointer in pcbopt, adding pseudo-option
1781  * with destination address if source routed.
1782  */
1783 static int
1784 ip6_pcbopts(pktopt, m, so)
1785 	struct ip6_pktopts **pktopt;
1786 	struct mbuf *m;
1787 	struct socket *so;
1788 {
1789 	struct ip6_pktopts *opt = *pktopt;
1790 	int error = 0;
1791 	struct proc *p = curproc;	/* XXX */
1792 	int priv = 0;
1793 
1794 	/* turn off any old options. */
1795 	if (opt) {
1796 		if (opt->ip6po_m)
1797 			(void)m_free(opt->ip6po_m);
1798 	} else
1799 		opt = malloc(sizeof(*opt), M_IP6OPT, M_WAITOK);
1800 	*pktopt = 0;
1801 
1802 	if (!m || m->m_len == 0) {
1803 		/*
1804 		 * Only turning off any previous options.
1805 		 */
1806 		free(opt, M_IP6OPT);
1807 		if (m)
1808 			(void)m_free(m);
1809 		return (0);
1810 	}
1811 
1812 	/*  set options specified by user. */
1813 	if (p && !suser(p->p_ucred, &p->p_acflag))
1814 		priv = 1;
1815 	if ((error = ip6_setpktoptions(m, opt, priv)) != 0) {
1816 		(void)m_free(m);
1817 		free(opt, M_IP6OPT);
1818 		return (error);
1819 	}
1820 	*pktopt = opt;
1821 	return (0);
1822 }
1823 
1824 /*
1825  * Set the IP6 multicast options in response to user setsockopt().
1826  */
1827 static int
1828 ip6_setmoptions(optname, im6op, m)
1829 	int optname;
1830 	struct ip6_moptions **im6op;
1831 	struct mbuf *m;
1832 {
1833 	int error = 0;
1834 	u_int loop, ifindex;
1835 	struct ipv6_mreq *mreq;
1836 	struct ifnet *ifp;
1837 	struct ip6_moptions *im6o = *im6op;
1838 	struct route_in6 ro;
1839 	struct in6_multi_mship *imm;
1840 	struct proc *p = curproc;	/* XXX */
1841 
1842 	if (im6o == NULL) {
1843 		/*
1844 		 * No multicast option buffer attached to the pcb;
1845 		 * allocate one and initialize to default values.
1846 		 */
1847 		im6o = (struct ip6_moptions *)
1848 			malloc(sizeof(*im6o), M_IPMOPTS, M_WAITOK);
1849 
1850 		if (im6o == NULL)
1851 			return (ENOBUFS);
1852 		*im6op = im6o;
1853 		im6o->im6o_multicast_ifp = NULL;
1854 		im6o->im6o_multicast_hlim = ip6_defmcasthlim;
1855 		im6o->im6o_multicast_loop = IPV6_DEFAULT_MULTICAST_LOOP;
1856 		LIST_INIT(&im6o->im6o_memberships);
1857 	}
1858 
1859 	switch (optname) {
1860 
1861 	case IPV6_MULTICAST_IF:
1862 		/*
1863 		 * Select the interface for outgoing multicast packets.
1864 		 */
1865 		if (m == NULL || m->m_len != sizeof(u_int)) {
1866 			error = EINVAL;
1867 			break;
1868 		}
1869 		bcopy(mtod(m, u_int *), &ifindex, sizeof(ifindex));
1870 		if (ifindex != 0) {
1871 			if (ifindex < 0 || if_indexlim <= ifindex ||
1872 			    !ifindex2ifnet[ifindex]) {
1873 				error = ENXIO;	/* XXX EINVAL? */
1874 				break;
1875 			}
1876 			ifp = ifindex2ifnet[ifindex];
1877 			if ((ifp->if_flags & IFF_MULTICAST) == 0) {
1878 				error = EADDRNOTAVAIL;
1879 				break;
1880 			}
1881 		} else
1882 			ifp = NULL;
1883 		im6o->im6o_multicast_ifp = ifp;
1884 		break;
1885 
1886 	case IPV6_MULTICAST_HOPS:
1887 	    {
1888 		/*
1889 		 * Set the IP6 hoplimit for outgoing multicast packets.
1890 		 */
1891 		int optval;
1892 		if (m == NULL || m->m_len != sizeof(int)) {
1893 			error = EINVAL;
1894 			break;
1895 		}
1896 		bcopy(mtod(m, u_int *), &optval, sizeof(optval));
1897 		if (optval < -1 || optval >= 256)
1898 			error = EINVAL;
1899 		else if (optval == -1)
1900 			im6o->im6o_multicast_hlim = ip6_defmcasthlim;
1901 		else
1902 			im6o->im6o_multicast_hlim = optval;
1903 		break;
1904 	    }
1905 
1906 	case IPV6_MULTICAST_LOOP:
1907 		/*
1908 		 * Set the loopback flag for outgoing multicast packets.
1909 		 * Must be zero or one.
1910 		 */
1911 		if (m == NULL || m->m_len != sizeof(u_int)) {
1912 			error = EINVAL;
1913 			break;
1914 		}
1915 		bcopy(mtod(m, u_int *), &loop, sizeof(loop));
1916 		if (loop > 1) {
1917 			error = EINVAL;
1918 			break;
1919 		}
1920 		im6o->im6o_multicast_loop = loop;
1921 		break;
1922 
1923 	case IPV6_JOIN_GROUP:
1924 		/*
1925 		 * Add a multicast group membership.
1926 		 * Group must be a valid IP6 multicast address.
1927 		 */
1928 		if (m == NULL || m->m_len != sizeof(struct ipv6_mreq)) {
1929 			error = EINVAL;
1930 			break;
1931 		}
1932 		mreq = mtod(m, struct ipv6_mreq *);
1933 		if (IN6_IS_ADDR_UNSPECIFIED(&mreq->ipv6mr_multiaddr)) {
1934 			/*
1935 			 * We use the unspecified address to specify to accept
1936 			 * all multicast addresses. Only super user is allowed
1937 			 * to do this.
1938 			 */
1939 			if (suser(p->p_ucred, &p->p_acflag))
1940 			{
1941 				error = EACCES;
1942 				break;
1943 			}
1944 		} else if (!IN6_IS_ADDR_MULTICAST(&mreq->ipv6mr_multiaddr)) {
1945 			error = EINVAL;
1946 			break;
1947 		}
1948 
1949 		/*
1950 		 * If no interface was explicitly specified, choose an
1951 		 * appropriate one according to the given multicast address.
1952 		 */
1953 		if (mreq->ipv6mr_interface == 0) {
1954 			struct sockaddr_in6 *dst;
1955 
1956 			/*
1957 			 * Look up the routing table for the
1958 			 * address, and choose the outgoing interface.
1959 			 *   XXX: is it a good approach?
1960 			 */
1961 			ro.ro_rt = NULL;
1962 			dst = (struct sockaddr_in6 *)&ro.ro_dst;
1963 			bzero(dst, sizeof(*dst));
1964 			dst->sin6_family = AF_INET6;
1965 			dst->sin6_len = sizeof(*dst);
1966 			dst->sin6_addr = mreq->ipv6mr_multiaddr;
1967 			rtalloc((struct route *)&ro);
1968 			if (ro.ro_rt == NULL) {
1969 				error = EADDRNOTAVAIL;
1970 				break;
1971 			}
1972 			ifp = ro.ro_rt->rt_ifp;
1973 			rtfree(ro.ro_rt);
1974 		} else {
1975 			/*
1976 			 * If the interface is specified, validate it.
1977 			 */
1978 			if (mreq->ipv6mr_interface < 0 ||
1979 			    if_indexlim <= mreq->ipv6mr_interface ||
1980 			    !ifindex2ifnet[mreq->ipv6mr_interface]) {
1981 				error = ENXIO;	/* XXX EINVAL? */
1982 				break;
1983 			}
1984 			ifp = ifindex2ifnet[mreq->ipv6mr_interface];
1985 		}
1986 
1987 		/*
1988 		 * See if we found an interface, and confirm that it
1989 		 * supports multicast
1990 		 */
1991 		if (ifp == NULL || (ifp->if_flags & IFF_MULTICAST) == 0) {
1992 			error = EADDRNOTAVAIL;
1993 			break;
1994 		}
1995 
1996 		if (in6_setscope(&mreq->ipv6mr_multiaddr, ifp, NULL)) {
1997 			error = EADDRNOTAVAIL; /* XXX: should not happen */
1998 			break;
1999 		}
2000 
2001 		/*
2002 		 * See if the membership already exists.
2003 		 */
2004 		for (imm = im6o->im6o_memberships.lh_first;
2005 		     imm != NULL; imm = imm->i6mm_chain.le_next)
2006 			if (imm->i6mm_maddr->in6m_ifp == ifp &&
2007 			    IN6_ARE_ADDR_EQUAL(&imm->i6mm_maddr->in6m_addr,
2008 			    &mreq->ipv6mr_multiaddr))
2009 				break;
2010 		if (imm != NULL) {
2011 			error = EADDRINUSE;
2012 			break;
2013 		}
2014 		/*
2015 		 * Everything looks good; add a new record to the multicast
2016 		 * address list for the given interface.
2017 		 */
2018 		imm = in6_joingroup(ifp, &mreq->ipv6mr_multiaddr, &error, 0);
2019 		if (imm == NULL)
2020 			break;
2021 		LIST_INSERT_HEAD(&im6o->im6o_memberships, imm, i6mm_chain);
2022 		break;
2023 
2024 	case IPV6_LEAVE_GROUP:
2025 		/*
2026 		 * Drop a multicast group membership.
2027 		 * Group must be a valid IP6 multicast address.
2028 		 */
2029 		if (m == NULL || m->m_len != sizeof(struct ipv6_mreq)) {
2030 			error = EINVAL;
2031 			break;
2032 		}
2033 		mreq = mtod(m, struct ipv6_mreq *);
2034 
2035 		/*
2036 		 * If an interface address was specified, get a pointer
2037 		 * to its ifnet structure.
2038 		 */
2039 		if (mreq->ipv6mr_interface != 0) {
2040 			if (mreq->ipv6mr_interface < 0 ||
2041 			    if_indexlim <= mreq->ipv6mr_interface ||
2042 			    !ifindex2ifnet[mreq->ipv6mr_interface]) {
2043 				error = ENXIO;	/* XXX EINVAL? */
2044 				break;
2045 			}
2046 			ifp = ifindex2ifnet[mreq->ipv6mr_interface];
2047 		} else
2048 			ifp = NULL;
2049 
2050 		/* Fill in the scope zone ID */
2051 		if (ifp) {
2052 			if (in6_setscope(&mreq->ipv6mr_multiaddr, ifp, NULL)) {
2053 				/* XXX: should not happen */
2054 				error = EADDRNOTAVAIL;
2055 				break;
2056 			}
2057 		} else if (mreq->ipv6mr_interface != 0) {
2058 			/*
2059 			 * XXX: This case would happens when the (positive)
2060 			 * index is in the valid range, but the corresponding
2061 			 * interface has been detached dynamically.  The above
2062 			 * check probably avoids such case to happen here, but
2063 			 * we check it explicitly for safety.
2064 			 */
2065 			error = EADDRNOTAVAIL;
2066 			break;
2067 		} else {	/* ipv6mr_interface == 0 */
2068 			struct sockaddr_in6 sa6_mc;
2069 
2070 			/*
2071 			 * The API spec says as follows:
2072 			 *  If the interface index is specified as 0, the
2073 			 *  system may choose a multicast group membership to
2074 			 *  drop by matching the multicast address only.
2075 			 * On the other hand, we cannot disambiguate the scope
2076 			 * zone unless an interface is provided.  Thus, we
2077 			 * check if there's ambiguity with the default scope
2078 			 * zone as the last resort.
2079 			 */
2080 			bzero(&sa6_mc, sizeof(sa6_mc));
2081 			sa6_mc.sin6_family = AF_INET6;
2082 			sa6_mc.sin6_len = sizeof(sa6_mc);
2083 			sa6_mc.sin6_addr = mreq->ipv6mr_multiaddr;
2084 			error = sa6_embedscope(&sa6_mc, ip6_use_defzone);
2085 			if (error != 0)
2086 				break;
2087 			mreq->ipv6mr_multiaddr = sa6_mc.sin6_addr;
2088 		}
2089 
2090 		/*
2091 		 * Find the membership in the membership list.
2092 		 */
2093 		for (imm = im6o->im6o_memberships.lh_first;
2094 		     imm != NULL; imm = imm->i6mm_chain.le_next) {
2095 			if ((ifp == NULL || imm->i6mm_maddr->in6m_ifp == ifp) &&
2096 			    IN6_ARE_ADDR_EQUAL(&imm->i6mm_maddr->in6m_addr,
2097 			    &mreq->ipv6mr_multiaddr))
2098 				break;
2099 		}
2100 		if (imm == NULL) {
2101 			/* Unable to resolve interface */
2102 			error = EADDRNOTAVAIL;
2103 			break;
2104 		}
2105 		/*
2106 		 * Give up the multicast address record to which the
2107 		 * membership points.
2108 		 */
2109 		LIST_REMOVE(imm, i6mm_chain);
2110 		in6_leavegroup(imm);
2111 		break;
2112 
2113 	default:
2114 		error = EOPNOTSUPP;
2115 		break;
2116 	}
2117 
2118 	/*
2119 	 * If all options have default values, no need to keep the mbuf.
2120 	 */
2121 	if (im6o->im6o_multicast_ifp == NULL &&
2122 	    im6o->im6o_multicast_hlim == ip6_defmcasthlim &&
2123 	    im6o->im6o_multicast_loop == IPV6_DEFAULT_MULTICAST_LOOP &&
2124 	    im6o->im6o_memberships.lh_first == NULL) {
2125 		free(*im6op, M_IPMOPTS);
2126 		*im6op = NULL;
2127 	}
2128 
2129 	return (error);
2130 }
2131 
2132 /*
2133  * Return the IP6 multicast options in response to user getsockopt().
2134  */
2135 static int
2136 ip6_getmoptions(optname, im6o, mp)
2137 	int optname;
2138 	struct ip6_moptions *im6o;
2139 	struct mbuf **mp;
2140 {
2141 	u_int *hlim, *loop, *ifindex;
2142 
2143 	*mp = m_get(M_WAIT, MT_SOOPTS);
2144 
2145 	switch (optname) {
2146 
2147 	case IPV6_MULTICAST_IF:
2148 		ifindex = mtod(*mp, u_int *);
2149 		(*mp)->m_len = sizeof(u_int);
2150 		if (im6o == NULL || im6o->im6o_multicast_ifp == NULL)
2151 			*ifindex = 0;
2152 		else
2153 			*ifindex = im6o->im6o_multicast_ifp->if_index;
2154 		return (0);
2155 
2156 	case IPV6_MULTICAST_HOPS:
2157 		hlim = mtod(*mp, u_int *);
2158 		(*mp)->m_len = sizeof(u_int);
2159 		if (im6o == NULL)
2160 			*hlim = ip6_defmcasthlim;
2161 		else
2162 			*hlim = im6o->im6o_multicast_hlim;
2163 		return (0);
2164 
2165 	case IPV6_MULTICAST_LOOP:
2166 		loop = mtod(*mp, u_int *);
2167 		(*mp)->m_len = sizeof(u_int);
2168 		if (im6o == NULL)
2169 			*loop = ip6_defmcasthlim;
2170 		else
2171 			*loop = im6o->im6o_multicast_loop;
2172 		return (0);
2173 
2174 	default:
2175 		return (EOPNOTSUPP);
2176 	}
2177 }
2178 
2179 /*
2180  * Discard the IP6 multicast options.
2181  */
2182 void
2183 ip6_freemoptions(im6o)
2184 	struct ip6_moptions *im6o;
2185 {
2186 	struct in6_multi_mship *imm;
2187 
2188 	if (im6o == NULL)
2189 		return;
2190 
2191 	while ((imm = im6o->im6o_memberships.lh_first) != NULL) {
2192 		LIST_REMOVE(imm, i6mm_chain);
2193 		in6_leavegroup(imm);
2194 	}
2195 	free(im6o, M_IPMOPTS);
2196 }
2197 
2198 /*
2199  * Set IPv6 outgoing packet options based on advanced API.
2200  */
2201 int
2202 ip6_setpktoptions(control, opt, priv)
2203 	struct mbuf *control;
2204 	struct ip6_pktopts *opt;
2205 	int priv;
2206 {
2207 	struct cmsghdr *cm = 0;
2208 
2209 	if (control == 0 || opt == 0)
2210 		return (EINVAL);
2211 
2212 	bzero(opt, sizeof(*opt));
2213 	opt->ip6po_hlim = -1; /* -1 means to use default hop limit */
2214 
2215 	/*
2216 	 * XXX: Currently, we assume all the optional information is stored
2217 	 * in a single mbuf.
2218 	 */
2219 	if (control->m_next)
2220 		return (EINVAL);
2221 
2222 	opt->ip6po_m = control;
2223 
2224 	for (; control->m_len; control->m_data += CMSG_ALIGN(cm->cmsg_len),
2225 	    control->m_len -= CMSG_ALIGN(cm->cmsg_len)) {
2226 		cm = mtod(control, struct cmsghdr *);
2227 		if (cm->cmsg_len == 0 || cm->cmsg_len > control->m_len)
2228 			return (EINVAL);
2229 		if (cm->cmsg_level != IPPROTO_IPV6)
2230 			continue;
2231 
2232 		switch (cm->cmsg_type) {
2233 		case IPV6_PKTINFO:
2234 			if (cm->cmsg_len != CMSG_LEN(sizeof(struct in6_pktinfo)))
2235 				return (EINVAL);
2236 			opt->ip6po_pktinfo = (struct in6_pktinfo *)CMSG_DATA(cm);
2237 			if (opt->ip6po_pktinfo->ipi6_ifindex >= if_indexlim ||
2238 			    opt->ip6po_pktinfo->ipi6_ifindex < 0)
2239 				return (ENXIO);
2240 			if (opt->ip6po_pktinfo->ipi6_ifindex > 0 &&
2241 			    !ifindex2ifnet[opt->ip6po_pktinfo->ipi6_ifindex])
2242 				return (ENXIO);
2243 
2244 			if (opt->ip6po_pktinfo->ipi6_ifindex) {
2245 				struct ifnet *ifp;
2246 				int error;
2247 
2248 				/* ipi6_ifindex must be valid here */
2249 				ifp = ifindex2ifnet[opt->ip6po_pktinfo->ipi6_ifindex];
2250 				error = in6_setscope(&opt->ip6po_pktinfo->ipi6_addr,
2251 				    ifp, NULL);
2252 				if (error != 0)
2253 					return (error);
2254 			}
2255 
2256 			/*
2257 			 * Check if the requested source address is indeed a
2258 			 * unicast address assigned to the node, and can be
2259 			 * used as the packet's source address.
2260 			 */
2261 			if (!IN6_IS_ADDR_UNSPECIFIED(&opt->ip6po_pktinfo->ipi6_addr)) {
2262 				struct ifaddr *ia;
2263 				struct in6_ifaddr *ia6;
2264 				struct sockaddr_in6 sin6;
2265 
2266 				bzero(&sin6, sizeof(sin6));
2267 				sin6.sin6_len = sizeof(sin6);
2268 				sin6.sin6_family = AF_INET6;
2269 				sin6.sin6_addr =
2270 					opt->ip6po_pktinfo->ipi6_addr;
2271 				ia = ifa_ifwithaddr(sin6tosa(&sin6));
2272 				if (ia == NULL ||
2273 				    (opt->ip6po_pktinfo->ipi6_ifindex &&
2274 				     (ia->ifa_ifp->if_index !=
2275 				      opt->ip6po_pktinfo->ipi6_ifindex))) {
2276 					return (EADDRNOTAVAIL);
2277 				}
2278 				ia6 = (struct in6_ifaddr *)ia;
2279 				if ((ia6->ia6_flags & (IN6_IFF_ANYCAST|IN6_IFF_NOTREADY)) != 0) {
2280 					return (EADDRNOTAVAIL);
2281 				}
2282 
2283 				/*
2284 				 * Check if the requested source address is
2285 				 * indeed a unicast address assigned to the
2286 				 * node.
2287 				 */
2288 				if (IN6_IS_ADDR_MULTICAST(&opt->ip6po_pktinfo->ipi6_addr))
2289 					return (EADDRNOTAVAIL);
2290 			}
2291 			break;
2292 
2293 		case IPV6_HOPLIMIT:
2294 			if (cm->cmsg_len != CMSG_LEN(sizeof(int)))
2295 				return (EINVAL);
2296 			else {
2297 				int t;
2298 
2299 				bcopy(CMSG_DATA(cm), &t, sizeof(t));
2300 				if (t < -1 || t > 255)
2301 					return (EINVAL);
2302 				opt->ip6po_hlim = t;
2303 			}
2304 			break;
2305 
2306 		case IPV6_NEXTHOP:
2307 			if (!priv)
2308 				return (EPERM);
2309 
2310 			/* check if cmsg_len is large enough for sa_len */
2311 			if (cm->cmsg_len < sizeof(u_char) ||
2312 			    cm->cmsg_len < CMSG_LEN(*CMSG_DATA(cm)))
2313 				return (EINVAL);
2314 
2315 			opt->ip6po_nexthop = (struct sockaddr *)CMSG_DATA(cm);
2316 
2317 			break;
2318 
2319 		case IPV6_HOPOPTS:
2320 			if (cm->cmsg_len < CMSG_LEN(sizeof(struct ip6_hbh)))
2321 				return (EINVAL);
2322 			else {
2323 				struct  ip6_hbh *t;
2324 
2325 				t = (struct ip6_hbh *)CMSG_DATA(cm);
2326 				if (cm->cmsg_len !=
2327 				    CMSG_LEN((t->ip6h_len + 1) << 3))
2328 					return (EINVAL);
2329 				opt->ip6po_hbh = t;
2330 			}
2331 			break;
2332 
2333 		case IPV6_DSTOPTS:
2334 			if (cm->cmsg_len < CMSG_LEN(sizeof(struct ip6_dest)))
2335 				return (EINVAL);
2336 
2337 			/*
2338 			 * If there is no routing header yet, the destination
2339 			 * options header should be put on the 1st part.
2340 			 * Otherwise, the header should be on the 2nd part.
2341 			 * (See RFC 2460, section 4.1)
2342 			 */
2343 			if (opt->ip6po_rthdr == NULL) {
2344 				struct ip6_dest *t;
2345 
2346 				t = (struct ip6_dest *)CMSG_DATA(cm);
2347 				if (cm->cmsg_len !=
2348 				    CMSG_LEN((t->ip6d_len + 1) << 3));
2349 					return (EINVAL);
2350 				opt->ip6po_dest1 = t;
2351 			}
2352 			else {
2353 				struct ip6_dest *t;
2354 
2355 				t = (struct ip6_dest *)CMSG_DATA(cm);
2356 				if (cm->cmsg_len !=
2357 				    CMSG_LEN((opt->ip6po_dest2->ip6d_len + 1) << 3))
2358 					return (EINVAL);
2359 				opt->ip6po_dest2 = t;
2360 			}
2361 			break;
2362 
2363 		case IPV6_RTHDR:
2364 			if (cm->cmsg_len < CMSG_LEN(sizeof(struct ip6_rthdr)))
2365 				return (EINVAL);
2366 			else {
2367 				struct ip6_rthdr *t;
2368 
2369 				t = (struct ip6_rthdr *)CMSG_DATA(cm);
2370 				if (cm->cmsg_len !=
2371 				    CMSG_LEN((t->ip6r_len + 1) << 3))
2372 					return (EINVAL);
2373 				switch (t->ip6r_type) {
2374 				case IPV6_RTHDR_TYPE_0:
2375 					if (t->ip6r_segleft == 0)
2376 						return (EINVAL);
2377 					break;
2378 				default:
2379 					return (EINVAL);
2380 				}
2381 				opt->ip6po_rthdr = t;
2382 			}
2383 			break;
2384 
2385 		default:
2386 			return (ENOPROTOOPT);
2387 		}
2388 	}
2389 
2390 	return (0);
2391 }
2392 
2393 /*
2394  * Routine called from ip6_output() to loop back a copy of an IP6 multicast
2395  * packet to the input queue of a specified interface.  Note that this
2396  * calls the output routine of the loopback "driver", but with an interface
2397  * pointer that might NOT be lo0ifp -- easier than replicating that code here.
2398  */
2399 void
2400 ip6_mloopback(ifp, m, dst)
2401 	struct ifnet *ifp;
2402 	struct mbuf *m;
2403 	struct sockaddr_in6 *dst;
2404 {
2405 	struct mbuf *copym;
2406 	struct ip6_hdr *ip6;
2407 
2408 	copym = m_copy(m, 0, M_COPYALL);
2409 	if (copym == NULL)
2410 		return;
2411 
2412 	/*
2413 	 * Make sure to deep-copy IPv6 header portion in case the data
2414 	 * is in an mbuf cluster, so that we can safely override the IPv6
2415 	 * header portion later.
2416 	 */
2417 	if ((copym->m_flags & M_EXT) != 0 ||
2418 	    copym->m_len < sizeof(struct ip6_hdr)) {
2419 		copym = m_pullup(copym, sizeof(struct ip6_hdr));
2420 		if (copym == NULL)
2421 			return;
2422 	}
2423 
2424 #ifdef DIAGNOSTIC
2425 	if (copym->m_len < sizeof(*ip6)) {
2426 		m_freem(copym);
2427 		return;
2428 	}
2429 #endif
2430 
2431 	ip6 = mtod(copym, struct ip6_hdr *);
2432 	/*
2433 	 * clear embedded scope identifiers if necessary.
2434 	 * in6_clearscope will touch the addresses only when necessary.
2435 	 */
2436 	in6_clearscope(&ip6->ip6_src);
2437 	in6_clearscope(&ip6->ip6_dst);
2438 
2439 	(void)looutput(ifp, copym, (struct sockaddr *)dst, NULL);
2440 }
2441 
2442 /*
2443  * Chop IPv6 header off from the payload.
2444  */
2445 static int
2446 ip6_splithdr(m, exthdrs)
2447 	struct mbuf *m;
2448 	struct ip6_exthdrs *exthdrs;
2449 {
2450 	struct mbuf *mh;
2451 	struct ip6_hdr *ip6;
2452 
2453 	ip6 = mtod(m, struct ip6_hdr *);
2454 	if (m->m_len > sizeof(*ip6)) {
2455 		MGETHDR(mh, M_DONTWAIT, MT_HEADER);
2456 		if (mh == 0) {
2457 			m_freem(m);
2458 			return ENOBUFS;
2459 		}
2460 		M_MOVE_PKTHDR(mh, m);
2461 		MH_ALIGN(mh, sizeof(*ip6));
2462 		m->m_len -= sizeof(*ip6);
2463 		m->m_data += sizeof(*ip6);
2464 		mh->m_next = m;
2465 		m = mh;
2466 		m->m_len = sizeof(*ip6);
2467 		bcopy((caddr_t)ip6, mtod(m, caddr_t), sizeof(*ip6));
2468 	}
2469 	exthdrs->ip6e_ip6 = m;
2470 	return 0;
2471 }
2472 
2473 /*
2474  * Compute IPv6 extension header length.
2475  */
2476 int
2477 ip6_optlen(in6p)
2478 	struct in6pcb *in6p;
2479 {
2480 	int len;
2481 
2482 	if (!in6p->in6p_outputopts)
2483 		return 0;
2484 
2485 	len = 0;
2486 #define elen(x) \
2487     (((struct ip6_ext *)(x)) ? (((struct ip6_ext *)(x))->ip6e_len + 1) << 3 : 0)
2488 
2489 	len += elen(in6p->in6p_outputopts->ip6po_hbh);
2490 	len += elen(in6p->in6p_outputopts->ip6po_dest1);
2491 	len += elen(in6p->in6p_outputopts->ip6po_rthdr);
2492 	len += elen(in6p->in6p_outputopts->ip6po_dest2);
2493 	return len;
2494 #undef elen
2495 }
2496