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