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