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