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