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