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