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