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