Home | History | Annotate | Line # | Download | only in netinet
ip_input.c revision 1.292
      1 /*	$NetBSD: ip_input.c,v 1.292 2010/12/11 22:37:46 matt 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 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  * 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  *
     49  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     50  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     51  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     52  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     53  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     54  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     55  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     56  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     57  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     58  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     59  * POSSIBILITY OF SUCH DAMAGE.
     60  */
     61 
     62 /*
     63  * Copyright (c) 1982, 1986, 1988, 1993
     64  *	The Regents of the University of California.  All rights reserved.
     65  *
     66  * Redistribution and use in source and binary forms, with or without
     67  * modification, are permitted provided that the following conditions
     68  * are met:
     69  * 1. Redistributions of source code must retain the above copyright
     70  *    notice, this list of conditions and the following disclaimer.
     71  * 2. Redistributions in binary form must reproduce the above copyright
     72  *    notice, this list of conditions and the following disclaimer in the
     73  *    documentation and/or other materials provided with the distribution.
     74  * 3. Neither the name of the University nor the names of its contributors
     75  *    may be used to endorse or promote products derived from this software
     76  *    without specific prior written permission.
     77  *
     78  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     79  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     80  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     81  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     82  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     83  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     84  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     85  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     86  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     87  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     88  * SUCH DAMAGE.
     89  *
     90  *	@(#)ip_input.c	8.2 (Berkeley) 1/4/94
     91  */
     92 
     93 #include <sys/cdefs.h>
     94 __KERNEL_RCSID(0, "$NetBSD: ip_input.c,v 1.292 2010/12/11 22:37:46 matt Exp $");
     95 
     96 #include "opt_inet.h"
     97 #include "opt_compat_netbsd.h"
     98 #include "opt_gateway.h"
     99 #include "opt_pfil_hooks.h"
    100 #include "opt_ipsec.h"
    101 #include "opt_mrouting.h"
    102 #include "opt_mbuftrace.h"
    103 #include "opt_inet_csum.h"
    104 
    105 #include <sys/param.h>
    106 #include <sys/systm.h>
    107 #include <sys/mbuf.h>
    108 #include <sys/domain.h>
    109 #include <sys/protosw.h>
    110 #include <sys/socket.h>
    111 #include <sys/socketvar.h>
    112 #include <sys/errno.h>
    113 #include <sys/time.h>
    114 #include <sys/kernel.h>
    115 #include <sys/pool.h>
    116 #include <sys/sysctl.h>
    117 #include <sys/kauth.h>
    118 
    119 #include <net/if.h>
    120 #include <net/if_dl.h>
    121 #include <net/route.h>
    122 #include <net/pfil.h>
    123 
    124 #include <netinet/in.h>
    125 #include <netinet/in_systm.h>
    126 #include <netinet/ip.h>
    127 #include <netinet/in_pcb.h>
    128 #include <netinet/in_proto.h>
    129 #include <netinet/in_var.h>
    130 #include <netinet/ip_var.h>
    131 #include <netinet/ip_private.h>
    132 #include <netinet/ip_icmp.h>
    133 /* just for gif_ttl */
    134 #include <netinet/in_gif.h>
    135 #include "gif.h"
    136 #include <net/if_gre.h>
    137 #include "gre.h"
    138 
    139 #ifdef MROUTING
    140 #include <netinet/ip_mroute.h>
    141 #endif
    142 
    143 #ifdef IPSEC
    144 #include <netinet6/ipsec.h>
    145 #include <netinet6/ipsec_private.h>
    146 #include <netkey/key.h>
    147 #endif
    148 #ifdef FAST_IPSEC
    149 #include <netipsec/ipsec.h>
    150 #include <netipsec/key.h>
    151 #endif	/* FAST_IPSEC*/
    152 
    153 #ifndef	IPFORWARDING
    154 #ifdef GATEWAY
    155 #define	IPFORWARDING	1	/* forward IP packets not for us */
    156 #else /* GATEWAY */
    157 #define	IPFORWARDING	0	/* don't forward IP packets not for us */
    158 #endif /* GATEWAY */
    159 #endif /* IPFORWARDING */
    160 #ifndef	IPSENDREDIRECTS
    161 #define	IPSENDREDIRECTS	1
    162 #endif
    163 #ifndef IPFORWSRCRT
    164 #define	IPFORWSRCRT	1	/* forward source-routed packets */
    165 #endif
    166 #ifndef IPALLOWSRCRT
    167 #define	IPALLOWSRCRT	1	/* allow source-routed packets */
    168 #endif
    169 #ifndef IPMTUDISC
    170 #define IPMTUDISC	1
    171 #endif
    172 #ifndef IPMTUDISCTIMEOUT
    173 #define IPMTUDISCTIMEOUT (10 * 60)	/* as per RFC 1191 */
    174 #endif
    175 
    176 #ifdef COMPAT_50
    177 #include <compat/sys/time.h>
    178 #include <compat/sys/socket.h>
    179 #endif
    180 
    181 /*
    182  * Note: DIRECTED_BROADCAST is handled this way so that previous
    183  * configuration using this option will Just Work.
    184  */
    185 #ifndef IPDIRECTEDBCAST
    186 #ifdef DIRECTED_BROADCAST
    187 #define IPDIRECTEDBCAST	1
    188 #else
    189 #define	IPDIRECTEDBCAST	0
    190 #endif /* DIRECTED_BROADCAST */
    191 #endif /* IPDIRECTEDBCAST */
    192 int	ipforwarding = IPFORWARDING;
    193 int	ipsendredirects = IPSENDREDIRECTS;
    194 int	ip_defttl = IPDEFTTL;
    195 int	ip_forwsrcrt = IPFORWSRCRT;
    196 int	ip_directedbcast = IPDIRECTEDBCAST;
    197 int	ip_allowsrcrt = IPALLOWSRCRT;
    198 int	ip_mtudisc = IPMTUDISC;
    199 int	ip_mtudisc_timeout = IPMTUDISCTIMEOUT;
    200 #ifdef DIAGNOSTIC
    201 int	ipprintfs = 0;
    202 #endif
    203 
    204 int	ip_do_randomid = 0;
    205 
    206 /*
    207  * XXX - Setting ip_checkinterface mostly implements the receive side of
    208  * the Strong ES model described in RFC 1122, but since the routing table
    209  * and transmit implementation do not implement the Strong ES model,
    210  * setting this to 1 results in an odd hybrid.
    211  *
    212  * XXX - ip_checkinterface currently must be disabled if you use ipnat
    213  * to translate the destination address to another local interface.
    214  *
    215  * XXX - ip_checkinterface must be disabled if you add IP aliases
    216  * to the loopback interface instead of the interface where the
    217  * packets for those addresses are received.
    218  */
    219 int	ip_checkinterface = 0;
    220 
    221 
    222 struct rttimer_queue *ip_mtudisc_timeout_q = NULL;
    223 
    224 int	ipqmaxlen = IFQ_MAXLEN;
    225 u_long	in_ifaddrhash;				/* size of hash table - 1 */
    226 int	in_ifaddrentries;			/* total number of addrs */
    227 struct in_ifaddrhead in_ifaddrhead;
    228 struct	in_ifaddrhashhead *in_ifaddrhashtbl;
    229 u_long	in_multihash;				/* size of hash table - 1 */
    230 int	in_multientries;			/* total number of addrs */
    231 struct	in_multihashhead *in_multihashtbl;
    232 struct	ifqueue ipintrq;
    233 
    234 ipid_state_t *		ip_ids;
    235 uint16_t ip_id;
    236 
    237 percpu_t *ipstat_percpu;
    238 
    239 #ifdef PFIL_HOOKS
    240 struct pfil_head inet_pfil_hook;
    241 #endif
    242 
    243 struct pool inmulti_pool;
    244 
    245 #ifdef INET_CSUM_COUNTERS
    246 #include <sys/device.h>
    247 
    248 struct evcnt ip_hwcsum_bad = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
    249     NULL, "inet", "hwcsum bad");
    250 struct evcnt ip_hwcsum_ok = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
    251     NULL, "inet", "hwcsum ok");
    252 struct evcnt ip_swcsum = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
    253     NULL, "inet", "swcsum");
    254 
    255 #define	INET_CSUM_COUNTER_INCR(ev)	(ev)->ev_count++
    256 
    257 EVCNT_ATTACH_STATIC(ip_hwcsum_bad);
    258 EVCNT_ATTACH_STATIC(ip_hwcsum_ok);
    259 EVCNT_ATTACH_STATIC(ip_swcsum);
    260 
    261 #else
    262 
    263 #define	INET_CSUM_COUNTER_INCR(ev)	/* nothing */
    264 
    265 #endif /* INET_CSUM_COUNTERS */
    266 
    267 /*
    268  * We need to save the IP options in case a protocol wants to respond
    269  * to an incoming packet over the same route if the packet got here
    270  * using IP source routing.  This allows connection establishment and
    271  * maintenance when the remote end is on a network that is not known
    272  * to us.
    273  */
    274 int	ip_nhops = 0;
    275 static	struct ip_srcrt {
    276 	struct	in_addr dst;			/* final destination */
    277 	char	nop;				/* one NOP to align */
    278 	char	srcopt[IPOPT_OFFSET + 1];	/* OPTVAL, OLEN and OFFSET */
    279 	struct	in_addr route[MAX_IPOPTLEN/sizeof(struct in_addr)];
    280 } ip_srcrt;
    281 
    282 static void save_rte(u_char *, struct in_addr);
    283 
    284 #ifdef MBUFTRACE
    285 struct mowner ip_rx_mowner = MOWNER_INIT("internet", "rx");
    286 struct mowner ip_tx_mowner = MOWNER_INIT("internet", "tx");
    287 #endif
    288 
    289 static void sysctl_net_inet_ip_setup(struct sysctllog **);
    290 
    291 /*
    292  * IP initialization: fill in IP protocol switch table.
    293  * All protocols not implemented in kernel go to raw IP protocol handler.
    294  */
    295 void
    296 ip_init(void)
    297 {
    298 	const struct protosw *pr;
    299 	int i;
    300 
    301 	sysctl_net_inet_ip_setup(NULL);
    302 
    303 	pool_init(&inmulti_pool, sizeof(struct in_multi), 0, 0, 0, "inmltpl",
    304 	    NULL, IPL_SOFTNET);
    305 
    306 	pr = pffindproto(PF_INET, IPPROTO_RAW, SOCK_RAW);
    307 	if (pr == 0)
    308 		panic("ip_init");
    309 	for (i = 0; i < IPPROTO_MAX; i++)
    310 		ip_protox[i] = pr - inetsw;
    311 	for (pr = inetdomain.dom_protosw;
    312 	    pr < inetdomain.dom_protoswNPROTOSW; pr++)
    313 		if (pr->pr_domain->dom_family == PF_INET &&
    314 		    pr->pr_protocol && pr->pr_protocol != IPPROTO_RAW)
    315 			ip_protox[pr->pr_protocol] = pr - inetsw;
    316 
    317 	ip_reass_init();
    318 
    319 	ip_ids = ip_id_init();
    320 	ip_id = time_second & 0xfffff;
    321 
    322 	ipintrq.ifq_maxlen = ipqmaxlen;
    323 
    324 	TAILQ_INIT(&in_ifaddrhead);
    325 	in_ifaddrhashtbl = hashinit(IN_IFADDR_HASH_SIZE, HASH_LIST, true,
    326 	    &in_ifaddrhash);
    327 	in_multihashtbl = hashinit(IN_IFADDR_HASH_SIZE, HASH_LIST, true,
    328 	    &in_multihash);
    329 	ip_mtudisc_timeout_q = rt_timer_queue_create(ip_mtudisc_timeout);
    330 #ifdef GATEWAY
    331 	ipflow_init(ip_hashsize);
    332 #endif
    333 
    334 #ifdef PFIL_HOOKS
    335 	/* Register our Packet Filter hook. */
    336 	inet_pfil_hook.ph_type = PFIL_TYPE_AF;
    337 	inet_pfil_hook.ph_af   = AF_INET;
    338 	i = pfil_head_register(&inet_pfil_hook);
    339 	if (i != 0)
    340 		printf("ip_init: WARNING: unable to register pfil hook, "
    341 		    "error %d\n", i);
    342 #endif /* PFIL_HOOKS */
    343 
    344 #ifdef MBUFTRACE
    345 	MOWNER_ATTACH(&ip_tx_mowner);
    346 	MOWNER_ATTACH(&ip_rx_mowner);
    347 #endif /* MBUFTRACE */
    348 
    349 	ipstat_percpu = percpu_alloc(sizeof(uint64_t) * IP_NSTATS);
    350 }
    351 
    352 struct	sockaddr_in ipaddr = {
    353 	.sin_len = sizeof(ipaddr),
    354 	.sin_family = AF_INET,
    355 };
    356 struct	route ipforward_rt;
    357 
    358 /*
    359  * IP software interrupt routine
    360  */
    361 void
    362 ipintr(void)
    363 {
    364 	int s;
    365 	struct mbuf *m;
    366 	struct ifqueue lcl_intrq;
    367 
    368 	memset(&lcl_intrq, 0, sizeof(lcl_intrq));
    369 	ipintrq.ifq_maxlen = ipqmaxlen;
    370 
    371 	mutex_enter(softnet_lock);
    372 	KERNEL_LOCK(1, NULL);
    373 	if (!IF_IS_EMPTY(&ipintrq)) {
    374 		s = splnet();
    375 
    376 		/* Take existing queue onto stack */
    377 		lcl_intrq = ipintrq;
    378 
    379 		/* Zero out global queue, preserving maxlen and drops */
    380 		ipintrq.ifq_head = NULL;
    381 		ipintrq.ifq_tail = NULL;
    382 		ipintrq.ifq_len = 0;
    383 		ipintrq.ifq_maxlen = lcl_intrq.ifq_maxlen;
    384 		ipintrq.ifq_drops = lcl_intrq.ifq_drops;
    385 
    386 		splx(s);
    387 	}
    388 	KERNEL_UNLOCK_ONE(NULL);
    389 	while (!IF_IS_EMPTY(&lcl_intrq)) {
    390 		IF_DEQUEUE(&lcl_intrq, m);
    391 		if (m == NULL)
    392 			break;
    393 		KERNEL_UNLOCK_ONE(NULL);
    394 		ip_input(m);
    395 		KERNEL_LOCK(1, NULL);
    396 	}
    397 	mutex_exit(softnet_lock);
    398 }
    399 
    400 /*
    401  * Ip input routine.  Checksum and byte swap header.  If fragmented
    402  * try to reassemble.  Process options.  Pass to next level.
    403  */
    404 void
    405 ip_input(struct mbuf *m)
    406 {
    407 	struct ip *ip = NULL;
    408 	struct in_ifaddr *ia;
    409 	struct ifaddr *ifa;
    410 	int hlen = 0, len;
    411 	int downmatch;
    412 	int checkif;
    413 	int srcrt = 0;
    414 #ifdef FAST_IPSEC
    415 	struct m_tag *mtag;
    416 	struct tdb_ident *tdbi;
    417 	struct secpolicy *sp;
    418 	int error, s;
    419 #endif /* FAST_IPSEC */
    420 
    421 	MCLAIM(m, &ip_rx_mowner);
    422 	KASSERT((m->m_flags & M_PKTHDR) != 0);
    423 
    424 	/*
    425 	 * If no IP addresses have been set yet but the interfaces
    426 	 * are receiving, can't do anything with incoming packets yet.
    427 	 */
    428 	if (TAILQ_FIRST(&in_ifaddrhead) == 0)
    429 		goto bad;
    430 	IP_STATINC(IP_STAT_TOTAL);
    431 	/*
    432 	 * If the IP header is not aligned, slurp it up into a new
    433 	 * mbuf with space for link headers, in the event we forward
    434 	 * it.  Otherwise, if it is aligned, make sure the entire
    435 	 * base IP header is in the first mbuf of the chain.
    436 	 */
    437 	if (IP_HDR_ALIGNED_P(mtod(m, void *)) == 0) {
    438 		if ((m = m_copyup(m, sizeof(struct ip),
    439 				  (max_linkhdr + 3) & ~3)) == NULL) {
    440 			/* XXXJRT new stat, please */
    441 			IP_STATINC(IP_STAT_TOOSMALL);
    442 			return;
    443 		}
    444 	} else if (__predict_false(m->m_len < sizeof (struct ip))) {
    445 		if ((m = m_pullup(m, sizeof (struct ip))) == NULL) {
    446 			IP_STATINC(IP_STAT_TOOSMALL);
    447 			return;
    448 		}
    449 	}
    450 	ip = mtod(m, struct ip *);
    451 	if (ip->ip_v != IPVERSION) {
    452 		IP_STATINC(IP_STAT_BADVERS);
    453 		goto bad;
    454 	}
    455 	hlen = ip->ip_hl << 2;
    456 	if (hlen < sizeof(struct ip)) {	/* minimum header length */
    457 		IP_STATINC(IP_STAT_BADHLEN);
    458 		goto bad;
    459 	}
    460 	if (hlen > m->m_len) {
    461 		if ((m = m_pullup(m, hlen)) == 0) {
    462 			IP_STATINC(IP_STAT_BADHLEN);
    463 			return;
    464 		}
    465 		ip = mtod(m, struct ip *);
    466 	}
    467 
    468 	/*
    469 	 * RFC1122: packets with a multicast source address are
    470 	 * not allowed.
    471 	 */
    472 	if (IN_MULTICAST(ip->ip_src.s_addr)) {
    473 		IP_STATINC(IP_STAT_BADADDR);
    474 		goto bad;
    475 	}
    476 
    477 	/* 127/8 must not appear on wire - RFC1122 */
    478 	if ((ntohl(ip->ip_dst.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET ||
    479 	    (ntohl(ip->ip_src.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET) {
    480 		if ((m->m_pkthdr.rcvif->if_flags & IFF_LOOPBACK) == 0) {
    481 			IP_STATINC(IP_STAT_BADADDR);
    482 			goto bad;
    483 		}
    484 	}
    485 
    486 	switch (m->m_pkthdr.csum_flags &
    487 		((m->m_pkthdr.rcvif->if_csum_flags_rx & M_CSUM_IPv4) |
    488 		 M_CSUM_IPv4_BAD)) {
    489 	case M_CSUM_IPv4|M_CSUM_IPv4_BAD:
    490 		INET_CSUM_COUNTER_INCR(&ip_hwcsum_bad);
    491 		goto badcsum;
    492 
    493 	case M_CSUM_IPv4:
    494 		/* Checksum was okay. */
    495 		INET_CSUM_COUNTER_INCR(&ip_hwcsum_ok);
    496 		break;
    497 
    498 	default:
    499 		/*
    500 		 * Must compute it ourselves.  Maybe skip checksum on
    501 		 * loopback interfaces.
    502 		 */
    503 		if (__predict_true(!(m->m_pkthdr.rcvif->if_flags &
    504 				     IFF_LOOPBACK) || ip_do_loopback_cksum)) {
    505 			INET_CSUM_COUNTER_INCR(&ip_swcsum);
    506 			if (in_cksum(m, hlen) != 0)
    507 				goto badcsum;
    508 		}
    509 		break;
    510 	}
    511 
    512 	/* Retrieve the packet length. */
    513 	len = ntohs(ip->ip_len);
    514 
    515 	/*
    516 	 * Check for additional length bogosity
    517 	 */
    518 	if (len < hlen) {
    519 		IP_STATINC(IP_STAT_BADLEN);
    520 		goto bad;
    521 	}
    522 
    523 	/*
    524 	 * Check that the amount of data in the buffers
    525 	 * is as at least much as the IP header would have us expect.
    526 	 * Trim mbufs if longer than we expect.
    527 	 * Drop packet if shorter than we expect.
    528 	 */
    529 	if (m->m_pkthdr.len < len) {
    530 		IP_STATINC(IP_STAT_TOOSHORT);
    531 		goto bad;
    532 	}
    533 	if (m->m_pkthdr.len > len) {
    534 		if (m->m_len == m->m_pkthdr.len) {
    535 			m->m_len = len;
    536 			m->m_pkthdr.len = len;
    537 		} else
    538 			m_adj(m, len - m->m_pkthdr.len);
    539 	}
    540 
    541 #if defined(IPSEC)
    542 	/* ipflow (IP fast forwarding) is not compatible with IPsec. */
    543 	m->m_flags &= ~M_CANFASTFWD;
    544 #else
    545 	/*
    546 	 * Assume that we can create a fast-forward IP flow entry
    547 	 * based on this packet.
    548 	 */
    549 	m->m_flags |= M_CANFASTFWD;
    550 #endif
    551 
    552 #ifdef PFIL_HOOKS
    553 	/*
    554 	 * Run through list of hooks for input packets.  If there are any
    555 	 * filters which require that additional packets in the flow are
    556 	 * not fast-forwarded, they must clear the M_CANFASTFWD flag.
    557 	 * Note that filters must _never_ set this flag, as another filter
    558 	 * in the list may have previously cleared it.
    559 	 */
    560 	/*
    561 	 * let ipfilter look at packet on the wire,
    562 	 * not the decapsulated packet.
    563 	 */
    564 #ifdef IPSEC
    565 	if (!ipsec_getnhist(m))
    566 #elif defined(FAST_IPSEC)
    567 	if (!ipsec_indone(m))
    568 #else
    569 	if (1)
    570 #endif
    571 	{
    572 		struct in_addr odst;
    573 
    574 		odst = ip->ip_dst;
    575 		if (pfil_run_hooks(&inet_pfil_hook, &m, m->m_pkthdr.rcvif,
    576 		    PFIL_IN) != 0)
    577 			return;
    578 		if (m == NULL)
    579 			return;
    580 		ip = mtod(m, struct ip *);
    581 		hlen = ip->ip_hl << 2;
    582 		/*
    583 		 * XXX The setting of "srcrt" here is to prevent ip_forward()
    584 		 * from generating ICMP redirects for packets that have
    585 		 * been redirected by a hook back out on to the same LAN that
    586 		 * they came from and is not an indication that the packet
    587 		 * is being inffluenced by source routing options.  This
    588 		 * allows things like
    589 		 * "rdr tlp0 0/0 port 80 -> 1.1.1.200 3128 tcp"
    590 		 * where tlp0 is both on the 1.1.1.0/24 network and is the
    591 		 * default route for hosts on 1.1.1.0/24.  Of course this
    592 		 * also requires a "map tlp0 ..." to complete the story.
    593 		 * One might argue whether or not this kind of network config.
    594 		 * should be supported in this manner...
    595 		 */
    596 		srcrt = (odst.s_addr != ip->ip_dst.s_addr);
    597 	}
    598 #endif /* PFIL_HOOKS */
    599 
    600 #ifdef ALTQ
    601 	/* XXX Temporary until ALTQ is changed to use a pfil hook */
    602 	if (altq_input != NULL && (*altq_input)(m, AF_INET) == 0) {
    603 		/* packet dropped by traffic conditioner */
    604 		return;
    605 	}
    606 #endif
    607 
    608 	/*
    609 	 * Process options and, if not destined for us,
    610 	 * ship it on.  ip_dooptions returns 1 when an
    611 	 * error was detected (causing an icmp message
    612 	 * to be sent and the original packet to be freed).
    613 	 */
    614 	ip_nhops = 0;		/* for source routed packets */
    615 	if (hlen > sizeof (struct ip) && ip_dooptions(m))
    616 		return;
    617 
    618 	/*
    619 	 * Enable a consistency check between the destination address
    620 	 * and the arrival interface for a unicast packet (the RFC 1122
    621 	 * strong ES model) if IP forwarding is disabled and the packet
    622 	 * is not locally generated.
    623 	 *
    624 	 * XXX - Checking also should be disabled if the destination
    625 	 * address is ipnat'ed to a different interface.
    626 	 *
    627 	 * XXX - Checking is incompatible with IP aliases added
    628 	 * to the loopback interface instead of the interface where
    629 	 * the packets are received.
    630 	 *
    631 	 * XXX - We need to add a per ifaddr flag for this so that
    632 	 * we get finer grain control.
    633 	 */
    634 	checkif = ip_checkinterface && (ipforwarding == 0) &&
    635 	    (m->m_pkthdr.rcvif != NULL) &&
    636 	    ((m->m_pkthdr.rcvif->if_flags & IFF_LOOPBACK) == 0);
    637 
    638 	/*
    639 	 * Check our list of addresses, to see if the packet is for us.
    640 	 *
    641 	 * Traditional 4.4BSD did not consult IFF_UP at all.
    642 	 * The behavior here is to treat addresses on !IFF_UP interface
    643 	 * as not mine.
    644 	 */
    645 	downmatch = 0;
    646 	LIST_FOREACH(ia, &IN_IFADDR_HASH(ip->ip_dst.s_addr), ia_hash) {
    647 		if (in_hosteq(ia->ia_addr.sin_addr, ip->ip_dst)) {
    648 			if (checkif && ia->ia_ifp != m->m_pkthdr.rcvif)
    649 				continue;
    650 			if ((ia->ia_ifp->if_flags & IFF_UP) != 0)
    651 				break;
    652 			else
    653 				downmatch++;
    654 		}
    655 	}
    656 	if (ia != NULL)
    657 		goto ours;
    658 	if (m->m_pkthdr.rcvif && m->m_pkthdr.rcvif->if_flags & IFF_BROADCAST) {
    659 		IFADDR_FOREACH(ifa, m->m_pkthdr.rcvif) {
    660 			if (ifa->ifa_addr->sa_family != AF_INET)
    661 				continue;
    662 			ia = ifatoia(ifa);
    663 			if (in_hosteq(ip->ip_dst, ia->ia_broadaddr.sin_addr) ||
    664 			    in_hosteq(ip->ip_dst, ia->ia_netbroadcast) ||
    665 			    /*
    666 			     * Look for all-0's host part (old broadcast addr),
    667 			     * either for subnet or net.
    668 			     */
    669 			    ip->ip_dst.s_addr == ia->ia_subnet ||
    670 			    ip->ip_dst.s_addr == ia->ia_net)
    671 				goto ours;
    672 			/*
    673 			 * An interface with IP address zero accepts
    674 			 * all packets that arrive on that interface.
    675 			 */
    676 			if (in_nullhost(ia->ia_addr.sin_addr))
    677 				goto ours;
    678 		}
    679 	}
    680 	if (IN_MULTICAST(ip->ip_dst.s_addr)) {
    681 		struct in_multi *inm;
    682 #ifdef MROUTING
    683 		extern struct socket *ip_mrouter;
    684 
    685 		if (ip_mrouter) {
    686 			/*
    687 			 * If we are acting as a multicast router, all
    688 			 * incoming multicast packets are passed to the
    689 			 * kernel-level multicast forwarding function.
    690 			 * The packet is returned (relatively) intact; if
    691 			 * ip_mforward() returns a non-zero value, the packet
    692 			 * must be discarded, else it may be accepted below.
    693 			 *
    694 			 * (The IP ident field is put in the same byte order
    695 			 * as expected when ip_mforward() is called from
    696 			 * ip_output().)
    697 			 */
    698 			if (ip_mforward(m, m->m_pkthdr.rcvif) != 0) {
    699 				IP_STATINC(IP_STAT_CANTFORWARD);
    700 				m_freem(m);
    701 				return;
    702 			}
    703 
    704 			/*
    705 			 * The process-level routing demon needs to receive
    706 			 * all multicast IGMP packets, whether or not this
    707 			 * host belongs to their destination groups.
    708 			 */
    709 			if (ip->ip_p == IPPROTO_IGMP)
    710 				goto ours;
    711 			IP_STATINC(IP_STAT_CANTFORWARD);
    712 		}
    713 #endif
    714 		/*
    715 		 * See if we belong to the destination multicast group on the
    716 		 * arrival interface.
    717 		 */
    718 		IN_LOOKUP_MULTI(ip->ip_dst, m->m_pkthdr.rcvif, inm);
    719 		if (inm == NULL) {
    720 			IP_STATINC(IP_STAT_CANTFORWARD);
    721 			m_freem(m);
    722 			return;
    723 		}
    724 		goto ours;
    725 	}
    726 	if (ip->ip_dst.s_addr == INADDR_BROADCAST ||
    727 	    in_nullhost(ip->ip_dst))
    728 		goto ours;
    729 
    730 	/*
    731 	 * Not for us; forward if possible and desirable.
    732 	 */
    733 	if (ipforwarding == 0) {
    734 		IP_STATINC(IP_STAT_CANTFORWARD);
    735 		m_freem(m);
    736 	} else {
    737 		/*
    738 		 * If ip_dst matched any of my address on !IFF_UP interface,
    739 		 * and there's no IFF_UP interface that matches ip_dst,
    740 		 * send icmp unreach.  Forwarding it will result in in-kernel
    741 		 * forwarding loop till TTL goes to 0.
    742 		 */
    743 		if (downmatch) {
    744 			icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_HOST, 0, 0);
    745 			IP_STATINC(IP_STAT_CANTFORWARD);
    746 			return;
    747 		}
    748 #ifdef IPSEC
    749 		if (ipsec4_in_reject(m, NULL)) {
    750 			IPSEC_STATINC(IPSEC_STAT_IN_POLVIO);
    751 			goto bad;
    752 		}
    753 #endif
    754 #ifdef FAST_IPSEC
    755 		mtag = m_tag_find(m, PACKET_TAG_IPSEC_IN_DONE, NULL);
    756 		s = splsoftnet();
    757 		if (mtag != NULL) {
    758 			tdbi = (struct tdb_ident *)(mtag + 1);
    759 			sp = ipsec_getpolicy(tdbi, IPSEC_DIR_INBOUND);
    760 		} else {
    761 			sp = ipsec_getpolicybyaddr(m, IPSEC_DIR_INBOUND,
    762 						   IP_FORWARDING, &error);
    763 		}
    764 		if (sp == NULL) {	/* NB: can happen if error */
    765 			splx(s);
    766 			/*XXX error stat???*/
    767 			DPRINTF(("ip_input: no SP for forwarding\n"));	/*XXX*/
    768 			goto bad;
    769 		}
    770 
    771 		/*
    772 		 * Check security policy against packet attributes.
    773 		 */
    774 		error = ipsec_in_reject(sp, m);
    775 		KEY_FREESP(&sp);
    776 		splx(s);
    777 		if (error) {
    778 			IP_STATINC(IP_STAT_CANTFORWARD);
    779 			goto bad;
    780 		}
    781 
    782 		/*
    783 		 * Peek at the outbound SP for this packet to determine if
    784 		 * it's a Fast Forward candidate.
    785 		 */
    786 		mtag = m_tag_find(m, PACKET_TAG_IPSEC_PENDING_TDB, NULL);
    787 		if (mtag != NULL)
    788 			m->m_flags &= ~M_CANFASTFWD;
    789 		else {
    790 			s = splsoftnet();
    791 			sp = ipsec4_checkpolicy(m, IPSEC_DIR_OUTBOUND,
    792 			    (IP_FORWARDING |
    793 			     (ip_directedbcast ? IP_ALLOWBROADCAST : 0)),
    794 			    &error, NULL);
    795 			if (sp != NULL) {
    796 				m->m_flags &= ~M_CANFASTFWD;
    797 				KEY_FREESP(&sp);
    798 			}
    799 			splx(s);
    800 		}
    801 #endif	/* FAST_IPSEC */
    802 
    803 		ip_forward(m, srcrt);
    804 	}
    805 	return;
    806 
    807 ours:
    808 	/*
    809 	 * If offset or IP_MF are set, must reassemble.
    810 	 */
    811 	if (ip->ip_off & ~htons(IP_DF|IP_RF)) {
    812 		/*
    813 		 * Pass to IP reassembly mechanism.
    814 		 */
    815 		if (ip_reass_packet(&m, ip) != 0) {
    816 			/* Failed; invalid fragment(s) or packet. */
    817 			goto bad;
    818 		}
    819 		if (m == NULL) {
    820 			/* More fragments should come; silently return. */
    821 			return;
    822 		}
    823 		/*
    824 		 * Reassembly is done, we have the final packet.
    825 		 * Updated cached data in local variable(s).
    826 		 */
    827 		ip = mtod(m, struct ip *);
    828 		hlen = ip->ip_hl << 2;
    829 	}
    830 
    831 #if defined(IPSEC)
    832 	/*
    833 	 * enforce IPsec policy checking if we are seeing last header.
    834 	 * note that we do not visit this with protocols with pcb layer
    835 	 * code - like udp/tcp/raw ip.
    836 	 */
    837 	if ((inetsw[ip_protox[ip->ip_p]].pr_flags & PR_LASTHDR) != 0 &&
    838 	    ipsec4_in_reject(m, NULL)) {
    839 		IPSEC_STATINC(IPSEC_STAT_IN_POLVIO);
    840 		goto bad;
    841 	}
    842 #endif
    843 #ifdef FAST_IPSEC
    844 	/*
    845 	 * enforce IPsec policy checking if we are seeing last header.
    846 	 * note that we do not visit this with protocols with pcb layer
    847 	 * code - like udp/tcp/raw ip.
    848 	 */
    849 	if ((inetsw[ip_protox[ip->ip_p]].pr_flags & PR_LASTHDR) != 0) {
    850 		/*
    851 		 * Check if the packet has already had IPsec processing
    852 		 * done.  If so, then just pass it along.  This tag gets
    853 		 * set during AH, ESP, etc. input handling, before the
    854 		 * packet is returned to the ip input queue for delivery.
    855 		 */
    856 		mtag = m_tag_find(m, PACKET_TAG_IPSEC_IN_DONE, NULL);
    857 		s = splsoftnet();
    858 		if (mtag != NULL) {
    859 			tdbi = (struct tdb_ident *)(mtag + 1);
    860 			sp = ipsec_getpolicy(tdbi, IPSEC_DIR_INBOUND);
    861 		} else {
    862 			sp = ipsec_getpolicybyaddr(m, IPSEC_DIR_INBOUND,
    863 						   IP_FORWARDING, &error);
    864 		}
    865 		if (sp != NULL) {
    866 			/*
    867 			 * Check security policy against packet attributes.
    868 			 */
    869 			error = ipsec_in_reject(sp, m);
    870 			KEY_FREESP(&sp);
    871 		} else {
    872 			/* XXX error stat??? */
    873 			error = EINVAL;
    874 DPRINTF(("ip_input: no SP, packet discarded\n"));/*XXX*/
    875 		}
    876 		splx(s);
    877 		if (error)
    878 			goto bad;
    879 	}
    880 #endif /* FAST_IPSEC */
    881 
    882 	/*
    883 	 * Switch out to protocol's input routine.
    884 	 */
    885 #if IFA_STATS
    886 	if (ia && ip)
    887 		ia->ia_ifa.ifa_data.ifad_inbytes += ntohs(ip->ip_len);
    888 #endif
    889 	IP_STATINC(IP_STAT_DELIVERED);
    890     {
    891 	int off = hlen, nh = ip->ip_p;
    892 
    893 	(*inetsw[ip_protox[nh]].pr_input)(m, off, nh);
    894 	return;
    895     }
    896 bad:
    897 	m_freem(m);
    898 	return;
    899 
    900 badcsum:
    901 	IP_STATINC(IP_STAT_BADSUM);
    902 	m_freem(m);
    903 }
    904 
    905 /*
    906  * IP timer processing.
    907  */
    908 void
    909 ip_slowtimo(void)
    910 {
    911 
    912 	mutex_enter(softnet_lock);
    913 	KERNEL_LOCK(1, NULL);
    914 
    915 	ip_reass_slowtimo();
    916 
    917 	KERNEL_UNLOCK_ONE(NULL);
    918 	mutex_exit(softnet_lock);
    919 }
    920 
    921 /*
    922  * IP drain processing.
    923  */
    924 void
    925 ip_drain(void)
    926 {
    927 
    928 	KERNEL_LOCK(1, NULL);
    929 	ip_reass_drain();
    930 	KERNEL_UNLOCK_ONE(NULL);
    931 }
    932 
    933 /*
    934  * Do option processing on a datagram,
    935  * possibly discarding it if bad options are encountered,
    936  * or forwarding it if source-routed.
    937  * Returns 1 if packet has been forwarded/freed,
    938  * 0 if the packet should be processed further.
    939  */
    940 int
    941 ip_dooptions(struct mbuf *m)
    942 {
    943 	struct ip *ip = mtod(m, struct ip *);
    944 	u_char *cp, *cp0;
    945 	struct ip_timestamp *ipt;
    946 	struct in_ifaddr *ia;
    947 	int opt, optlen, cnt, off, code, type = ICMP_PARAMPROB, forward = 0;
    948 	struct in_addr dst;
    949 	n_time ntime;
    950 
    951 	dst = ip->ip_dst;
    952 	cp = (u_char *)(ip + 1);
    953 	cnt = (ip->ip_hl << 2) - sizeof (struct ip);
    954 	for (; cnt > 0; cnt -= optlen, cp += optlen) {
    955 		opt = cp[IPOPT_OPTVAL];
    956 		if (opt == IPOPT_EOL)
    957 			break;
    958 		if (opt == IPOPT_NOP)
    959 			optlen = 1;
    960 		else {
    961 			if (cnt < IPOPT_OLEN + sizeof(*cp)) {
    962 				code = &cp[IPOPT_OLEN] - (u_char *)ip;
    963 				goto bad;
    964 			}
    965 			optlen = cp[IPOPT_OLEN];
    966 			if (optlen < IPOPT_OLEN + sizeof(*cp) || optlen > cnt) {
    967 				code = &cp[IPOPT_OLEN] - (u_char *)ip;
    968 				goto bad;
    969 			}
    970 		}
    971 		switch (opt) {
    972 
    973 		default:
    974 			break;
    975 
    976 		/*
    977 		 * Source routing with record.
    978 		 * Find interface with current destination address.
    979 		 * If none on this machine then drop if strictly routed,
    980 		 * or do nothing if loosely routed.
    981 		 * Record interface address and bring up next address
    982 		 * component.  If strictly routed make sure next
    983 		 * address is on directly accessible net.
    984 		 */
    985 		case IPOPT_LSRR:
    986 		case IPOPT_SSRR:
    987 			if (ip_allowsrcrt == 0) {
    988 				type = ICMP_UNREACH;
    989 				code = ICMP_UNREACH_NET_PROHIB;
    990 				goto bad;
    991 			}
    992 			if (optlen < IPOPT_OFFSET + sizeof(*cp)) {
    993 				code = &cp[IPOPT_OLEN] - (u_char *)ip;
    994 				goto bad;
    995 			}
    996 			if ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {
    997 				code = &cp[IPOPT_OFFSET] - (u_char *)ip;
    998 				goto bad;
    999 			}
   1000 			ipaddr.sin_addr = ip->ip_dst;
   1001 			ia = ifatoia(ifa_ifwithaddr(sintosa(&ipaddr)));
   1002 			if (ia == 0) {
   1003 				if (opt == IPOPT_SSRR) {
   1004 					type = ICMP_UNREACH;
   1005 					code = ICMP_UNREACH_SRCFAIL;
   1006 					goto bad;
   1007 				}
   1008 				/*
   1009 				 * Loose routing, and not at next destination
   1010 				 * yet; nothing to do except forward.
   1011 				 */
   1012 				break;
   1013 			}
   1014 			off--;			/* 0 origin */
   1015 			if ((off + sizeof(struct in_addr)) > optlen) {
   1016 				/*
   1017 				 * End of source route.  Should be for us.
   1018 				 */
   1019 				save_rte(cp, ip->ip_src);
   1020 				break;
   1021 			}
   1022 			/*
   1023 			 * locate outgoing interface
   1024 			 */
   1025 			memcpy((void *)&ipaddr.sin_addr, (void *)(cp + off),
   1026 			    sizeof(ipaddr.sin_addr));
   1027 			if (opt == IPOPT_SSRR)
   1028 				ia = ifatoia(ifa_ifwithladdr(sintosa(&ipaddr)));
   1029 			else
   1030 				ia = ip_rtaddr(ipaddr.sin_addr);
   1031 			if (ia == 0) {
   1032 				type = ICMP_UNREACH;
   1033 				code = ICMP_UNREACH_SRCFAIL;
   1034 				goto bad;
   1035 			}
   1036 			ip->ip_dst = ipaddr.sin_addr;
   1037 			bcopy((void *)&ia->ia_addr.sin_addr,
   1038 			    (void *)(cp + off), sizeof(struct in_addr));
   1039 			cp[IPOPT_OFFSET] += sizeof(struct in_addr);
   1040 			/*
   1041 			 * Let ip_intr's mcast routing check handle mcast pkts
   1042 			 */
   1043 			forward = !IN_MULTICAST(ip->ip_dst.s_addr);
   1044 			break;
   1045 
   1046 		case IPOPT_RR:
   1047 			if (optlen < IPOPT_OFFSET + sizeof(*cp)) {
   1048 				code = &cp[IPOPT_OLEN] - (u_char *)ip;
   1049 				goto bad;
   1050 			}
   1051 			if ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {
   1052 				code = &cp[IPOPT_OFFSET] - (u_char *)ip;
   1053 				goto bad;
   1054 			}
   1055 			/*
   1056 			 * If no space remains, ignore.
   1057 			 */
   1058 			off--;			/* 0 origin */
   1059 			if ((off + sizeof(struct in_addr)) > optlen)
   1060 				break;
   1061 			memcpy((void *)&ipaddr.sin_addr, (void *)(&ip->ip_dst),
   1062 			    sizeof(ipaddr.sin_addr));
   1063 			/*
   1064 			 * locate outgoing interface; if we're the destination,
   1065 			 * use the incoming interface (should be same).
   1066 			 */
   1067 			if ((ia = ifatoia(ifa_ifwithaddr(sintosa(&ipaddr))))
   1068 			    == NULL &&
   1069 			    (ia = ip_rtaddr(ipaddr.sin_addr)) == NULL) {
   1070 				type = ICMP_UNREACH;
   1071 				code = ICMP_UNREACH_HOST;
   1072 				goto bad;
   1073 			}
   1074 			bcopy((void *)&ia->ia_addr.sin_addr,
   1075 			    (void *)(cp + off), sizeof(struct in_addr));
   1076 			cp[IPOPT_OFFSET] += sizeof(struct in_addr);
   1077 			break;
   1078 
   1079 		case IPOPT_TS:
   1080 			code = cp - (u_char *)ip;
   1081 			ipt = (struct ip_timestamp *)cp;
   1082 			if (ipt->ipt_len < 4 || ipt->ipt_len > 40) {
   1083 				code = (u_char *)&ipt->ipt_len - (u_char *)ip;
   1084 				goto bad;
   1085 			}
   1086 			if (ipt->ipt_ptr < 5) {
   1087 				code = (u_char *)&ipt->ipt_ptr - (u_char *)ip;
   1088 				goto bad;
   1089 			}
   1090 			if (ipt->ipt_ptr > ipt->ipt_len - sizeof (int32_t)) {
   1091 				if (++ipt->ipt_oflw == 0) {
   1092 					code = (u_char *)&ipt->ipt_ptr -
   1093 					    (u_char *)ip;
   1094 					goto bad;
   1095 				}
   1096 				break;
   1097 			}
   1098 			cp0 = (cp + ipt->ipt_ptr - 1);
   1099 			switch (ipt->ipt_flg) {
   1100 
   1101 			case IPOPT_TS_TSONLY:
   1102 				break;
   1103 
   1104 			case IPOPT_TS_TSANDADDR:
   1105 				if (ipt->ipt_ptr - 1 + sizeof(n_time) +
   1106 				    sizeof(struct in_addr) > ipt->ipt_len) {
   1107 					code = (u_char *)&ipt->ipt_ptr -
   1108 					    (u_char *)ip;
   1109 					goto bad;
   1110 				}
   1111 				ipaddr.sin_addr = dst;
   1112 				ia = ifatoia(ifaof_ifpforaddr(sintosa(&ipaddr),
   1113 				    m->m_pkthdr.rcvif));
   1114 				if (ia == 0)
   1115 					continue;
   1116 				bcopy(&ia->ia_addr.sin_addr,
   1117 				    cp0, sizeof(struct in_addr));
   1118 				ipt->ipt_ptr += sizeof(struct in_addr);
   1119 				break;
   1120 
   1121 			case IPOPT_TS_PRESPEC:
   1122 				if (ipt->ipt_ptr - 1 + sizeof(n_time) +
   1123 				    sizeof(struct in_addr) > ipt->ipt_len) {
   1124 					code = (u_char *)&ipt->ipt_ptr -
   1125 					    (u_char *)ip;
   1126 					goto bad;
   1127 				}
   1128 				memcpy(&ipaddr.sin_addr, cp0,
   1129 				    sizeof(struct in_addr));
   1130 				if (ifatoia(ifa_ifwithaddr(sintosa(&ipaddr)))
   1131 				    == NULL)
   1132 					continue;
   1133 				ipt->ipt_ptr += sizeof(struct in_addr);
   1134 				break;
   1135 
   1136 			default:
   1137 				/* XXX can't take &ipt->ipt_flg */
   1138 				code = (u_char *)&ipt->ipt_ptr -
   1139 				    (u_char *)ip + 1;
   1140 				goto bad;
   1141 			}
   1142 			ntime = iptime();
   1143 			cp0 = (u_char *) &ntime; /* XXX grumble, GCC... */
   1144 			memmove((char *)cp + ipt->ipt_ptr - 1, cp0,
   1145 			    sizeof(n_time));
   1146 			ipt->ipt_ptr += sizeof(n_time);
   1147 		}
   1148 	}
   1149 	if (forward) {
   1150 		if (ip_forwsrcrt == 0) {
   1151 			type = ICMP_UNREACH;
   1152 			code = ICMP_UNREACH_SRCFAIL;
   1153 			goto bad;
   1154 		}
   1155 		ip_forward(m, 1);
   1156 		return (1);
   1157 	}
   1158 	return (0);
   1159 bad:
   1160 	icmp_error(m, type, code, 0, 0);
   1161 	IP_STATINC(IP_STAT_BADOPTIONS);
   1162 	return (1);
   1163 }
   1164 
   1165 /*
   1166  * Given address of next destination (final or next hop),
   1167  * return internet address info of interface to be used to get there.
   1168  */
   1169 struct in_ifaddr *
   1170 ip_rtaddr(struct in_addr dst)
   1171 {
   1172 	struct rtentry *rt;
   1173 	union {
   1174 		struct sockaddr		dst;
   1175 		struct sockaddr_in	dst4;
   1176 	} u;
   1177 
   1178 	sockaddr_in_init(&u.dst4, &dst, 0);
   1179 
   1180 	if ((rt = rtcache_lookup(&ipforward_rt, &u.dst)) == NULL)
   1181 		return NULL;
   1182 
   1183 	return ifatoia(rt->rt_ifa);
   1184 }
   1185 
   1186 /*
   1187  * Save incoming source route for use in replies,
   1188  * to be picked up later by ip_srcroute if the receiver is interested.
   1189  */
   1190 void
   1191 save_rte(u_char *option, struct in_addr dst)
   1192 {
   1193 	unsigned olen;
   1194 
   1195 	olen = option[IPOPT_OLEN];
   1196 #ifdef DIAGNOSTIC
   1197 	if (ipprintfs)
   1198 		printf("save_rte: olen %d\n", olen);
   1199 #endif /* 0 */
   1200 	if (olen > sizeof(ip_srcrt) - (1 + sizeof(dst)))
   1201 		return;
   1202 	memcpy((void *)ip_srcrt.srcopt, (void *)option, olen);
   1203 	ip_nhops = (olen - IPOPT_OFFSET - 1) / sizeof(struct in_addr);
   1204 	ip_srcrt.dst = dst;
   1205 }
   1206 
   1207 /*
   1208  * Retrieve incoming source route for use in replies,
   1209  * in the same form used by setsockopt.
   1210  * The first hop is placed before the options, will be removed later.
   1211  */
   1212 struct mbuf *
   1213 ip_srcroute(void)
   1214 {
   1215 	struct in_addr *p, *q;
   1216 	struct mbuf *m;
   1217 
   1218 	if (ip_nhops == 0)
   1219 		return NULL;
   1220 	m = m_get(M_DONTWAIT, MT_SOOPTS);
   1221 	if (m == 0)
   1222 		return NULL;
   1223 
   1224 	MCLAIM(m, &inetdomain.dom_mowner);
   1225 #define OPTSIZ	(sizeof(ip_srcrt.nop) + sizeof(ip_srcrt.srcopt))
   1226 
   1227 	/* length is (nhops+1)*sizeof(addr) + sizeof(nop + srcrt header) */
   1228 	m->m_len = ip_nhops * sizeof(struct in_addr) + sizeof(struct in_addr) +
   1229 	    OPTSIZ;
   1230 #ifdef DIAGNOSTIC
   1231 	if (ipprintfs)
   1232 		printf("ip_srcroute: nhops %d mlen %d", ip_nhops, m->m_len);
   1233 #endif
   1234 
   1235 	/*
   1236 	 * First save first hop for return route
   1237 	 */
   1238 	p = &ip_srcrt.route[ip_nhops - 1];
   1239 	*(mtod(m, struct in_addr *)) = *p--;
   1240 #ifdef DIAGNOSTIC
   1241 	if (ipprintfs)
   1242 		printf(" hops %x", ntohl(mtod(m, struct in_addr *)->s_addr));
   1243 #endif
   1244 
   1245 	/*
   1246 	 * Copy option fields and padding (nop) to mbuf.
   1247 	 */
   1248 	ip_srcrt.nop = IPOPT_NOP;
   1249 	ip_srcrt.srcopt[IPOPT_OFFSET] = IPOPT_MINOFF;
   1250 	memmove(mtod(m, char *) + sizeof(struct in_addr), &ip_srcrt.nop,
   1251 	    OPTSIZ);
   1252 	q = (struct in_addr *)(mtod(m, char *) +
   1253 	    sizeof(struct in_addr) + OPTSIZ);
   1254 #undef OPTSIZ
   1255 	/*
   1256 	 * Record return path as an IP source route,
   1257 	 * reversing the path (pointers are now aligned).
   1258 	 */
   1259 	while (p >= ip_srcrt.route) {
   1260 #ifdef DIAGNOSTIC
   1261 		if (ipprintfs)
   1262 			printf(" %x", ntohl(q->s_addr));
   1263 #endif
   1264 		*q++ = *p--;
   1265 	}
   1266 	/*
   1267 	 * Last hop goes to final destination.
   1268 	 */
   1269 	*q = ip_srcrt.dst;
   1270 #ifdef DIAGNOSTIC
   1271 	if (ipprintfs)
   1272 		printf(" %x\n", ntohl(q->s_addr));
   1273 #endif
   1274 	return (m);
   1275 }
   1276 
   1277 const int inetctlerrmap[PRC_NCMDS] = {
   1278 	[PRC_MSGSIZE] = EMSGSIZE,
   1279 	[PRC_HOSTDEAD] = EHOSTDOWN,
   1280 	[PRC_HOSTUNREACH] = EHOSTUNREACH,
   1281 	[PRC_UNREACH_NET] = EHOSTUNREACH,
   1282 	[PRC_UNREACH_HOST] = EHOSTUNREACH,
   1283 	[PRC_UNREACH_PROTOCOL] = ECONNREFUSED,
   1284 	[PRC_UNREACH_PORT] = ECONNREFUSED,
   1285 	[PRC_UNREACH_SRCFAIL] = EHOSTUNREACH,
   1286 	[PRC_PARAMPROB] = ENOPROTOOPT,
   1287 };
   1288 
   1289 /*
   1290  * Forward a packet.  If some error occurs return the sender
   1291  * an icmp packet.  Note we can't always generate a meaningful
   1292  * icmp message because icmp doesn't have a large enough repertoire
   1293  * of codes and types.
   1294  *
   1295  * If not forwarding, just drop the packet.  This could be confusing
   1296  * if ipforwarding was zero but some routing protocol was advancing
   1297  * us as a gateway to somewhere.  However, we must let the routing
   1298  * protocol deal with that.
   1299  *
   1300  * The srcrt parameter indicates whether the packet is being forwarded
   1301  * via a source route.
   1302  */
   1303 void
   1304 ip_forward(struct mbuf *m, int srcrt)
   1305 {
   1306 	struct ip *ip = mtod(m, struct ip *);
   1307 	struct rtentry *rt;
   1308 	int error, type = 0, code = 0, destmtu = 0;
   1309 	struct mbuf *mcopy;
   1310 	n_long dest;
   1311 	union {
   1312 		struct sockaddr		dst;
   1313 		struct sockaddr_in	dst4;
   1314 	} u;
   1315 
   1316 	/*
   1317 	 * We are now in the output path.
   1318 	 */
   1319 	MCLAIM(m, &ip_tx_mowner);
   1320 
   1321 	/*
   1322 	 * Clear any in-bound checksum flags for this packet.
   1323 	 */
   1324 	m->m_pkthdr.csum_flags = 0;
   1325 
   1326 	dest = 0;
   1327 #ifdef DIAGNOSTIC
   1328 	if (ipprintfs) {
   1329 		printf("forward: src %s ", inet_ntoa(ip->ip_src));
   1330 		printf("dst %s ttl %x\n", inet_ntoa(ip->ip_dst), ip->ip_ttl);
   1331 	}
   1332 #endif
   1333 	if (m->m_flags & (M_BCAST|M_MCAST) || in_canforward(ip->ip_dst) == 0) {
   1334 		IP_STATINC(IP_STAT_CANTFORWARD);
   1335 		m_freem(m);
   1336 		return;
   1337 	}
   1338 	if (ip->ip_ttl <= IPTTLDEC) {
   1339 		icmp_error(m, ICMP_TIMXCEED, ICMP_TIMXCEED_INTRANS, dest, 0);
   1340 		return;
   1341 	}
   1342 
   1343 	sockaddr_in_init(&u.dst4, &ip->ip_dst, 0);
   1344 	if ((rt = rtcache_lookup(&ipforward_rt, &u.dst)) == NULL) {
   1345 		icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_NET, dest, 0);
   1346 		return;
   1347 	}
   1348 
   1349 	/*
   1350 	 * Save at most 68 bytes of the packet in case
   1351 	 * we need to generate an ICMP message to the src.
   1352 	 * Pullup to avoid sharing mbuf cluster between m and mcopy.
   1353 	 */
   1354 	mcopy = m_copym(m, 0, imin(ntohs(ip->ip_len), 68), M_DONTWAIT);
   1355 	if (mcopy)
   1356 		mcopy = m_pullup(mcopy, ip->ip_hl << 2);
   1357 
   1358 	ip->ip_ttl -= IPTTLDEC;
   1359 
   1360 	/*
   1361 	 * If forwarding packet using same interface that it came in on,
   1362 	 * perhaps should send a redirect to sender to shortcut a hop.
   1363 	 * Only send redirect if source is sending directly to us,
   1364 	 * and if packet was not source routed (or has any options).
   1365 	 * Also, don't send redirect if forwarding using a default route
   1366 	 * or a route modified by a redirect.
   1367 	 */
   1368 	if (rt->rt_ifp == m->m_pkthdr.rcvif &&
   1369 	    (rt->rt_flags & (RTF_DYNAMIC|RTF_MODIFIED)) == 0 &&
   1370 	    !in_nullhost(satocsin(rt_getkey(rt))->sin_addr) &&
   1371 	    ipsendredirects && !srcrt) {
   1372 		if (rt->rt_ifa &&
   1373 		    (ip->ip_src.s_addr & ifatoia(rt->rt_ifa)->ia_subnetmask) ==
   1374 		    ifatoia(rt->rt_ifa)->ia_subnet) {
   1375 			if (rt->rt_flags & RTF_GATEWAY)
   1376 				dest = satosin(rt->rt_gateway)->sin_addr.s_addr;
   1377 			else
   1378 				dest = ip->ip_dst.s_addr;
   1379 			/*
   1380 			 * Router requirements says to only send host
   1381 			 * redirects.
   1382 			 */
   1383 			type = ICMP_REDIRECT;
   1384 			code = ICMP_REDIRECT_HOST;
   1385 #ifdef DIAGNOSTIC
   1386 			if (ipprintfs)
   1387 				printf("redirect (%d) to %x\n", code,
   1388 				    (u_int32_t)dest);
   1389 #endif
   1390 		}
   1391 	}
   1392 
   1393 	error = ip_output(m, NULL, &ipforward_rt,
   1394 	    (IP_FORWARDING | (ip_directedbcast ? IP_ALLOWBROADCAST : 0)),
   1395 	    (struct ip_moptions *)NULL, (struct socket *)NULL);
   1396 
   1397 	if (error)
   1398 		IP_STATINC(IP_STAT_CANTFORWARD);
   1399 	else {
   1400 		uint64_t *ips = IP_STAT_GETREF();
   1401 		ips[IP_STAT_FORWARD]++;
   1402 		if (type) {
   1403 			ips[IP_STAT_REDIRECTSENT]++;
   1404 			IP_STAT_PUTREF();
   1405 		} else {
   1406 			IP_STAT_PUTREF();
   1407 			if (mcopy) {
   1408 #ifdef GATEWAY
   1409 				if (mcopy->m_flags & M_CANFASTFWD)
   1410 					ipflow_create(&ipforward_rt, mcopy);
   1411 #endif
   1412 				m_freem(mcopy);
   1413 			}
   1414 			return;
   1415 		}
   1416 	}
   1417 	if (mcopy == NULL)
   1418 		return;
   1419 
   1420 	switch (error) {
   1421 
   1422 	case 0:				/* forwarded, but need redirect */
   1423 		/* type, code set above */
   1424 		break;
   1425 
   1426 	case ENETUNREACH:		/* shouldn't happen, checked above */
   1427 	case EHOSTUNREACH:
   1428 	case ENETDOWN:
   1429 	case EHOSTDOWN:
   1430 	default:
   1431 		type = ICMP_UNREACH;
   1432 		code = ICMP_UNREACH_HOST;
   1433 		break;
   1434 
   1435 	case EMSGSIZE:
   1436 		type = ICMP_UNREACH;
   1437 		code = ICMP_UNREACH_NEEDFRAG;
   1438 
   1439 		if ((rt = rtcache_validate(&ipforward_rt)) != NULL)
   1440 			destmtu = rt->rt_ifp->if_mtu;
   1441 
   1442 #if defined(IPSEC) || defined(FAST_IPSEC)
   1443 		{
   1444 			/*
   1445 			 * If the packet is routed over IPsec tunnel, tell the
   1446 			 * originator the tunnel MTU.
   1447 			 *	tunnel MTU = if MTU - sizeof(IP) - ESP/AH hdrsiz
   1448 			 * XXX quickhack!!!
   1449 			 */
   1450 
   1451 			struct secpolicy *sp;
   1452 			int ipsecerror;
   1453 			size_t ipsechdr;
   1454 			struct route *ro;
   1455 
   1456 			sp = ipsec4_getpolicybyaddr(mcopy,
   1457 			    IPSEC_DIR_OUTBOUND, IP_FORWARDING,
   1458 			    &ipsecerror);
   1459 
   1460 			if (sp != NULL) {
   1461 				/* count IPsec header size */
   1462 				ipsechdr = ipsec4_hdrsiz(mcopy,
   1463 				    IPSEC_DIR_OUTBOUND, NULL);
   1464 
   1465 				/*
   1466 				 * find the correct route for outer IPv4
   1467 				 * header, compute tunnel MTU.
   1468 				 */
   1469 
   1470 				if (sp->req != NULL
   1471 				 && sp->req->sav != NULL
   1472 				 && sp->req->sav->sah != NULL) {
   1473 					ro = &sp->req->sav->sah->sa_route;
   1474 					rt = rtcache_validate(ro);
   1475 					if (rt && rt->rt_ifp) {
   1476 						destmtu =
   1477 						    rt->rt_rmx.rmx_mtu ?
   1478 						    rt->rt_rmx.rmx_mtu :
   1479 						    rt->rt_ifp->if_mtu;
   1480 						destmtu -= ipsechdr;
   1481 					}
   1482 				}
   1483 
   1484 #ifdef	IPSEC
   1485 				key_freesp(sp);
   1486 #else
   1487 				KEY_FREESP(&sp);
   1488 #endif
   1489 			}
   1490 		}
   1491 #endif /*defined(IPSEC) || defined(FAST_IPSEC)*/
   1492 		IP_STATINC(IP_STAT_CANTFRAG);
   1493 		break;
   1494 
   1495 	case ENOBUFS:
   1496 #if 1
   1497 		/*
   1498 		 * a router should not generate ICMP_SOURCEQUENCH as
   1499 		 * required in RFC1812 Requirements for IP Version 4 Routers.
   1500 		 * source quench could be a big problem under DoS attacks,
   1501 		 * or if the underlying interface is rate-limited.
   1502 		 */
   1503 		if (mcopy)
   1504 			m_freem(mcopy);
   1505 		return;
   1506 #else
   1507 		type = ICMP_SOURCEQUENCH;
   1508 		code = 0;
   1509 		break;
   1510 #endif
   1511 	}
   1512 	icmp_error(mcopy, type, code, dest, destmtu);
   1513 }
   1514 
   1515 void
   1516 ip_savecontrol(struct inpcb *inp, struct mbuf **mp, struct ip *ip,
   1517     struct mbuf *m)
   1518 {
   1519 
   1520 	if (inp->inp_socket->so_options & SO_TIMESTAMP
   1521 #ifdef SO_OTIMESTAMP
   1522 	    || inp->inp_socket->so_options & SO_OTIMESTAMP
   1523 #endif
   1524 	    ) {
   1525 		struct timeval tv;
   1526 
   1527 		microtime(&tv);
   1528 #ifdef SO_OTIMESTAMP
   1529 		if (inp->inp_socket->so_options & SO_OTIMESTAMP) {
   1530 			struct timeval50 tv50;
   1531 			timeval_to_timeval50(&tv, &tv50);
   1532 			*mp = sbcreatecontrol((void *) &tv50, sizeof(tv50),
   1533 			    SCM_OTIMESTAMP, SOL_SOCKET);
   1534 		} else
   1535 #endif
   1536 		*mp = sbcreatecontrol((void *) &tv, sizeof(tv),
   1537 		    SCM_TIMESTAMP, SOL_SOCKET);
   1538 		if (*mp)
   1539 			mp = &(*mp)->m_next;
   1540 	}
   1541 	if (inp->inp_flags & INP_RECVDSTADDR) {
   1542 		*mp = sbcreatecontrol((void *) &ip->ip_dst,
   1543 		    sizeof(struct in_addr), IP_RECVDSTADDR, IPPROTO_IP);
   1544 		if (*mp)
   1545 			mp = &(*mp)->m_next;
   1546 	}
   1547 #ifdef notyet
   1548 	/*
   1549 	 * XXX
   1550 	 * Moving these out of udp_input() made them even more broken
   1551 	 * than they already were.
   1552 	 *	- fenner (at) parc.xerox.com
   1553 	 */
   1554 	/* options were tossed already */
   1555 	if (inp->inp_flags & INP_RECVOPTS) {
   1556 		*mp = sbcreatecontrol((void *) opts_deleted_above,
   1557 		    sizeof(struct in_addr), IP_RECVOPTS, IPPROTO_IP);
   1558 		if (*mp)
   1559 			mp = &(*mp)->m_next;
   1560 	}
   1561 	/* ip_srcroute doesn't do what we want here, need to fix */
   1562 	if (inp->inp_flags & INP_RECVRETOPTS) {
   1563 		*mp = sbcreatecontrol((void *) ip_srcroute(),
   1564 		    sizeof(struct in_addr), IP_RECVRETOPTS, IPPROTO_IP);
   1565 		if (*mp)
   1566 			mp = &(*mp)->m_next;
   1567 	}
   1568 #endif
   1569 	if (inp->inp_flags & INP_RECVIF) {
   1570 		struct sockaddr_dl sdl;
   1571 
   1572 		sockaddr_dl_init(&sdl, sizeof(sdl),
   1573 		    (m->m_pkthdr.rcvif != NULL)
   1574 		        ?  m->m_pkthdr.rcvif->if_index
   1575 			: 0,
   1576 			0, NULL, 0, NULL, 0);
   1577 		*mp = sbcreatecontrol(&sdl, sdl.sdl_len, IP_RECVIF, IPPROTO_IP);
   1578 		if (*mp)
   1579 			mp = &(*mp)->m_next;
   1580 	}
   1581 	if (inp->inp_flags & INP_RECVTTL) {
   1582 		*mp = sbcreatecontrol((void *) &ip->ip_ttl,
   1583 		    sizeof(uint8_t), IP_RECVTTL, IPPROTO_IP);
   1584 		if (*mp)
   1585 			mp = &(*mp)->m_next;
   1586 	}
   1587 }
   1588 
   1589 /*
   1590  * sysctl helper routine for net.inet.ip.forwsrcrt.
   1591  */
   1592 static int
   1593 sysctl_net_inet_ip_forwsrcrt(SYSCTLFN_ARGS)
   1594 {
   1595 	int error, tmp;
   1596 	struct sysctlnode node;
   1597 
   1598 	node = *rnode;
   1599 	tmp = ip_forwsrcrt;
   1600 	node.sysctl_data = &tmp;
   1601 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
   1602 	if (error || newp == NULL)
   1603 		return (error);
   1604 
   1605 	error = kauth_authorize_network(l->l_cred, KAUTH_NETWORK_FORWSRCRT,
   1606 	    0, NULL, NULL, NULL);
   1607 	if (error)
   1608 		return (error);
   1609 
   1610 	ip_forwsrcrt = tmp;
   1611 
   1612 	return (0);
   1613 }
   1614 
   1615 /*
   1616  * sysctl helper routine for net.inet.ip.mtudisctimeout.  checks the
   1617  * range of the new value and tweaks timers if it changes.
   1618  */
   1619 static int
   1620 sysctl_net_inet_ip_pmtudto(SYSCTLFN_ARGS)
   1621 {
   1622 	int error, tmp;
   1623 	struct sysctlnode node;
   1624 
   1625 	node = *rnode;
   1626 	tmp = ip_mtudisc_timeout;
   1627 	node.sysctl_data = &tmp;
   1628 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
   1629 	if (error || newp == NULL)
   1630 		return (error);
   1631 	if (tmp < 0)
   1632 		return (EINVAL);
   1633 
   1634 	mutex_enter(softnet_lock);
   1635 
   1636 	ip_mtudisc_timeout = tmp;
   1637 	rt_timer_queue_change(ip_mtudisc_timeout_q, ip_mtudisc_timeout);
   1638 
   1639 	mutex_exit(softnet_lock);
   1640 
   1641 	return (0);
   1642 }
   1643 
   1644 #ifdef GATEWAY
   1645 /*
   1646  * sysctl helper routine for net.inet.ip.maxflows.
   1647  */
   1648 static int
   1649 sysctl_net_inet_ip_maxflows(SYSCTLFN_ARGS)
   1650 {
   1651 	int error;
   1652 
   1653 	error = sysctl_lookup(SYSCTLFN_CALL(rnode));
   1654 	if (error || newp == NULL)
   1655 		return (error);
   1656 
   1657 	mutex_enter(softnet_lock);
   1658 	KERNEL_LOCK(1, NULL);
   1659 
   1660 	ipflow_prune();
   1661 
   1662 	KERNEL_UNLOCK_ONE(NULL);
   1663 	mutex_exit(softnet_lock);
   1664 
   1665 	return (0);
   1666 }
   1667 
   1668 static int
   1669 sysctl_net_inet_ip_hashsize(SYSCTLFN_ARGS)
   1670 {
   1671 	int error, tmp;
   1672 	struct sysctlnode node;
   1673 
   1674 	node = *rnode;
   1675 	tmp = ip_hashsize;
   1676 	node.sysctl_data = &tmp;
   1677 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
   1678 	if (error || newp == NULL)
   1679 		return (error);
   1680 
   1681 	if ((tmp & (tmp - 1)) == 0 && tmp != 0) {
   1682 		/*
   1683 		 * Can only fail due to malloc()
   1684 		 */
   1685 		mutex_enter(softnet_lock);
   1686 		KERNEL_LOCK(1, NULL);
   1687 
   1688 		error = ipflow_invalidate_all(tmp);
   1689 
   1690 		KERNEL_UNLOCK_ONE(NULL);
   1691 		mutex_exit(softnet_lock);
   1692 
   1693 	} else {
   1694 		/*
   1695 		 * EINVAL if not a power of 2
   1696 	         */
   1697 		error = EINVAL;
   1698 	}
   1699 
   1700 	return error;
   1701 }
   1702 #endif /* GATEWAY */
   1703 
   1704 static int
   1705 sysctl_net_inet_ip_stats(SYSCTLFN_ARGS)
   1706 {
   1707 
   1708 	return (NETSTAT_SYSCTL(ipstat_percpu, IP_NSTATS));
   1709 }
   1710 
   1711 static void
   1712 sysctl_net_inet_ip_setup(struct sysctllog **clog)
   1713 {
   1714 	extern int subnetsarelocal, hostzeroisbroadcast;
   1715 
   1716 	sysctl_createv(clog, 0, NULL, NULL,
   1717 		       CTLFLAG_PERMANENT,
   1718 		       CTLTYPE_NODE, "net", NULL,
   1719 		       NULL, 0, NULL, 0,
   1720 		       CTL_NET, CTL_EOL);
   1721 	sysctl_createv(clog, 0, NULL, NULL,
   1722 		       CTLFLAG_PERMANENT,
   1723 		       CTLTYPE_NODE, "inet",
   1724 		       SYSCTL_DESCR("PF_INET related settings"),
   1725 		       NULL, 0, NULL, 0,
   1726 		       CTL_NET, PF_INET, CTL_EOL);
   1727 	sysctl_createv(clog, 0, NULL, NULL,
   1728 		       CTLFLAG_PERMANENT,
   1729 		       CTLTYPE_NODE, "ip",
   1730 		       SYSCTL_DESCR("IPv4 related settings"),
   1731 		       NULL, 0, NULL, 0,
   1732 		       CTL_NET, PF_INET, IPPROTO_IP, CTL_EOL);
   1733 
   1734 	sysctl_createv(clog, 0, NULL, NULL,
   1735 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   1736 		       CTLTYPE_INT, "forwarding",
   1737 		       SYSCTL_DESCR("Enable forwarding of INET datagrams"),
   1738 		       NULL, 0, &ipforwarding, 0,
   1739 		       CTL_NET, PF_INET, IPPROTO_IP,
   1740 		       IPCTL_FORWARDING, CTL_EOL);
   1741 	sysctl_createv(clog, 0, NULL, NULL,
   1742 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   1743 		       CTLTYPE_INT, "redirect",
   1744 		       SYSCTL_DESCR("Enable sending of ICMP redirect messages"),
   1745 		       NULL, 0, &ipsendredirects, 0,
   1746 		       CTL_NET, PF_INET, IPPROTO_IP,
   1747 		       IPCTL_SENDREDIRECTS, CTL_EOL);
   1748 	sysctl_createv(clog, 0, NULL, NULL,
   1749 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   1750 		       CTLTYPE_INT, "ttl",
   1751 		       SYSCTL_DESCR("Default TTL for an INET datagram"),
   1752 		       NULL, 0, &ip_defttl, 0,
   1753 		       CTL_NET, PF_INET, IPPROTO_IP,
   1754 		       IPCTL_DEFTTL, CTL_EOL);
   1755 #ifdef IPCTL_DEFMTU
   1756 	sysctl_createv(clog, 0, NULL, NULL,
   1757 		       CTLFLAG_PERMANENT /* |CTLFLAG_READWRITE? */,
   1758 		       CTLTYPE_INT, "mtu",
   1759 		       SYSCTL_DESCR("Default MTA for an INET route"),
   1760 		       NULL, 0, &ip_mtu, 0,
   1761 		       CTL_NET, PF_INET, IPPROTO_IP,
   1762 		       IPCTL_DEFMTU, CTL_EOL);
   1763 #endif /* IPCTL_DEFMTU */
   1764 	sysctl_createv(clog, 0, NULL, NULL,
   1765 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   1766 		       CTLTYPE_INT, "forwsrcrt",
   1767 		       SYSCTL_DESCR("Enable forwarding of source-routed "
   1768 				    "datagrams"),
   1769 		       sysctl_net_inet_ip_forwsrcrt, 0, &ip_forwsrcrt, 0,
   1770 		       CTL_NET, PF_INET, IPPROTO_IP,
   1771 		       IPCTL_FORWSRCRT, CTL_EOL);
   1772 	sysctl_createv(clog, 0, NULL, NULL,
   1773 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   1774 		       CTLTYPE_INT, "directed-broadcast",
   1775 		       SYSCTL_DESCR("Enable forwarding of broadcast datagrams"),
   1776 		       NULL, 0, &ip_directedbcast, 0,
   1777 		       CTL_NET, PF_INET, IPPROTO_IP,
   1778 		       IPCTL_DIRECTEDBCAST, CTL_EOL);
   1779 	sysctl_createv(clog, 0, NULL, NULL,
   1780 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   1781 		       CTLTYPE_INT, "allowsrcrt",
   1782 		       SYSCTL_DESCR("Accept source-routed datagrams"),
   1783 		       NULL, 0, &ip_allowsrcrt, 0,
   1784 		       CTL_NET, PF_INET, IPPROTO_IP,
   1785 		       IPCTL_ALLOWSRCRT, CTL_EOL);
   1786 	sysctl_createv(clog, 0, NULL, NULL,
   1787 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   1788 		       CTLTYPE_INT, "subnetsarelocal",
   1789 		       SYSCTL_DESCR("Whether logical subnets are considered "
   1790 				    "local"),
   1791 		       NULL, 0, &subnetsarelocal, 0,
   1792 		       CTL_NET, PF_INET, IPPROTO_IP,
   1793 		       IPCTL_SUBNETSARELOCAL, CTL_EOL);
   1794 	sysctl_createv(clog, 0, NULL, NULL,
   1795 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   1796 		       CTLTYPE_INT, "mtudisc",
   1797 		       SYSCTL_DESCR("Use RFC1191 Path MTU Discovery"),
   1798 		       NULL, 0, &ip_mtudisc, 0,
   1799 		       CTL_NET, PF_INET, IPPROTO_IP,
   1800 		       IPCTL_MTUDISC, CTL_EOL);
   1801 	sysctl_createv(clog, 0, NULL, NULL,
   1802 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   1803 		       CTLTYPE_INT, "anonportmin",
   1804 		       SYSCTL_DESCR("Lowest ephemeral port number to assign"),
   1805 		       sysctl_net_inet_ip_ports, 0, &anonportmin, 0,
   1806 		       CTL_NET, PF_INET, IPPROTO_IP,
   1807 		       IPCTL_ANONPORTMIN, CTL_EOL);
   1808 	sysctl_createv(clog, 0, NULL, NULL,
   1809 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   1810 		       CTLTYPE_INT, "anonportmax",
   1811 		       SYSCTL_DESCR("Highest ephemeral port number to assign"),
   1812 		       sysctl_net_inet_ip_ports, 0, &anonportmax, 0,
   1813 		       CTL_NET, PF_INET, IPPROTO_IP,
   1814 		       IPCTL_ANONPORTMAX, CTL_EOL);
   1815 	sysctl_createv(clog, 0, NULL, NULL,
   1816 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   1817 		       CTLTYPE_INT, "mtudisctimeout",
   1818 		       SYSCTL_DESCR("Lifetime of a Path MTU Discovered route"),
   1819 		       sysctl_net_inet_ip_pmtudto, 0, &ip_mtudisc_timeout, 0,
   1820 		       CTL_NET, PF_INET, IPPROTO_IP,
   1821 		       IPCTL_MTUDISCTIMEOUT, CTL_EOL);
   1822 #ifdef GATEWAY
   1823 	sysctl_createv(clog, 0, NULL, NULL,
   1824 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   1825 		       CTLTYPE_INT, "maxflows",
   1826 		       SYSCTL_DESCR("Number of flows for fast forwarding"),
   1827 		       sysctl_net_inet_ip_maxflows, 0, &ip_maxflows, 0,
   1828 		       CTL_NET, PF_INET, IPPROTO_IP,
   1829 		       IPCTL_MAXFLOWS, CTL_EOL);
   1830 	sysctl_createv(clog, 0, NULL, NULL,
   1831 			CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   1832 			CTLTYPE_INT, "hashsize",
   1833 			SYSCTL_DESCR("Size of hash table for fast forwarding (IPv4)"),
   1834 			sysctl_net_inet_ip_hashsize, 0, &ip_hashsize, 0,
   1835 			CTL_NET, PF_INET, IPPROTO_IP,
   1836 			CTL_CREATE, CTL_EOL);
   1837 #endif /* GATEWAY */
   1838 	sysctl_createv(clog, 0, NULL, NULL,
   1839 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   1840 		       CTLTYPE_INT, "hostzerobroadcast",
   1841 		       SYSCTL_DESCR("All zeroes address is broadcast address"),
   1842 		       NULL, 0, &hostzeroisbroadcast, 0,
   1843 		       CTL_NET, PF_INET, IPPROTO_IP,
   1844 		       IPCTL_HOSTZEROBROADCAST, CTL_EOL);
   1845 #if NGIF > 0
   1846 	sysctl_createv(clog, 0, NULL, NULL,
   1847 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   1848 		       CTLTYPE_INT, "gifttl",
   1849 		       SYSCTL_DESCR("Default TTL for a gif tunnel datagram"),
   1850 		       NULL, 0, &ip_gif_ttl, 0,
   1851 		       CTL_NET, PF_INET, IPPROTO_IP,
   1852 		       IPCTL_GIF_TTL, CTL_EOL);
   1853 #endif /* NGIF */
   1854 #ifndef IPNOPRIVPORTS
   1855 	sysctl_createv(clog, 0, NULL, NULL,
   1856 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   1857 		       CTLTYPE_INT, "lowportmin",
   1858 		       SYSCTL_DESCR("Lowest privileged ephemeral port number "
   1859 				    "to assign"),
   1860 		       sysctl_net_inet_ip_ports, 0, &lowportmin, 0,
   1861 		       CTL_NET, PF_INET, IPPROTO_IP,
   1862 		       IPCTL_LOWPORTMIN, CTL_EOL);
   1863 	sysctl_createv(clog, 0, NULL, NULL,
   1864 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   1865 		       CTLTYPE_INT, "lowportmax",
   1866 		       SYSCTL_DESCR("Highest privileged ephemeral port number "
   1867 				    "to assign"),
   1868 		       sysctl_net_inet_ip_ports, 0, &lowportmax, 0,
   1869 		       CTL_NET, PF_INET, IPPROTO_IP,
   1870 		       IPCTL_LOWPORTMAX, CTL_EOL);
   1871 #endif /* IPNOPRIVPORTS */
   1872 #if NGRE > 0
   1873 	sysctl_createv(clog, 0, NULL, NULL,
   1874 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   1875 		       CTLTYPE_INT, "grettl",
   1876 		       SYSCTL_DESCR("Default TTL for a gre tunnel datagram"),
   1877 		       NULL, 0, &ip_gre_ttl, 0,
   1878 		       CTL_NET, PF_INET, IPPROTO_IP,
   1879 		       IPCTL_GRE_TTL, CTL_EOL);
   1880 #endif /* NGRE */
   1881 	sysctl_createv(clog, 0, NULL, NULL,
   1882 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   1883 		       CTLTYPE_INT, "checkinterface",
   1884 		       SYSCTL_DESCR("Enable receive side of Strong ES model "
   1885 				    "from RFC1122"),
   1886 		       NULL, 0, &ip_checkinterface, 0,
   1887 		       CTL_NET, PF_INET, IPPROTO_IP,
   1888 		       IPCTL_CHECKINTERFACE, CTL_EOL);
   1889 	sysctl_createv(clog, 0, NULL, NULL,
   1890 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   1891 		       CTLTYPE_INT, "random_id",
   1892 		       SYSCTL_DESCR("Assign random ip_id values"),
   1893 		       NULL, 0, &ip_do_randomid, 0,
   1894 		       CTL_NET, PF_INET, IPPROTO_IP,
   1895 		       IPCTL_RANDOMID, CTL_EOL);
   1896 	sysctl_createv(clog, 0, NULL, NULL,
   1897 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   1898 		       CTLTYPE_INT, "do_loopback_cksum",
   1899 		       SYSCTL_DESCR("Perform IP checksum on loopback"),
   1900 		       NULL, 0, &ip_do_loopback_cksum, 0,
   1901 		       CTL_NET, PF_INET, IPPROTO_IP,
   1902 		       IPCTL_LOOPBACKCKSUM, CTL_EOL);
   1903 	sysctl_createv(clog, 0, NULL, NULL,
   1904 		       CTLFLAG_PERMANENT,
   1905 		       CTLTYPE_STRUCT, "stats",
   1906 		       SYSCTL_DESCR("IP statistics"),
   1907 		       sysctl_net_inet_ip_stats, 0, NULL, 0,
   1908 		       CTL_NET, PF_INET, IPPROTO_IP, IPCTL_STATS,
   1909 		       CTL_EOL);
   1910 }
   1911 
   1912 void
   1913 ip_statinc(u_int stat)
   1914 {
   1915 
   1916 	KASSERT(stat < IP_NSTATS);
   1917 	IP_STATINC(stat);
   1918 }
   1919