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