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