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