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