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