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