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