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