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