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