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