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