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