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