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