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