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