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