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