xref: /netbsd-src/sys/netinet/ip_icmp.c (revision c38e7cc395b1472a774ff828e46123de44c628e9)
1 /*	$NetBSD: ip_icmp.c,v 1.169 2018/04/26 07:28:21 maxv Exp $	*/
2 
3 /*
4  * Copyright (c) 1998, 2000 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Public Access Networks Corporation ("Panix").  It was developed under
9  * contract to Panix by Eric Haszlakiewicz and Thor Lancelot Simon.
10  *
11  * This code is derived from software contributed to The NetBSD Foundation
12  * by Jason R. Thorpe of Zembu Labs, Inc.
13  *
14  * Redistribution and use in source and binary forms, with or without
15  * modification, are permitted provided that the following conditions
16  * are met:
17  * 1. Redistributions of source code must retain the above copyright
18  *    notice, this list of conditions and the following disclaimer.
19  * 2. Redistributions in binary form must reproduce the above copyright
20  *    notice, this list of conditions and the following disclaimer in the
21  *    documentation and/or other materials provided with the distribution.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
24  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
25  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
26  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
27  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
28  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
29  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
30  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
31  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
32  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
33  * POSSIBILITY OF SUCH DAMAGE.
34  */
35 
36 /*
37  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
38  * All rights reserved.
39  *
40  * Redistribution and use in source and binary forms, with or without
41  * modification, are permitted provided that the following conditions
42  * are met:
43  * 1. Redistributions of source code must retain the above copyright
44  *    notice, this list of conditions and the following disclaimer.
45  * 2. Redistributions in binary form must reproduce the above copyright
46  *    notice, this list of conditions and the following disclaimer in the
47  *    documentation and/or other materials provided with the distribution.
48  * 3. Neither the name of the project nor the names of its contributors
49  *    may be used to endorse or promote products derived from this software
50  *    without specific prior written permission.
51  *
52  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
53  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
54  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
55  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
56  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
57  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
58  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
59  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
60  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
61  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
62  * SUCH DAMAGE.
63  */
64 
65 /*
66  * Copyright (c) 1982, 1986, 1988, 1993
67  *	The Regents of the University of California.  All rights reserved.
68  *
69  * Redistribution and use in source and binary forms, with or without
70  * modification, are permitted provided that the following conditions
71  * are met:
72  * 1. Redistributions of source code must retain the above copyright
73  *    notice, this list of conditions and the following disclaimer.
74  * 2. Redistributions in binary form must reproduce the above copyright
75  *    notice, this list of conditions and the following disclaimer in the
76  *    documentation and/or other materials provided with the distribution.
77  * 3. Neither the name of the University nor the names of its contributors
78  *    may be used to endorse or promote products derived from this software
79  *    without specific prior written permission.
80  *
81  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
82  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
83  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
84  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
85  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
86  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
87  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
88  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
89  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
90  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
91  * SUCH DAMAGE.
92  *
93  *	@(#)ip_icmp.c	8.2 (Berkeley) 1/4/94
94  */
95 
96 #include <sys/cdefs.h>
97 __KERNEL_RCSID(0, "$NetBSD: ip_icmp.c,v 1.169 2018/04/26 07:28:21 maxv Exp $");
98 
99 #ifdef _KERNEL_OPT
100 #include "opt_ipsec.h"
101 #endif
102 
103 #include <sys/param.h>
104 #include <sys/systm.h>
105 #include <sys/mbuf.h>
106 #include <sys/protosw.h>
107 #include <sys/socket.h>
108 #include <sys/socketvar.h> /* For softnet_lock */
109 #include <sys/kmem.h>
110 #include <sys/time.h>
111 #include <sys/kernel.h>
112 #include <sys/syslog.h>
113 #include <sys/sysctl.h>
114 
115 #include <net/if.h>
116 #include <net/route.h>
117 
118 #include <netinet/in.h>
119 #include <netinet/in_systm.h>
120 #include <netinet/in_var.h>
121 #include <netinet/ip.h>
122 #include <netinet/ip_icmp.h>
123 #include <netinet/ip_var.h>
124 #include <netinet/in_pcb.h>
125 #include <netinet/in_proto.h>
126 #include <netinet/icmp_var.h>
127 #include <netinet/icmp_private.h>
128 #include <netinet/wqinput.h>
129 
130 #ifdef IPSEC
131 #include <netipsec/ipsec.h>
132 #include <netipsec/key.h>
133 #endif
134 
135 /*
136  * ICMP routines: error generation, receive packet processing, and
137  * routines to turnaround packets back to the originator, and
138  * host table maintenance routines.
139  */
140 
141 int icmpmaskrepl = 0;
142 int icmpbmcastecho = 0;
143 #ifdef ICMPPRINTFS
144 int icmpprintfs = 0;
145 #endif
146 int icmpreturndatabytes = 8;
147 
148 percpu_t *icmpstat_percpu;
149 
150 /*
151  * List of callbacks to notify when Path MTU changes are made.
152  */
153 struct icmp_mtudisc_callback {
154 	LIST_ENTRY(icmp_mtudisc_callback) mc_list;
155 	void (*mc_func)(struct in_addr);
156 };
157 
158 LIST_HEAD(, icmp_mtudisc_callback) icmp_mtudisc_callbacks =
159     LIST_HEAD_INITIALIZER(&icmp_mtudisc_callbacks);
160 
161 /* unused... */
162 u_int ip_next_mtu(u_int, int);
163 
164 static int icmperrppslim = 100;			/* 100pps */
165 static int icmperrpps_count = 0;
166 static struct timeval icmperrppslim_last;
167 static int icmp_rediraccept = 1;
168 static int icmp_redirtimeout = 600;
169 static struct rttimer_queue *icmp_redirect_timeout_q = NULL;
170 
171 /* Protect mtudisc and redirect stuff */
172 static kmutex_t icmp_mtx __cacheline_aligned;
173 
174 static void icmp_send(struct mbuf *, struct mbuf *);
175 static void icmp_mtudisc_timeout(struct rtentry *, struct rttimer *);
176 static void icmp_redirect_timeout(struct rtentry *, struct rttimer *);
177 
178 static void sysctl_netinet_icmp_setup(struct sysctllog **);
179 
180 /* workqueue-based pr_input */
181 static struct wqinput *icmp_wqinput;
182 static void _icmp_input(struct mbuf *, int, int);
183 
184 void
185 icmp_init(void)
186 {
187 
188 	sysctl_netinet_icmp_setup(NULL);
189 
190 	mutex_init(&icmp_mtx, MUTEX_DEFAULT, IPL_NONE);
191 	/*
192 	 * This is only useful if the user initializes redirtimeout to
193 	 * something other than zero.
194 	 */
195 	mutex_enter(&icmp_mtx);
196 	icmp_redirect_timeout_q = rt_timer_queue_create(icmp_redirtimeout);
197 	mutex_exit(&icmp_mtx);
198 
199 	icmpstat_percpu = percpu_alloc(sizeof(uint64_t) * ICMP_NSTATS);
200 	icmp_wqinput = wqinput_create("icmp", _icmp_input);
201 }
202 
203 void
204 icmp_mtudisc_lock(void)
205 {
206 
207 	mutex_enter(&icmp_mtx);
208 }
209 
210 void
211 icmp_mtudisc_unlock(void)
212 {
213 
214 	mutex_exit(&icmp_mtx);
215 }
216 
217 /*
218  * Register a Path MTU Discovery callback.
219  */
220 void
221 icmp_mtudisc_callback_register(void (*func)(struct in_addr))
222 {
223 	struct icmp_mtudisc_callback *mc, *new;
224 
225 	new = kmem_alloc(sizeof(*mc), KM_SLEEP);
226 
227 	mutex_enter(&icmp_mtx);
228 	for (mc = LIST_FIRST(&icmp_mtudisc_callbacks); mc != NULL;
229 	     mc = LIST_NEXT(mc, mc_list)) {
230 		if (mc->mc_func == func) {
231 			mutex_exit(&icmp_mtx);
232 			kmem_free(new, sizeof(*mc));
233 			return;
234 		}
235 	}
236 
237 	new->mc_func = func;
238 	LIST_INSERT_HEAD(&icmp_mtudisc_callbacks, new, mc_list);
239 	mutex_exit(&icmp_mtx);
240 }
241 
242 /*
243  * Generate an error packet of type error in response to a bad IP packet. 'n'
244  * contains this packet. We create 'm' and send it.
245  *
246  * As we are not required to return everything we have, we return whatever
247  * we can return at ease.
248  *
249  * Note that ICMP datagrams longer than 576 octets are out of spec according
250  * to RFC1812; the limit on icmpreturndatabytes will keep things below that
251  * limit.
252  */
253 void
254 icmp_error(struct mbuf *n, int type, int code, n_long dest, int destmtu)
255 {
256 	struct ip *oip = mtod(n, struct ip *), *nip;
257 	const unsigned oiphlen = oip->ip_hl << 2;
258 	struct icmp *icp;
259 	struct mbuf *m;
260 	struct m_tag *mtag;
261 	unsigned datalen, mblen;
262 	int totlen;
263 
264 #ifdef ICMPPRINTFS
265 	if (icmpprintfs)
266 		printf("icmp_error(%p, type:%d, code:%d)\n", oip, type, code);
267 #endif
268 
269 	if (type != ICMP_REDIRECT)
270 		ICMP_STATINC(ICMP_STAT_ERROR);
271 
272 	/*
273 	 * Don't send error if:
274 	 *  - The original packet was encrypted.
275 	 *  - The packet is multicast or broadcast.
276 	 *  - The packet is not the first fragment of the message.
277 	 *  - The packet is an ICMP message with an unknown type.
278 	 */
279 	if (n->m_flags & M_DECRYPTED)
280 		goto freeit;
281 	if (n->m_flags & (M_BCAST|M_MCAST))
282 		goto freeit;
283 	if (oip->ip_off &~ htons(IP_MF|IP_DF))
284 		goto freeit;
285 	if (oip->ip_p == IPPROTO_ICMP && type != ICMP_REDIRECT &&
286 	    n->m_len >= oiphlen + ICMP_MINLEN) {
287 		struct icmp *oicp = (struct icmp *)((char *)oip + oiphlen);
288 		if (!ICMP_INFOTYPE(oicp->icmp_type)) {
289 			ICMP_STATINC(ICMP_STAT_OLDICMP);
290 			goto freeit;
291 		}
292 	}
293 
294 	/*
295 	 * First, do a rate limitation check.
296 	 */
297 	if (icmp_ratelimit(&oip->ip_src, type, code)) {
298 		/* XXX stat */
299 		goto freeit;
300 	}
301 
302 	/*
303 	 * Compute the number of bytes we will put in 'icmp_ip'. Truncate
304 	 * it to the size of the mbuf, if it's too big.
305 	 */
306 	datalen = oiphlen + min(icmpreturndatabytes,
307 	    ntohs(oip->ip_len) - oiphlen);
308 	mblen = 0;
309 	for (m = n; m && (mblen < datalen); m = m->m_next)
310 		mblen += m->m_len;
311 	datalen = min(mblen, datalen);
312 
313 	/*
314 	 * Compute the total length of the new packet. Truncate it if it's
315 	 * bigger than the size of a cluster.
316 	 */
317 	CTASSERT(ICMP_MINLEN + sizeof(struct ip) <= MCLBYTES);
318 	totlen = sizeof(struct ip) + ICMP_MINLEN + datalen;
319 	if (totlen > MCLBYTES) {
320 		datalen = MCLBYTES - ICMP_MINLEN - sizeof(struct ip);
321 		totlen = MCLBYTES;
322 	}
323 
324 	/*
325 	 * Allocate the mbuf for the new packet.
326 	 */
327 	m = m_gethdr(M_DONTWAIT, MT_HEADER);
328 	if (m && (totlen > MHLEN)) {
329 		MCLGET(m, M_DONTWAIT);
330 		if ((m->m_flags & M_EXT) == 0) {
331 			m_freem(m);
332 			m = NULL;
333 		}
334 	}
335 	if (m == NULL)
336 		goto freeit;
337 	MCLAIM(m, n->m_owner);
338 	m->m_len = totlen;
339 	m->m_pkthdr.len = m->m_len;
340 	m_copy_rcvif(m, n);
341 
342 	if ((u_int)type > ICMP_MAXTYPE)
343 		panic("icmp_error");
344 	ICMP_STATINC(ICMP_STAT_OUTHIST + type);
345 
346 	if ((m->m_flags & M_EXT) == 0)
347 		MH_ALIGN(m, m->m_len);
348 
349 	/*
350 	 * Get pointers on the IP header and the ICMP header.
351 	 */
352 	nip = mtod(m, struct ip *);
353 	icp = (struct icmp *)(nip + 1);
354 
355 	/*
356 	 * Fill in the fields of the ICMP header: icmp_type, icmp_code
357 	 * and icmp_ip. icmp_cksum gets filled later.
358 	 */
359 	icp->icmp_type = type;
360 	if (type == ICMP_REDIRECT) {
361 		icp->icmp_gwaddr.s_addr = dest;
362 	} else {
363 		icp->icmp_void = 0;
364 		/*
365 		 * The following assignments assume an overlay with the
366 		 * zeroed icmp_void field.
367 		 */
368 		if (type == ICMP_PARAMPROB) {
369 			icp->icmp_pptr = code;
370 			code = 0;
371 		} else if (type == ICMP_UNREACH &&
372 		    code == ICMP_UNREACH_NEEDFRAG && destmtu)
373 			icp->icmp_nextmtu = htons(destmtu);
374 	}
375 	icp->icmp_code = code;
376 	m_copydata(n, 0, datalen, (void *)&icp->icmp_ip);
377 
378 	/*
379 	 * Now, copy the old IP header (without options) in front of the
380 	 * ICMP message. The src/dst fields will be swapped in icmp_reflect.
381 	 */
382 	/* ip_v set in ip_output */
383 	nip->ip_hl = sizeof(struct ip) >> 2;
384 	nip->ip_tos = 0;
385 	nip->ip_len = htons(m->m_len);
386 	/* ip_id set in ip_output */
387 	nip->ip_off = htons(0);
388 	/* ip_ttl set in icmp_reflect */
389 	nip->ip_p = IPPROTO_ICMP;
390 	nip->ip_src = oip->ip_src;
391 	nip->ip_dst = oip->ip_dst;
392 	/* move PF m_tag to new packet, if it exists */
393 	mtag = m_tag_find(n, PACKET_TAG_PF, NULL);
394 	if (mtag != NULL) {
395 		m_tag_unlink(n, mtag);
396 		m_tag_prepend(m, mtag);
397 	}
398 
399 	icmp_reflect(m);
400 
401 freeit:
402 	m_freem(n);
403 }
404 
405 struct sockaddr_in icmpsrc = {
406 	.sin_len = sizeof(struct sockaddr_in),
407 	.sin_family = AF_INET,
408 };
409 
410 /*
411  * Process a received ICMP message.
412  */
413 static void
414 _icmp_input(struct mbuf *m, int hlen, int proto)
415 {
416 	struct icmp *icp;
417 	struct ip *ip = mtod(m, struct ip *);
418 	int icmplen;
419 	int i;
420 	struct in_ifaddr *ia;
421 	void *(*ctlfunc)(int, const struct sockaddr *, void *);
422 	int code;
423 	struct rtentry *rt;
424 	struct sockaddr_in icmpdst = {
425 		.sin_len = sizeof(struct sockaddr_in),
426 		.sin_family = AF_INET,
427 	};
428 	struct sockaddr_in icmpgw = {
429 		.sin_len = sizeof(struct sockaddr_in),
430 		.sin_family = AF_INET,
431 	};
432 
433 	/*
434 	 * Locate icmp structure in mbuf, and check
435 	 * that not corrupted and of at least minimum length.
436 	 */
437 	icmplen = ntohs(ip->ip_len) - hlen;
438 #ifdef ICMPPRINTFS
439 	if (icmpprintfs) {
440 		char sbuf[INET_ADDRSTRLEN], dbuf[INET_ADDRSTRLEN];
441 		printf("icmp_input from `%s' to `%s', len %d\n",
442 		    IN_PRINT(sbuf, &ip->ip_src), IN_PRINT(dbuf, &ip->ip_dst),
443 		    icmplen);
444 	}
445 #endif
446 	if (icmplen < ICMP_MINLEN) {
447 		ICMP_STATINC(ICMP_STAT_TOOSHORT);
448 		goto freeit;
449 	}
450 	i = hlen + min(icmplen, ICMP_ADVLENMIN);
451 	if (M_UNWRITABLE(m, i) && (m = m_pullup(m, i)) == NULL) {
452 		ICMP_STATINC(ICMP_STAT_TOOSHORT);
453 		return;
454 	}
455 	ip = mtod(m, struct ip *);
456 	m->m_len -= hlen;
457 	m->m_data += hlen;
458 	icp = mtod(m, struct icmp *);
459 	/* Don't need to assert alignment, here. */
460 	if (in_cksum(m, icmplen)) {
461 		ICMP_STATINC(ICMP_STAT_CHECKSUM);
462 		goto freeit;
463 	}
464 	m->m_len += hlen;
465 	m->m_data -= hlen;
466 
467 #ifdef ICMPPRINTFS
468 	/*
469 	 * Message type specific processing.
470 	 */
471 	if (icmpprintfs)
472 		printf("icmp_input(type:%d, code:%d)\n", icp->icmp_type,
473 		    icp->icmp_code);
474 #endif
475 	if (icp->icmp_type > ICMP_MAXTYPE)
476 		goto raw;
477 	ICMP_STATINC(ICMP_STAT_INHIST + icp->icmp_type);
478 	code = icp->icmp_code;
479 
480 	switch (icp->icmp_type) {
481 	case ICMP_UNREACH:
482 		switch (code) {
483 		case ICMP_UNREACH_PROTOCOL:
484 			code = PRC_UNREACH_PROTOCOL;
485 			break;
486 
487 		case ICMP_UNREACH_PORT:
488 			code = PRC_UNREACH_PORT;
489 			break;
490 
491 		case ICMP_UNREACH_SRCFAIL:
492 			code = PRC_UNREACH_SRCFAIL;
493 			break;
494 
495 		case ICMP_UNREACH_NEEDFRAG:
496 			code = PRC_MSGSIZE;
497 			break;
498 
499 		case ICMP_UNREACH_NET:
500 		case ICMP_UNREACH_NET_UNKNOWN:
501 		case ICMP_UNREACH_NET_PROHIB:
502 		case ICMP_UNREACH_TOSNET:
503 			code = PRC_UNREACH_NET;
504 			break;
505 
506 		case ICMP_UNREACH_HOST:
507 		case ICMP_UNREACH_HOST_UNKNOWN:
508 		case ICMP_UNREACH_ISOLATED:
509 		case ICMP_UNREACH_HOST_PROHIB:
510 		case ICMP_UNREACH_TOSHOST:
511 		case ICMP_UNREACH_ADMIN_PROHIBIT:
512 		case ICMP_UNREACH_HOST_PREC:
513 		case ICMP_UNREACH_PREC_CUTOFF:
514 			code = PRC_UNREACH_HOST;
515 			break;
516 
517 		default:
518 			goto badcode;
519 		}
520 		goto deliver;
521 
522 	case ICMP_TIMXCEED:
523 		if (code > 1)
524 			goto badcode;
525 		code += PRC_TIMXCEED_INTRANS;
526 		goto deliver;
527 
528 	case ICMP_PARAMPROB:
529 		if (code > 1)
530 			goto badcode;
531 		code = PRC_PARAMPROB;
532 		goto deliver;
533 
534 	case ICMP_SOURCEQUENCH:
535 		if (code)
536 			goto badcode;
537 		code = PRC_QUENCH;
538 		goto deliver;
539 
540 	deliver:
541 		/*
542 		 * Problem with datagram; advise higher level routines.
543 		 */
544 		if (icmplen < ICMP_ADVLENMIN || icmplen < ICMP_ADVLEN(icp) ||
545 		    icp->icmp_ip.ip_hl < (sizeof(struct ip) >> 2)) {
546 			ICMP_STATINC(ICMP_STAT_BADLEN);
547 			goto freeit;
548 		}
549 		if (m->m_len < hlen + ICMP_ADVLEN(icp)) {
550 			m = m_pullup(m, hlen + ICMP_ADVLEN(icp));
551 			if (m == NULL)
552 				goto freeit;
553 		}
554 		ip = mtod(m, struct ip *);
555 		icp = (struct icmp *)(mtod(m, uint8_t *) + hlen);
556 
557 		if (IN_MULTICAST(icp->icmp_ip.ip_dst.s_addr))
558 			goto badcode;
559 #ifdef ICMPPRINTFS
560 		if (icmpprintfs)
561 			printf("deliver to protocol %d\n", icp->icmp_ip.ip_p);
562 #endif
563 		icmpsrc.sin_addr = icp->icmp_ip.ip_dst;
564 		ctlfunc = inetsw[ip_protox[icp->icmp_ip.ip_p]].pr_ctlinput;
565 		if (ctlfunc)
566 			(void) (*ctlfunc)(code, sintosa(&icmpsrc),
567 			    &icp->icmp_ip);
568 		break;
569 
570 	badcode:
571 		ICMP_STATINC(ICMP_STAT_BADCODE);
572 		break;
573 
574 	case ICMP_ECHO:
575 		if (!icmpbmcastecho &&
576 		    (m->m_flags & (M_MCAST | M_BCAST)) != 0)  {
577 			ICMP_STATINC(ICMP_STAT_BMCASTECHO);
578 			break;
579 		}
580 		icp->icmp_type = ICMP_ECHOREPLY;
581 		goto reflect;
582 
583 	case ICMP_TSTAMP:
584 		if (icmplen < ICMP_TSLEN) {
585 			ICMP_STATINC(ICMP_STAT_BADLEN);
586 			break;
587 		}
588 		if (!icmpbmcastecho &&
589 		    (m->m_flags & (M_MCAST | M_BCAST)) != 0)  {
590 			ICMP_STATINC(ICMP_STAT_BMCASTTSTAMP);
591 			break;
592 		}
593 		icp->icmp_type = ICMP_TSTAMPREPLY;
594 		icp->icmp_rtime = iptime();
595 		icp->icmp_ttime = icp->icmp_rtime;	/* bogus, do later! */
596 		goto reflect;
597 
598 	case ICMP_MASKREQ: {
599 		struct ifnet *rcvif;
600 		int s, ss;
601 		struct ifaddr *ifa = NULL;
602 
603 		if (icmpmaskrepl == 0)
604 			break;
605 		/*
606 		 * We are not able to respond with all ones broadcast
607 		 * unless we receive it over a point-to-point interface.
608 		 */
609 		if (icmplen < ICMP_MASKLEN) {
610 			ICMP_STATINC(ICMP_STAT_BADLEN);
611 			break;
612 		}
613 		if (ip->ip_dst.s_addr == INADDR_BROADCAST ||
614 		    in_nullhost(ip->ip_dst))
615 			icmpdst.sin_addr = ip->ip_src;
616 		else
617 			icmpdst.sin_addr = ip->ip_dst;
618 		ss = pserialize_read_enter();
619 		rcvif = m_get_rcvif(m, &s);
620 		if (__predict_true(rcvif != NULL))
621 			ifa = ifaof_ifpforaddr(sintosa(&icmpdst), rcvif);
622 		m_put_rcvif(rcvif, &s);
623 		if (ifa == NULL) {
624 			pserialize_read_exit(ss);
625 			break;
626 		}
627 		ia = ifatoia(ifa);
628 		icp->icmp_type = ICMP_MASKREPLY;
629 		icp->icmp_mask = ia->ia_sockmask.sin_addr.s_addr;
630 		if (in_nullhost(ip->ip_src)) {
631 			if (ia->ia_ifp->if_flags & IFF_BROADCAST)
632 				ip->ip_src = ia->ia_broadaddr.sin_addr;
633 			else if (ia->ia_ifp->if_flags & IFF_POINTOPOINT)
634 				ip->ip_src = ia->ia_dstaddr.sin_addr;
635 		}
636 		pserialize_read_exit(ss);
637 reflect:
638 		{
639 			uint64_t *icps = percpu_getref(icmpstat_percpu);
640 			icps[ICMP_STAT_REFLECT]++;
641 			icps[ICMP_STAT_OUTHIST + icp->icmp_type]++;
642 			percpu_putref(icmpstat_percpu);
643 		}
644 		icmp_reflect(m);
645 		return;
646 	}
647 
648 	case ICMP_REDIRECT:
649 		if (code > 3)
650 			goto badcode;
651 		if (icmp_rediraccept == 0)
652 			goto freeit;
653 		if (icmplen < ICMP_ADVLENMIN || icmplen < ICMP_ADVLEN(icp) ||
654 		    icp->icmp_ip.ip_hl < (sizeof(struct ip) >> 2)) {
655 			ICMP_STATINC(ICMP_STAT_BADLEN);
656 			break;
657 		}
658 		/*
659 		 * Short circuit routing redirects to force
660 		 * immediate change in the kernel's routing
661 		 * tables.  The message is also handed to anyone
662 		 * listening on a raw socket (e.g. the routing
663 		 * daemon for use in updating its tables).
664 		 */
665 		icmpgw.sin_addr = ip->ip_src;
666 		icmpdst.sin_addr = icp->icmp_gwaddr;
667 #ifdef	ICMPPRINTFS
668 		if (icmpprintfs) {
669 			char gbuf[INET_ADDRSTRLEN], dbuf[INET_ADDRSTRLEN];
670 			printf("redirect dst `%s' to `%s'\n",
671 			    IN_PRINT(dbuf, &icp->icmp_ip.ip_dst),
672 			    IN_PRINT(gbuf, &icp->icmp_gwaddr));
673 		}
674 #endif
675 		icmpsrc.sin_addr = icp->icmp_ip.ip_dst;
676 		rt = NULL;
677 		rtredirect(sintosa(&icmpsrc), sintosa(&icmpdst),
678 		    NULL, RTF_GATEWAY | RTF_HOST, sintosa(&icmpgw), &rt);
679 		mutex_enter(&icmp_mtx);
680 		if (rt != NULL && icmp_redirtimeout != 0) {
681 			i = rt_timer_add(rt, icmp_redirect_timeout,
682 					 icmp_redirect_timeout_q);
683 			if (i) {
684 				char buf[INET_ADDRSTRLEN];
685 				log(LOG_ERR, "ICMP:  redirect failed to "
686 				    "register timeout for route to %s, "
687 				    "code %d\n",
688 				    IN_PRINT(buf, &icp->icmp_ip.ip_dst), i);
689 			}
690 		}
691 		mutex_exit(&icmp_mtx);
692 		if (rt != NULL)
693 			rt_unref(rt);
694 
695 		pfctlinput(PRC_REDIRECT_HOST, sintosa(&icmpsrc));
696 #if defined(IPSEC)
697 		if (ipsec_used)
698 			key_sa_routechange((struct sockaddr *)&icmpsrc);
699 #endif
700 		break;
701 
702 	/*
703 	 * No kernel processing for the following;
704 	 * just fall through to send to raw listener.
705 	 */
706 	case ICMP_ECHOREPLY:
707 	case ICMP_ROUTERADVERT:
708 	case ICMP_ROUTERSOLICIT:
709 	case ICMP_TSTAMPREPLY:
710 	case ICMP_IREQREPLY:
711 	case ICMP_MASKREPLY:
712 	default:
713 		break;
714 	}
715 
716 raw:
717 	rip_input(m, hlen, proto);
718 	return;
719 
720 freeit:
721 	m_freem(m);
722 	return;
723 }
724 
725 void
726 icmp_input(struct mbuf *m, ...)
727 {
728 	int hlen, proto;
729 	va_list ap;
730 
731 	va_start(ap, m);
732 	hlen = va_arg(ap, int);
733 	proto = va_arg(ap, int);
734 	va_end(ap);
735 
736 	wqinput_input(icmp_wqinput, m, hlen, proto);
737 }
738 
739 /*
740  * Reflect the ip packet back to the source
741  */
742 void
743 icmp_reflect(struct mbuf *m)
744 {
745 	struct ip *ip = mtod(m, struct ip *);
746 	struct in_ifaddr *ia;
747 	struct ifaddr *ifa;
748 	struct sockaddr_in *sin;
749 	struct in_addr t;
750 	struct mbuf *opts = NULL;
751 	int optlen = (ip->ip_hl << 2) - sizeof(struct ip);
752 	struct ifnet *rcvif;
753 	struct psref psref, psref_ia;
754 	int s;
755 	int bound;
756 
757 	bound = curlwp_bind();
758 
759 	if (!in_canforward(ip->ip_src) &&
760 	    ((ip->ip_src.s_addr & IN_CLASSA_NET) !=
761 	     htonl(IN_LOOPBACKNET << IN_CLASSA_NSHIFT))) {
762 		m_freem(m);	/* Bad return address */
763 		goto done;	/* ip_output() will check for broadcast */
764 	}
765 	t = ip->ip_dst;
766 	ip->ip_dst = ip->ip_src;
767 
768 	/*
769 	 * If the incoming packet was addressed directly to us, use
770 	 * dst as the src for the reply.  Otherwise (broadcast or
771 	 * anonymous), use an address which corresponds to the
772 	 * incoming interface, with a preference for the address which
773 	 * corresponds to the route to the destination of the ICMP.
774 	 */
775 
776 	/* Look for packet addressed to us */
777 	ia = in_get_ia_psref(t, &psref_ia);
778 	if (ia && (ia->ia4_flags & IN_IFF_NOTREADY)) {
779 		ia4_release(ia, &psref_ia);
780 		ia = NULL;
781 	}
782 
783 	rcvif = m_get_rcvif_psref(m, &psref);
784 
785 	/* look for packet sent to broadcast address */
786 	if (ia == NULL && rcvif &&
787 	    (rcvif->if_flags & IFF_BROADCAST)) {
788 		s = pserialize_read_enter();
789 		IFADDR_READER_FOREACH(ifa, rcvif) {
790 			if (ifa->ifa_addr->sa_family != AF_INET)
791 				continue;
792 			if (in_hosteq(t,ifatoia(ifa)->ia_broadaddr.sin_addr)) {
793 				ia = ifatoia(ifa);
794 				if ((ia->ia4_flags & IN_IFF_NOTREADY) == 0)
795 					break;
796 				ia = NULL;
797 			}
798 		}
799 		if (ia != NULL)
800 			ia4_acquire(ia, &psref_ia);
801 		pserialize_read_exit(s);
802 	}
803 
804 	sin = ia ? &ia->ia_addr : NULL;
805 
806 	/*
807 	 * if the packet is addressed somewhere else, compute the
808 	 * source address for packets routed back to the source, and
809 	 * use that, if it's an address on the interface which
810 	 * received the packet
811 	 */
812 	if (sin == NULL && rcvif) {
813 		struct sockaddr_in sin_dst;
814 		struct route icmproute;
815 		int errornum;
816 
817 		sockaddr_in_init(&sin_dst, &ip->ip_dst, 0);
818 		memset(&icmproute, 0, sizeof(icmproute));
819 		errornum = 0;
820 		ia = in_selectsrc(&sin_dst, &icmproute, 0, NULL, &errornum,
821 		    &psref_ia);
822 		/* errornum is never used */
823 		rtcache_free(&icmproute);
824 		/* check to make sure sin is a source address on rcvif */
825 		if (ia != NULL) {
826 			sin = &ia->ia_addr;
827 			t = sin->sin_addr;
828 			sin = NULL;
829 			ia4_release(ia, &psref_ia);
830 			ia = in_get_ia_on_iface_psref(t, rcvif, &psref_ia);
831 			if (ia != NULL)
832 				sin = &ia->ia_addr;
833 		}
834 	}
835 
836 	/*
837 	 * if it was not addressed to us, but the route doesn't go out
838 	 * the source interface, pick an address on the source
839 	 * interface.  This can happen when routing is asymmetric, or
840 	 * when the incoming packet was encapsulated
841 	 */
842 	if (sin == NULL && rcvif) {
843 		KASSERT(ia == NULL);
844 		s = pserialize_read_enter();
845 		IFADDR_READER_FOREACH(ifa, rcvif) {
846 			if (ifa->ifa_addr->sa_family != AF_INET)
847 				continue;
848 			sin = &(ifatoia(ifa)->ia_addr);
849 			ia = ifatoia(ifa);
850 			ia4_acquire(ia, &psref_ia);
851 			break;
852 		}
853 		pserialize_read_exit(s);
854 	}
855 
856 	m_put_rcvif_psref(rcvif, &psref);
857 
858 	/*
859 	 * The following happens if the packet was not addressed to us,
860 	 * and was received on an interface with no IP address:
861 	 * We find the first AF_INET address on the first non-loopback
862 	 * interface.
863 	 */
864 	if (sin == NULL) {
865 		KASSERT(ia == NULL);
866 		s = pserialize_read_enter();
867 		IN_ADDRLIST_READER_FOREACH(ia) {
868 			if (ia->ia_ifp->if_flags & IFF_LOOPBACK)
869 				continue;
870 			sin = &ia->ia_addr;
871 			ia4_acquire(ia, &psref_ia);
872 			break;
873 		}
874 		pserialize_read_exit(s);
875 	}
876 
877 	/*
878 	 * If we still didn't find an address, punt.  We could have an
879 	 * interface up (and receiving packets) with no address.
880 	 */
881 	if (sin == NULL) {
882 		KASSERT(ia == NULL);
883 		m_freem(m);
884 		goto done;
885 	}
886 
887 	ip->ip_src = sin->sin_addr;
888 	ip->ip_ttl = MAXTTL;
889 
890 	if (ia != NULL)
891 		ia4_release(ia, &psref_ia);
892 
893 	if (optlen > 0) {
894 		u_char *cp;
895 		int opt, cnt;
896 		u_int len;
897 
898 		/*
899 		 * Retrieve any source routing from the incoming packet;
900 		 * add on any record-route or timestamp options.
901 		 */
902 		cp = (u_char *)(ip + 1);
903 		if ((opts = ip_srcroute(m)) == NULL &&
904 		    (opts = m_gethdr(M_DONTWAIT, MT_HEADER))) {
905 			MCLAIM(opts, m->m_owner);
906 			opts->m_len = sizeof(struct in_addr);
907 			*mtod(opts, struct in_addr *) = zeroin_addr;
908 		}
909 
910 		if (opts) {
911 #ifdef ICMPPRINTFS
912 			if (icmpprintfs)
913 				printf("icmp_reflect optlen %d rt %d => ",
914 				    optlen, opts->m_len);
915 #endif
916 			for (cnt = optlen; cnt > 0; cnt -= len, cp += len) {
917 				opt = cp[IPOPT_OPTVAL];
918 				if (opt == IPOPT_EOL)
919 					break;
920 				if (opt == IPOPT_NOP)
921 					len = 1;
922 				else {
923 					if (cnt < IPOPT_OLEN + sizeof(*cp))
924 						break;
925 					len = cp[IPOPT_OLEN];
926 					if (len < IPOPT_OLEN + sizeof(*cp) ||
927 					    len > cnt)
928 						break;
929 				}
930 
931 				/* Overflows can't happen */
932 				KASSERT(opts->m_len + len <= MHLEN);
933 
934 				if (opt == IPOPT_RR || opt == IPOPT_TS ||
935 				    opt == IPOPT_SECURITY) {
936 					memmove(mtod(opts, char *) +
937 					    opts->m_len, cp, len);
938 					opts->m_len += len;
939 				}
940 			}
941 
942 			/* Terminate & pad, if necessary */
943 			if ((cnt = opts->m_len % 4) != 0) {
944 				for (; cnt < 4; cnt++) {
945 					*(mtod(opts, char *) + opts->m_len) =
946 					    IPOPT_EOL;
947 					opts->m_len++;
948 				}
949 			}
950 #ifdef ICMPPRINTFS
951 			if (icmpprintfs)
952 				printf("%d\n", opts->m_len);
953 #endif
954 		}
955 
956 		/*
957 		 * Now strip out original options by copying rest of first
958 		 * mbuf's data back, and adjust the IP length.
959 		 */
960 		ip->ip_len = htons(ntohs(ip->ip_len) - optlen);
961 		ip->ip_hl = sizeof(struct ip) >> 2;
962 		m->m_len -= optlen;
963 		if (m->m_flags & M_PKTHDR)
964 			m->m_pkthdr.len -= optlen;
965 		optlen += sizeof(struct ip);
966 		memmove(ip + 1, (char *)ip + optlen,
967 		    (unsigned)(m->m_len - sizeof(struct ip)));
968 	}
969 	m_tag_delete_nonpersistent(m);
970 	m->m_flags &= ~(M_BCAST|M_MCAST);
971 
972 	/*
973 	 * Clear any in-bound checksum flags for this packet.
974 	 */
975 	if (m->m_flags & M_PKTHDR)
976 		m->m_pkthdr.csum_flags = 0;
977 
978 	icmp_send(m, opts);
979 done:
980 	curlwp_bindx(bound);
981 	if (opts)
982 		(void)m_free(opts);
983 }
984 
985 /*
986  * Send an icmp packet back to the ip level,
987  * after supplying a checksum.
988  */
989 static void
990 icmp_send(struct mbuf *m, struct mbuf *opts)
991 {
992 	struct ip *ip = mtod(m, struct ip *);
993 	int hlen;
994 	struct icmp *icp;
995 
996 	hlen = ip->ip_hl << 2;
997 	m->m_data += hlen;
998 	m->m_len -= hlen;
999 	icp = mtod(m, struct icmp *);
1000 	icp->icmp_cksum = 0;
1001 	icp->icmp_cksum = in_cksum(m, ntohs(ip->ip_len) - hlen);
1002 	m->m_data -= hlen;
1003 	m->m_len += hlen;
1004 #ifdef ICMPPRINTFS
1005 	if (icmpprintfs) {
1006 		char sbuf[INET_ADDRSTRLEN], dbuf[INET_ADDRSTRLEN];
1007 		printf("icmp_send to destination `%s' from `%s'\n",
1008 		    IN_PRINT(dbuf, &ip->ip_dst), IN_PRINT(sbuf, &ip->ip_src));
1009 	}
1010 #endif
1011 	(void)ip_output(m, opts, NULL, 0, NULL, NULL);
1012 }
1013 
1014 n_time
1015 iptime(void)
1016 {
1017 	struct timeval atv;
1018 	u_long t;
1019 
1020 	microtime(&atv);
1021 	t = (atv.tv_sec % (24*60*60)) * 1000 + atv.tv_usec / 1000;
1022 	return (htonl(t));
1023 }
1024 
1025 /*
1026  * sysctl helper routine for net.inet.icmp.returndatabytes.  ensures
1027  * that the new value is in the correct range.
1028  */
1029 static int
1030 sysctl_net_inet_icmp_returndatabytes(SYSCTLFN_ARGS)
1031 {
1032 	int error, t;
1033 	struct sysctlnode node;
1034 
1035 	node = *rnode;
1036 	node.sysctl_data = &t;
1037 	t = icmpreturndatabytes;
1038 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
1039 	if (error || newp == NULL)
1040 		return error;
1041 
1042 	if (t < 8 || t > 512)
1043 		return EINVAL;
1044 	icmpreturndatabytes = t;
1045 
1046 	return 0;
1047 }
1048 
1049 /*
1050  * sysctl helper routine for net.inet.icmp.redirtimeout.  ensures that
1051  * the given value is not less than zero and then resets the timeout
1052  * queue.
1053  */
1054 static int
1055 sysctl_net_inet_icmp_redirtimeout(SYSCTLFN_ARGS)
1056 {
1057 	int error, tmp;
1058 	struct sysctlnode node;
1059 
1060 	mutex_enter(&icmp_mtx);
1061 
1062 	node = *rnode;
1063 	node.sysctl_data = &tmp;
1064 	tmp = icmp_redirtimeout;
1065 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
1066 	if (error || newp == NULL)
1067 		goto out;
1068 	if (tmp < 0) {
1069 		error = EINVAL;
1070 		goto out;
1071 	}
1072 	icmp_redirtimeout = tmp;
1073 
1074 	/*
1075 	 * was it a *defined* side-effect that anyone even *reading*
1076 	 * this value causes these things to happen?
1077 	 */
1078 	if (icmp_redirect_timeout_q != NULL) {
1079 		if (icmp_redirtimeout == 0) {
1080 			rt_timer_queue_destroy(icmp_redirect_timeout_q);
1081 			icmp_redirect_timeout_q = NULL;
1082 		} else {
1083 			rt_timer_queue_change(icmp_redirect_timeout_q,
1084 			    icmp_redirtimeout);
1085 		}
1086 	} else if (icmp_redirtimeout > 0) {
1087 		icmp_redirect_timeout_q =
1088 		    rt_timer_queue_create(icmp_redirtimeout);
1089 	}
1090 	error = 0;
1091 out:
1092 	mutex_exit(&icmp_mtx);
1093 	return error;
1094 }
1095 
1096 static int
1097 sysctl_net_inet_icmp_stats(SYSCTLFN_ARGS)
1098 {
1099 
1100 	return (NETSTAT_SYSCTL(icmpstat_percpu, ICMP_NSTATS));
1101 }
1102 
1103 static void
1104 sysctl_netinet_icmp_setup(struct sysctllog **clog)
1105 {
1106 
1107 	sysctl_createv(clog, 0, NULL, NULL,
1108 		       CTLFLAG_PERMANENT,
1109 		       CTLTYPE_NODE, "inet", NULL,
1110 		       NULL, 0, NULL, 0,
1111 		       CTL_NET, PF_INET, CTL_EOL);
1112 	sysctl_createv(clog, 0, NULL, NULL,
1113 		       CTLFLAG_PERMANENT,
1114 		       CTLTYPE_NODE, "icmp",
1115 		       SYSCTL_DESCR("ICMPv4 related settings"),
1116 		       NULL, 0, NULL, 0,
1117 		       CTL_NET, PF_INET, IPPROTO_ICMP, CTL_EOL);
1118 
1119 	sysctl_createv(clog, 0, NULL, NULL,
1120 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
1121 		       CTLTYPE_INT, "maskrepl",
1122 		       SYSCTL_DESCR("Respond to ICMP_MASKREQ messages"),
1123 		       NULL, 0, &icmpmaskrepl, 0,
1124 		       CTL_NET, PF_INET, IPPROTO_ICMP,
1125 		       ICMPCTL_MASKREPL, CTL_EOL);
1126 	sysctl_createv(clog, 0, NULL, NULL,
1127 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
1128 		       CTLTYPE_INT, "returndatabytes",
1129 		       SYSCTL_DESCR("Number of bytes to return in an ICMP "
1130 				    "error message"),
1131 		       sysctl_net_inet_icmp_returndatabytes, 0,
1132 		       &icmpreturndatabytes, 0,
1133 		       CTL_NET, PF_INET, IPPROTO_ICMP,
1134 		       ICMPCTL_RETURNDATABYTES, CTL_EOL);
1135 	sysctl_createv(clog, 0, NULL, NULL,
1136 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
1137 		       CTLTYPE_INT, "errppslimit",
1138 		       SYSCTL_DESCR("Maximum number of outgoing ICMP error "
1139 				    "messages per second"),
1140 		       NULL, 0, &icmperrppslim, 0,
1141 		       CTL_NET, PF_INET, IPPROTO_ICMP,
1142 		       ICMPCTL_ERRPPSLIMIT, CTL_EOL);
1143 	sysctl_createv(clog, 0, NULL, NULL,
1144 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
1145 		       CTLTYPE_INT, "rediraccept",
1146 		       SYSCTL_DESCR("Accept ICMP_REDIRECT messages"),
1147 		       NULL, 0, &icmp_rediraccept, 0,
1148 		       CTL_NET, PF_INET, IPPROTO_ICMP,
1149 		       ICMPCTL_REDIRACCEPT, CTL_EOL);
1150 	sysctl_createv(clog, 0, NULL, NULL,
1151 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
1152 		       CTLTYPE_INT, "redirtimeout",
1153 		       SYSCTL_DESCR("Lifetime of ICMP_REDIRECT generated "
1154 				    "routes"),
1155 		       sysctl_net_inet_icmp_redirtimeout, 0,
1156 		       &icmp_redirtimeout, 0,
1157 		       CTL_NET, PF_INET, IPPROTO_ICMP,
1158 		       ICMPCTL_REDIRTIMEOUT, CTL_EOL);
1159 	sysctl_createv(clog, 0, NULL, NULL,
1160 		       CTLFLAG_PERMANENT,
1161 		       CTLTYPE_STRUCT, "stats",
1162 		       SYSCTL_DESCR("ICMP statistics"),
1163 		       sysctl_net_inet_icmp_stats, 0, NULL, 0,
1164 		       CTL_NET, PF_INET, IPPROTO_ICMP, ICMPCTL_STATS,
1165 		       CTL_EOL);
1166 	sysctl_createv(clog, 0, NULL, NULL,
1167 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
1168 		       CTLTYPE_INT, "bmcastecho",
1169 		       SYSCTL_DESCR("Respond to ICMP_ECHO or ICMP_TIMESTAMP "
1170 				    "message to the broadcast or multicast"),
1171 		       NULL, 0, &icmpbmcastecho, 0,
1172 		       CTL_NET, PF_INET, IPPROTO_ICMP, ICMPCTL_BMCASTECHO,
1173 		       CTL_EOL);
1174 }
1175 
1176 void
1177 icmp_statinc(u_int stat)
1178 {
1179 
1180 	KASSERT(stat < ICMP_NSTATS);
1181 	ICMP_STATINC(stat);
1182 }
1183 
1184 /* Table of common MTUs */
1185 static const u_int mtu_table[] = {
1186 	65535, 65280, 32000, 17914, 9180, 8166,
1187 	4352, 2002, 1492, 1006, 508, 296, 68, 0
1188 };
1189 
1190 void
1191 icmp_mtudisc(struct icmp *icp, struct in_addr faddr)
1192 {
1193 	struct icmp_mtudisc_callback *mc;
1194 	struct sockaddr *dst = sintosa(&icmpsrc);
1195 	struct rtentry *rt;
1196 	u_long mtu = ntohs(icp->icmp_nextmtu);  /* Why a long?  IPv6 */
1197 	int error;
1198 
1199 	rt = rtalloc1(dst, 1);
1200 	if (rt == NULL)
1201 		return;
1202 
1203 	/* If we didn't get a host route, allocate one */
1204 	if ((rt->rt_flags & RTF_HOST) == 0) {
1205 		struct rtentry *nrt;
1206 
1207 		error = rtrequest(RTM_ADD, dst, rt->rt_gateway, NULL,
1208 		    RTF_GATEWAY | RTF_HOST | RTF_DYNAMIC, &nrt);
1209 		if (error) {
1210 			rt_unref(rt);
1211 			return;
1212 		}
1213 		nrt->rt_rmx = rt->rt_rmx;
1214 		rt_unref(rt);
1215 		rt = nrt;
1216 	}
1217 
1218 	mutex_enter(&icmp_mtx);
1219 	error = rt_timer_add(rt, icmp_mtudisc_timeout, ip_mtudisc_timeout_q);
1220 	mutex_exit(&icmp_mtx);
1221 	if (error) {
1222 		rt_unref(rt);
1223 		return;
1224 	}
1225 
1226 	if (mtu == 0) {
1227 		int i = 0;
1228 
1229 		mtu = ntohs(icp->icmp_ip.ip_len);
1230 		/* Some 4.2BSD-based routers incorrectly adjust the ip_len */
1231 		if (mtu > rt->rt_rmx.rmx_mtu && rt->rt_rmx.rmx_mtu != 0)
1232 			mtu -= (icp->icmp_ip.ip_hl << 2);
1233 
1234 		/* If we still can't guess a value, try the route */
1235 		if (mtu == 0) {
1236 			mtu = rt->rt_rmx.rmx_mtu;
1237 
1238 			/* If no route mtu, default to the interface mtu */
1239 			if (mtu == 0)
1240 				mtu = rt->rt_ifp->if_mtu;
1241 		}
1242 
1243 		for (i = 0; i < sizeof(mtu_table) / sizeof(mtu_table[0]); i++) {
1244 			if (mtu > mtu_table[i]) {
1245 				mtu = mtu_table[i];
1246 				break;
1247 			}
1248 		}
1249 	}
1250 
1251 	/*
1252 	 * XXX:   RTV_MTU is overloaded, since the admin can set it
1253 	 *	  to turn off PMTU for a route, and the kernel can
1254 	 *	  set it to indicate a serious problem with PMTU
1255 	 *	  on a route.  We should be using a separate flag
1256 	 *	  for the kernel to indicate this.
1257 	 */
1258 
1259 	if ((rt->rt_rmx.rmx_locks & RTV_MTU) == 0) {
1260 		if (mtu < 296 || mtu > rt->rt_ifp->if_mtu)
1261 			rt->rt_rmx.rmx_locks |= RTV_MTU;
1262 		else if (rt->rt_rmx.rmx_mtu > mtu ||
1263 			 rt->rt_rmx.rmx_mtu == 0) {
1264 			ICMP_STATINC(ICMP_STAT_PMTUCHG);
1265 			rt->rt_rmx.rmx_mtu = mtu;
1266 		}
1267 	}
1268 
1269 	if (rt != NULL)
1270 		rt_unref(rt);
1271 
1272 	/*
1273 	 * Notify protocols that the MTU for this destination
1274 	 * has changed.
1275 	 */
1276 	mutex_enter(&icmp_mtx);
1277 	for (mc = LIST_FIRST(&icmp_mtudisc_callbacks); mc != NULL;
1278 	     mc = LIST_NEXT(mc, mc_list))
1279 		(*mc->mc_func)(faddr);
1280 	mutex_exit(&icmp_mtx);
1281 }
1282 
1283 /*
1284  * Return the next larger or smaller MTU plateau (table from RFC 1191)
1285  * given current value MTU.  If DIR is less than zero, a larger plateau
1286  * is returned; otherwise, a smaller value is returned.
1287  */
1288 u_int
1289 ip_next_mtu(u_int mtu, int dir)	/* XXX unused */
1290 {
1291 	int i;
1292 
1293 	for (i = 0; i < (sizeof mtu_table) / (sizeof mtu_table[0]); i++) {
1294 		if (mtu >= mtu_table[i])
1295 			break;
1296 	}
1297 
1298 	if (dir < 0) {
1299 		if (i == 0) {
1300 			return 0;
1301 		} else {
1302 			return mtu_table[i - 1];
1303 		}
1304 	} else {
1305 		if (mtu_table[i] == 0) {
1306 			return 0;
1307 		} else if (mtu > mtu_table[i]) {
1308 			return mtu_table[i];
1309 		} else {
1310 			return mtu_table[i + 1];
1311 		}
1312 	}
1313 }
1314 
1315 static void
1316 icmp_mtudisc_timeout(struct rtentry *rt, struct rttimer *r)
1317 {
1318 
1319 	KASSERT(rt != NULL);
1320 	rt_assert_referenced(rt);
1321 
1322 	if ((rt->rt_flags & (RTF_DYNAMIC | RTF_HOST)) ==
1323 	    (RTF_DYNAMIC | RTF_HOST)) {
1324 		rtrequest(RTM_DELETE, rt_getkey(rt),
1325 		    rt->rt_gateway, rt_mask(rt), rt->rt_flags, NULL);
1326 	} else {
1327 		if ((rt->rt_rmx.rmx_locks & RTV_MTU) == 0) {
1328 			rt->rt_rmx.rmx_mtu = 0;
1329 		}
1330 	}
1331 }
1332 
1333 static void
1334 icmp_redirect_timeout(struct rtentry *rt, struct rttimer *r)
1335 {
1336 
1337 	KASSERT(rt != NULL);
1338 	rt_assert_referenced(rt);
1339 
1340 	if ((rt->rt_flags & (RTF_DYNAMIC | RTF_HOST)) ==
1341 	    (RTF_DYNAMIC | RTF_HOST)) {
1342 		rtrequest(RTM_DELETE, rt_getkey(rt),
1343 		    rt->rt_gateway, rt_mask(rt), rt->rt_flags, NULL);
1344 	}
1345 }
1346 
1347 /*
1348  * Perform rate limit check.
1349  * Returns 0 if it is okay to send the icmp packet.
1350  * Returns 1 if the router SHOULD NOT send this icmp packet due to rate
1351  * limitation.
1352  *
1353  * XXX per-destination/type check necessary?
1354  */
1355 int
1356 icmp_ratelimit(const struct in_addr *dst, const int type,
1357     const int code)
1358 {
1359 
1360 	/* PPS limit */
1361 	if (!ppsratecheck(&icmperrppslim_last, &icmperrpps_count,
1362 	    icmperrppslim)) {
1363 		/* The packet is subject to rate limit */
1364 		return 1;
1365 	}
1366 
1367 	/* okay to send */
1368 	return 0;
1369 }
1370