]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/netinet6/icmp6.c
sys/{x86,amd64}: remove one of doubled ;s
[FreeBSD/FreeBSD.git] / sys / netinet6 / icmp6.c
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the project nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  *
31  *      $KAME: icmp6.c,v 1.211 2001/04/04 05:56:20 itojun Exp $
32  */
33
34 /*-
35  * Copyright (c) 1982, 1986, 1988, 1993
36  *      The Regents of the University of California.  All rights reserved.
37  *
38  * Redistribution and use in source and binary forms, with or without
39  * modification, are permitted provided that the following conditions
40  * are met:
41  * 1. Redistributions of source code must retain the above copyright
42  *    notice, this list of conditions and the following disclaimer.
43  * 2. Redistributions in binary form must reproduce the above copyright
44  *    notice, this list of conditions and the following disclaimer in the
45  *    documentation and/or other materials provided with the distribution.
46  * 3. Neither the name of the University nor the names of its contributors
47  *    may be used to endorse or promote products derived from this software
48  *    without specific prior written permission.
49  *
50  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
51  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
52  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
53  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
54  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
55  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
56  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
57  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
58  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
59  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
60  * SUCH DAMAGE.
61  *
62  *      @(#)ip_icmp.c   8.2 (Berkeley) 1/4/94
63  */
64
65 #include <sys/cdefs.h>
66 __FBSDID("$FreeBSD$");
67
68 #define MBUF_PRIVATE    /* XXXRW: Optimisation tries to avoid M_EXT mbufs */
69
70 #include "opt_inet.h"
71 #include "opt_inet6.h"
72
73 #include <sys/param.h>
74 #include <sys/domain.h>
75 #include <sys/jail.h>
76 #include <sys/kernel.h>
77 #include <sys/lock.h>
78 #include <sys/malloc.h>
79 #include <sys/mbuf.h>
80 #include <sys/proc.h>
81 #include <sys/protosw.h>
82 #include <sys/signalvar.h>
83 #include <sys/socket.h>
84 #include <sys/socketvar.h>
85 #include <sys/sx.h>
86 #include <sys/syslog.h>
87 #include <sys/systm.h>
88 #include <sys/time.h>
89
90 #include <net/if.h>
91 #include <net/if_var.h>
92 #include <net/if_dl.h>
93 #include <net/if_llatbl.h>
94 #include <net/if_types.h>
95 #include <net/route.h>
96 #include <net/vnet.h>
97
98 #include <netinet/in.h>
99 #include <netinet/in_pcb.h>
100 #include <netinet/in_var.h>
101 #include <netinet/ip6.h>
102 #include <netinet/icmp6.h>
103 #include <netinet/tcp_var.h>
104
105 #include <netinet6/in6_fib.h>
106 #include <netinet6/in6_ifattach.h>
107 #include <netinet6/in6_pcb.h>
108 #include <netinet6/ip6protosw.h>
109 #include <netinet6/ip6_var.h>
110 #include <netinet6/scope6_var.h>
111 #include <netinet6/mld6_var.h>
112 #include <netinet6/nd6.h>
113 #include <netinet6/send.h>
114
115 extern struct domain inet6domain;
116
117 VNET_PCPUSTAT_DEFINE(struct icmp6stat, icmp6stat);
118 VNET_PCPUSTAT_SYSINIT(icmp6stat);
119
120 #ifdef VIMAGE
121 VNET_PCPUSTAT_SYSUNINIT(icmp6stat);
122 #endif /* VIMAGE */
123
124 VNET_DECLARE(struct inpcbinfo, ripcbinfo);
125 VNET_DECLARE(struct inpcbhead, ripcb);
126 VNET_DECLARE(int, icmp6errppslim);
127 VNET_DEFINE_STATIC(int, icmp6errpps_count) = 0;
128 VNET_DEFINE_STATIC(struct timeval, icmp6errppslim_last);
129 VNET_DECLARE(int, icmp6_nodeinfo);
130
131 #define V_ripcbinfo                     VNET(ripcbinfo)
132 #define V_ripcb                         VNET(ripcb)
133 #define V_icmp6errppslim                VNET(icmp6errppslim)
134 #define V_icmp6errpps_count             VNET(icmp6errpps_count)
135 #define V_icmp6errppslim_last           VNET(icmp6errppslim_last)
136 #define V_icmp6_nodeinfo                VNET(icmp6_nodeinfo)
137
138 static void icmp6_errcount(int, int);
139 static int icmp6_rip6_input(struct mbuf **, int);
140 static int icmp6_ratelimit(const struct in6_addr *, const int, const int);
141 static const char *icmp6_redirect_diag(struct in6_addr *,
142         struct in6_addr *, struct in6_addr *);
143 static struct mbuf *ni6_input(struct mbuf *, int, struct prison *);
144 static struct mbuf *ni6_nametodns(const char *, int, int);
145 static int ni6_dnsmatch(const char *, int, const char *, int);
146 static int ni6_addrs(struct icmp6_nodeinfo *, struct mbuf *,
147                           struct ifnet **, struct in6_addr *);
148 static int ni6_store_addrs(struct icmp6_nodeinfo *, struct icmp6_nodeinfo *,
149                                 struct ifnet *, int);
150 static int icmp6_notify_error(struct mbuf **, int, int, int);
151
152 /*
153  * Kernel module interface for updating icmp6stat.  The argument is an index
154  * into icmp6stat treated as an array of u_quad_t.  While this encodes the
155  * general layout of icmp6stat into the caller, it doesn't encode its
156  * location, so that future changes to add, for example, per-CPU stats
157  * support won't cause binary compatibility problems for kernel modules.
158  */
159 void
160 kmod_icmp6stat_inc(int statnum)
161 {
162
163         counter_u64_add(VNET(icmp6stat)[statnum], 1);
164 }
165
166 static void
167 icmp6_errcount(int type, int code)
168 {
169         switch (type) {
170         case ICMP6_DST_UNREACH:
171                 switch (code) {
172                 case ICMP6_DST_UNREACH_NOROUTE:
173                         ICMP6STAT_INC(icp6s_odst_unreach_noroute);
174                         return;
175                 case ICMP6_DST_UNREACH_ADMIN:
176                         ICMP6STAT_INC(icp6s_odst_unreach_admin);
177                         return;
178                 case ICMP6_DST_UNREACH_BEYONDSCOPE:
179                         ICMP6STAT_INC(icp6s_odst_unreach_beyondscope);
180                         return;
181                 case ICMP6_DST_UNREACH_ADDR:
182                         ICMP6STAT_INC(icp6s_odst_unreach_addr);
183                         return;
184                 case ICMP6_DST_UNREACH_NOPORT:
185                         ICMP6STAT_INC(icp6s_odst_unreach_noport);
186                         return;
187                 }
188                 break;
189         case ICMP6_PACKET_TOO_BIG:
190                 ICMP6STAT_INC(icp6s_opacket_too_big);
191                 return;
192         case ICMP6_TIME_EXCEEDED:
193                 switch (code) {
194                 case ICMP6_TIME_EXCEED_TRANSIT:
195                         ICMP6STAT_INC(icp6s_otime_exceed_transit);
196                         return;
197                 case ICMP6_TIME_EXCEED_REASSEMBLY:
198                         ICMP6STAT_INC(icp6s_otime_exceed_reassembly);
199                         return;
200                 }
201                 break;
202         case ICMP6_PARAM_PROB:
203                 switch (code) {
204                 case ICMP6_PARAMPROB_HEADER:
205                         ICMP6STAT_INC(icp6s_oparamprob_header);
206                         return;
207                 case ICMP6_PARAMPROB_NEXTHEADER:
208                         ICMP6STAT_INC(icp6s_oparamprob_nextheader);
209                         return;
210                 case ICMP6_PARAMPROB_OPTION:
211                         ICMP6STAT_INC(icp6s_oparamprob_option);
212                         return;
213                 }
214                 break;
215         case ND_REDIRECT:
216                 ICMP6STAT_INC(icp6s_oredirect);
217                 return;
218         }
219         ICMP6STAT_INC(icp6s_ounknown);
220 }
221
222 /*
223  * A wrapper function for icmp6_error() necessary when the erroneous packet
224  * may not contain enough scope zone information.
225  */
226 void
227 icmp6_error2(struct mbuf *m, int type, int code, int param,
228     struct ifnet *ifp)
229 {
230         struct ip6_hdr *ip6;
231
232         if (ifp == NULL)
233                 return;
234
235 #ifndef PULLDOWN_TEST
236         IP6_EXTHDR_CHECK(m, 0, sizeof(struct ip6_hdr), );
237 #else
238         if (m->m_len < sizeof(struct ip6_hdr)) {
239                 m = m_pullup(m, sizeof(struct ip6_hdr));
240                 if (m == NULL)
241                         return;
242         }
243 #endif
244
245         ip6 = mtod(m, struct ip6_hdr *);
246
247         if (in6_setscope(&ip6->ip6_src, ifp, NULL) != 0)
248                 return;
249         if (in6_setscope(&ip6->ip6_dst, ifp, NULL) != 0)
250                 return;
251
252         icmp6_error(m, type, code, param);
253 }
254
255 /*
256  * Generate an error packet of type error in response to bad IP6 packet.
257  */
258 void
259 icmp6_error(struct mbuf *m, int type, int code, int param)
260 {
261         struct ip6_hdr *oip6, *nip6;
262         struct icmp6_hdr *icmp6;
263         u_int preplen;
264         int off;
265         int nxt;
266
267         ICMP6STAT_INC(icp6s_error);
268
269         /* count per-type-code statistics */
270         icmp6_errcount(type, code);
271
272 #ifdef M_DECRYPTED      /*not openbsd*/
273         if (m->m_flags & M_DECRYPTED) {
274                 ICMP6STAT_INC(icp6s_canterror);
275                 goto freeit;
276         }
277 #endif
278
279 #ifndef PULLDOWN_TEST
280         IP6_EXTHDR_CHECK(m, 0, sizeof(struct ip6_hdr), );
281 #else
282         if (m->m_len < sizeof(struct ip6_hdr)) {
283                 m = m_pullup(m, sizeof(struct ip6_hdr));
284                 if (m == NULL)
285                         return;
286         }
287 #endif
288         oip6 = mtod(m, struct ip6_hdr *);
289
290         /*
291          * If the destination address of the erroneous packet is a multicast
292          * address, or the packet was sent using link-layer multicast,
293          * we should basically suppress sending an error (RFC 2463, Section
294          * 2.4).
295          * We have two exceptions (the item e.2 in that section):
296          * - the Packet Too Big message can be sent for path MTU discovery.
297          * - the Parameter Problem Message that can be allowed an icmp6 error
298          *   in the option type field.  This check has been done in
299          *   ip6_unknown_opt(), so we can just check the type and code.
300          */
301         if ((m->m_flags & (M_BCAST|M_MCAST) ||
302              IN6_IS_ADDR_MULTICAST(&oip6->ip6_dst)) &&
303             (type != ICMP6_PACKET_TOO_BIG &&
304              (type != ICMP6_PARAM_PROB ||
305               code != ICMP6_PARAMPROB_OPTION)))
306                 goto freeit;
307
308         /*
309          * RFC 2463, 2.4 (e.5): source address check.
310          * XXX: the case of anycast source?
311          */
312         if (IN6_IS_ADDR_UNSPECIFIED(&oip6->ip6_src) ||
313             IN6_IS_ADDR_MULTICAST(&oip6->ip6_src))
314                 goto freeit;
315
316         /*
317          * If we are about to send ICMPv6 against ICMPv6 error/redirect,
318          * don't do it.
319          */
320         nxt = -1;
321         off = ip6_lasthdr(m, 0, IPPROTO_IPV6, &nxt);
322         if (off >= 0 && nxt == IPPROTO_ICMPV6) {
323                 struct icmp6_hdr *icp;
324
325 #ifndef PULLDOWN_TEST
326                 IP6_EXTHDR_CHECK(m, 0, off + sizeof(struct icmp6_hdr), );
327                 icp = (struct icmp6_hdr *)(mtod(m, caddr_t) + off);
328 #else
329                 IP6_EXTHDR_GET(icp, struct icmp6_hdr *, m, off,
330                         sizeof(*icp));
331                 if (icp == NULL) {
332                         ICMP6STAT_INC(icp6s_tooshort);
333                         return;
334                 }
335 #endif
336                 if (icp->icmp6_type < ICMP6_ECHO_REQUEST ||
337                     icp->icmp6_type == ND_REDIRECT) {
338                         /*
339                          * ICMPv6 error
340                          * Special case: for redirect (which is
341                          * informational) we must not send icmp6 error.
342                          */
343                         ICMP6STAT_INC(icp6s_canterror);
344                         goto freeit;
345                 } else {
346                         /* ICMPv6 informational - send the error */
347                 }
348         } else {
349                 /* non-ICMPv6 - send the error */
350         }
351
352         oip6 = mtod(m, struct ip6_hdr *); /* adjust pointer */
353
354         /* Finally, do rate limitation check. */
355         if (icmp6_ratelimit(&oip6->ip6_src, type, code)) {
356                 ICMP6STAT_INC(icp6s_toofreq);
357                 goto freeit;
358         }
359
360         /*
361          * OK, ICMP6 can be generated.
362          */
363
364         if (m->m_pkthdr.len >= ICMPV6_PLD_MAXLEN)
365                 m_adj(m, ICMPV6_PLD_MAXLEN - m->m_pkthdr.len);
366
367         preplen = sizeof(struct ip6_hdr) + sizeof(struct icmp6_hdr);
368         M_PREPEND(m, preplen, M_NOWAIT);        /* FIB is also copied over. */
369         if (m == NULL) {
370                 nd6log((LOG_DEBUG, "ENOBUFS in icmp6_error %d\n", __LINE__));
371                 return;
372         }
373
374         nip6 = mtod(m, struct ip6_hdr *);
375         nip6->ip6_src  = oip6->ip6_src;
376         nip6->ip6_dst  = oip6->ip6_dst;
377
378         in6_clearscope(&oip6->ip6_src);
379         in6_clearscope(&oip6->ip6_dst);
380
381         icmp6 = (struct icmp6_hdr *)(nip6 + 1);
382         icmp6->icmp6_type = type;
383         icmp6->icmp6_code = code;
384         icmp6->icmp6_pptr = htonl((u_int32_t)param);
385
386         ICMP6STAT_INC(icp6s_outhist[type]);
387         icmp6_reflect(m, sizeof(struct ip6_hdr)); /* header order: IPv6 - ICMPv6 */
388
389         return;
390
391   freeit:
392         /*
393          * If we can't tell whether or not we can generate ICMP6, free it.
394          */
395         m_freem(m);
396 }
397
398 /*
399  * Process a received ICMP6 message.
400  */
401 int
402 icmp6_input(struct mbuf **mp, int *offp, int proto)
403 {
404         struct mbuf *m = *mp, *n;
405         struct ifnet *ifp;
406         struct ip6_hdr *ip6, *nip6;
407         struct icmp6_hdr *icmp6, *nicmp6;
408         int off = *offp;
409         int icmp6len = m->m_pkthdr.len - *offp;
410         int code, sum, noff;
411         char ip6bufs[INET6_ADDRSTRLEN], ip6bufd[INET6_ADDRSTRLEN];
412         int ip6len, error;
413
414         ifp = m->m_pkthdr.rcvif;
415
416 #ifndef PULLDOWN_TEST
417         IP6_EXTHDR_CHECK(m, off, sizeof(struct icmp6_hdr), IPPROTO_DONE);
418         /* m might change if M_LOOP.  So, call mtod after this */
419 #endif
420
421         /*
422          * Locate icmp6 structure in mbuf, and check
423          * that not corrupted and of at least minimum length
424          */
425
426         ip6 = mtod(m, struct ip6_hdr *);
427         ip6len = sizeof(struct ip6_hdr) + ntohs(ip6->ip6_plen);
428         if (icmp6len < sizeof(struct icmp6_hdr)) {
429                 ICMP6STAT_INC(icp6s_tooshort);
430                 goto freeit;
431         }
432
433         /*
434          * Check multicast group membership.
435          * Note: SSM filters are not applied for ICMPv6 traffic.
436          */
437         if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
438                 struct in6_multi        *inm;
439
440                 inm = in6m_lookup(ifp, &ip6->ip6_dst);
441                 if (inm == NULL) {
442                         IP6STAT_INC(ip6s_notmember);
443                         in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_discard);
444                         goto freeit;
445                 }
446         }
447
448         /*
449          * calculate the checksum
450          */
451 #ifndef PULLDOWN_TEST
452         icmp6 = (struct icmp6_hdr *)((caddr_t)ip6 + off);
453 #else
454         IP6_EXTHDR_GET(icmp6, struct icmp6_hdr *, m, off, sizeof(*icmp6));
455         if (icmp6 == NULL) {
456                 ICMP6STAT_INC(icp6s_tooshort);
457                 return IPPROTO_DONE;
458         }
459 #endif
460         code = icmp6->icmp6_code;
461
462         if ((sum = in6_cksum(m, IPPROTO_ICMPV6, off, icmp6len)) != 0) {
463                 nd6log((LOG_ERR,
464                     "ICMP6 checksum error(%d|%x) %s\n",
465                     icmp6->icmp6_type, sum,
466                     ip6_sprintf(ip6bufs, &ip6->ip6_src)));
467                 ICMP6STAT_INC(icp6s_checksum);
468                 goto freeit;
469         }
470
471         ICMP6STAT_INC(icp6s_inhist[icmp6->icmp6_type]);
472         icmp6_ifstat_inc(ifp, ifs6_in_msg);
473         if (icmp6->icmp6_type < ICMP6_INFOMSG_MASK)
474                 icmp6_ifstat_inc(ifp, ifs6_in_error);
475
476         switch (icmp6->icmp6_type) {
477         case ICMP6_DST_UNREACH:
478                 icmp6_ifstat_inc(ifp, ifs6_in_dstunreach);
479                 switch (code) {
480                 case ICMP6_DST_UNREACH_NOROUTE:
481                 case ICMP6_DST_UNREACH_ADDR:    /* PRC_HOSTDEAD is a DOS */
482                         code = PRC_UNREACH_NET;
483                         break;
484                 case ICMP6_DST_UNREACH_ADMIN:
485                         icmp6_ifstat_inc(ifp, ifs6_in_adminprohib);
486                         code = PRC_UNREACH_ADMIN_PROHIB;
487                         break;
488                 case ICMP6_DST_UNREACH_BEYONDSCOPE:
489                         /* I mean "source address was incorrect." */
490                         code = PRC_PARAMPROB;
491                         break;
492                 case ICMP6_DST_UNREACH_NOPORT:
493                         code = PRC_UNREACH_PORT;
494                         break;
495                 default:
496                         goto badcode;
497                 }
498                 goto deliver;
499                 break;
500
501         case ICMP6_PACKET_TOO_BIG:
502                 icmp6_ifstat_inc(ifp, ifs6_in_pkttoobig);
503
504                 /* validation is made in icmp6_mtudisc_update */
505
506                 code = PRC_MSGSIZE;
507
508                 /*
509                  * Updating the path MTU will be done after examining
510                  * intermediate extension headers.
511                  */
512                 goto deliver;
513                 break;
514
515         case ICMP6_TIME_EXCEEDED:
516                 icmp6_ifstat_inc(ifp, ifs6_in_timeexceed);
517                 switch (code) {
518                 case ICMP6_TIME_EXCEED_TRANSIT:
519                         code = PRC_TIMXCEED_INTRANS;
520                         break;
521                 case ICMP6_TIME_EXCEED_REASSEMBLY:
522                         code = PRC_TIMXCEED_REASS;
523                         break;
524                 default:
525                         goto badcode;
526                 }
527                 goto deliver;
528                 break;
529
530         case ICMP6_PARAM_PROB:
531                 icmp6_ifstat_inc(ifp, ifs6_in_paramprob);
532                 switch (code) {
533                 case ICMP6_PARAMPROB_NEXTHEADER:
534                         code = PRC_UNREACH_PROTOCOL;
535                         break;
536                 case ICMP6_PARAMPROB_HEADER:
537                 case ICMP6_PARAMPROB_OPTION:
538                         code = PRC_PARAMPROB;
539                         break;
540                 default:
541                         goto badcode;
542                 }
543                 goto deliver;
544                 break;
545
546         case ICMP6_ECHO_REQUEST:
547                 icmp6_ifstat_inc(ifp, ifs6_in_echo);
548                 if (code != 0)
549                         goto badcode;
550                 if ((n = m_copym(m, 0, M_COPYALL, M_NOWAIT)) == NULL) {
551                         /* Give up remote */
552                         break;
553                 }
554                 if (!M_WRITABLE(n)
555                  || n->m_len < off + sizeof(struct icmp6_hdr)) {
556                         struct mbuf *n0 = n;
557                         int n0len;
558
559                         CTASSERT(sizeof(*nip6) + sizeof(*nicmp6) <= MHLEN);
560                         n = m_gethdr(M_NOWAIT, n0->m_type);
561                         if (n == NULL) {
562                                 /* Give up remote */
563                                 m_freem(n0);
564                                 break;
565                         }
566
567                         m_move_pkthdr(n, n0);   /* FIB copied. */
568                         n0len = n0->m_pkthdr.len;       /* save for use below */
569                         /*
570                          * Copy IPv6 and ICMPv6 only.
571                          */
572                         nip6 = mtod(n, struct ip6_hdr *);
573                         bcopy(ip6, nip6, sizeof(struct ip6_hdr));
574                         nicmp6 = (struct icmp6_hdr *)(nip6 + 1);
575                         bcopy(icmp6, nicmp6, sizeof(struct icmp6_hdr));
576                         noff = sizeof(struct ip6_hdr);
577                         /* new mbuf contains only ipv6+icmpv6 headers */
578                         n->m_len = noff + sizeof(struct icmp6_hdr);
579                         /*
580                          * Adjust mbuf.  ip6_plen will be adjusted in
581                          * ip6_output().
582                          */
583                         m_adj(n0, off + sizeof(struct icmp6_hdr));
584                         /* recalculate complete packet size */
585                         n->m_pkthdr.len = n0len + (noff - off);
586                         n->m_next = n0;
587                 } else {
588                         IP6_EXTHDR_GET(nicmp6, struct icmp6_hdr *, n, off,
589                             sizeof(*nicmp6));
590                         noff = off;
591                 }
592                 if (n) {
593                         nicmp6->icmp6_type = ICMP6_ECHO_REPLY;
594                         nicmp6->icmp6_code = 0;
595                         ICMP6STAT_INC(icp6s_reflect);
596                         ICMP6STAT_INC(icp6s_outhist[ICMP6_ECHO_REPLY]);
597                         icmp6_reflect(n, noff);
598                 }
599                 break;
600
601         case ICMP6_ECHO_REPLY:
602                 icmp6_ifstat_inc(ifp, ifs6_in_echoreply);
603                 if (code != 0)
604                         goto badcode;
605                 break;
606
607         case MLD_LISTENER_QUERY:
608         case MLD_LISTENER_REPORT:
609         case MLD_LISTENER_DONE:
610         case MLDV2_LISTENER_REPORT:
611                 /*
612                  * Drop MLD traffic which is not link-local, has a hop limit
613                  * of greater than 1 hop, or which does not have the
614                  * IPv6 HBH Router Alert option.
615                  * As IPv6 HBH options are stripped in ip6_input() we must
616                  * check an mbuf header flag.
617                  * XXX Should we also sanity check that these messages
618                  * were directed to a link-local multicast prefix?
619                  */
620                 if ((ip6->ip6_hlim != 1) || (m->m_flags & M_RTALERT_MLD) == 0)
621                         goto freeit;
622                 if (mld_input(m, off, icmp6len) != 0)
623                         return (IPPROTO_DONE);
624                 /* m stays. */
625                 break;
626
627         case ICMP6_WRUREQUEST:  /* ICMP6_FQDN_QUERY */
628             {
629                 enum { WRU, FQDN } mode;
630                 struct prison *pr;
631
632                 if (!V_icmp6_nodeinfo)
633                         break;
634
635                 if (icmp6len == sizeof(struct icmp6_hdr) + 4)
636                         mode = WRU;
637                 else if (icmp6len >= sizeof(struct icmp6_nodeinfo))
638                         mode = FQDN;
639                 else
640                         goto badlen;
641
642                 pr = NULL;
643                 sx_slock(&allprison_lock);
644                 TAILQ_FOREACH(pr, &allprison, pr_list)
645                         if (pr->pr_vnet == ifp->if_vnet)
646                                 break; 
647                 sx_sunlock(&allprison_lock);
648                 if (pr == NULL)
649                         pr = curthread->td_ucred->cr_prison;
650                 if (mode == FQDN) {
651 #ifndef PULLDOWN_TEST
652                         IP6_EXTHDR_CHECK(m, off, sizeof(struct icmp6_nodeinfo),
653                             IPPROTO_DONE);
654 #endif
655                         n = m_copym(m, 0, M_COPYALL, M_NOWAIT);
656                         if (n)
657                                 n = ni6_input(n, off, pr);
658                         /* XXX meaningless if n == NULL */
659                         noff = sizeof(struct ip6_hdr);
660                 } else {
661                         u_char *p;
662                         int maxhlen, hlen;
663
664                         /*
665                          * XXX: this combination of flags is pointless,
666                          * but should we keep this for compatibility?
667                          */
668                         if ((V_icmp6_nodeinfo & (ICMP6_NODEINFO_FQDNOK |
669                             ICMP6_NODEINFO_TMPADDROK)) !=
670                             (ICMP6_NODEINFO_FQDNOK | ICMP6_NODEINFO_TMPADDROK))
671                                 break;
672
673                         if (code != 0)
674                                 goto badcode;
675
676                         CTASSERT(sizeof(*nip6) + sizeof(*nicmp6) + 4 <= MHLEN);
677                         n = m_gethdr(M_NOWAIT, m->m_type);
678                         if (n == NULL) {
679                                 /* Give up remote */
680                                 break;
681                         }
682                         if (!m_dup_pkthdr(n, m, M_NOWAIT)) {
683                                 /*
684                                  * Previous code did a blind M_COPY_PKTHDR
685                                  * and said "just for rcvif".  If true, then
686                                  * we could tolerate the dup failing (due to
687                                  * the deep copy of the tag chain).  For now
688                                  * be conservative and just fail.
689                                  */
690                                 m_free(n);
691                                 n = NULL;
692                                 break;
693                         }
694                         /*
695                          * Copy IPv6 and ICMPv6 only.
696                          */
697                         nip6 = mtod(n, struct ip6_hdr *);
698                         bcopy(ip6, nip6, sizeof(struct ip6_hdr));
699                         nicmp6 = (struct icmp6_hdr *)(nip6 + 1);
700                         bcopy(icmp6, nicmp6, sizeof(struct icmp6_hdr));
701                         p = (u_char *)(nicmp6 + 1);
702                         bzero(p, 4);
703
704                         maxhlen = M_TRAILINGSPACE(n) -
705                             (sizeof(*nip6) + sizeof(*nicmp6) + 4);
706                         mtx_lock(&pr->pr_mtx);
707                         hlen = strlen(pr->pr_hostname);
708                         if (maxhlen > hlen)
709                                 maxhlen = hlen;
710                         /* meaningless TTL */
711                         bcopy(pr->pr_hostname, p + 4, maxhlen);
712                         mtx_unlock(&pr->pr_mtx);
713                         noff = sizeof(struct ip6_hdr);
714                         n->m_pkthdr.len = n->m_len = sizeof(struct ip6_hdr) +
715                                 sizeof(struct icmp6_hdr) + 4 + maxhlen;
716                         nicmp6->icmp6_type = ICMP6_WRUREPLY;
717                         nicmp6->icmp6_code = 0;
718                 }
719                 if (n) {
720                         ICMP6STAT_INC(icp6s_reflect);
721                         ICMP6STAT_INC(icp6s_outhist[ICMP6_WRUREPLY]);
722                         icmp6_reflect(n, noff);
723                 }
724                 break;
725             }
726
727         case ICMP6_WRUREPLY:
728                 if (code != 0)
729                         goto badcode;
730                 break;
731
732         case ND_ROUTER_SOLICIT:
733                 icmp6_ifstat_inc(ifp, ifs6_in_routersolicit);
734                 if (code != 0)
735                         goto badcode;
736                 if (icmp6len < sizeof(struct nd_router_solicit))
737                         goto badlen;
738                 if (send_sendso_input_hook != NULL) {
739                         IP6_EXTHDR_CHECK(m, off, icmp6len, IPPROTO_DONE);
740                         error = send_sendso_input_hook(m, ifp, SND_IN, ip6len);
741                         if (error == 0) {
742                                 m = NULL;
743                                 goto freeit;
744                         }
745                 }
746                 n = m_copym(m, 0, M_COPYALL, M_NOWAIT);
747                 nd6_rs_input(m, off, icmp6len);
748                 m = n;
749                 if (m == NULL)
750                         goto freeit;
751                 break;
752
753         case ND_ROUTER_ADVERT:
754                 icmp6_ifstat_inc(ifp, ifs6_in_routeradvert);
755                 if (code != 0)
756                         goto badcode;
757                 if (icmp6len < sizeof(struct nd_router_advert))
758                         goto badlen;
759                 if (send_sendso_input_hook != NULL) {
760                         error = send_sendso_input_hook(m, ifp, SND_IN, ip6len);
761                         if (error == 0) {
762                                 m = NULL;
763                                 goto freeit;
764                         }
765                 }
766                 n = m_copym(m, 0, M_COPYALL, M_NOWAIT);
767                 nd6_ra_input(m, off, icmp6len);
768                 m = n;
769                 if (m == NULL)
770                         goto freeit;
771                 break;
772
773         case ND_NEIGHBOR_SOLICIT:
774                 icmp6_ifstat_inc(ifp, ifs6_in_neighborsolicit);
775                 if (code != 0)
776                         goto badcode;
777                 if (icmp6len < sizeof(struct nd_neighbor_solicit))
778                         goto badlen;
779                 if (send_sendso_input_hook != NULL) {
780                         error = send_sendso_input_hook(m, ifp, SND_IN, ip6len);
781                         if (error == 0) {
782                                 m = NULL;
783                                 goto freeit;
784                         }
785                 }
786                 n = m_copym(m, 0, M_COPYALL, M_NOWAIT);
787                 nd6_ns_input(m, off, icmp6len);
788                 m = n;
789                 if (m == NULL)
790                         goto freeit;
791                 break;
792
793         case ND_NEIGHBOR_ADVERT:
794                 icmp6_ifstat_inc(ifp, ifs6_in_neighboradvert);
795                 if (code != 0)
796                         goto badcode;
797                 if (icmp6len < sizeof(struct nd_neighbor_advert))
798                         goto badlen;
799                 if (send_sendso_input_hook != NULL) {
800                         error = send_sendso_input_hook(m, ifp, SND_IN, ip6len);
801                         if (error == 0) {
802                                 m = NULL;
803                                 goto freeit;
804                         }
805                 }
806                 n = m_copym(m, 0, M_COPYALL, M_NOWAIT);
807                 nd6_na_input(m, off, icmp6len);
808                 m = n;
809                 if (m == NULL)
810                         goto freeit;
811                 break;
812
813         case ND_REDIRECT:
814                 icmp6_ifstat_inc(ifp, ifs6_in_redirect);
815                 if (code != 0)
816                         goto badcode;
817                 if (icmp6len < sizeof(struct nd_redirect))
818                         goto badlen;
819                 if (send_sendso_input_hook != NULL) {
820                         error = send_sendso_input_hook(m, ifp, SND_IN, ip6len);
821                         if (error == 0) {
822                                 m = NULL;
823                                 goto freeit;
824                         }
825                 }
826                 n = m_copym(m, 0, M_COPYALL, M_NOWAIT);
827                 icmp6_redirect_input(m, off);
828                 m = n;
829                 if (m == NULL)
830                         goto freeit;
831                 break;
832
833         case ICMP6_ROUTER_RENUMBERING:
834                 if (code != ICMP6_ROUTER_RENUMBERING_COMMAND &&
835                     code != ICMP6_ROUTER_RENUMBERING_RESULT)
836                         goto badcode;
837                 if (icmp6len < sizeof(struct icmp6_router_renum))
838                         goto badlen;
839                 break;
840
841         default:
842                 nd6log((LOG_DEBUG,
843                     "icmp6_input: unknown type %d(src=%s, dst=%s, ifid=%d)\n",
844                     icmp6->icmp6_type, ip6_sprintf(ip6bufs, &ip6->ip6_src),
845                     ip6_sprintf(ip6bufd, &ip6->ip6_dst),
846                     ifp ? ifp->if_index : 0));
847                 if (icmp6->icmp6_type < ICMP6_ECHO_REQUEST) {
848                         /* ICMPv6 error: MUST deliver it by spec... */
849                         code = PRC_NCMDS;
850                         /* deliver */
851                 } else {
852                         /* ICMPv6 informational: MUST not deliver */
853                         break;
854                 }
855         deliver:
856                 if (icmp6_notify_error(&m, off, icmp6len, code) != 0) {
857                         /* In this case, m should've been freed. */
858                         return (IPPROTO_DONE);
859                 }
860                 break;
861
862         badcode:
863                 ICMP6STAT_INC(icp6s_badcode);
864                 break;
865
866         badlen:
867                 ICMP6STAT_INC(icp6s_badlen);
868                 break;
869         }
870
871         /* deliver the packet to appropriate sockets */
872         icmp6_rip6_input(&m, *offp);
873
874         return IPPROTO_DONE;
875
876  freeit:
877         m_freem(m);
878         return IPPROTO_DONE;
879 }
880
881 static int
882 icmp6_notify_error(struct mbuf **mp, int off, int icmp6len, int code)
883 {
884         struct mbuf *m = *mp;
885         struct icmp6_hdr *icmp6;
886         struct ip6_hdr *eip6;
887         u_int32_t notifymtu;
888         struct sockaddr_in6 icmp6src, icmp6dst;
889
890         if (icmp6len < sizeof(struct icmp6_hdr) + sizeof(struct ip6_hdr)) {
891                 ICMP6STAT_INC(icp6s_tooshort);
892                 goto freeit;
893         }
894 #ifndef PULLDOWN_TEST
895         IP6_EXTHDR_CHECK(m, off,
896             sizeof(struct icmp6_hdr) + sizeof(struct ip6_hdr), -1);
897         icmp6 = (struct icmp6_hdr *)(mtod(m, caddr_t) + off);
898 #else
899         IP6_EXTHDR_GET(icmp6, struct icmp6_hdr *, m, off,
900             sizeof(*icmp6) + sizeof(struct ip6_hdr));
901         if (icmp6 == NULL) {
902                 ICMP6STAT_INC(icp6s_tooshort);
903                 return (-1);
904         }
905 #endif
906         eip6 = (struct ip6_hdr *)(icmp6 + 1);
907
908         /* Detect the upper level protocol */
909         {
910                 void (*ctlfunc)(int, struct sockaddr *, void *);
911                 u_int8_t nxt = eip6->ip6_nxt;
912                 int eoff = off + sizeof(struct icmp6_hdr) +
913                     sizeof(struct ip6_hdr);
914                 struct ip6ctlparam ip6cp;
915                 struct in6_addr *finaldst = NULL;
916                 int icmp6type = icmp6->icmp6_type;
917                 struct ip6_frag *fh;
918                 struct ip6_rthdr *rth;
919                 struct ip6_rthdr0 *rth0;
920                 int rthlen;
921
922                 while (1) { /* XXX: should avoid infinite loop explicitly? */
923                         struct ip6_ext *eh;
924
925                         switch (nxt) {
926                         case IPPROTO_HOPOPTS:
927                         case IPPROTO_DSTOPTS:
928                         case IPPROTO_AH:
929 #ifndef PULLDOWN_TEST
930                                 IP6_EXTHDR_CHECK(m, 0,
931                                     eoff + sizeof(struct ip6_ext), -1);
932                                 eh = (struct ip6_ext *)(mtod(m, caddr_t) + eoff);
933 #else
934                                 IP6_EXTHDR_GET(eh, struct ip6_ext *, m,
935                                     eoff, sizeof(*eh));
936                                 if (eh == NULL) {
937                                         ICMP6STAT_INC(icp6s_tooshort);
938                                         return (-1);
939                                 }
940 #endif
941
942                                 if (nxt == IPPROTO_AH)
943                                         eoff += (eh->ip6e_len + 2) << 2;
944                                 else
945                                         eoff += (eh->ip6e_len + 1) << 3;
946                                 nxt = eh->ip6e_nxt;
947                                 break;
948                         case IPPROTO_ROUTING:
949                                 /*
950                                  * When the erroneous packet contains a
951                                  * routing header, we should examine the
952                                  * header to determine the final destination.
953                                  * Otherwise, we can't properly update
954                                  * information that depends on the final
955                                  * destination (e.g. path MTU).
956                                  */
957 #ifndef PULLDOWN_TEST
958                                 IP6_EXTHDR_CHECK(m, 0, eoff + sizeof(*rth), -1);
959                                 rth = (struct ip6_rthdr *)
960                                     (mtod(m, caddr_t) + eoff);
961 #else
962                                 IP6_EXTHDR_GET(rth, struct ip6_rthdr *, m,
963                                     eoff, sizeof(*rth));
964                                 if (rth == NULL) {
965                                         ICMP6STAT_INC(icp6s_tooshort);
966                                         return (-1);
967                                 }
968 #endif
969                                 rthlen = (rth->ip6r_len + 1) << 3;
970                                 /*
971                                  * XXX: currently there is no
972                                  * officially defined type other
973                                  * than type-0.
974                                  * Note that if the segment left field
975                                  * is 0, all intermediate hops must
976                                  * have been passed.
977                                  */
978                                 if (rth->ip6r_segleft &&
979                                     rth->ip6r_type == IPV6_RTHDR_TYPE_0) {
980                                         int hops;
981
982 #ifndef PULLDOWN_TEST
983                                         IP6_EXTHDR_CHECK(m, 0, eoff + rthlen, -1);
984                                         rth0 = (struct ip6_rthdr0 *)
985                                             (mtod(m, caddr_t) + eoff);
986 #else
987                                         IP6_EXTHDR_GET(rth0,
988                                             struct ip6_rthdr0 *, m,
989                                             eoff, rthlen);
990                                         if (rth0 == NULL) {
991                                                 ICMP6STAT_INC(icp6s_tooshort);
992                                                 return (-1);
993                                         }
994 #endif
995                                         /* just ignore a bogus header */
996                                         if ((rth0->ip6r0_len % 2) == 0 &&
997                                             (hops = rth0->ip6r0_len/2))
998                                                 finaldst = (struct in6_addr *)(rth0 + 1) + (hops - 1);
999                                 }
1000                                 eoff += rthlen;
1001                                 nxt = rth->ip6r_nxt;
1002                                 break;
1003                         case IPPROTO_FRAGMENT:
1004 #ifndef PULLDOWN_TEST
1005                                 IP6_EXTHDR_CHECK(m, 0, eoff +
1006                                     sizeof(struct ip6_frag), -1);
1007                                 fh = (struct ip6_frag *)(mtod(m, caddr_t) +
1008                                     eoff);
1009 #else
1010                                 IP6_EXTHDR_GET(fh, struct ip6_frag *, m,
1011                                     eoff, sizeof(*fh));
1012                                 if (fh == NULL) {
1013                                         ICMP6STAT_INC(icp6s_tooshort);
1014                                         return (-1);
1015                                 }
1016 #endif
1017                                 /*
1018                                  * Data after a fragment header is meaningless
1019                                  * unless it is the first fragment, but
1020                                  * we'll go to the notify label for path MTU
1021                                  * discovery.
1022                                  */
1023                                 if (fh->ip6f_offlg & IP6F_OFF_MASK)
1024                                         goto notify;
1025
1026                                 eoff += sizeof(struct ip6_frag);
1027                                 nxt = fh->ip6f_nxt;
1028                                 break;
1029                         default:
1030                                 /*
1031                                  * This case includes ESP and the No Next
1032                                  * Header.  In such cases going to the notify
1033                                  * label does not have any meaning
1034                                  * (i.e. ctlfunc will be NULL), but we go
1035                                  * anyway since we might have to update
1036                                  * path MTU information.
1037                                  */
1038                                 goto notify;
1039                         }
1040                 }
1041           notify:
1042 #ifndef PULLDOWN_TEST
1043                 icmp6 = (struct icmp6_hdr *)(mtod(m, caddr_t) + off);
1044 #else
1045                 IP6_EXTHDR_GET(icmp6, struct icmp6_hdr *, m, off,
1046                     sizeof(*icmp6) + sizeof(struct ip6_hdr));
1047                 if (icmp6 == NULL) {
1048                         ICMP6STAT_INC(icp6s_tooshort);
1049                         return (-1);
1050                 }
1051 #endif
1052
1053                 /*
1054                  * retrieve parameters from the inner IPv6 header, and convert
1055                  * them into sockaddr structures.
1056                  * XXX: there is no guarantee that the source or destination
1057                  * addresses of the inner packet are in the same scope as
1058                  * the addresses of the icmp packet.  But there is no other
1059                  * way to determine the zone.
1060                  */
1061                 eip6 = (struct ip6_hdr *)(icmp6 + 1);
1062
1063                 bzero(&icmp6dst, sizeof(icmp6dst));
1064                 icmp6dst.sin6_len = sizeof(struct sockaddr_in6);
1065                 icmp6dst.sin6_family = AF_INET6;
1066                 if (finaldst == NULL)
1067                         icmp6dst.sin6_addr = eip6->ip6_dst;
1068                 else
1069                         icmp6dst.sin6_addr = *finaldst;
1070                 if (in6_setscope(&icmp6dst.sin6_addr, m->m_pkthdr.rcvif, NULL))
1071                         goto freeit;
1072                 bzero(&icmp6src, sizeof(icmp6src));
1073                 icmp6src.sin6_len = sizeof(struct sockaddr_in6);
1074                 icmp6src.sin6_family = AF_INET6;
1075                 icmp6src.sin6_addr = eip6->ip6_src;
1076                 if (in6_setscope(&icmp6src.sin6_addr, m->m_pkthdr.rcvif, NULL))
1077                         goto freeit;
1078                 icmp6src.sin6_flowinfo =
1079                     (eip6->ip6_flow & IPV6_FLOWLABEL_MASK);
1080
1081                 if (finaldst == NULL)
1082                         finaldst = &eip6->ip6_dst;
1083                 ip6cp.ip6c_m = m;
1084                 ip6cp.ip6c_icmp6 = icmp6;
1085                 ip6cp.ip6c_ip6 = (struct ip6_hdr *)(icmp6 + 1);
1086                 ip6cp.ip6c_off = eoff;
1087                 ip6cp.ip6c_finaldst = finaldst;
1088                 ip6cp.ip6c_src = &icmp6src;
1089                 ip6cp.ip6c_nxt = nxt;
1090
1091                 if (icmp6type == ICMP6_PACKET_TOO_BIG) {
1092                         notifymtu = ntohl(icmp6->icmp6_mtu);
1093                         ip6cp.ip6c_cmdarg = (void *)&notifymtu;
1094                         icmp6_mtudisc_update(&ip6cp, 1);        /*XXX*/
1095                 }
1096
1097                 ctlfunc = (void (*)(int, struct sockaddr *, void *))
1098                     (inet6sw[ip6_protox[nxt]].pr_ctlinput);
1099                 if (ctlfunc) {
1100                         (void) (*ctlfunc)(code, (struct sockaddr *)&icmp6dst,
1101                             &ip6cp);
1102                 }
1103         }
1104         *mp = m;
1105         return (0);
1106
1107   freeit:
1108         m_freem(m);
1109         return (-1);
1110 }
1111
1112 void
1113 icmp6_mtudisc_update(struct ip6ctlparam *ip6cp, int validated)
1114 {
1115         struct in6_addr *dst = ip6cp->ip6c_finaldst;
1116         struct icmp6_hdr *icmp6 = ip6cp->ip6c_icmp6;
1117         struct mbuf *m = ip6cp->ip6c_m; /* will be necessary for scope issue */
1118         u_int mtu = ntohl(icmp6->icmp6_mtu);
1119         struct in_conninfo inc;
1120
1121 #if 0
1122         /*
1123          * RFC2460 section 5, last paragraph.
1124          * even though minimum link MTU for IPv6 is IPV6_MMTU,
1125          * we may see ICMPv6 too big with mtu < IPV6_MMTU
1126          * due to packet translator in the middle.
1127          * see ip6_output() and ip6_getpmtu() "alwaysfrag" case for
1128          * special handling.
1129          */
1130         if (mtu < IPV6_MMTU)
1131                 return;
1132 #endif
1133
1134         /*
1135          * we reject ICMPv6 too big with abnormally small value.
1136          * XXX what is the good definition of "abnormally small"?
1137          */
1138         if (mtu < sizeof(struct ip6_hdr) + sizeof(struct ip6_frag) + 8)
1139                 return;
1140
1141         if (!validated)
1142                 return;
1143
1144         /*
1145          * In case the suggested mtu is less than IPV6_MMTU, we
1146          * only need to remember that it was for above mentioned
1147          * "alwaysfrag" case.
1148          * Try to be as close to the spec as possible.
1149          */
1150         if (mtu < IPV6_MMTU)
1151                 mtu = IPV6_MMTU - 8;
1152
1153         bzero(&inc, sizeof(inc));
1154         inc.inc_fibnum = M_GETFIB(m);
1155         inc.inc_flags |= INC_ISIPV6;
1156         inc.inc6_faddr = *dst;
1157         if (in6_setscope(&inc.inc6_faddr, m->m_pkthdr.rcvif, NULL))
1158                 return;
1159
1160         if (mtu < tcp_maxmtu6(&inc, NULL)) {
1161                 tcp_hc_updatemtu(&inc, mtu);
1162                 ICMP6STAT_INC(icp6s_pmtuchg);
1163         }
1164 }
1165
1166 /*
1167  * Process a Node Information Query packet, based on
1168  * draft-ietf-ipngwg-icmp-name-lookups-07.
1169  *
1170  * Spec incompatibilities:
1171  * - IPv6 Subject address handling
1172  * - IPv4 Subject address handling support missing
1173  * - Proxy reply (answer even if it's not for me)
1174  * - joins NI group address at in6_ifattach() time only, does not cope
1175  *   with hostname changes by sethostname(3)
1176  */
1177 static struct mbuf *
1178 ni6_input(struct mbuf *m, int off, struct prison *pr)
1179 {
1180         struct icmp6_nodeinfo *ni6, *nni6;
1181         struct mbuf *n = NULL;
1182         u_int16_t qtype;
1183         int subjlen;
1184         int replylen = sizeof(struct ip6_hdr) + sizeof(struct icmp6_nodeinfo);
1185         struct ni_reply_fqdn *fqdn;
1186         int addrs;              /* for NI_QTYPE_NODEADDR */
1187         struct ifnet *ifp = NULL; /* for NI_QTYPE_NODEADDR */
1188         struct in6_addr in6_subj; /* subject address */
1189         struct ip6_hdr *ip6;
1190         int oldfqdn = 0;        /* if 1, return pascal string (03 draft) */
1191         char *subj = NULL;
1192         struct in6_ifaddr *ia6 = NULL;
1193
1194         ip6 = mtod(m, struct ip6_hdr *);
1195 #ifndef PULLDOWN_TEST
1196         ni6 = (struct icmp6_nodeinfo *)(mtod(m, caddr_t) + off);
1197 #else
1198         IP6_EXTHDR_GET(ni6, struct icmp6_nodeinfo *, m, off, sizeof(*ni6));
1199         if (ni6 == NULL) {
1200                 /* m is already reclaimed */
1201                 return (NULL);
1202         }
1203 #endif
1204
1205         /*
1206          * Validate IPv6 source address.
1207          * The default configuration MUST be to refuse answering queries from
1208          * global-scope addresses according to RFC4602.
1209          * Notes:
1210          *  - it's not very clear what "refuse" means; this implementation
1211          *    simply drops it.
1212          *  - it's not very easy to identify global-scope (unicast) addresses
1213          *    since there are many prefixes for them.  It should be safer
1214          *    and in practice sufficient to check "all" but loopback and
1215          *    link-local (note that site-local unicast was deprecated and
1216          *    ULA is defined as global scope-wise)
1217          */
1218         if ((V_icmp6_nodeinfo & ICMP6_NODEINFO_GLOBALOK) == 0 &&
1219             !IN6_IS_ADDR_LOOPBACK(&ip6->ip6_src) &&
1220             !IN6_IS_ADDR_LINKLOCAL(&ip6->ip6_src))
1221                 goto bad;
1222
1223         /*
1224          * Validate IPv6 destination address.
1225          *
1226          * The Responder must discard the Query without further processing
1227          * unless it is one of the Responder's unicast or anycast addresses, or
1228          * a link-local scope multicast address which the Responder has joined.
1229          * [RFC4602, Section 5.]
1230          */
1231         if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
1232                 if (!IN6_IS_ADDR_MC_LINKLOCAL(&ip6->ip6_dst))
1233                         goto bad;
1234                 /* else it's a link-local multicast, fine */
1235         } else {                /* unicast or anycast */
1236                 ia6 = in6ifa_ifwithaddr(&ip6->ip6_dst, 0 /* XXX */);
1237                 if (ia6 == NULL)
1238                         goto bad; /* XXX impossible */
1239
1240                 if ((ia6->ia6_flags & IN6_IFF_TEMPORARY) &&
1241                     !(V_icmp6_nodeinfo & ICMP6_NODEINFO_TMPADDROK)) {
1242                         ifa_free(&ia6->ia_ifa);
1243                         nd6log((LOG_DEBUG, "ni6_input: ignore node info to "
1244                                 "a temporary address in %s:%d",
1245                                __FILE__, __LINE__));
1246                         goto bad;
1247                 }
1248                 ifa_free(&ia6->ia_ifa);
1249         }
1250
1251         /* validate query Subject field. */
1252         qtype = ntohs(ni6->ni_qtype);
1253         subjlen = m->m_pkthdr.len - off - sizeof(struct icmp6_nodeinfo);
1254         switch (qtype) {
1255         case NI_QTYPE_NOOP:
1256         case NI_QTYPE_SUPTYPES:
1257                 /* 07 draft */
1258                 if (ni6->ni_code == ICMP6_NI_SUBJ_FQDN && subjlen == 0)
1259                         break;
1260                 /* FALLTHROUGH */
1261         case NI_QTYPE_FQDN:
1262         case NI_QTYPE_NODEADDR:
1263         case NI_QTYPE_IPV4ADDR:
1264                 switch (ni6->ni_code) {
1265                 case ICMP6_NI_SUBJ_IPV6:
1266 #if ICMP6_NI_SUBJ_IPV6 != 0
1267                 case 0:
1268 #endif
1269                         /*
1270                          * backward compatibility - try to accept 03 draft
1271                          * format, where no Subject is present.
1272                          */
1273                         if (qtype == NI_QTYPE_FQDN && ni6->ni_code == 0 &&
1274                             subjlen == 0) {
1275                                 oldfqdn++;
1276                                 break;
1277                         }
1278 #if ICMP6_NI_SUBJ_IPV6 != 0
1279                         if (ni6->ni_code != ICMP6_NI_SUBJ_IPV6)
1280                                 goto bad;
1281 #endif
1282
1283                         if (subjlen != sizeof(struct in6_addr))
1284                                 goto bad;
1285
1286                         /*
1287                          * Validate Subject address.
1288                          *
1289                          * Not sure what exactly "address belongs to the node"
1290                          * means in the spec, is it just unicast, or what?
1291                          *
1292                          * At this moment we consider Subject address as
1293                          * "belong to the node" if the Subject address equals
1294                          * to the IPv6 destination address; validation for
1295                          * IPv6 destination address should have done enough
1296                          * check for us.
1297                          *
1298                          * We do not do proxy at this moment.
1299                          */
1300                         /* m_pulldown instead of copy? */
1301                         m_copydata(m, off + sizeof(struct icmp6_nodeinfo),
1302                             subjlen, (caddr_t)&in6_subj);
1303                         if (in6_setscope(&in6_subj, m->m_pkthdr.rcvif, NULL))
1304                                 goto bad;
1305
1306                         subj = (char *)&in6_subj;
1307                         if (IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst, &in6_subj))
1308                                 break;
1309
1310                         /*
1311                          * XXX if we are to allow other cases, we should really
1312                          * be careful about scope here.
1313                          * basically, we should disallow queries toward IPv6
1314                          * destination X with subject Y,
1315                          * if scope(X) > scope(Y).
1316                          * if we allow scope(X) > scope(Y), it will result in
1317                          * information leakage across scope boundary.
1318                          */
1319                         goto bad;
1320
1321                 case ICMP6_NI_SUBJ_FQDN:
1322                         /*
1323                          * Validate Subject name with gethostname(3).
1324                          *
1325                          * The behavior may need some debate, since:
1326                          * - we are not sure if the node has FQDN as
1327                          *   hostname (returned by gethostname(3)).
1328                          * - the code does wildcard match for truncated names.
1329                          *   however, we are not sure if we want to perform
1330                          *   wildcard match, if gethostname(3) side has
1331                          *   truncated hostname.
1332                          */
1333                         mtx_lock(&pr->pr_mtx);
1334                         n = ni6_nametodns(pr->pr_hostname,
1335                             strlen(pr->pr_hostname), 0);
1336                         mtx_unlock(&pr->pr_mtx);
1337                         if (!n || n->m_next || n->m_len == 0)
1338                                 goto bad;
1339                         IP6_EXTHDR_GET(subj, char *, m,
1340                             off + sizeof(struct icmp6_nodeinfo), subjlen);
1341                         if (subj == NULL)
1342                                 goto bad;
1343                         if (!ni6_dnsmatch(subj, subjlen, mtod(n, const char *),
1344                             n->m_len)) {
1345                                 goto bad;
1346                         }
1347                         m_freem(n);
1348                         n = NULL;
1349                         break;
1350
1351                 case ICMP6_NI_SUBJ_IPV4:        /* XXX: to be implemented? */
1352                 default:
1353                         goto bad;
1354                 }
1355                 break;
1356         }
1357
1358         /* refuse based on configuration.  XXX ICMP6_NI_REFUSED? */
1359         switch (qtype) {
1360         case NI_QTYPE_FQDN:
1361                 if ((V_icmp6_nodeinfo & ICMP6_NODEINFO_FQDNOK) == 0)
1362                         goto bad;
1363                 break;
1364         case NI_QTYPE_NODEADDR:
1365         case NI_QTYPE_IPV4ADDR:
1366                 if ((V_icmp6_nodeinfo & ICMP6_NODEINFO_NODEADDROK) == 0)
1367                         goto bad;
1368                 break;
1369         }
1370
1371         /* guess reply length */
1372         switch (qtype) {
1373         case NI_QTYPE_NOOP:
1374                 break;          /* no reply data */
1375         case NI_QTYPE_SUPTYPES:
1376                 replylen += sizeof(u_int32_t);
1377                 break;
1378         case NI_QTYPE_FQDN:
1379                 /* XXX will append an mbuf */
1380                 replylen += offsetof(struct ni_reply_fqdn, ni_fqdn_namelen);
1381                 break;
1382         case NI_QTYPE_NODEADDR:
1383                 addrs = ni6_addrs(ni6, m, &ifp, (struct in6_addr *)subj);
1384                 if ((replylen += addrs * (sizeof(struct in6_addr) +
1385                     sizeof(u_int32_t))) > MCLBYTES)
1386                         replylen = MCLBYTES; /* XXX: will truncate pkt later */
1387                 break;
1388         case NI_QTYPE_IPV4ADDR:
1389                 /* unsupported - should respond with unknown Qtype? */
1390                 break;
1391         default:
1392                 /*
1393                  * XXX: We must return a reply with the ICMP6 code
1394                  * `unknown Qtype' in this case.  However we regard the case
1395                  * as an FQDN query for backward compatibility.
1396                  * Older versions set a random value to this field,
1397                  * so it rarely varies in the defined qtypes.
1398                  * But the mechanism is not reliable...
1399                  * maybe we should obsolete older versions.
1400                  */
1401                 qtype = NI_QTYPE_FQDN;
1402                 /* XXX will append an mbuf */
1403                 replylen += offsetof(struct ni_reply_fqdn, ni_fqdn_namelen);
1404                 oldfqdn++;
1405                 break;
1406         }
1407
1408         /* Allocate an mbuf to reply. */
1409         if (replylen > MCLBYTES) {
1410                 /*
1411                  * XXX: should we try to allocate more? But MCLBYTES
1412                  * is probably much larger than IPV6_MMTU...
1413                  */
1414                 goto bad;
1415         }
1416         if (replylen > MHLEN)
1417                 n = m_getcl(M_NOWAIT, m->m_type, M_PKTHDR);
1418         else
1419                 n = m_gethdr(M_NOWAIT, m->m_type);
1420         if (n == NULL) {
1421                 m_freem(m);
1422                 return (NULL);
1423         }
1424         m_move_pkthdr(n, m); /* just for recvif and FIB */
1425         n->m_pkthdr.len = n->m_len = replylen;
1426
1427         /* copy mbuf header and IPv6 + Node Information base headers */
1428         bcopy(mtod(m, caddr_t), mtod(n, caddr_t), sizeof(struct ip6_hdr));
1429         nni6 = (struct icmp6_nodeinfo *)(mtod(n, struct ip6_hdr *) + 1);
1430         bcopy((caddr_t)ni6, (caddr_t)nni6, sizeof(struct icmp6_nodeinfo));
1431
1432         /* qtype dependent procedure */
1433         switch (qtype) {
1434         case NI_QTYPE_NOOP:
1435                 nni6->ni_code = ICMP6_NI_SUCCESS;
1436                 nni6->ni_flags = 0;
1437                 break;
1438         case NI_QTYPE_SUPTYPES:
1439         {
1440                 u_int32_t v;
1441                 nni6->ni_code = ICMP6_NI_SUCCESS;
1442                 nni6->ni_flags = htons(0x0000); /* raw bitmap */
1443                 /* supports NOOP, SUPTYPES, FQDN, and NODEADDR */
1444                 v = (u_int32_t)htonl(0x0000000f);
1445                 bcopy(&v, nni6 + 1, sizeof(u_int32_t));
1446                 break;
1447         }
1448         case NI_QTYPE_FQDN:
1449                 nni6->ni_code = ICMP6_NI_SUCCESS;
1450                 fqdn = (struct ni_reply_fqdn *)(mtod(n, caddr_t) +
1451                     sizeof(struct ip6_hdr) + sizeof(struct icmp6_nodeinfo));
1452                 nni6->ni_flags = 0; /* XXX: meaningless TTL */
1453                 fqdn->ni_fqdn_ttl = 0;  /* ditto. */
1454                 /*
1455                  * XXX do we really have FQDN in hostname?
1456                  */
1457                 mtx_lock(&pr->pr_mtx);
1458                 n->m_next = ni6_nametodns(pr->pr_hostname,
1459                     strlen(pr->pr_hostname), oldfqdn);
1460                 mtx_unlock(&pr->pr_mtx);
1461                 if (n->m_next == NULL)
1462                         goto bad;
1463                 /* XXX we assume that n->m_next is not a chain */
1464                 if (n->m_next->m_next != NULL)
1465                         goto bad;
1466                 n->m_pkthdr.len += n->m_next->m_len;
1467                 break;
1468         case NI_QTYPE_NODEADDR:
1469         {
1470                 int lenlim, copied;
1471
1472                 nni6->ni_code = ICMP6_NI_SUCCESS;
1473                 n->m_pkthdr.len = n->m_len =
1474                     sizeof(struct ip6_hdr) + sizeof(struct icmp6_nodeinfo);
1475                 lenlim = M_TRAILINGSPACE(n);
1476                 copied = ni6_store_addrs(ni6, nni6, ifp, lenlim);
1477                 /* XXX: reset mbuf length */
1478                 n->m_pkthdr.len = n->m_len = sizeof(struct ip6_hdr) +
1479                     sizeof(struct icmp6_nodeinfo) + copied;
1480                 break;
1481         }
1482         default:
1483                 break;          /* XXX impossible! */
1484         }
1485
1486         nni6->ni_type = ICMP6_NI_REPLY;
1487         m_freem(m);
1488         return (n);
1489
1490   bad:
1491         m_freem(m);
1492         if (n)
1493                 m_freem(n);
1494         return (NULL);
1495 }
1496
1497 /*
1498  * make a mbuf with DNS-encoded string.  no compression support.
1499  *
1500  * XXX names with less than 2 dots (like "foo" or "foo.section") will be
1501  * treated as truncated name (two \0 at the end).  this is a wild guess.
1502  *
1503  * old - return pascal string if non-zero
1504  */
1505 static struct mbuf *
1506 ni6_nametodns(const char *name, int namelen, int old)
1507 {
1508         struct mbuf *m;
1509         char *cp, *ep;
1510         const char *p, *q;
1511         int i, len, nterm;
1512
1513         if (old)
1514                 len = namelen + 1;
1515         else
1516                 len = MCLBYTES;
1517
1518         /* Because MAXHOSTNAMELEN is usually 256, we use cluster mbuf. */
1519         if (len > MLEN)
1520                 m = m_getcl(M_NOWAIT, MT_DATA, 0);
1521         else
1522                 m = m_get(M_NOWAIT, MT_DATA);
1523         if (m == NULL)
1524                 goto fail;
1525
1526         if (old) {
1527                 m->m_len = len;
1528                 *mtod(m, char *) = namelen;
1529                 bcopy(name, mtod(m, char *) + 1, namelen);
1530                 return m;
1531         } else {
1532                 m->m_len = 0;
1533                 cp = mtod(m, char *);
1534                 ep = mtod(m, char *) + M_TRAILINGSPACE(m);
1535
1536                 /* if not certain about my name, return empty buffer */
1537                 if (namelen == 0)
1538                         return m;
1539
1540                 /*
1541                  * guess if it looks like shortened hostname, or FQDN.
1542                  * shortened hostname needs two trailing "\0".
1543                  */
1544                 i = 0;
1545                 for (p = name; p < name + namelen; p++) {
1546                         if (*p && *p == '.')
1547                                 i++;
1548                 }
1549                 if (i < 2)
1550                         nterm = 2;
1551                 else
1552                         nterm = 1;
1553
1554                 p = name;
1555                 while (cp < ep && p < name + namelen) {
1556                         i = 0;
1557                         for (q = p; q < name + namelen && *q && *q != '.'; q++)
1558                                 i++;
1559                         /* result does not fit into mbuf */
1560                         if (cp + i + 1 >= ep)
1561                                 goto fail;
1562                         /*
1563                          * DNS label length restriction, RFC1035 page 8.
1564                          * "i == 0" case is included here to avoid returning
1565                          * 0-length label on "foo..bar".
1566                          */
1567                         if (i <= 0 || i >= 64)
1568                                 goto fail;
1569                         *cp++ = i;
1570                         bcopy(p, cp, i);
1571                         cp += i;
1572                         p = q;
1573                         if (p < name + namelen && *p == '.')
1574                                 p++;
1575                 }
1576                 /* termination */
1577                 if (cp + nterm >= ep)
1578                         goto fail;
1579                 while (nterm-- > 0)
1580                         *cp++ = '\0';
1581                 m->m_len = cp - mtod(m, char *);
1582                 return m;
1583         }
1584
1585         panic("should not reach here");
1586         /* NOTREACHED */
1587
1588  fail:
1589         if (m)
1590                 m_freem(m);
1591         return NULL;
1592 }
1593
1594 /*
1595  * check if two DNS-encoded string matches.  takes care of truncated
1596  * form (with \0\0 at the end).  no compression support.
1597  * XXX upper/lowercase match (see RFC2065)
1598  */
1599 static int
1600 ni6_dnsmatch(const char *a, int alen, const char *b, int blen)
1601 {
1602         const char *a0, *b0;
1603         int l;
1604
1605         /* simplest case - need validation? */
1606         if (alen == blen && bcmp(a, b, alen) == 0)
1607                 return 1;
1608
1609         a0 = a;
1610         b0 = b;
1611
1612         /* termination is mandatory */
1613         if (alen < 2 || blen < 2)
1614                 return 0;
1615         if (a0[alen - 1] != '\0' || b0[blen - 1] != '\0')
1616                 return 0;
1617         alen--;
1618         blen--;
1619
1620         while (a - a0 < alen && b - b0 < blen) {
1621                 if (a - a0 + 1 > alen || b - b0 + 1 > blen)
1622                         return 0;
1623
1624                 if ((signed char)a[0] < 0 || (signed char)b[0] < 0)
1625                         return 0;
1626                 /* we don't support compression yet */
1627                 if (a[0] >= 64 || b[0] >= 64)
1628                         return 0;
1629
1630                 /* truncated case */
1631                 if (a[0] == 0 && a - a0 == alen - 1)
1632                         return 1;
1633                 if (b[0] == 0 && b - b0 == blen - 1)
1634                         return 1;
1635                 if (a[0] == 0 || b[0] == 0)
1636                         return 0;
1637
1638                 if (a[0] != b[0])
1639                         return 0;
1640                 l = a[0];
1641                 if (a - a0 + 1 + l > alen || b - b0 + 1 + l > blen)
1642                         return 0;
1643                 if (bcmp(a + 1, b + 1, l) != 0)
1644                         return 0;
1645
1646                 a += 1 + l;
1647                 b += 1 + l;
1648         }
1649
1650         if (a - a0 == alen && b - b0 == blen)
1651                 return 1;
1652         else
1653                 return 0;
1654 }
1655
1656 /*
1657  * calculate the number of addresses to be returned in the node info reply.
1658  */
1659 static int
1660 ni6_addrs(struct icmp6_nodeinfo *ni6, struct mbuf *m, struct ifnet **ifpp,
1661     struct in6_addr *subj)
1662 {
1663         struct epoch_tracker et;
1664         struct ifnet *ifp;
1665         struct in6_ifaddr *ifa6;
1666         struct ifaddr *ifa;
1667         int addrs = 0, addrsofif, iffound = 0;
1668         int niflags = ni6->ni_flags;
1669
1670         if ((niflags & NI_NODEADDR_FLAG_ALL) == 0) {
1671                 switch (ni6->ni_code) {
1672                 case ICMP6_NI_SUBJ_IPV6:
1673                         if (subj == NULL) /* must be impossible... */
1674                                 return (0);
1675                         break;
1676                 default:
1677                         /*
1678                          * XXX: we only support IPv6 subject address for
1679                          * this Qtype.
1680                          */
1681                         return (0);
1682                 }
1683         }
1684
1685         NET_EPOCH_ENTER(et);
1686         CK_STAILQ_FOREACH(ifp, &V_ifnet, if_link) {
1687                 addrsofif = 0;
1688                 CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1689                         if (ifa->ifa_addr->sa_family != AF_INET6)
1690                                 continue;
1691                         ifa6 = (struct in6_ifaddr *)ifa;
1692
1693                         if ((niflags & NI_NODEADDR_FLAG_ALL) == 0 &&
1694                             IN6_ARE_ADDR_EQUAL(subj, &ifa6->ia_addr.sin6_addr))
1695                                 iffound = 1;
1696
1697                         /*
1698                          * IPv4-mapped addresses can only be returned by a
1699                          * Node Information proxy, since they represent
1700                          * addresses of IPv4-only nodes, which perforce do
1701                          * not implement this protocol.
1702                          * [icmp-name-lookups-07, Section 5.4]
1703                          * So we don't support NI_NODEADDR_FLAG_COMPAT in
1704                          * this function at this moment.
1705                          */
1706
1707                         /* What do we have to do about ::1? */
1708                         switch (in6_addrscope(&ifa6->ia_addr.sin6_addr)) {
1709                         case IPV6_ADDR_SCOPE_LINKLOCAL:
1710                                 if ((niflags & NI_NODEADDR_FLAG_LINKLOCAL) == 0)
1711                                         continue;
1712                                 break;
1713                         case IPV6_ADDR_SCOPE_SITELOCAL:
1714                                 if ((niflags & NI_NODEADDR_FLAG_SITELOCAL) == 0)
1715                                         continue;
1716                                 break;
1717                         case IPV6_ADDR_SCOPE_GLOBAL:
1718                                 if ((niflags & NI_NODEADDR_FLAG_GLOBAL) == 0)
1719                                         continue;
1720                                 break;
1721                         default:
1722                                 continue;
1723                         }
1724
1725                         /*
1726                          * check if anycast is okay.
1727                          * XXX: just experimental.  not in the spec.
1728                          */
1729                         if ((ifa6->ia6_flags & IN6_IFF_ANYCAST) != 0 &&
1730                             (niflags & NI_NODEADDR_FLAG_ANYCAST) == 0)
1731                                 continue; /* we need only unicast addresses */
1732                         if ((ifa6->ia6_flags & IN6_IFF_TEMPORARY) != 0 &&
1733                             (V_icmp6_nodeinfo & ICMP6_NODEINFO_TMPADDROK) == 0) {
1734                                 continue;
1735                         }
1736                         addrsofif++; /* count the address */
1737                 }
1738                 if (iffound) {
1739                         *ifpp = ifp;
1740                         NET_EPOCH_EXIT(et);
1741                         return (addrsofif);
1742                 }
1743
1744                 addrs += addrsofif;
1745         }
1746         NET_EPOCH_EXIT(et);
1747
1748         return (addrs);
1749 }
1750
1751 static int
1752 ni6_store_addrs(struct icmp6_nodeinfo *ni6, struct icmp6_nodeinfo *nni6,
1753     struct ifnet *ifp0, int resid)
1754 {
1755         struct epoch_tracker et;
1756         struct ifnet *ifp;
1757         struct in6_ifaddr *ifa6;
1758         struct ifaddr *ifa;
1759         struct ifnet *ifp_dep = NULL;
1760         int copied = 0, allow_deprecated = 0;
1761         u_char *cp = (u_char *)(nni6 + 1);
1762         int niflags = ni6->ni_flags;
1763         u_int32_t ltime;
1764
1765         if (ifp0 == NULL && !(niflags & NI_NODEADDR_FLAG_ALL))
1766                 return (0);     /* needless to copy */
1767
1768         NET_EPOCH_ENTER(et);
1769         ifp = ifp0 ? ifp0 : CK_STAILQ_FIRST(&V_ifnet);
1770   again:
1771
1772         for (; ifp; ifp = CK_STAILQ_NEXT(ifp, if_link)) {
1773                 CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1774                         if (ifa->ifa_addr->sa_family != AF_INET6)
1775                                 continue;
1776                         ifa6 = (struct in6_ifaddr *)ifa;
1777
1778                         if ((ifa6->ia6_flags & IN6_IFF_DEPRECATED) != 0 &&
1779                             allow_deprecated == 0) {
1780                                 /*
1781                                  * prefererred address should be put before
1782                                  * deprecated addresses.
1783                                  */
1784
1785                                 /* record the interface for later search */
1786                                 if (ifp_dep == NULL)
1787                                         ifp_dep = ifp;
1788
1789                                 continue;
1790                         } else if ((ifa6->ia6_flags & IN6_IFF_DEPRECATED) == 0 &&
1791                             allow_deprecated != 0)
1792                                 continue; /* we now collect deprecated addrs */
1793
1794                         /* What do we have to do about ::1? */
1795                         switch (in6_addrscope(&ifa6->ia_addr.sin6_addr)) {
1796                         case IPV6_ADDR_SCOPE_LINKLOCAL:
1797                                 if ((niflags & NI_NODEADDR_FLAG_LINKLOCAL) == 0)
1798                                         continue;
1799                                 break;
1800                         case IPV6_ADDR_SCOPE_SITELOCAL:
1801                                 if ((niflags & NI_NODEADDR_FLAG_SITELOCAL) == 0)
1802                                         continue;
1803                                 break;
1804                         case IPV6_ADDR_SCOPE_GLOBAL:
1805                                 if ((niflags & NI_NODEADDR_FLAG_GLOBAL) == 0)
1806                                         continue;
1807                                 break;
1808                         default:
1809                                 continue;
1810                         }
1811
1812                         /*
1813                          * check if anycast is okay.
1814                          * XXX: just experimental.  not in the spec.
1815                          */
1816                         if ((ifa6->ia6_flags & IN6_IFF_ANYCAST) != 0 &&
1817                             (niflags & NI_NODEADDR_FLAG_ANYCAST) == 0)
1818                                 continue;
1819                         if ((ifa6->ia6_flags & IN6_IFF_TEMPORARY) != 0 &&
1820                             (V_icmp6_nodeinfo & ICMP6_NODEINFO_TMPADDROK) == 0) {
1821                                 continue;
1822                         }
1823
1824                         /* now we can copy the address */
1825                         if (resid < sizeof(struct in6_addr) +
1826                             sizeof(u_int32_t)) {
1827                                 /*
1828                                  * We give up much more copy.
1829                                  * Set the truncate flag and return.
1830                                  */
1831                                 nni6->ni_flags |= NI_NODEADDR_FLAG_TRUNCATE;
1832                                 NET_EPOCH_EXIT(et);
1833                                 return (copied);
1834                         }
1835
1836                         /*
1837                          * Set the TTL of the address.
1838                          * The TTL value should be one of the following
1839                          * according to the specification:
1840                          *
1841                          * 1. The remaining lifetime of a DHCP lease on the
1842                          *    address, or
1843                          * 2. The remaining Valid Lifetime of a prefix from
1844                          *    which the address was derived through Stateless
1845                          *    Autoconfiguration.
1846                          *
1847                          * Note that we currently do not support stateful
1848                          * address configuration by DHCPv6, so the former
1849                          * case can't happen.
1850                          */
1851                         if (ifa6->ia6_lifetime.ia6t_expire == 0)
1852                                 ltime = ND6_INFINITE_LIFETIME;
1853                         else {
1854                                 if (ifa6->ia6_lifetime.ia6t_expire >
1855                                     time_uptime)
1856                                         ltime = htonl(ifa6->ia6_lifetime.ia6t_expire - time_uptime);
1857                                 else
1858                                         ltime = 0;
1859                         }
1860
1861                         bcopy(&ltime, cp, sizeof(u_int32_t));
1862                         cp += sizeof(u_int32_t);
1863
1864                         /* copy the address itself */
1865                         bcopy(&ifa6->ia_addr.sin6_addr, cp,
1866                             sizeof(struct in6_addr));
1867                         in6_clearscope((struct in6_addr *)cp); /* XXX */
1868                         cp += sizeof(struct in6_addr);
1869
1870                         resid -= (sizeof(struct in6_addr) + sizeof(u_int32_t));
1871                         copied += (sizeof(struct in6_addr) + sizeof(u_int32_t));
1872                 }
1873                 if (ifp0)       /* we need search only on the specified IF */
1874                         break;
1875         }
1876
1877         if (allow_deprecated == 0 && ifp_dep != NULL) {
1878                 ifp = ifp_dep;
1879                 allow_deprecated = 1;
1880
1881                 goto again;
1882         }
1883
1884         NET_EPOCH_EXIT(et);
1885
1886         return (copied);
1887 }
1888
1889 /*
1890  * XXX almost dup'ed code with rip6_input.
1891  */
1892 static int
1893 icmp6_rip6_input(struct mbuf **mp, int off)
1894 {
1895         struct mbuf *m = *mp;
1896         struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
1897         struct inpcb *inp;
1898         struct inpcb *last = NULL;
1899         struct sockaddr_in6 fromsa;
1900         struct icmp6_hdr *icmp6;
1901         struct epoch_tracker et;
1902         struct mbuf *opts = NULL;
1903
1904 #ifndef PULLDOWN_TEST
1905         /* this is assumed to be safe. */
1906         icmp6 = (struct icmp6_hdr *)((caddr_t)ip6 + off);
1907 #else
1908         IP6_EXTHDR_GET(icmp6, struct icmp6_hdr *, m, off, sizeof(*icmp6));
1909         if (icmp6 == NULL) {
1910                 /* m is already reclaimed */
1911                 return (IPPROTO_DONE);
1912         }
1913 #endif
1914
1915         /*
1916          * XXX: the address may have embedded scope zone ID, which should be
1917          * hidden from applications.
1918          */
1919         bzero(&fromsa, sizeof(fromsa));
1920         fromsa.sin6_family = AF_INET6;
1921         fromsa.sin6_len = sizeof(struct sockaddr_in6);
1922         fromsa.sin6_addr = ip6->ip6_src;
1923         if (sa6_recoverscope(&fromsa)) {
1924                 m_freem(m);
1925                 return (IPPROTO_DONE);
1926         }
1927
1928         INP_INFO_RLOCK_ET(&V_ripcbinfo, et);
1929         CK_LIST_FOREACH(inp, &V_ripcb, inp_list) {
1930                 if ((inp->inp_vflag & INP_IPV6) == 0)
1931                         continue;
1932                 if (inp->inp_ip_p != IPPROTO_ICMPV6)
1933                         continue;
1934                 if (!IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr) &&
1935                    !IN6_ARE_ADDR_EQUAL(&inp->in6p_laddr, &ip6->ip6_dst))
1936                         continue;
1937                 if (!IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr) &&
1938                    !IN6_ARE_ADDR_EQUAL(&inp->in6p_faddr, &ip6->ip6_src))
1939                         continue;
1940                 INP_RLOCK(inp);
1941                 if (__predict_false(inp->inp_flags2 & INP_FREED)) {
1942                         INP_RUNLOCK(inp);
1943                         continue;
1944                 }
1945                 if (ICMP6_FILTER_WILLBLOCK(icmp6->icmp6_type,
1946                     inp->in6p_icmp6filt)) {
1947                         INP_RUNLOCK(inp);
1948                         continue;
1949                 }
1950                 if (last != NULL) {
1951                         struct  mbuf *n = NULL;
1952
1953                         /*
1954                          * Recent network drivers tend to allocate a single
1955                          * mbuf cluster, rather than to make a couple of
1956                          * mbufs without clusters.  Also, since the IPv6 code
1957                          * path tries to avoid m_pullup(), it is highly
1958                          * probable that we still have an mbuf cluster here
1959                          * even though the necessary length can be stored in an
1960                          * mbuf's internal buffer.
1961                          * Meanwhile, the default size of the receive socket
1962                          * buffer for raw sockets is not so large.  This means
1963                          * the possibility of packet loss is relatively higher
1964                          * than before.  To avoid this scenario, we copy the
1965                          * received data to a separate mbuf that does not use
1966                          * a cluster, if possible.
1967                          * XXX: it is better to copy the data after stripping
1968                          * intermediate headers.
1969                          */
1970                         if ((m->m_flags & M_EXT) && m->m_next == NULL &&
1971                             m->m_len <= MHLEN) {
1972                                 n = m_get(M_NOWAIT, m->m_type);
1973                                 if (n != NULL) {
1974                                         if (m_dup_pkthdr(n, m, M_NOWAIT)) {
1975                                                 bcopy(m->m_data, n->m_data,
1976                                                       m->m_len);
1977                                                 n->m_len = m->m_len;
1978                                         } else {
1979                                                 m_free(n);
1980                                                 n = NULL;
1981                                         }
1982                                 }
1983                         }
1984                         if (n != NULL ||
1985                             (n = m_copym(m, 0, M_COPYALL, M_NOWAIT)) != NULL) {
1986                                 if (last->inp_flags & INP_CONTROLOPTS)
1987                                         ip6_savecontrol(last, n, &opts);
1988                                 /* strip intermediate headers */
1989                                 m_adj(n, off);
1990                                 SOCKBUF_LOCK(&last->inp_socket->so_rcv);
1991                                 if (sbappendaddr_locked(
1992                                     &last->inp_socket->so_rcv,
1993                                     (struct sockaddr *)&fromsa, n, opts)
1994                                     == 0) {
1995                                         /* should notify about lost packet */
1996                                         m_freem(n);
1997                                         if (opts) {
1998                                                 m_freem(opts);
1999                                         }
2000                                         SOCKBUF_UNLOCK(
2001                                             &last->inp_socket->so_rcv);
2002                                 } else
2003                                         sorwakeup_locked(last->inp_socket);
2004                                 opts = NULL;
2005                         }
2006                         INP_RUNLOCK(last);
2007                 }
2008                 last = inp;
2009         }
2010         INP_INFO_RUNLOCK_ET(&V_ripcbinfo, et);
2011         if (last != NULL) {
2012                 if (last->inp_flags & INP_CONTROLOPTS)
2013                         ip6_savecontrol(last, m, &opts);
2014                 /* strip intermediate headers */
2015                 m_adj(m, off);
2016
2017                 /* avoid using mbuf clusters if possible (see above) */
2018                 if ((m->m_flags & M_EXT) && m->m_next == NULL &&
2019                     m->m_len <= MHLEN) {
2020                         struct mbuf *n;
2021
2022                         n = m_get(M_NOWAIT, m->m_type);
2023                         if (n != NULL) {
2024                                 if (m_dup_pkthdr(n, m, M_NOWAIT)) {
2025                                         bcopy(m->m_data, n->m_data, m->m_len);
2026                                         n->m_len = m->m_len;
2027
2028                                         m_freem(m);
2029                                         m = n;
2030                                 } else {
2031                                         m_freem(n);
2032                                         n = NULL;
2033                                 }
2034                         }
2035                 }
2036                 SOCKBUF_LOCK(&last->inp_socket->so_rcv);
2037                 if (sbappendaddr_locked(&last->inp_socket->so_rcv,
2038                     (struct sockaddr *)&fromsa, m, opts) == 0) {
2039                         m_freem(m);
2040                         if (opts)
2041                                 m_freem(opts);
2042                         SOCKBUF_UNLOCK(&last->inp_socket->so_rcv);
2043                 } else
2044                         sorwakeup_locked(last->inp_socket);
2045                 INP_RUNLOCK(last);
2046         } else {
2047                 m_freem(m);
2048                 IP6STAT_DEC(ip6s_delivered);
2049         }
2050         return IPPROTO_DONE;
2051 }
2052
2053 /*
2054  * Reflect the ip6 packet back to the source.
2055  * OFF points to the icmp6 header, counted from the top of the mbuf.
2056  */
2057 void
2058 icmp6_reflect(struct mbuf *m, size_t off)
2059 {
2060         struct in6_addr src6, *srcp;
2061         struct ip6_hdr *ip6;
2062         struct icmp6_hdr *icmp6;
2063         struct in6_ifaddr *ia = NULL;
2064         struct ifnet *outif = NULL;
2065         int plen;
2066         int type, code, hlim;
2067
2068         /* too short to reflect */
2069         if (off < sizeof(struct ip6_hdr)) {
2070                 nd6log((LOG_DEBUG,
2071                     "sanity fail: off=%lx, sizeof(ip6)=%lx in %s:%d\n",
2072                     (u_long)off, (u_long)sizeof(struct ip6_hdr),
2073                     __FILE__, __LINE__));
2074                 goto bad;
2075         }
2076
2077         /*
2078          * If there are extra headers between IPv6 and ICMPv6, strip
2079          * off that header first.
2080          */
2081 #ifdef DIAGNOSTIC
2082         if (sizeof(struct ip6_hdr) + sizeof(struct icmp6_hdr) > MHLEN)
2083                 panic("assumption failed in icmp6_reflect");
2084 #endif
2085         if (off > sizeof(struct ip6_hdr)) {
2086                 size_t l;
2087                 struct ip6_hdr nip6;
2088
2089                 l = off - sizeof(struct ip6_hdr);
2090                 m_copydata(m, 0, sizeof(nip6), (caddr_t)&nip6);
2091                 m_adj(m, l);
2092                 l = sizeof(struct ip6_hdr) + sizeof(struct icmp6_hdr);
2093                 if (m->m_len < l) {
2094                         if ((m = m_pullup(m, l)) == NULL)
2095                                 return;
2096                 }
2097                 bcopy((caddr_t)&nip6, mtod(m, caddr_t), sizeof(nip6));
2098         } else /* off == sizeof(struct ip6_hdr) */ {
2099                 size_t l;
2100                 l = sizeof(struct ip6_hdr) + sizeof(struct icmp6_hdr);
2101                 if (m->m_len < l) {
2102                         if ((m = m_pullup(m, l)) == NULL)
2103                                 return;
2104                 }
2105         }
2106         plen = m->m_pkthdr.len - sizeof(struct ip6_hdr);
2107         ip6 = mtod(m, struct ip6_hdr *);
2108         ip6->ip6_nxt = IPPROTO_ICMPV6;
2109         icmp6 = (struct icmp6_hdr *)(ip6 + 1);
2110         type = icmp6->icmp6_type; /* keep type for statistics */
2111         code = icmp6->icmp6_code; /* ditto. */
2112         hlim = 0;
2113         srcp = NULL;
2114
2115         /*
2116          * If the incoming packet was addressed directly to us (i.e. unicast),
2117          * use dst as the src for the reply.
2118          * The IN6_IFF_NOTREADY case should be VERY rare, but is possible
2119          * (for example) when we encounter an error while forwarding procedure
2120          * destined to a duplicated address of ours.
2121          */
2122         if (!IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
2123                 ia = in6ifa_ifwithaddr(&ip6->ip6_dst, 0 /* XXX */);
2124                 if (ia != NULL && !(ia->ia6_flags &
2125                     (IN6_IFF_ANYCAST|IN6_IFF_NOTREADY))) {
2126                         src6 = ia->ia_addr.sin6_addr;
2127                         srcp = &src6;
2128
2129                         if (m->m_pkthdr.rcvif != NULL) {
2130                                 /* XXX: This may not be the outgoing interface */
2131                                 hlim = ND_IFINFO(m->m_pkthdr.rcvif)->chlim;
2132                         } else
2133                                 hlim = V_ip6_defhlim;
2134                 }
2135                 if (ia != NULL)
2136                         ifa_free(&ia->ia_ifa);
2137         }
2138
2139         if (srcp == NULL) {
2140                 int error;
2141                 struct in6_addr dst6;
2142                 uint32_t scopeid;
2143
2144                 /*
2145                  * This case matches to multicasts, our anycast, or unicasts
2146                  * that we do not own.  Select a source address based on the
2147                  * source address of the erroneous packet.
2148                  */
2149                 in6_splitscope(&ip6->ip6_src, &dst6, &scopeid);
2150                 error = in6_selectsrc_addr(M_GETFIB(m), &dst6,
2151                     scopeid, NULL, &src6, &hlim);
2152
2153                 if (error) {
2154                         char ip6buf[INET6_ADDRSTRLEN];
2155                         nd6log((LOG_DEBUG,
2156                             "icmp6_reflect: source can't be determined: "
2157                             "dst=%s, error=%d\n",
2158                             ip6_sprintf(ip6buf, &ip6->ip6_dst), error));
2159                         goto bad;
2160                 }
2161                 srcp = &src6;
2162         }
2163         /*
2164          * ip6_input() drops a packet if its src is multicast.
2165          * So, the src is never multicast.
2166          */
2167         ip6->ip6_dst = ip6->ip6_src;
2168         ip6->ip6_src = *srcp;
2169         ip6->ip6_flow = 0;
2170         ip6->ip6_vfc &= ~IPV6_VERSION_MASK;
2171         ip6->ip6_vfc |= IPV6_VERSION;
2172         ip6->ip6_nxt = IPPROTO_ICMPV6;
2173         ip6->ip6_hlim = hlim;
2174
2175         icmp6->icmp6_cksum = 0;
2176         icmp6->icmp6_cksum = in6_cksum(m, IPPROTO_ICMPV6,
2177             sizeof(struct ip6_hdr), plen);
2178
2179         /*
2180          * XXX option handling
2181          */
2182
2183         m->m_flags &= ~(M_BCAST|M_MCAST);
2184         m->m_pkthdr.rcvif = NULL;
2185         ip6_output(m, NULL, NULL, 0, NULL, &outif, NULL);
2186         if (outif)
2187                 icmp6_ifoutstat_inc(outif, type, code);
2188
2189         return;
2190
2191  bad:
2192         m_freem(m);
2193         return;
2194 }
2195
2196 void
2197 icmp6_fasttimo(void)
2198 {
2199
2200         mld_fasttimo();
2201 }
2202
2203 void
2204 icmp6_slowtimo(void)
2205 {
2206
2207         mld_slowtimo();
2208 }
2209
2210 static const char *
2211 icmp6_redirect_diag(struct in6_addr *src6, struct in6_addr *dst6,
2212     struct in6_addr *tgt6)
2213 {
2214         static char buf[1024];
2215         char ip6bufs[INET6_ADDRSTRLEN];
2216         char ip6bufd[INET6_ADDRSTRLEN];
2217         char ip6buft[INET6_ADDRSTRLEN];
2218         snprintf(buf, sizeof(buf), "(src=%s dst=%s tgt=%s)",
2219             ip6_sprintf(ip6bufs, src6), ip6_sprintf(ip6bufd, dst6),
2220             ip6_sprintf(ip6buft, tgt6));
2221         return buf;
2222 }
2223
2224 void
2225 icmp6_redirect_input(struct mbuf *m, int off)
2226 {
2227         struct ifnet *ifp;
2228         struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
2229         struct nd_redirect *nd_rd;
2230         int icmp6len = ntohs(ip6->ip6_plen);
2231         char *lladdr = NULL;
2232         int lladdrlen = 0;
2233         int is_router;
2234         int is_onlink;
2235         struct in6_addr src6 = ip6->ip6_src;
2236         struct in6_addr redtgt6;
2237         struct in6_addr reddst6;
2238         union nd_opts ndopts;
2239         char ip6buf[INET6_ADDRSTRLEN];
2240
2241         M_ASSERTPKTHDR(m);
2242         KASSERT(m->m_pkthdr.rcvif != NULL, ("%s: no rcvif", __func__));
2243
2244         ifp = m->m_pkthdr.rcvif;
2245
2246         /* XXX if we are router, we don't update route by icmp6 redirect */
2247         if (V_ip6_forwarding)
2248                 goto freeit;
2249         if (!V_icmp6_rediraccept)
2250                 goto freeit;
2251
2252         /* RFC 6980: Nodes MUST silently ignore fragments */
2253         if(m->m_flags & M_FRAGMENTED)
2254                 goto freeit;
2255
2256 #ifndef PULLDOWN_TEST
2257         IP6_EXTHDR_CHECK(m, off, icmp6len,);
2258         nd_rd = (struct nd_redirect *)((caddr_t)ip6 + off);
2259 #else
2260         IP6_EXTHDR_GET(nd_rd, struct nd_redirect *, m, off, icmp6len);
2261         if (nd_rd == NULL) {
2262                 ICMP6STAT_INC(icp6s_tooshort);
2263                 return;
2264         }
2265 #endif
2266         redtgt6 = nd_rd->nd_rd_target;
2267         reddst6 = nd_rd->nd_rd_dst;
2268
2269         if (in6_setscope(&redtgt6, m->m_pkthdr.rcvif, NULL) ||
2270             in6_setscope(&reddst6, m->m_pkthdr.rcvif, NULL)) {
2271                 goto freeit;
2272         }
2273
2274         /* validation */
2275         if (!IN6_IS_ADDR_LINKLOCAL(&src6)) {
2276                 nd6log((LOG_ERR,
2277                     "ICMP6 redirect sent from %s rejected; "
2278                     "must be from linklocal\n",
2279                     ip6_sprintf(ip6buf, &src6)));
2280                 goto bad;
2281         }
2282         if (ip6->ip6_hlim != 255) {
2283                 nd6log((LOG_ERR,
2284                     "ICMP6 redirect sent from %s rejected; "
2285                     "hlim=%d (must be 255)\n",
2286                     ip6_sprintf(ip6buf, &src6), ip6->ip6_hlim));
2287                 goto bad;
2288         }
2289     {
2290         /* ip6->ip6_src must be equal to gw for icmp6->icmp6_reddst */
2291         struct nhop6_basic nh6;
2292         struct in6_addr kdst;
2293         uint32_t scopeid;
2294
2295         in6_splitscope(&reddst6, &kdst, &scopeid);
2296         if (fib6_lookup_nh_basic(ifp->if_fib, &kdst, scopeid, 0, 0,&nh6)==0){
2297                 if ((nh6.nh_flags & NHF_GATEWAY) == 0) {
2298                         nd6log((LOG_ERR,
2299                             "ICMP6 redirect rejected; no route "
2300                             "with inet6 gateway found for redirect dst: %s\n",
2301                             icmp6_redirect_diag(&src6, &reddst6, &redtgt6)));
2302                         goto bad;
2303                 }
2304
2305                 /*
2306                  * Embed scope zone id into next hop address, since
2307                  * fib6_lookup_nh_basic() returns address without embedded
2308                  * scope zone id.
2309                  */
2310                 if (in6_setscope(&nh6.nh_addr, m->m_pkthdr.rcvif, NULL))
2311                         goto freeit;
2312
2313                 if (IN6_ARE_ADDR_EQUAL(&src6, &nh6.nh_addr) == 0) {
2314                         nd6log((LOG_ERR,
2315                             "ICMP6 redirect rejected; "
2316                             "not equal to gw-for-src=%s (must be same): "
2317                             "%s\n",
2318                             ip6_sprintf(ip6buf, &nh6.nh_addr),
2319                             icmp6_redirect_diag(&src6, &reddst6, &redtgt6)));
2320                         goto bad;
2321                 }
2322         } else {
2323                 nd6log((LOG_ERR,
2324                     "ICMP6 redirect rejected; "
2325                     "no route found for redirect dst: %s\n",
2326                     icmp6_redirect_diag(&src6, &reddst6, &redtgt6)));
2327                 goto bad;
2328         }
2329     }
2330         if (IN6_IS_ADDR_MULTICAST(&reddst6)) {
2331                 nd6log((LOG_ERR,
2332                     "ICMP6 redirect rejected; "
2333                     "redirect dst must be unicast: %s\n",
2334                     icmp6_redirect_diag(&src6, &reddst6, &redtgt6)));
2335                 goto bad;
2336         }
2337
2338         is_router = is_onlink = 0;
2339         if (IN6_IS_ADDR_LINKLOCAL(&redtgt6))
2340                 is_router = 1;  /* router case */
2341         if (bcmp(&redtgt6, &reddst6, sizeof(redtgt6)) == 0)
2342                 is_onlink = 1;  /* on-link destination case */
2343         if (!is_router && !is_onlink) {
2344                 nd6log((LOG_ERR,
2345                     "ICMP6 redirect rejected; "
2346                     "neither router case nor onlink case: %s\n",
2347                     icmp6_redirect_diag(&src6, &reddst6, &redtgt6)));
2348                 goto bad;
2349         }
2350
2351         icmp6len -= sizeof(*nd_rd);
2352         nd6_option_init(nd_rd + 1, icmp6len, &ndopts);
2353         if (nd6_options(&ndopts) < 0) {
2354                 nd6log((LOG_INFO, "%s: invalid ND option, rejected: %s\n",
2355                     __func__, icmp6_redirect_diag(&src6, &reddst6, &redtgt6)));
2356                 /* nd6_options have incremented stats */
2357                 goto freeit;
2358         }
2359
2360         if (ndopts.nd_opts_tgt_lladdr) {
2361                 lladdr = (char *)(ndopts.nd_opts_tgt_lladdr + 1);
2362                 lladdrlen = ndopts.nd_opts_tgt_lladdr->nd_opt_len << 3;
2363         }
2364
2365         if (lladdr && ((ifp->if_addrlen + 2 + 7) & ~7) != lladdrlen) {
2366                 nd6log((LOG_INFO, "%s: lladdrlen mismatch for %s "
2367                     "(if %d, icmp6 packet %d): %s\n",
2368                     __func__, ip6_sprintf(ip6buf, &redtgt6),
2369                     ifp->if_addrlen, lladdrlen - 2,
2370                     icmp6_redirect_diag(&src6, &reddst6, &redtgt6)));
2371                 goto bad;
2372         }
2373
2374         /* Validation passed. */
2375
2376         /* RFC 2461 8.3 */
2377         nd6_cache_lladdr(ifp, &redtgt6, lladdr, lladdrlen, ND_REDIRECT,
2378             is_onlink ? ND_REDIRECT_ONLINK : ND_REDIRECT_ROUTER);
2379
2380         /*
2381          * Install a gateway route in the better-router case or an interface
2382          * route in the on-link-destination case.
2383          */
2384         {
2385                 struct sockaddr_in6 sdst;
2386                 struct sockaddr_in6 sgw;
2387                 struct sockaddr_in6 ssrc;
2388                 struct sockaddr *gw;
2389                 int rt_flags;
2390                 u_int fibnum;
2391
2392                 bzero(&sdst, sizeof(sdst));
2393                 bzero(&ssrc, sizeof(ssrc));
2394                 sdst.sin6_family = ssrc.sin6_family = AF_INET6;
2395                 sdst.sin6_len = ssrc.sin6_len = sizeof(struct sockaddr_in6);
2396                 bcopy(&reddst6, &sdst.sin6_addr, sizeof(struct in6_addr));
2397                 bcopy(&src6, &ssrc.sin6_addr, sizeof(struct in6_addr));
2398                 rt_flags = RTF_HOST;
2399                 if (is_router) {
2400                         bzero(&sgw, sizeof(sgw));
2401                         sgw.sin6_family = AF_INET6;
2402                         sgw.sin6_len = sizeof(struct sockaddr_in6);
2403                         bcopy(&redtgt6, &sgw.sin6_addr,
2404                                 sizeof(struct in6_addr));
2405                         gw = (struct sockaddr *)&sgw;
2406                         rt_flags |= RTF_GATEWAY;
2407                 } else
2408                         gw = ifp->if_addr->ifa_addr;
2409                 for (fibnum = 0; fibnum < rt_numfibs; fibnum++)
2410                         in6_rtredirect((struct sockaddr *)&sdst, gw,
2411                             (struct sockaddr *)NULL, rt_flags,
2412                             (struct sockaddr *)&ssrc, fibnum);
2413         }
2414         /* finally update cached route in each socket via pfctlinput */
2415     {
2416         struct sockaddr_in6 sdst;
2417
2418         bzero(&sdst, sizeof(sdst));
2419         sdst.sin6_family = AF_INET6;
2420         sdst.sin6_len = sizeof(struct sockaddr_in6);
2421         bcopy(&reddst6, &sdst.sin6_addr, sizeof(struct in6_addr));
2422         pfctlinput(PRC_REDIRECT_HOST, (struct sockaddr *)&sdst);
2423     }
2424
2425  freeit:
2426         m_freem(m);
2427         return;
2428
2429  bad:
2430         ICMP6STAT_INC(icp6s_badredirect);
2431         m_freem(m);
2432 }
2433
2434 void
2435 icmp6_redirect_output(struct mbuf *m0, struct rtentry *rt)
2436 {
2437         struct ifnet *ifp;      /* my outgoing interface */
2438         struct in6_addr *ifp_ll6;
2439         struct in6_addr *router_ll6;
2440         struct ip6_hdr *sip6;   /* m0 as struct ip6_hdr */
2441         struct mbuf *m = NULL;  /* newly allocated one */
2442         struct m_tag *mtag;
2443         struct ip6_hdr *ip6;    /* m as struct ip6_hdr */
2444         struct nd_redirect *nd_rd;
2445         struct llentry *ln = NULL;
2446         size_t maxlen;
2447         u_char *p;
2448         struct ifnet *outif = NULL;
2449         struct sockaddr_in6 src_sa;
2450
2451         icmp6_errcount(ND_REDIRECT, 0);
2452
2453         /* if we are not router, we don't send icmp6 redirect */
2454         if (!V_ip6_forwarding)
2455                 goto fail;
2456
2457         /* sanity check */
2458         if (!m0 || !rt || !(rt->rt_flags & RTF_UP) || !(ifp = rt->rt_ifp))
2459                 goto fail;
2460
2461         /*
2462          * Address check:
2463          *  the source address must identify a neighbor, and
2464          *  the destination address must not be a multicast address
2465          *  [RFC 2461, sec 8.2]
2466          */
2467         sip6 = mtod(m0, struct ip6_hdr *);
2468         bzero(&src_sa, sizeof(src_sa));
2469         src_sa.sin6_family = AF_INET6;
2470         src_sa.sin6_len = sizeof(src_sa);
2471         src_sa.sin6_addr = sip6->ip6_src;
2472         if (nd6_is_addr_neighbor(&src_sa, ifp) == 0)
2473                 goto fail;
2474         if (IN6_IS_ADDR_MULTICAST(&sip6->ip6_dst))
2475                 goto fail;      /* what should we do here? */
2476
2477         /* rate limit */
2478         if (icmp6_ratelimit(&sip6->ip6_src, ND_REDIRECT, 0))
2479                 goto fail;
2480
2481         /*
2482          * Since we are going to append up to 1280 bytes (= IPV6_MMTU),
2483          * we almost always ask for an mbuf cluster for simplicity.
2484          * (MHLEN < IPV6_MMTU is almost always true)
2485          */
2486 #if IPV6_MMTU >= MCLBYTES
2487 # error assumption failed about IPV6_MMTU and MCLBYTES
2488 #endif
2489         m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
2490         if (m == NULL)
2491                 goto fail;
2492         M_SETFIB(m, rt->rt_fibnum);
2493         maxlen = M_TRAILINGSPACE(m);
2494         maxlen = min(IPV6_MMTU, maxlen);
2495         /* just for safety */
2496         if (maxlen < sizeof(struct ip6_hdr) + sizeof(struct icmp6_hdr) +
2497             ((sizeof(struct nd_opt_hdr) + ifp->if_addrlen + 7) & ~7)) {
2498                 goto fail;
2499         }
2500
2501         {
2502                 /* get ip6 linklocal address for ifp(my outgoing interface). */
2503                 struct in6_ifaddr *ia;
2504                 if ((ia = in6ifa_ifpforlinklocal(ifp,
2505                                                  IN6_IFF_NOTREADY|
2506                                                  IN6_IFF_ANYCAST)) == NULL)
2507                         goto fail;
2508                 ifp_ll6 = &ia->ia_addr.sin6_addr;
2509                 /* XXXRW: reference released prematurely. */
2510                 ifa_free(&ia->ia_ifa);
2511         }
2512
2513         /* get ip6 linklocal address for the router. */
2514         if (rt->rt_gateway && (rt->rt_flags & RTF_GATEWAY)) {
2515                 struct sockaddr_in6 *sin6;
2516                 sin6 = (struct sockaddr_in6 *)rt->rt_gateway;
2517                 router_ll6 = &sin6->sin6_addr;
2518                 if (!IN6_IS_ADDR_LINKLOCAL(router_ll6))
2519                         router_ll6 = (struct in6_addr *)NULL;
2520         } else
2521                 router_ll6 = (struct in6_addr *)NULL;
2522
2523         /* ip6 */
2524         ip6 = mtod(m, struct ip6_hdr *);
2525         ip6->ip6_flow = 0;
2526         ip6->ip6_vfc &= ~IPV6_VERSION_MASK;
2527         ip6->ip6_vfc |= IPV6_VERSION;
2528         /* ip6->ip6_plen will be set later */
2529         ip6->ip6_nxt = IPPROTO_ICMPV6;
2530         ip6->ip6_hlim = 255;
2531         /* ip6->ip6_src must be linklocal addr for my outgoing if. */
2532         bcopy(ifp_ll6, &ip6->ip6_src, sizeof(struct in6_addr));
2533         bcopy(&sip6->ip6_src, &ip6->ip6_dst, sizeof(struct in6_addr));
2534
2535         /* ND Redirect */
2536         nd_rd = (struct nd_redirect *)(ip6 + 1);
2537         nd_rd->nd_rd_type = ND_REDIRECT;
2538         nd_rd->nd_rd_code = 0;
2539         nd_rd->nd_rd_reserved = 0;
2540         if (rt->rt_flags & RTF_GATEWAY) {
2541                 /*
2542                  * nd_rd->nd_rd_target must be a link-local address in
2543                  * better router cases.
2544                  */
2545                 if (!router_ll6)
2546                         goto fail;
2547                 bcopy(router_ll6, &nd_rd->nd_rd_target,
2548                     sizeof(nd_rd->nd_rd_target));
2549                 bcopy(&sip6->ip6_dst, &nd_rd->nd_rd_dst,
2550                     sizeof(nd_rd->nd_rd_dst));
2551         } else {
2552                 /* make sure redtgt == reddst */
2553                 bcopy(&sip6->ip6_dst, &nd_rd->nd_rd_target,
2554                     sizeof(nd_rd->nd_rd_target));
2555                 bcopy(&sip6->ip6_dst, &nd_rd->nd_rd_dst,
2556                     sizeof(nd_rd->nd_rd_dst));
2557         }
2558
2559         p = (u_char *)(nd_rd + 1);
2560
2561         if (!router_ll6)
2562                 goto nolladdropt;
2563
2564         {
2565                 /* target lladdr option */
2566                 struct epoch_tracker et;
2567                 int len;
2568                 struct nd_opt_hdr *nd_opt;
2569                 char *lladdr;
2570
2571                 NET_EPOCH_ENTER(et);
2572                 ln = nd6_lookup(router_ll6, 0, ifp);
2573                 NET_EPOCH_EXIT(et);
2574                 if (ln == NULL)
2575                         goto nolladdropt;
2576
2577                 len = sizeof(*nd_opt) + ifp->if_addrlen;
2578                 len = (len + 7) & ~7;   /* round by 8 */
2579                 /* safety check */
2580                 if (len + (p - (u_char *)ip6) > maxlen)                         
2581                         goto nolladdropt;
2582
2583                 if (ln->la_flags & LLE_VALID) {
2584                         nd_opt = (struct nd_opt_hdr *)p;
2585                         nd_opt->nd_opt_type = ND_OPT_TARGET_LINKADDR;
2586                         nd_opt->nd_opt_len = len >> 3;
2587                         lladdr = (char *)(nd_opt + 1);
2588                         bcopy(ln->ll_addr, lladdr, ifp->if_addrlen);
2589                         p += len;
2590                 }
2591         }
2592 nolladdropt:
2593         if (ln != NULL)
2594                 LLE_RUNLOCK(ln);
2595                 
2596         m->m_pkthdr.len = m->m_len = p - (u_char *)ip6;
2597
2598         /* just to be safe */
2599 #ifdef M_DECRYPTED      /*not openbsd*/
2600         if (m0->m_flags & M_DECRYPTED)
2601                 goto noredhdropt;
2602 #endif
2603         if (p - (u_char *)ip6 > maxlen)
2604                 goto noredhdropt;
2605
2606         {
2607                 /* redirected header option */
2608                 int len;
2609                 struct nd_opt_rd_hdr *nd_opt_rh;
2610
2611                 /*
2612                  * compute the maximum size for icmp6 redirect header option.
2613                  * XXX room for auth header?
2614                  */
2615                 len = maxlen - (p - (u_char *)ip6);
2616                 len &= ~7;
2617
2618                 /* This is just for simplicity. */
2619                 if (m0->m_pkthdr.len != m0->m_len) {
2620                         if (m0->m_next) {
2621                                 m_freem(m0->m_next);
2622                                 m0->m_next = NULL;
2623                         }
2624                         m0->m_pkthdr.len = m0->m_len;
2625                 }
2626
2627                 /*
2628                  * Redirected header option spec (RFC2461 4.6.3) talks nothing
2629                  * about padding/truncate rule for the original IP packet.
2630                  * From the discussion on IPv6imp in Feb 1999,
2631                  * the consensus was:
2632                  * - "attach as much as possible" is the goal
2633                  * - pad if not aligned (original size can be guessed by
2634                  *   original ip6 header)
2635                  * Following code adds the padding if it is simple enough,
2636                  * and truncates if not.
2637                  */
2638                 if (m0->m_next || m0->m_pkthdr.len != m0->m_len)
2639                         panic("assumption failed in %s:%d", __FILE__,
2640                             __LINE__);
2641
2642                 if (len - sizeof(*nd_opt_rh) < m0->m_pkthdr.len) {
2643                         /* not enough room, truncate */
2644                         m0->m_pkthdr.len = m0->m_len = len -
2645                             sizeof(*nd_opt_rh);
2646                 } else {
2647                         /* enough room, pad or truncate */
2648                         size_t extra;
2649
2650                         extra = m0->m_pkthdr.len % 8;
2651                         if (extra) {
2652                                 /* pad if easy enough, truncate if not */
2653                                 if (8 - extra <= M_TRAILINGSPACE(m0)) {
2654                                         /* pad */
2655                                         m0->m_len += (8 - extra);
2656                                         m0->m_pkthdr.len += (8 - extra);
2657                                 } else {
2658                                         /* truncate */
2659                                         m0->m_pkthdr.len -= extra;
2660                                         m0->m_len -= extra;
2661                                 }
2662                         }
2663                         len = m0->m_pkthdr.len + sizeof(*nd_opt_rh);
2664                         m0->m_pkthdr.len = m0->m_len = len -
2665                             sizeof(*nd_opt_rh);
2666                 }
2667
2668                 nd_opt_rh = (struct nd_opt_rd_hdr *)p;
2669                 bzero(nd_opt_rh, sizeof(*nd_opt_rh));
2670                 nd_opt_rh->nd_opt_rh_type = ND_OPT_REDIRECTED_HEADER;
2671                 nd_opt_rh->nd_opt_rh_len = len >> 3;
2672                 p += sizeof(*nd_opt_rh);
2673                 m->m_pkthdr.len = m->m_len = p - (u_char *)ip6;
2674
2675                 /* connect m0 to m */
2676                 m_tag_delete_chain(m0, NULL);
2677                 m0->m_flags &= ~M_PKTHDR;
2678                 m->m_next = m0;
2679                 m->m_pkthdr.len = m->m_len + m0->m_len;
2680                 m0 = NULL;
2681         }
2682 noredhdropt:;
2683         if (m0) {
2684                 m_freem(m0);
2685                 m0 = NULL;
2686         }
2687
2688         /* XXX: clear embedded link IDs in the inner header */
2689         in6_clearscope(&sip6->ip6_src);
2690         in6_clearscope(&sip6->ip6_dst);
2691         in6_clearscope(&nd_rd->nd_rd_target);
2692         in6_clearscope(&nd_rd->nd_rd_dst);
2693
2694         ip6->ip6_plen = htons(m->m_pkthdr.len - sizeof(struct ip6_hdr));
2695
2696         nd_rd->nd_rd_cksum = 0;
2697         nd_rd->nd_rd_cksum = in6_cksum(m, IPPROTO_ICMPV6,
2698             sizeof(*ip6), ntohs(ip6->ip6_plen));
2699
2700         if (send_sendso_input_hook != NULL) {
2701                 mtag = m_tag_get(PACKET_TAG_ND_OUTGOING, sizeof(unsigned short),
2702                         M_NOWAIT);
2703                 if (mtag == NULL)
2704                         goto fail;
2705                 *(unsigned short *)(mtag + 1) = nd_rd->nd_rd_type;
2706                 m_tag_prepend(m, mtag);
2707         }
2708
2709         /* send the packet to outside... */
2710         ip6_output(m, NULL, NULL, 0, NULL, &outif, NULL);
2711         if (outif) {
2712                 icmp6_ifstat_inc(outif, ifs6_out_msg);
2713                 icmp6_ifstat_inc(outif, ifs6_out_redirect);
2714         }
2715         ICMP6STAT_INC(icp6s_outhist[ND_REDIRECT]);
2716
2717         return;
2718
2719 fail:
2720         if (m)
2721                 m_freem(m);
2722         if (m0)
2723                 m_freem(m0);
2724 }
2725
2726 /*
2727  * ICMPv6 socket option processing.
2728  */
2729 int
2730 icmp6_ctloutput(struct socket *so, struct sockopt *sopt)
2731 {
2732         int error = 0;
2733         int optlen;
2734         struct inpcb *inp = sotoinpcb(so);
2735         int level, op, optname;
2736
2737         if (sopt) {
2738                 level = sopt->sopt_level;
2739                 op = sopt->sopt_dir;
2740                 optname = sopt->sopt_name;
2741                 optlen = sopt->sopt_valsize;
2742         } else
2743                 level = op = optname = optlen = 0;
2744
2745         if (level != IPPROTO_ICMPV6) {
2746                 return EINVAL;
2747         }
2748
2749         switch (op) {
2750         case PRCO_SETOPT:
2751                 switch (optname) {
2752                 case ICMP6_FILTER:
2753                     {
2754                         struct icmp6_filter ic6f;
2755
2756                         if (optlen != sizeof(ic6f)) {
2757                                 error = EMSGSIZE;
2758                                 break;
2759                         }
2760                         error = sooptcopyin(sopt, &ic6f, optlen, optlen);
2761                         if (error == 0) {
2762                                 INP_WLOCK(inp);
2763                                 *inp->in6p_icmp6filt = ic6f;
2764                                 INP_WUNLOCK(inp);
2765                         }
2766                         break;
2767                     }
2768
2769                 default:
2770                         error = ENOPROTOOPT;
2771                         break;
2772                 }
2773                 break;
2774
2775         case PRCO_GETOPT:
2776                 switch (optname) {
2777                 case ICMP6_FILTER:
2778                     {
2779                         struct icmp6_filter ic6f;
2780
2781                         INP_RLOCK(inp);
2782                         ic6f = *inp->in6p_icmp6filt;
2783                         INP_RUNLOCK(inp);
2784                         error = sooptcopyout(sopt, &ic6f, sizeof(ic6f));
2785                         break;
2786                     }
2787
2788                 default:
2789                         error = ENOPROTOOPT;
2790                         break;
2791                 }
2792                 break;
2793         }
2794
2795         return (error);
2796 }
2797
2798 /*
2799  * Perform rate limit check.
2800  * Returns 0 if it is okay to send the icmp6 packet.
2801  * Returns 1 if the router SHOULD NOT send this icmp6 packet due to rate
2802  * limitation.
2803  *
2804  * XXX per-destination/type check necessary?
2805  *
2806  * dst - not used at this moment
2807  * type - not used at this moment
2808  * code - not used at this moment
2809  */
2810 static int
2811 icmp6_ratelimit(const struct in6_addr *dst, const int type,
2812     const int code)
2813 {
2814         int ret;
2815
2816         ret = 0;        /* okay to send */
2817
2818         /* PPS limit */
2819         if (!ppsratecheck(&V_icmp6errppslim_last, &V_icmp6errpps_count,
2820             V_icmp6errppslim)) {
2821                 /* The packet is subject to rate limit */
2822                 ret++;
2823         }
2824
2825         return ret;
2826 }