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