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