Home | History | Annotate | Line # | Download | only in netinet
ip_icmp.c revision 1.167
      1 /*	$NetBSD: ip_icmp.c,v 1.167 2018/02/05 08:38:06 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.167 2018/02/05 08:38:06 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->m_len < i || M_READONLY(m)) && (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 (IN_MULTICAST(icp->icmp_ip.ip_dst.s_addr))
    550 			goto badcode;
    551 #ifdef ICMPPRINTFS
    552 		if (icmpprintfs)
    553 			printf("deliver to protocol %d\n", icp->icmp_ip.ip_p);
    554 #endif
    555 		icmpsrc.sin_addr = icp->icmp_ip.ip_dst;
    556 		ctlfunc = inetsw[ip_protox[icp->icmp_ip.ip_p]].pr_ctlinput;
    557 		if (ctlfunc)
    558 			(void) (*ctlfunc)(code, sintosa(&icmpsrc),
    559 			    &icp->icmp_ip);
    560 		break;
    561 
    562 	badcode:
    563 		ICMP_STATINC(ICMP_STAT_BADCODE);
    564 		break;
    565 
    566 	case ICMP_ECHO:
    567 		if (!icmpbmcastecho &&
    568 		    (m->m_flags & (M_MCAST | M_BCAST)) != 0)  {
    569 			ICMP_STATINC(ICMP_STAT_BMCASTECHO);
    570 			break;
    571 		}
    572 		icp->icmp_type = ICMP_ECHOREPLY;
    573 		goto reflect;
    574 
    575 	case ICMP_TSTAMP:
    576 		if (icmplen < ICMP_TSLEN) {
    577 			ICMP_STATINC(ICMP_STAT_BADLEN);
    578 			break;
    579 		}
    580 		if (!icmpbmcastecho &&
    581 		    (m->m_flags & (M_MCAST | M_BCAST)) != 0)  {
    582 			ICMP_STATINC(ICMP_STAT_BMCASTTSTAMP);
    583 			break;
    584 		}
    585 		icp->icmp_type = ICMP_TSTAMPREPLY;
    586 		icp->icmp_rtime = iptime();
    587 		icp->icmp_ttime = icp->icmp_rtime;	/* bogus, do later! */
    588 		goto reflect;
    589 
    590 	case ICMP_MASKREQ: {
    591 		struct ifnet *rcvif;
    592 		int s, ss;
    593 		struct ifaddr *ifa = NULL;
    594 
    595 		if (icmpmaskrepl == 0)
    596 			break;
    597 		/*
    598 		 * We are not able to respond with all ones broadcast
    599 		 * unless we receive it over a point-to-point interface.
    600 		 */
    601 		if (icmplen < ICMP_MASKLEN) {
    602 			ICMP_STATINC(ICMP_STAT_BADLEN);
    603 			break;
    604 		}
    605 		if (ip->ip_dst.s_addr == INADDR_BROADCAST ||
    606 		    in_nullhost(ip->ip_dst))
    607 			icmpdst.sin_addr = ip->ip_src;
    608 		else
    609 			icmpdst.sin_addr = ip->ip_dst;
    610 		ss = pserialize_read_enter();
    611 		rcvif = m_get_rcvif(m, &s);
    612 		if (__predict_true(rcvif != NULL))
    613 			ifa = ifaof_ifpforaddr(sintosa(&icmpdst), rcvif);
    614 		m_put_rcvif(rcvif, &s);
    615 		if (ifa == NULL) {
    616 			pserialize_read_exit(ss);
    617 			break;
    618 		}
    619 		ia = ifatoia(ifa);
    620 		icp->icmp_type = ICMP_MASKREPLY;
    621 		icp->icmp_mask = ia->ia_sockmask.sin_addr.s_addr;
    622 		if (in_nullhost(ip->ip_src)) {
    623 			if (ia->ia_ifp->if_flags & IFF_BROADCAST)
    624 				ip->ip_src = ia->ia_broadaddr.sin_addr;
    625 			else if (ia->ia_ifp->if_flags & IFF_POINTOPOINT)
    626 				ip->ip_src = ia->ia_dstaddr.sin_addr;
    627 		}
    628 		pserialize_read_exit(ss);
    629 reflect:
    630 		{
    631 			uint64_t *icps = percpu_getref(icmpstat_percpu);
    632 			icps[ICMP_STAT_REFLECT]++;
    633 			icps[ICMP_STAT_OUTHIST + icp->icmp_type]++;
    634 			percpu_putref(icmpstat_percpu);
    635 		}
    636 		icmp_reflect(m);
    637 		return;
    638 	}
    639 
    640 	case ICMP_REDIRECT:
    641 		if (code > 3)
    642 			goto badcode;
    643 		if (icmp_rediraccept == 0)
    644 			goto freeit;
    645 		if (icmplen < ICMP_ADVLENMIN || icmplen < ICMP_ADVLEN(icp) ||
    646 		    icp->icmp_ip.ip_hl < (sizeof(struct ip) >> 2)) {
    647 			ICMP_STATINC(ICMP_STAT_BADLEN);
    648 			break;
    649 		}
    650 		/*
    651 		 * Short circuit routing redirects to force
    652 		 * immediate change in the kernel's routing
    653 		 * tables.  The message is also handed to anyone
    654 		 * listening on a raw socket (e.g. the routing
    655 		 * daemon for use in updating its tables).
    656 		 */
    657 		icmpgw.sin_addr = ip->ip_src;
    658 		icmpdst.sin_addr = icp->icmp_gwaddr;
    659 #ifdef	ICMPPRINTFS
    660 		if (icmpprintfs) {
    661 			char gbuf[INET_ADDRSTRLEN], dbuf[INET_ADDRSTRLEN];
    662 			printf("redirect dst `%s' to `%s'\n",
    663 			    IN_PRINT(dbuf, &icp->icmp_ip.ip_dst),
    664 			    IN_PRINT(gbuf, &icp->icmp_gwaddr));
    665 		}
    666 #endif
    667 		icmpsrc.sin_addr = icp->icmp_ip.ip_dst;
    668 		rt = NULL;
    669 		rtredirect(sintosa(&icmpsrc), sintosa(&icmpdst),
    670 		    NULL, RTF_GATEWAY | RTF_HOST, sintosa(&icmpgw), &rt);
    671 		mutex_enter(&icmp_mtx);
    672 		if (rt != NULL && icmp_redirtimeout != 0) {
    673 			i = rt_timer_add(rt, icmp_redirect_timeout,
    674 					 icmp_redirect_timeout_q);
    675 			if (i) {
    676 				char buf[INET_ADDRSTRLEN];
    677 				log(LOG_ERR, "ICMP:  redirect failed to "
    678 				    "register timeout for route to %s, "
    679 				    "code %d\n",
    680 				    IN_PRINT(buf, &icp->icmp_ip.ip_dst), i);
    681 			}
    682 		}
    683 		mutex_exit(&icmp_mtx);
    684 		if (rt != NULL)
    685 			rt_unref(rt);
    686 
    687 		pfctlinput(PRC_REDIRECT_HOST, sintosa(&icmpsrc));
    688 #if defined(IPSEC)
    689 		if (ipsec_used)
    690 			key_sa_routechange((struct sockaddr *)&icmpsrc);
    691 #endif
    692 		break;
    693 
    694 	/*
    695 	 * No kernel processing for the following;
    696 	 * just fall through to send to raw listener.
    697 	 */
    698 	case ICMP_ECHOREPLY:
    699 	case ICMP_ROUTERADVERT:
    700 	case ICMP_ROUTERSOLICIT:
    701 	case ICMP_TSTAMPREPLY:
    702 	case ICMP_IREQREPLY:
    703 	case ICMP_MASKREPLY:
    704 	default:
    705 		break;
    706 	}
    707 
    708 raw:
    709 	rip_input(m, hlen, proto);
    710 	return;
    711 
    712 freeit:
    713 	m_freem(m);
    714 	return;
    715 }
    716 
    717 void
    718 icmp_input(struct mbuf *m, ...)
    719 {
    720 	int hlen, proto;
    721 	va_list ap;
    722 
    723 	va_start(ap, m);
    724 	hlen = va_arg(ap, int);
    725 	proto = va_arg(ap, int);
    726 	va_end(ap);
    727 
    728 	wqinput_input(icmp_wqinput, m, hlen, proto);
    729 }
    730 
    731 /*
    732  * Reflect the ip packet back to the source
    733  */
    734 void
    735 icmp_reflect(struct mbuf *m)
    736 {
    737 	struct ip *ip = mtod(m, struct ip *);
    738 	struct in_ifaddr *ia;
    739 	struct ifaddr *ifa;
    740 	struct sockaddr_in *sin;
    741 	struct in_addr t;
    742 	struct mbuf *opts = NULL;
    743 	int optlen = (ip->ip_hl << 2) - sizeof(struct ip);
    744 	struct ifnet *rcvif;
    745 	struct psref psref, psref_ia;
    746 	int s;
    747 	int bound;
    748 
    749 	bound = curlwp_bind();
    750 
    751 	if (!in_canforward(ip->ip_src) &&
    752 	    ((ip->ip_src.s_addr & IN_CLASSA_NET) !=
    753 	     htonl(IN_LOOPBACKNET << IN_CLASSA_NSHIFT))) {
    754 		m_freem(m);	/* Bad return address */
    755 		goto done;	/* ip_output() will check for broadcast */
    756 	}
    757 	t = ip->ip_dst;
    758 	ip->ip_dst = ip->ip_src;
    759 
    760 	/*
    761 	 * If the incoming packet was addressed directly to us, use
    762 	 * dst as the src for the reply.  Otherwise (broadcast or
    763 	 * anonymous), use an address which corresponds to the
    764 	 * incoming interface, with a preference for the address which
    765 	 * corresponds to the route to the destination of the ICMP.
    766 	 */
    767 
    768 	/* Look for packet addressed to us */
    769 	ia = in_get_ia_psref(t, &psref_ia);
    770 	if (ia && (ia->ia4_flags & IN_IFF_NOTREADY)) {
    771 		ia4_release(ia, &psref_ia);
    772 		ia = NULL;
    773 	}
    774 
    775 	rcvif = m_get_rcvif_psref(m, &psref);
    776 
    777 	/* look for packet sent to broadcast address */
    778 	if (ia == NULL && rcvif &&
    779 	    (rcvif->if_flags & IFF_BROADCAST)) {
    780 		s = pserialize_read_enter();
    781 		IFADDR_READER_FOREACH(ifa, rcvif) {
    782 			if (ifa->ifa_addr->sa_family != AF_INET)
    783 				continue;
    784 			if (in_hosteq(t,ifatoia(ifa)->ia_broadaddr.sin_addr)) {
    785 				ia = ifatoia(ifa);
    786 				if ((ia->ia4_flags & IN_IFF_NOTREADY) == 0)
    787 					break;
    788 				ia = NULL;
    789 			}
    790 		}
    791 		if (ia != NULL)
    792 			ia4_acquire(ia, &psref_ia);
    793 		pserialize_read_exit(s);
    794 	}
    795 
    796 	sin = ia ? &ia->ia_addr : NULL;
    797 
    798 	/*
    799 	 * if the packet is addressed somewhere else, compute the
    800 	 * source address for packets routed back to the source, and
    801 	 * use that, if it's an address on the interface which
    802 	 * received the packet
    803 	 */
    804 	if (sin == NULL && rcvif) {
    805 		struct sockaddr_in sin_dst;
    806 		struct route icmproute;
    807 		int errornum;
    808 
    809 		sockaddr_in_init(&sin_dst, &ip->ip_dst, 0);
    810 		memset(&icmproute, 0, sizeof(icmproute));
    811 		errornum = 0;
    812 		ia = in_selectsrc(&sin_dst, &icmproute, 0, NULL, &errornum,
    813 		    &psref_ia);
    814 		/* errornum is never used */
    815 		rtcache_free(&icmproute);
    816 		/* check to make sure sin is a source address on rcvif */
    817 		if (ia != NULL) {
    818 			sin = &ia->ia_addr;
    819 			t = sin->sin_addr;
    820 			sin = NULL;
    821 			ia4_release(ia, &psref_ia);
    822 			ia = in_get_ia_on_iface_psref(t, rcvif, &psref_ia);
    823 			if (ia != NULL)
    824 				sin = &ia->ia_addr;
    825 		}
    826 	}
    827 
    828 	/*
    829 	 * if it was not addressed to us, but the route doesn't go out
    830 	 * the source interface, pick an address on the source
    831 	 * interface.  This can happen when routing is asymmetric, or
    832 	 * when the incoming packet was encapsulated
    833 	 */
    834 	if (sin == NULL && rcvif) {
    835 		KASSERT(ia == NULL);
    836 		s = pserialize_read_enter();
    837 		IFADDR_READER_FOREACH(ifa, rcvif) {
    838 			if (ifa->ifa_addr->sa_family != AF_INET)
    839 				continue;
    840 			sin = &(ifatoia(ifa)->ia_addr);
    841 			ia = ifatoia(ifa);
    842 			ia4_acquire(ia, &psref_ia);
    843 			break;
    844 		}
    845 		pserialize_read_exit(s);
    846 	}
    847 
    848 	m_put_rcvif_psref(rcvif, &psref);
    849 
    850 	/*
    851 	 * The following happens if the packet was not addressed to us,
    852 	 * and was received on an interface with no IP address:
    853 	 * We find the first AF_INET address on the first non-loopback
    854 	 * interface.
    855 	 */
    856 	if (sin == NULL) {
    857 		KASSERT(ia == NULL);
    858 		s = pserialize_read_enter();
    859 		IN_ADDRLIST_READER_FOREACH(ia) {
    860 			if (ia->ia_ifp->if_flags & IFF_LOOPBACK)
    861 				continue;
    862 			sin = &ia->ia_addr;
    863 			ia4_acquire(ia, &psref_ia);
    864 			break;
    865 		}
    866 		pserialize_read_exit(s);
    867 	}
    868 
    869 	/*
    870 	 * If we still didn't find an address, punt.  We could have an
    871 	 * interface up (and receiving packets) with no address.
    872 	 */
    873 	if (sin == NULL) {
    874 		KASSERT(ia == NULL);
    875 		m_freem(m);
    876 		goto done;
    877 	}
    878 
    879 	ip->ip_src = sin->sin_addr;
    880 	ip->ip_ttl = MAXTTL;
    881 
    882 	if (ia != NULL)
    883 		ia4_release(ia, &psref_ia);
    884 
    885 	if (optlen > 0) {
    886 		u_char *cp;
    887 		int opt, cnt;
    888 		u_int len;
    889 
    890 		/*
    891 		 * Retrieve any source routing from the incoming packet;
    892 		 * add on any record-route or timestamp options.
    893 		 */
    894 		cp = (u_char *)(ip + 1);
    895 		if ((opts = ip_srcroute(m)) == NULL &&
    896 		    (opts = m_gethdr(M_DONTWAIT, MT_HEADER))) {
    897 			MCLAIM(opts, m->m_owner);
    898 			opts->m_len = sizeof(struct in_addr);
    899 			*mtod(opts, struct in_addr *) = zeroin_addr;
    900 		}
    901 
    902 		if (opts) {
    903 #ifdef ICMPPRINTFS
    904 			if (icmpprintfs)
    905 				printf("icmp_reflect optlen %d rt %d => ",
    906 				    optlen, opts->m_len);
    907 #endif
    908 			for (cnt = optlen; cnt > 0; cnt -= len, cp += len) {
    909 				opt = cp[IPOPT_OPTVAL];
    910 				if (opt == IPOPT_EOL)
    911 					break;
    912 				if (opt == IPOPT_NOP)
    913 					len = 1;
    914 				else {
    915 					if (cnt < IPOPT_OLEN + sizeof(*cp))
    916 						break;
    917 					len = cp[IPOPT_OLEN];
    918 					if (len < IPOPT_OLEN + sizeof(*cp) ||
    919 					    len > cnt)
    920 						break;
    921 				}
    922 
    923 				/* Overflows can't happen */
    924 				KASSERT(opts->m_len + len <= MHLEN);
    925 
    926 				if (opt == IPOPT_RR || opt == IPOPT_TS ||
    927 				    opt == IPOPT_SECURITY) {
    928 					memmove(mtod(opts, char *) +
    929 					    opts->m_len, cp, len);
    930 					opts->m_len += len;
    931 				}
    932 			}
    933 
    934 			/* Terminate & pad, if necessary */
    935 			if ((cnt = opts->m_len % 4) != 0) {
    936 				for (; cnt < 4; cnt++) {
    937 					*(mtod(opts, char *) + opts->m_len) =
    938 					    IPOPT_EOL;
    939 					opts->m_len++;
    940 				}
    941 			}
    942 #ifdef ICMPPRINTFS
    943 			if (icmpprintfs)
    944 				printf("%d\n", opts->m_len);
    945 #endif
    946 		}
    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 static 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 static const u_int mtu_table[] = {
   1178 	65535, 65280, 32000, 17914, 9180, 8166,
   1179 	4352, 2002, 1492, 1006, 508, 296, 68, 0
   1180 };
   1181 
   1182 void
   1183 icmp_mtudisc(struct icmp *icp, struct in_addr faddr)
   1184 {
   1185 	struct icmp_mtudisc_callback *mc;
   1186 	struct sockaddr *dst = sintosa(&icmpsrc);
   1187 	struct rtentry *rt;
   1188 	u_long mtu = ntohs(icp->icmp_nextmtu);  /* Why a long?  IPv6 */
   1189 	int error;
   1190 
   1191 	rt = rtalloc1(dst, 1);
   1192 	if (rt == NULL)
   1193 		return;
   1194 
   1195 	/* If we didn't get a host route, allocate one */
   1196 	if ((rt->rt_flags & RTF_HOST) == 0) {
   1197 		struct rtentry *nrt;
   1198 
   1199 		error = rtrequest(RTM_ADD, dst, rt->rt_gateway, NULL,
   1200 		    RTF_GATEWAY | RTF_HOST | RTF_DYNAMIC, &nrt);
   1201 		if (error) {
   1202 			rt_unref(rt);
   1203 			return;
   1204 		}
   1205 		nrt->rt_rmx = rt->rt_rmx;
   1206 		rt_unref(rt);
   1207 		rt = nrt;
   1208 	}
   1209 
   1210 	mutex_enter(&icmp_mtx);
   1211 	error = rt_timer_add(rt, icmp_mtudisc_timeout, ip_mtudisc_timeout_q);
   1212 	mutex_exit(&icmp_mtx);
   1213 	if (error) {
   1214 		rt_unref(rt);
   1215 		return;
   1216 	}
   1217 
   1218 	if (mtu == 0) {
   1219 		int i = 0;
   1220 
   1221 		mtu = ntohs(icp->icmp_ip.ip_len);
   1222 		/* Some 4.2BSD-based routers incorrectly adjust the ip_len */
   1223 		if (mtu > rt->rt_rmx.rmx_mtu && rt->rt_rmx.rmx_mtu != 0)
   1224 			mtu -= (icp->icmp_ip.ip_hl << 2);
   1225 
   1226 		/* If we still can't guess a value, try the route */
   1227 		if (mtu == 0) {
   1228 			mtu = rt->rt_rmx.rmx_mtu;
   1229 
   1230 			/* If no route mtu, default to the interface mtu */
   1231 			if (mtu == 0)
   1232 				mtu = rt->rt_ifp->if_mtu;
   1233 		}
   1234 
   1235 		for (i = 0; i < sizeof(mtu_table) / sizeof(mtu_table[0]); i++) {
   1236 			if (mtu > mtu_table[i]) {
   1237 				mtu = mtu_table[i];
   1238 				break;
   1239 			}
   1240 		}
   1241 	}
   1242 
   1243 	/*
   1244 	 * XXX:   RTV_MTU is overloaded, since the admin can set it
   1245 	 *	  to turn off PMTU for a route, and the kernel can
   1246 	 *	  set it to indicate a serious problem with PMTU
   1247 	 *	  on a route.  We should be using a separate flag
   1248 	 *	  for the kernel to indicate this.
   1249 	 */
   1250 
   1251 	if ((rt->rt_rmx.rmx_locks & RTV_MTU) == 0) {
   1252 		if (mtu < 296 || mtu > rt->rt_ifp->if_mtu)
   1253 			rt->rt_rmx.rmx_locks |= RTV_MTU;
   1254 		else if (rt->rt_rmx.rmx_mtu > mtu ||
   1255 			 rt->rt_rmx.rmx_mtu == 0) {
   1256 			ICMP_STATINC(ICMP_STAT_PMTUCHG);
   1257 			rt->rt_rmx.rmx_mtu = mtu;
   1258 		}
   1259 	}
   1260 
   1261 	if (rt != NULL)
   1262 		rt_unref(rt);
   1263 
   1264 	/*
   1265 	 * Notify protocols that the MTU for this destination
   1266 	 * has changed.
   1267 	 */
   1268 	mutex_enter(&icmp_mtx);
   1269 	for (mc = LIST_FIRST(&icmp_mtudisc_callbacks); mc != NULL;
   1270 	     mc = LIST_NEXT(mc, mc_list))
   1271 		(*mc->mc_func)(faddr);
   1272 	mutex_exit(&icmp_mtx);
   1273 }
   1274 
   1275 /*
   1276  * Return the next larger or smaller MTU plateau (table from RFC 1191)
   1277  * given current value MTU.  If DIR is less than zero, a larger plateau
   1278  * is returned; otherwise, a smaller value is returned.
   1279  */
   1280 u_int
   1281 ip_next_mtu(u_int mtu, int dir)	/* XXX unused */
   1282 {
   1283 	int i;
   1284 
   1285 	for (i = 0; i < (sizeof mtu_table) / (sizeof mtu_table[0]); i++) {
   1286 		if (mtu >= mtu_table[i])
   1287 			break;
   1288 	}
   1289 
   1290 	if (dir < 0) {
   1291 		if (i == 0) {
   1292 			return 0;
   1293 		} else {
   1294 			return mtu_table[i - 1];
   1295 		}
   1296 	} else {
   1297 		if (mtu_table[i] == 0) {
   1298 			return 0;
   1299 		} else if (mtu > mtu_table[i]) {
   1300 			return mtu_table[i];
   1301 		} else {
   1302 			return mtu_table[i + 1];
   1303 		}
   1304 	}
   1305 }
   1306 
   1307 static void
   1308 icmp_mtudisc_timeout(struct rtentry *rt, struct rttimer *r)
   1309 {
   1310 
   1311 	KASSERT(rt != NULL);
   1312 	rt_assert_referenced(rt);
   1313 
   1314 	if ((rt->rt_flags & (RTF_DYNAMIC | RTF_HOST)) ==
   1315 	    (RTF_DYNAMIC | RTF_HOST)) {
   1316 		rtrequest(RTM_DELETE, rt_getkey(rt),
   1317 		    rt->rt_gateway, rt_mask(rt), rt->rt_flags, NULL);
   1318 	} else {
   1319 		if ((rt->rt_rmx.rmx_locks & RTV_MTU) == 0) {
   1320 			rt->rt_rmx.rmx_mtu = 0;
   1321 		}
   1322 	}
   1323 }
   1324 
   1325 static void
   1326 icmp_redirect_timeout(struct rtentry *rt, struct rttimer *r)
   1327 {
   1328 
   1329 	KASSERT(rt != NULL);
   1330 	rt_assert_referenced(rt);
   1331 
   1332 	if ((rt->rt_flags & (RTF_DYNAMIC | RTF_HOST)) ==
   1333 	    (RTF_DYNAMIC | RTF_HOST)) {
   1334 		rtrequest(RTM_DELETE, rt_getkey(rt),
   1335 		    rt->rt_gateway, rt_mask(rt), rt->rt_flags, NULL);
   1336 	}
   1337 }
   1338 
   1339 /*
   1340  * Perform rate limit check.
   1341  * Returns 0 if it is okay to send the icmp packet.
   1342  * Returns 1 if the router SHOULD NOT send this icmp packet due to rate
   1343  * limitation.
   1344  *
   1345  * XXX per-destination/type check necessary?
   1346  */
   1347 int
   1348 icmp_ratelimit(const struct in_addr *dst, const int type,
   1349     const int code)
   1350 {
   1351 
   1352 	/* PPS limit */
   1353 	if (!ppsratecheck(&icmperrppslim_last, &icmperrpps_count,
   1354 	    icmperrppslim)) {
   1355 		/* The packet is subject to rate limit */
   1356 		return 1;
   1357 	}
   1358 
   1359 	/* okay to send */
   1360 	return 0;
   1361 }
   1362