Home | History | Annotate | Line # | Download | only in netinet
ip_input.c revision 1.267
      1 /*	$NetBSD: ip_input.c,v 1.267 2008/04/23 06:09:04 thorpej 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  * 3. All advertising materials mentioning features or use of this software
     49  *    must display the following acknowledgement:
     50  *	This product includes software developed by the NetBSD
     51  *	Foundation, Inc. and its contributors.
     52  * 4. Neither the name of The NetBSD Foundation nor the names of its
     53  *    contributors may be used to endorse or promote products derived
     54  *    from this software without specific prior written permission.
     55  *
     56  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     57  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     58  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     59  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     60  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     61  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     62  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     63  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     64  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     65  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     66  * POSSIBILITY OF SUCH DAMAGE.
     67  */
     68 
     69 /*
     70  * Copyright (c) 1982, 1986, 1988, 1993
     71  *	The Regents of the University of California.  All rights reserved.
     72  *
     73  * Redistribution and use in source and binary forms, with or without
     74  * modification, are permitted provided that the following conditions
     75  * are met:
     76  * 1. Redistributions of source code must retain the above copyright
     77  *    notice, this list of conditions and the following disclaimer.
     78  * 2. Redistributions in binary form must reproduce the above copyright
     79  *    notice, this list of conditions and the following disclaimer in the
     80  *    documentation and/or other materials provided with the distribution.
     81  * 3. Neither the name of the University nor the names of its contributors
     82  *    may be used to endorse or promote products derived from this software
     83  *    without specific prior written permission.
     84  *
     85  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     86  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     87  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     88  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     89  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     90  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     91  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     92  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     93  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     94  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     95  * SUCH DAMAGE.
     96  *
     97  *	@(#)ip_input.c	8.2 (Berkeley) 1/4/94
     98  */
     99 
    100 #include <sys/cdefs.h>
    101 __KERNEL_RCSID(0, "$NetBSD: ip_input.c,v 1.267 2008/04/23 06:09:04 thorpej Exp $");
    102 
    103 #include "opt_inet.h"
    104 #include "opt_gateway.h"
    105 #include "opt_pfil_hooks.h"
    106 #include "opt_ipsec.h"
    107 #include "opt_mrouting.h"
    108 #include "opt_mbuftrace.h"
    109 #include "opt_inet_csum.h"
    110 
    111 #include <sys/param.h>
    112 #include <sys/systm.h>
    113 #include <sys/malloc.h>
    114 #include <sys/mbuf.h>
    115 #include <sys/domain.h>
    116 #include <sys/protosw.h>
    117 #include <sys/socket.h>
    118 #include <sys/socketvar.h>
    119 #include <sys/errno.h>
    120 #include <sys/time.h>
    121 #include <sys/kernel.h>
    122 #include <sys/pool.h>
    123 #include <sys/sysctl.h>
    124 #include <sys/kauth.h>
    125 
    126 #include <net/if.h>
    127 #include <net/if_dl.h>
    128 #include <net/route.h>
    129 #include <net/pfil.h>
    130 
    131 #include <netinet/in.h>
    132 #include <netinet/in_systm.h>
    133 #include <netinet/ip.h>
    134 #include <netinet/in_pcb.h>
    135 #include <netinet/in_proto.h>
    136 #include <netinet/in_var.h>
    137 #include <netinet/ip_var.h>
    138 #include <netinet/ip_private.h>
    139 #include <netinet/ip_icmp.h>
    140 /* just for gif_ttl */
    141 #include <netinet/in_gif.h>
    142 #include "gif.h"
    143 #include <net/if_gre.h>
    144 #include "gre.h"
    145 
    146 #ifdef MROUTING
    147 #include <netinet/ip_mroute.h>
    148 #endif
    149 
    150 #ifdef IPSEC
    151 #include <netinet6/ipsec.h>
    152 #include <netinet6/ipsec_private.h>
    153 #include <netkey/key.h>
    154 #endif
    155 #ifdef FAST_IPSEC
    156 #include <netipsec/ipsec.h>
    157 #include <netipsec/key.h>
    158 #endif	/* FAST_IPSEC*/
    159 
    160 #ifndef	IPFORWARDING
    161 #ifdef GATEWAY
    162 #define	IPFORWARDING	1	/* forward IP packets not for us */
    163 #else /* GATEWAY */
    164 #define	IPFORWARDING	0	/* don't forward IP packets not for us */
    165 #endif /* GATEWAY */
    166 #endif /* IPFORWARDING */
    167 #ifndef	IPSENDREDIRECTS
    168 #define	IPSENDREDIRECTS	1
    169 #endif
    170 #ifndef IPFORWSRCRT
    171 #define	IPFORWSRCRT	1	/* forward source-routed packets */
    172 #endif
    173 #ifndef IPALLOWSRCRT
    174 #define	IPALLOWSRCRT	1	/* allow source-routed packets */
    175 #endif
    176 #ifndef IPMTUDISC
    177 #define IPMTUDISC	1
    178 #endif
    179 #ifndef IPMTUDISCTIMEOUT
    180 #define IPMTUDISCTIMEOUT (10 * 60)	/* as per RFC 1191 */
    181 #endif
    182 
    183 /*
    184  * Note: DIRECTED_BROADCAST is handled this way so that previous
    185  * configuration using this option will Just Work.
    186  */
    187 #ifndef IPDIRECTEDBCAST
    188 #ifdef DIRECTED_BROADCAST
    189 #define IPDIRECTEDBCAST	1
    190 #else
    191 #define	IPDIRECTEDBCAST	0
    192 #endif /* DIRECTED_BROADCAST */
    193 #endif /* IPDIRECTEDBCAST */
    194 int	ipforwarding = IPFORWARDING;
    195 int	ipsendredirects = IPSENDREDIRECTS;
    196 int	ip_defttl = IPDEFTTL;
    197 int	ip_forwsrcrt = IPFORWSRCRT;
    198 int	ip_directedbcast = IPDIRECTEDBCAST;
    199 int	ip_allowsrcrt = IPALLOWSRCRT;
    200 int	ip_mtudisc = IPMTUDISC;
    201 int	ip_mtudisc_timeout = IPMTUDISCTIMEOUT;
    202 #ifdef DIAGNOSTIC
    203 int	ipprintfs = 0;
    204 #endif
    205 
    206 int	ip_do_randomid = 0;
    207 
    208 /*
    209  * XXX - Setting ip_checkinterface mostly implements the receive side of
    210  * the Strong ES model described in RFC 1122, but since the routing table
    211  * and transmit implementation do not implement the Strong ES model,
    212  * setting this to 1 results in an odd hybrid.
    213  *
    214  * XXX - ip_checkinterface currently must be disabled if you use ipnat
    215  * to translate the destination address to another local interface.
    216  *
    217  * XXX - ip_checkinterface must be disabled if you add IP aliases
    218  * to the loopback interface instead of the interface where the
    219  * packets for those addresses are received.
    220  */
    221 int	ip_checkinterface = 0;
    222 
    223 
    224 struct rttimer_queue *ip_mtudisc_timeout_q = NULL;
    225 
    226 int	ipqmaxlen = IFQ_MAXLEN;
    227 u_long	in_ifaddrhash;				/* size of hash table - 1 */
    228 int	in_ifaddrentries;			/* total number of addrs */
    229 struct in_ifaddrhead in_ifaddrhead;
    230 struct	in_ifaddrhashhead *in_ifaddrhashtbl;
    231 u_long	in_multihash;				/* size of hash table - 1 */
    232 int	in_multientries;			/* total number of addrs */
    233 struct	in_multihashhead *in_multihashtbl;
    234 struct	ifqueue ipintrq;
    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 /*
    244  * Cached copy of nmbclusters. If nbclusters is different,
    245  * recalculate IP parameters derived from nmbclusters.
    246  */
    247 static int	ip_nmbclusters;			/* copy of nmbclusters */
    248 static void	ip_nmbclusters_changed(void);	/* recalc limits */
    249 
    250 #define CHECK_NMBCLUSTER_PARAMS()				\
    251 do {								\
    252 	if (__predict_false(ip_nmbclusters != nmbclusters))	\
    253 		ip_nmbclusters_changed();			\
    254 } while (/*CONSTCOND*/0)
    255 
    256 /* IP datagram reassembly queues (hashed) */
    257 #define IPREASS_NHASH_LOG2      6
    258 #define IPREASS_NHASH           (1 << IPREASS_NHASH_LOG2)
    259 #define IPREASS_HMASK           (IPREASS_NHASH - 1)
    260 #define IPREASS_HASH(x,y) \
    261 	(((((x) & 0xF) | ((((x) >> 8) & 0xF) << 4)) ^ (y)) & IPREASS_HMASK)
    262 struct ipqhead ipq[IPREASS_NHASH];
    263 int	ipq_locked;
    264 static int	ip_nfragpackets;	/* packets in reass queue */
    265 static int	ip_nfrags;		/* total fragments in reass queues */
    266 
    267 int	ip_maxfragpackets = 200;	/* limit on packets. XXX sysctl */
    268 int	ip_maxfrags;		        /* limit on fragments. XXX sysctl */
    269 
    270 
    271 /*
    272  * Additive-Increase/Multiplicative-Decrease (AIMD) strategy for
    273  * IP reassembly queue buffer managment.
    274  *
    275  * We keep a count of total IP fragments (NB: not fragmented packets!)
    276  * awaiting reassembly (ip_nfrags) and a limit (ip_maxfrags) on fragments.
    277  * If ip_nfrags exceeds ip_maxfrags the limit, we drop half the
    278  * total fragments in  reassembly queues.This AIMD policy avoids
    279  * repeatedly deleting single packets under heavy fragmentation load
    280  * (e.g., from lossy NFS peers).
    281  */
    282 static u_int	ip_reass_ttl_decr(u_int ticks);
    283 static void	ip_reass_drophalf(void);
    284 
    285 
    286 static inline int ipq_lock_try(void);
    287 static inline void ipq_unlock(void);
    288 
    289 static inline int
    290 ipq_lock_try(void)
    291 {
    292 	int s;
    293 
    294 	/*
    295 	 * Use splvm() -- we're blocking things that would cause
    296 	 * mbuf allocation.
    297 	 */
    298 	s = splvm();
    299 	if (ipq_locked) {
    300 		splx(s);
    301 		return (0);
    302 	}
    303 	ipq_locked = 1;
    304 	splx(s);
    305 	return (1);
    306 }
    307 
    308 static inline void
    309 ipq_unlock(void)
    310 {
    311 	int s;
    312 
    313 	s = splvm();
    314 	ipq_locked = 0;
    315 	splx(s);
    316 }
    317 
    318 #ifdef DIAGNOSTIC
    319 #define	IPQ_LOCK()							\
    320 do {									\
    321 	if (ipq_lock_try() == 0) {					\
    322 		printf("%s:%d: ipq already locked\n", __FILE__, __LINE__); \
    323 		panic("ipq_lock");					\
    324 	}								\
    325 } while (/*CONSTCOND*/ 0)
    326 #define	IPQ_LOCK_CHECK()						\
    327 do {									\
    328 	if (ipq_locked == 0) {						\
    329 		printf("%s:%d: ipq lock not held\n", __FILE__, __LINE__); \
    330 		panic("ipq lock check");				\
    331 	}								\
    332 } while (/*CONSTCOND*/ 0)
    333 #else
    334 #define	IPQ_LOCK()		(void) ipq_lock_try()
    335 #define	IPQ_LOCK_CHECK()	/* nothing */
    336 #endif
    337 
    338 #define	IPQ_UNLOCK()		ipq_unlock()
    339 
    340 POOL_INIT(inmulti_pool, sizeof(struct in_multi), 0, 0, 0, "inmltpl", NULL,
    341     IPL_SOFTNET);
    342 POOL_INIT(ipqent_pool, sizeof(struct ipqent), 0, 0, 0, "ipqepl", NULL,
    343     IPL_VM);
    344 
    345 #ifdef INET_CSUM_COUNTERS
    346 #include <sys/device.h>
    347 
    348 struct evcnt ip_hwcsum_bad = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
    349     NULL, "inet", "hwcsum bad");
    350 struct evcnt ip_hwcsum_ok = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
    351     NULL, "inet", "hwcsum ok");
    352 struct evcnt ip_swcsum = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
    353     NULL, "inet", "swcsum");
    354 
    355 #define	INET_CSUM_COUNTER_INCR(ev)	(ev)->ev_count++
    356 
    357 EVCNT_ATTACH_STATIC(ip_hwcsum_bad);
    358 EVCNT_ATTACH_STATIC(ip_hwcsum_ok);
    359 EVCNT_ATTACH_STATIC(ip_swcsum);
    360 
    361 #else
    362 
    363 #define	INET_CSUM_COUNTER_INCR(ev)	/* nothing */
    364 
    365 #endif /* INET_CSUM_COUNTERS */
    366 
    367 /*
    368  * We need to save the IP options in case a protocol wants to respond
    369  * to an incoming packet over the same route if the packet got here
    370  * using IP source routing.  This allows connection establishment and
    371  * maintenance when the remote end is on a network that is not known
    372  * to us.
    373  */
    374 int	ip_nhops = 0;
    375 static	struct ip_srcrt {
    376 	struct	in_addr dst;			/* final destination */
    377 	char	nop;				/* one NOP to align */
    378 	char	srcopt[IPOPT_OFFSET + 1];	/* OPTVAL, OLEN and OFFSET */
    379 	struct	in_addr route[MAX_IPOPTLEN/sizeof(struct in_addr)];
    380 } ip_srcrt;
    381 
    382 static void save_rte(u_char *, struct in_addr);
    383 
    384 #ifdef MBUFTRACE
    385 struct mowner ip_rx_mowner = MOWNER_INIT("internet", "rx");
    386 struct mowner ip_tx_mowner = MOWNER_INIT("internet", "tx");
    387 #endif
    388 
    389 /*
    390  * Compute IP limits derived from the value of nmbclusters.
    391  */
    392 static void
    393 ip_nmbclusters_changed(void)
    394 {
    395 	ip_maxfrags = nmbclusters / 4;
    396 	ip_nmbclusters =  nmbclusters;
    397 }
    398 
    399 /*
    400  * IP initialization: fill in IP protocol switch table.
    401  * All protocols not implemented in kernel go to raw IP protocol handler.
    402  */
    403 void
    404 ip_init(void)
    405 {
    406 	const struct protosw *pr;
    407 	int i;
    408 
    409 	pr = pffindproto(PF_INET, IPPROTO_RAW, SOCK_RAW);
    410 	if (pr == 0)
    411 		panic("ip_init");
    412 	for (i = 0; i < IPPROTO_MAX; i++)
    413 		ip_protox[i] = pr - inetsw;
    414 	for (pr = inetdomain.dom_protosw;
    415 	    pr < inetdomain.dom_protoswNPROTOSW; pr++)
    416 		if (pr->pr_domain->dom_family == PF_INET &&
    417 		    pr->pr_protocol && pr->pr_protocol != IPPROTO_RAW)
    418 			ip_protox[pr->pr_protocol] = pr - inetsw;
    419 
    420 	for (i = 0; i < IPREASS_NHASH; i++)
    421 	    	LIST_INIT(&ipq[i]);
    422 
    423 	ip_initid();
    424 	ip_id = time_second & 0xfffff;
    425 
    426 	ipintrq.ifq_maxlen = ipqmaxlen;
    427 	ip_nmbclusters_changed();
    428 
    429 	TAILQ_INIT(&in_ifaddrhead);
    430 	in_ifaddrhashtbl = hashinit(IN_IFADDR_HASH_SIZE, HASH_LIST, M_IFADDR,
    431 	    M_WAITOK, &in_ifaddrhash);
    432 	in_multihashtbl = hashinit(IN_IFADDR_HASH_SIZE, HASH_LIST, M_IPMADDR,
    433 	    M_WAITOK, &in_multihash);
    434 	ip_mtudisc_timeout_q = rt_timer_queue_create(ip_mtudisc_timeout);
    435 #ifdef GATEWAY
    436 	ipflow_init(ip_hashsize);
    437 #endif
    438 
    439 #ifdef PFIL_HOOKS
    440 	/* Register our Packet Filter hook. */
    441 	inet_pfil_hook.ph_type = PFIL_TYPE_AF;
    442 	inet_pfil_hook.ph_af   = AF_INET;
    443 	i = pfil_head_register(&inet_pfil_hook);
    444 	if (i != 0)
    445 		printf("ip_init: WARNING: unable to register pfil hook, "
    446 		    "error %d\n", i);
    447 #endif /* PFIL_HOOKS */
    448 
    449 #ifdef MBUFTRACE
    450 	MOWNER_ATTACH(&ip_tx_mowner);
    451 	MOWNER_ATTACH(&ip_rx_mowner);
    452 #endif /* MBUFTRACE */
    453 
    454 	ipstat_percpu = percpu_alloc(sizeof(uint64_t) * IP_NSTATS);
    455 }
    456 
    457 struct	sockaddr_in ipaddr = {
    458 	.sin_len = sizeof(ipaddr),
    459 	.sin_family = AF_INET,
    460 };
    461 struct	route ipforward_rt;
    462 
    463 /*
    464  * IP software interrupt routine
    465  */
    466 void
    467 ipintr(void)
    468 {
    469 	int s;
    470 	struct mbuf *m;
    471 
    472 	while (!IF_IS_EMPTY(&ipintrq)) {
    473 		s = splnet();
    474 		IF_DEQUEUE(&ipintrq, m);
    475 		splx(s);
    476 		if (m == 0)
    477 			return;
    478 		ip_input(m);
    479 	}
    480 }
    481 
    482 /*
    483  * Ip input routine.  Checksum and byte swap header.  If fragmented
    484  * try to reassemble.  Process options.  Pass to next level.
    485  */
    486 void
    487 ip_input(struct mbuf *m)
    488 {
    489 	struct ip *ip = NULL;
    490 	struct ipq *fp;
    491 	struct in_ifaddr *ia;
    492 	struct ifaddr *ifa;
    493 	struct ipqent *ipqe;
    494 	int hlen = 0, mff, len;
    495 	int downmatch;
    496 	int checkif;
    497 	int srcrt = 0;
    498 	int s;
    499 	u_int hash;
    500 #ifdef FAST_IPSEC
    501 	struct m_tag *mtag;
    502 	struct tdb_ident *tdbi;
    503 	struct secpolicy *sp;
    504 	int error;
    505 #endif /* FAST_IPSEC */
    506 
    507 	MCLAIM(m, &ip_rx_mowner);
    508 #ifdef	DIAGNOSTIC
    509 	if ((m->m_flags & M_PKTHDR) == 0)
    510 		panic("ipintr no HDR");
    511 #endif
    512 
    513 	/*
    514 	 * If no IP addresses have been set yet but the interfaces
    515 	 * are receiving, can't do anything with incoming packets yet.
    516 	 */
    517 	if (TAILQ_FIRST(&in_ifaddrhead) == 0)
    518 		goto bad;
    519 	IP_STATINC(IP_STAT_TOTAL);
    520 	/*
    521 	 * If the IP header is not aligned, slurp it up into a new
    522 	 * mbuf with space for link headers, in the event we forward
    523 	 * it.  Otherwise, if it is aligned, make sure the entire
    524 	 * base IP header is in the first mbuf of the chain.
    525 	 */
    526 	if (IP_HDR_ALIGNED_P(mtod(m, void *)) == 0) {
    527 		if ((m = m_copyup(m, sizeof(struct ip),
    528 				  (max_linkhdr + 3) & ~3)) == NULL) {
    529 			/* XXXJRT new stat, please */
    530 			IP_STATINC(IP_STAT_TOOSMALL);
    531 			return;
    532 		}
    533 	} else if (__predict_false(m->m_len < sizeof (struct ip))) {
    534 		if ((m = m_pullup(m, sizeof (struct ip))) == NULL) {
    535 			IP_STATINC(IP_STAT_TOOSMALL);
    536 			return;
    537 		}
    538 	}
    539 	ip = mtod(m, struct ip *);
    540 	if (ip->ip_v != IPVERSION) {
    541 		IP_STATINC(IP_STAT_BADVERS);
    542 		goto bad;
    543 	}
    544 	hlen = ip->ip_hl << 2;
    545 	if (hlen < sizeof(struct ip)) {	/* minimum header length */
    546 		IP_STATINC(IP_STAT_BADHLEN);
    547 		goto bad;
    548 	}
    549 	if (hlen > m->m_len) {
    550 		if ((m = m_pullup(m, hlen)) == 0) {
    551 			IP_STATINC(IP_STAT_BADHLEN);
    552 			return;
    553 		}
    554 		ip = mtod(m, struct ip *);
    555 	}
    556 
    557 	/*
    558 	 * RFC1122: packets with a multicast source address are
    559 	 * not allowed.
    560 	 */
    561 	if (IN_MULTICAST(ip->ip_src.s_addr)) {
    562 		IP_STATINC(IP_STAT_BADADDR);
    563 		goto bad;
    564 	}
    565 
    566 	/* 127/8 must not appear on wire - RFC1122 */
    567 	if ((ntohl(ip->ip_dst.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET ||
    568 	    (ntohl(ip->ip_src.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET) {
    569 		if ((m->m_pkthdr.rcvif->if_flags & IFF_LOOPBACK) == 0) {
    570 			IP_STATINC(IP_STAT_BADADDR);
    571 			goto bad;
    572 		}
    573 	}
    574 
    575 	switch (m->m_pkthdr.csum_flags &
    576 		((m->m_pkthdr.rcvif->if_csum_flags_rx & M_CSUM_IPv4) |
    577 		 M_CSUM_IPv4_BAD)) {
    578 	case M_CSUM_IPv4|M_CSUM_IPv4_BAD:
    579 		INET_CSUM_COUNTER_INCR(&ip_hwcsum_bad);
    580 		goto badcsum;
    581 
    582 	case M_CSUM_IPv4:
    583 		/* Checksum was okay. */
    584 		INET_CSUM_COUNTER_INCR(&ip_hwcsum_ok);
    585 		break;
    586 
    587 	default:
    588 		/*
    589 		 * Must compute it ourselves.  Maybe skip checksum on
    590 		 * loopback interfaces.
    591 		 */
    592 		if (__predict_true(!(m->m_pkthdr.rcvif->if_flags &
    593 				     IFF_LOOPBACK) || ip_do_loopback_cksum)) {
    594 			INET_CSUM_COUNTER_INCR(&ip_swcsum);
    595 			if (in_cksum(m, hlen) != 0)
    596 				goto badcsum;
    597 		}
    598 		break;
    599 	}
    600 
    601 	/* Retrieve the packet length. */
    602 	len = ntohs(ip->ip_len);
    603 
    604 	/*
    605 	 * Check for additional length bogosity
    606 	 */
    607 	if (len < hlen) {
    608 		IP_STATINC(IP_STAT_BADLEN);
    609 		goto bad;
    610 	}
    611 
    612 	/*
    613 	 * Check that the amount of data in the buffers
    614 	 * is as at least much as the IP header would have us expect.
    615 	 * Trim mbufs if longer than we expect.
    616 	 * Drop packet if shorter than we expect.
    617 	 */
    618 	if (m->m_pkthdr.len < len) {
    619 		IP_STATINC(IP_STAT_TOOSHORT);
    620 		goto bad;
    621 	}
    622 	if (m->m_pkthdr.len > len) {
    623 		if (m->m_len == m->m_pkthdr.len) {
    624 			m->m_len = len;
    625 			m->m_pkthdr.len = len;
    626 		} else
    627 			m_adj(m, len - m->m_pkthdr.len);
    628 	}
    629 
    630 #if defined(IPSEC)
    631 	/* ipflow (IP fast forwarding) is not compatible with IPsec. */
    632 	m->m_flags &= ~M_CANFASTFWD;
    633 #else
    634 	/*
    635 	 * Assume that we can create a fast-forward IP flow entry
    636 	 * based on this packet.
    637 	 */
    638 	m->m_flags |= M_CANFASTFWD;
    639 #endif
    640 
    641 #ifdef PFIL_HOOKS
    642 	/*
    643 	 * Run through list of hooks for input packets.  If there are any
    644 	 * filters which require that additional packets in the flow are
    645 	 * not fast-forwarded, they must clear the M_CANFASTFWD flag.
    646 	 * Note that filters must _never_ set this flag, as another filter
    647 	 * in the list may have previously cleared it.
    648 	 */
    649 	/*
    650 	 * let ipfilter look at packet on the wire,
    651 	 * not the decapsulated packet.
    652 	 */
    653 #ifdef IPSEC
    654 	if (!ipsec_getnhist(m))
    655 #elif defined(FAST_IPSEC)
    656 	if (!ipsec_indone(m))
    657 #else
    658 	if (1)
    659 #endif
    660 	{
    661 		struct in_addr odst;
    662 
    663 		odst = ip->ip_dst;
    664 		if (pfil_run_hooks(&inet_pfil_hook, &m, m->m_pkthdr.rcvif,
    665 		    PFIL_IN) != 0)
    666 			return;
    667 		if (m == NULL)
    668 			return;
    669 		ip = mtod(m, struct ip *);
    670 		hlen = ip->ip_hl << 2;
    671 		/*
    672 		 * XXX The setting of "srcrt" here is to prevent ip_forward()
    673 		 * from generating ICMP redirects for packets that have
    674 		 * been redirected by a hook back out on to the same LAN that
    675 		 * they came from and is not an indication that the packet
    676 		 * is being inffluenced by source routing options.  This
    677 		 * allows things like
    678 		 * "rdr tlp0 0/0 port 80 -> 1.1.1.200 3128 tcp"
    679 		 * where tlp0 is both on the 1.1.1.0/24 network and is the
    680 		 * default route for hosts on 1.1.1.0/24.  Of course this
    681 		 * also requires a "map tlp0 ..." to complete the story.
    682 		 * One might argue whether or not this kind of network config.
    683 		 * should be supported in this manner...
    684 		 */
    685 		srcrt = (odst.s_addr != ip->ip_dst.s_addr);
    686 	}
    687 #endif /* PFIL_HOOKS */
    688 
    689 #ifdef ALTQ
    690 	/* XXX Temporary until ALTQ is changed to use a pfil hook */
    691 	if (altq_input != NULL && (*altq_input)(m, AF_INET) == 0) {
    692 		/* packet dropped by traffic conditioner */
    693 		return;
    694 	}
    695 #endif
    696 
    697 	/*
    698 	 * Process options and, if not destined for us,
    699 	 * ship it on.  ip_dooptions returns 1 when an
    700 	 * error was detected (causing an icmp message
    701 	 * to be sent and the original packet to be freed).
    702 	 */
    703 	ip_nhops = 0;		/* for source routed packets */
    704 	if (hlen > sizeof (struct ip) && ip_dooptions(m))
    705 		return;
    706 
    707 	/*
    708 	 * Enable a consistency check between the destination address
    709 	 * and the arrival interface for a unicast packet (the RFC 1122
    710 	 * strong ES model) if IP forwarding is disabled and the packet
    711 	 * is not locally generated.
    712 	 *
    713 	 * XXX - Checking also should be disabled if the destination
    714 	 * address is ipnat'ed to a different interface.
    715 	 *
    716 	 * XXX - Checking is incompatible with IP aliases added
    717 	 * to the loopback interface instead of the interface where
    718 	 * the packets are received.
    719 	 *
    720 	 * XXX - We need to add a per ifaddr flag for this so that
    721 	 * we get finer grain control.
    722 	 */
    723 	checkif = ip_checkinterface && (ipforwarding == 0) &&
    724 	    (m->m_pkthdr.rcvif != NULL) &&
    725 	    ((m->m_pkthdr.rcvif->if_flags & IFF_LOOPBACK) == 0);
    726 
    727 	/*
    728 	 * Check our list of addresses, to see if the packet is for us.
    729 	 *
    730 	 * Traditional 4.4BSD did not consult IFF_UP at all.
    731 	 * The behavior here is to treat addresses on !IFF_UP interface
    732 	 * as not mine.
    733 	 */
    734 	downmatch = 0;
    735 	LIST_FOREACH(ia, &IN_IFADDR_HASH(ip->ip_dst.s_addr), ia_hash) {
    736 		if (in_hosteq(ia->ia_addr.sin_addr, ip->ip_dst)) {
    737 			if (checkif && ia->ia_ifp != m->m_pkthdr.rcvif)
    738 				continue;
    739 			if ((ia->ia_ifp->if_flags & IFF_UP) != 0)
    740 				break;
    741 			else
    742 				downmatch++;
    743 		}
    744 	}
    745 	if (ia != NULL)
    746 		goto ours;
    747 	if (m->m_pkthdr.rcvif && m->m_pkthdr.rcvif->if_flags & IFF_BROADCAST) {
    748 		IFADDR_FOREACH(ifa, m->m_pkthdr.rcvif) {
    749 			if (ifa->ifa_addr->sa_family != AF_INET)
    750 				continue;
    751 			ia = ifatoia(ifa);
    752 			if (in_hosteq(ip->ip_dst, ia->ia_broadaddr.sin_addr) ||
    753 			    in_hosteq(ip->ip_dst, ia->ia_netbroadcast) ||
    754 			    /*
    755 			     * Look for all-0's host part (old broadcast addr),
    756 			     * either for subnet or net.
    757 			     */
    758 			    ip->ip_dst.s_addr == ia->ia_subnet ||
    759 			    ip->ip_dst.s_addr == ia->ia_net)
    760 				goto ours;
    761 			/*
    762 			 * An interface with IP address zero accepts
    763 			 * all packets that arrive on that interface.
    764 			 */
    765 			if (in_nullhost(ia->ia_addr.sin_addr))
    766 				goto ours;
    767 		}
    768 	}
    769 	if (IN_MULTICAST(ip->ip_dst.s_addr)) {
    770 		struct in_multi *inm;
    771 #ifdef MROUTING
    772 		extern struct socket *ip_mrouter;
    773 
    774 		if (ip_mrouter) {
    775 			/*
    776 			 * If we are acting as a multicast router, all
    777 			 * incoming multicast packets are passed to the
    778 			 * kernel-level multicast forwarding function.
    779 			 * The packet is returned (relatively) intact; if
    780 			 * ip_mforward() returns a non-zero value, the packet
    781 			 * must be discarded, else it may be accepted below.
    782 			 *
    783 			 * (The IP ident field is put in the same byte order
    784 			 * as expected when ip_mforward() is called from
    785 			 * ip_output().)
    786 			 */
    787 			if (ip_mforward(m, m->m_pkthdr.rcvif) != 0) {
    788 				IP_STATINC(IP_STAT_CANTFORWARD);
    789 				m_freem(m);
    790 				return;
    791 			}
    792 
    793 			/*
    794 			 * The process-level routing demon needs to receive
    795 			 * all multicast IGMP packets, whether or not this
    796 			 * host belongs to their destination groups.
    797 			 */
    798 			if (ip->ip_p == IPPROTO_IGMP)
    799 				goto ours;
    800 			IP_STATINC(IP_STAT_CANTFORWARD);
    801 		}
    802 #endif
    803 		/*
    804 		 * See if we belong to the destination multicast group on the
    805 		 * arrival interface.
    806 		 */
    807 		IN_LOOKUP_MULTI(ip->ip_dst, m->m_pkthdr.rcvif, inm);
    808 		if (inm == NULL) {
    809 			IP_STATINC(IP_STAT_CANTFORWARD);
    810 			m_freem(m);
    811 			return;
    812 		}
    813 		goto ours;
    814 	}
    815 	if (ip->ip_dst.s_addr == INADDR_BROADCAST ||
    816 	    in_nullhost(ip->ip_dst))
    817 		goto ours;
    818 
    819 	/*
    820 	 * Not for us; forward if possible and desirable.
    821 	 */
    822 	if (ipforwarding == 0) {
    823 		IP_STATINC(IP_STAT_CANTFORWARD);
    824 		m_freem(m);
    825 	} else {
    826 		/*
    827 		 * If ip_dst matched any of my address on !IFF_UP interface,
    828 		 * and there's no IFF_UP interface that matches ip_dst,
    829 		 * send icmp unreach.  Forwarding it will result in in-kernel
    830 		 * forwarding loop till TTL goes to 0.
    831 		 */
    832 		if (downmatch) {
    833 			icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_HOST, 0, 0);
    834 			IP_STATINC(IP_STAT_CANTFORWARD);
    835 			return;
    836 		}
    837 #ifdef IPSEC
    838 		if (ipsec4_in_reject(m, NULL)) {
    839 			IPSEC_STATINC(IPSEC_STAT_IN_POLVIO);
    840 			goto bad;
    841 		}
    842 #endif
    843 #ifdef FAST_IPSEC
    844 		mtag = m_tag_find(m, PACKET_TAG_IPSEC_IN_DONE, NULL);
    845 		s = splsoftnet();
    846 		if (mtag != NULL) {
    847 			tdbi = (struct tdb_ident *)(mtag + 1);
    848 			sp = ipsec_getpolicy(tdbi, IPSEC_DIR_INBOUND);
    849 		} else {
    850 			sp = ipsec_getpolicybyaddr(m, IPSEC_DIR_INBOUND,
    851 						   IP_FORWARDING, &error);
    852 		}
    853 		if (sp == NULL) {	/* NB: can happen if error */
    854 			splx(s);
    855 			/*XXX error stat???*/
    856 			DPRINTF(("ip_input: no SP for forwarding\n"));	/*XXX*/
    857 			goto bad;
    858 		}
    859 
    860 		/*
    861 		 * Check security policy against packet attributes.
    862 		 */
    863 		error = ipsec_in_reject(sp, m);
    864 		KEY_FREESP(&sp);
    865 		splx(s);
    866 		if (error) {
    867 			IP_STATINC(IP_STAT_CANTFORWARD);
    868 			goto bad;
    869 		}
    870 
    871 		/*
    872 		 * Peek at the outbound SP for this packet to determine if
    873 		 * it's a Fast Forward candidate.
    874 		 */
    875 		mtag = m_tag_find(m, PACKET_TAG_IPSEC_PENDING_TDB, NULL);
    876 		if (mtag != NULL)
    877 			m->m_flags &= ~M_CANFASTFWD;
    878 		else {
    879 			s = splsoftnet();
    880 			sp = ipsec4_checkpolicy(m, IPSEC_DIR_OUTBOUND,
    881 			    (IP_FORWARDING |
    882 			     (ip_directedbcast ? IP_ALLOWBROADCAST : 0)),
    883 			    &error, NULL);
    884 			if (sp != NULL) {
    885 				m->m_flags &= ~M_CANFASTFWD;
    886 				KEY_FREESP(&sp);
    887 			}
    888 			splx(s);
    889 		}
    890 #endif	/* FAST_IPSEC */
    891 
    892 		ip_forward(m, srcrt);
    893 	}
    894 	return;
    895 
    896 ours:
    897 	/*
    898 	 * If offset or IP_MF are set, must reassemble.
    899 	 * Otherwise, nothing need be done.
    900 	 * (We could look in the reassembly queue to see
    901 	 * if the packet was previously fragmented,
    902 	 * but it's not worth the time; just let them time out.)
    903 	 */
    904 	if (ip->ip_off & ~htons(IP_DF|IP_RF)) {
    905 		uint16_t off;
    906 		/*
    907 		 * Prevent TCP blind data attacks by not allowing non-initial
    908 		 * fragments to start at less than 68 bytes (minimal fragment
    909 		 * size) and making sure the first fragment is at least 68
    910 		 * bytes.
    911 		 */
    912 		off = (ntohs(ip->ip_off) & IP_OFFMASK) << 3;
    913 		if ((off > 0 ? off + hlen : len) < IP_MINFRAGSIZE - 1) {
    914 			IP_STATINC(IP_STAT_BADFRAGS);
    915 			goto bad;
    916 		}
    917 		/*
    918 		 * Look for queue of fragments
    919 		 * of this datagram.
    920 		 */
    921 		IPQ_LOCK();
    922 		hash = IPREASS_HASH(ip->ip_src.s_addr, ip->ip_id);
    923 		LIST_FOREACH(fp, &ipq[hash], ipq_q) {
    924 			if (ip->ip_id == fp->ipq_id &&
    925 			    in_hosteq(ip->ip_src, fp->ipq_src) &&
    926 			    in_hosteq(ip->ip_dst, fp->ipq_dst) &&
    927 			    ip->ip_p == fp->ipq_p) {
    928 				/*
    929 				 * Make sure the TOS is matches previous
    930 				 * fragments.
    931 				 */
    932 				if (ip->ip_tos != fp->ipq_tos) {
    933 					IP_STATINC(IP_STAT_BADFRAGS);
    934 					goto bad;
    935 				}
    936 				goto found;
    937 			}
    938 		}
    939 		fp = 0;
    940 found:
    941 
    942 		/*
    943 		 * Adjust ip_len to not reflect header,
    944 		 * set ipqe_mff if more fragments are expected,
    945 		 * convert offset of this to bytes.
    946 		 */
    947 		ip->ip_len = htons(ntohs(ip->ip_len) - hlen);
    948 		mff = (ip->ip_off & htons(IP_MF)) != 0;
    949 		if (mff) {
    950 		        /*
    951 		         * Make sure that fragments have a data length
    952 			 * that's a non-zero multiple of 8 bytes.
    953 		         */
    954 			if (ntohs(ip->ip_len) == 0 ||
    955 			    (ntohs(ip->ip_len) & 0x7) != 0) {
    956 				IP_STATINC(IP_STAT_BADFRAGS);
    957 				IPQ_UNLOCK();
    958 				goto bad;
    959 			}
    960 		}
    961 		ip->ip_off = htons((ntohs(ip->ip_off) & IP_OFFMASK) << 3);
    962 
    963 		/*
    964 		 * If datagram marked as having more fragments
    965 		 * or if this is not the first fragment,
    966 		 * attempt reassembly; if it succeeds, proceed.
    967 		 */
    968 		if (mff || ip->ip_off != htons(0)) {
    969 			IP_STATINC(IP_STAT_FRAGMENTS);
    970 			s = splvm();
    971 			ipqe = pool_get(&ipqent_pool, PR_NOWAIT);
    972 			splx(s);
    973 			if (ipqe == NULL) {
    974 				IP_STATINC(IP_STAT_RCVMEMDROP);
    975 				IPQ_UNLOCK();
    976 				goto bad;
    977 			}
    978 			ipqe->ipqe_mff = mff;
    979 			ipqe->ipqe_m = m;
    980 			ipqe->ipqe_ip = ip;
    981 			m = ip_reass(ipqe, fp, &ipq[hash]);
    982 			if (m == 0) {
    983 				IPQ_UNLOCK();
    984 				return;
    985 			}
    986 			IP_STATINC(IP_STAT_REASSEMBLED);
    987 			ip = mtod(m, struct ip *);
    988 			hlen = ip->ip_hl << 2;
    989 			ip->ip_len = htons(ntohs(ip->ip_len) + hlen);
    990 		} else
    991 			if (fp)
    992 				ip_freef(fp);
    993 		IPQ_UNLOCK();
    994 	}
    995 
    996 #if defined(IPSEC)
    997 	/*
    998 	 * enforce IPsec policy checking if we are seeing last header.
    999 	 * note that we do not visit this with protocols with pcb layer
   1000 	 * code - like udp/tcp/raw ip.
   1001 	 */
   1002 	if ((inetsw[ip_protox[ip->ip_p]].pr_flags & PR_LASTHDR) != 0 &&
   1003 	    ipsec4_in_reject(m, NULL)) {
   1004 		IPSEC_STATINC(IPSEC_STAT_IN_POLVIO);
   1005 		goto bad;
   1006 	}
   1007 #endif
   1008 #ifdef FAST_IPSEC
   1009 	/*
   1010 	 * enforce IPsec policy checking if we are seeing last header.
   1011 	 * note that we do not visit this with protocols with pcb layer
   1012 	 * code - like udp/tcp/raw ip.
   1013 	 */
   1014 	if ((inetsw[ip_protox[ip->ip_p]].pr_flags & PR_LASTHDR) != 0) {
   1015 		/*
   1016 		 * Check if the packet has already had IPsec processing
   1017 		 * done.  If so, then just pass it along.  This tag gets
   1018 		 * set during AH, ESP, etc. input handling, before the
   1019 		 * packet is returned to the ip input queue for delivery.
   1020 		 */
   1021 		mtag = m_tag_find(m, PACKET_TAG_IPSEC_IN_DONE, NULL);
   1022 		s = splsoftnet();
   1023 		if (mtag != NULL) {
   1024 			tdbi = (struct tdb_ident *)(mtag + 1);
   1025 			sp = ipsec_getpolicy(tdbi, IPSEC_DIR_INBOUND);
   1026 		} else {
   1027 			sp = ipsec_getpolicybyaddr(m, IPSEC_DIR_INBOUND,
   1028 						   IP_FORWARDING, &error);
   1029 		}
   1030 		if (sp != NULL) {
   1031 			/*
   1032 			 * Check security policy against packet attributes.
   1033 			 */
   1034 			error = ipsec_in_reject(sp, m);
   1035 			KEY_FREESP(&sp);
   1036 		} else {
   1037 			/* XXX error stat??? */
   1038 			error = EINVAL;
   1039 DPRINTF(("ip_input: no SP, packet discarded\n"));/*XXX*/
   1040 		}
   1041 		splx(s);
   1042 		if (error)
   1043 			goto bad;
   1044 	}
   1045 #endif /* FAST_IPSEC */
   1046 
   1047 	/*
   1048 	 * Switch out to protocol's input routine.
   1049 	 */
   1050 #if IFA_STATS
   1051 	if (ia && ip)
   1052 		ia->ia_ifa.ifa_data.ifad_inbytes += ntohs(ip->ip_len);
   1053 #endif
   1054 	IP_STATINC(IP_STAT_DELIVERED);
   1055     {
   1056 	int off = hlen, nh = ip->ip_p;
   1057 
   1058 	(*inetsw[ip_protox[nh]].pr_input)(m, off, nh);
   1059 	return;
   1060     }
   1061 bad:
   1062 	m_freem(m);
   1063 	return;
   1064 
   1065 badcsum:
   1066 	IP_STATINC(IP_STAT_BADSUM);
   1067 	m_freem(m);
   1068 }
   1069 
   1070 /*
   1071  * Take incoming datagram fragment and try to
   1072  * reassemble it into whole datagram.  If a chain for
   1073  * reassembly of this datagram already exists, then it
   1074  * is given as fp; otherwise have to make a chain.
   1075  */
   1076 struct mbuf *
   1077 ip_reass(struct ipqent *ipqe, struct ipq *fp, struct ipqhead *ipqhead)
   1078 {
   1079 	struct mbuf *m = ipqe->ipqe_m;
   1080 	struct ipqent *nq, *p, *q;
   1081 	struct ip *ip;
   1082 	struct mbuf *t;
   1083 	int hlen = ipqe->ipqe_ip->ip_hl << 2;
   1084 	int i, next, s;
   1085 
   1086 	IPQ_LOCK_CHECK();
   1087 
   1088 	/*
   1089 	 * Presence of header sizes in mbufs
   1090 	 * would confuse code below.
   1091 	 */
   1092 	m->m_data += hlen;
   1093 	m->m_len -= hlen;
   1094 
   1095 #ifdef	notyet
   1096 	/* make sure fragment limit is up-to-date */
   1097 	CHECK_NMBCLUSTER_PARAMS();
   1098 
   1099 	/* If we have too many fragments, drop the older half. */
   1100 	if (ip_nfrags >= ip_maxfrags)
   1101 		ip_reass_drophalf(void);
   1102 #endif
   1103 
   1104 	/*
   1105 	 * We are about to add a fragment; increment frag count.
   1106 	 */
   1107 	ip_nfrags++;
   1108 
   1109 	/*
   1110 	 * If first fragment to arrive, create a reassembly queue.
   1111 	 */
   1112 	if (fp == 0) {
   1113 		/*
   1114 		 * Enforce upper bound on number of fragmented packets
   1115 		 * for which we attempt reassembly;
   1116 		 * If maxfrag is 0, never accept fragments.
   1117 		 * If maxfrag is -1, accept all fragments without limitation.
   1118 		 */
   1119 		if (ip_maxfragpackets < 0)
   1120 			;
   1121 		else if (ip_nfragpackets >= ip_maxfragpackets)
   1122 			goto dropfrag;
   1123 		ip_nfragpackets++;
   1124 		MALLOC(fp, struct ipq *, sizeof (struct ipq),
   1125 		    M_FTABLE, M_NOWAIT);
   1126 		if (fp == NULL)
   1127 			goto dropfrag;
   1128 		LIST_INSERT_HEAD(ipqhead, fp, ipq_q);
   1129 		fp->ipq_nfrags = 1;
   1130 		fp->ipq_ttl = IPFRAGTTL;
   1131 		fp->ipq_p = ipqe->ipqe_ip->ip_p;
   1132 		fp->ipq_id = ipqe->ipqe_ip->ip_id;
   1133 		fp->ipq_tos = ipqe->ipqe_ip->ip_tos;
   1134 		TAILQ_INIT(&fp->ipq_fragq);
   1135 		fp->ipq_src = ipqe->ipqe_ip->ip_src;
   1136 		fp->ipq_dst = ipqe->ipqe_ip->ip_dst;
   1137 		p = NULL;
   1138 		goto insert;
   1139 	} else {
   1140 		fp->ipq_nfrags++;
   1141 	}
   1142 
   1143 	/*
   1144 	 * Find a segment which begins after this one does.
   1145 	 */
   1146 	for (p = NULL, q = TAILQ_FIRST(&fp->ipq_fragq); q != NULL;
   1147 	    p = q, q = TAILQ_NEXT(q, ipqe_q))
   1148 		if (ntohs(q->ipqe_ip->ip_off) > ntohs(ipqe->ipqe_ip->ip_off))
   1149 			break;
   1150 
   1151 	/*
   1152 	 * If there is a preceding segment, it may provide some of
   1153 	 * our data already.  If so, drop the data from the incoming
   1154 	 * segment.  If it provides all of our data, drop us.
   1155 	 */
   1156 	if (p != NULL) {
   1157 		i = ntohs(p->ipqe_ip->ip_off) + ntohs(p->ipqe_ip->ip_len) -
   1158 		    ntohs(ipqe->ipqe_ip->ip_off);
   1159 		if (i > 0) {
   1160 			if (i >= ntohs(ipqe->ipqe_ip->ip_len))
   1161 				goto dropfrag;
   1162 			m_adj(ipqe->ipqe_m, i);
   1163 			ipqe->ipqe_ip->ip_off =
   1164 			    htons(ntohs(ipqe->ipqe_ip->ip_off) + i);
   1165 			ipqe->ipqe_ip->ip_len =
   1166 			    htons(ntohs(ipqe->ipqe_ip->ip_len) - i);
   1167 		}
   1168 	}
   1169 
   1170 	/*
   1171 	 * While we overlap succeeding segments trim them or,
   1172 	 * if they are completely covered, dequeue them.
   1173 	 */
   1174 	for (; q != NULL &&
   1175 	    ntohs(ipqe->ipqe_ip->ip_off) + ntohs(ipqe->ipqe_ip->ip_len) >
   1176 	    ntohs(q->ipqe_ip->ip_off); q = nq) {
   1177 		i = (ntohs(ipqe->ipqe_ip->ip_off) +
   1178 		    ntohs(ipqe->ipqe_ip->ip_len)) - ntohs(q->ipqe_ip->ip_off);
   1179 		if (i < ntohs(q->ipqe_ip->ip_len)) {
   1180 			q->ipqe_ip->ip_len =
   1181 			    htons(ntohs(q->ipqe_ip->ip_len) - i);
   1182 			q->ipqe_ip->ip_off =
   1183 			    htons(ntohs(q->ipqe_ip->ip_off) + i);
   1184 			m_adj(q->ipqe_m, i);
   1185 			break;
   1186 		}
   1187 		nq = TAILQ_NEXT(q, ipqe_q);
   1188 		m_freem(q->ipqe_m);
   1189 		TAILQ_REMOVE(&fp->ipq_fragq, q, ipqe_q);
   1190 		s = splvm();
   1191 		pool_put(&ipqent_pool, q);
   1192 		splx(s);
   1193 		fp->ipq_nfrags--;
   1194 		ip_nfrags--;
   1195 	}
   1196 
   1197 insert:
   1198 	/*
   1199 	 * Stick new segment in its place;
   1200 	 * check for complete reassembly.
   1201 	 */
   1202 	if (p == NULL) {
   1203 		TAILQ_INSERT_HEAD(&fp->ipq_fragq, ipqe, ipqe_q);
   1204 	} else {
   1205 		TAILQ_INSERT_AFTER(&fp->ipq_fragq, p, ipqe, ipqe_q);
   1206 	}
   1207 	next = 0;
   1208 	for (p = NULL, q = TAILQ_FIRST(&fp->ipq_fragq); q != NULL;
   1209 	    p = q, q = TAILQ_NEXT(q, ipqe_q)) {
   1210 		if (ntohs(q->ipqe_ip->ip_off) != next)
   1211 			return (0);
   1212 		next += ntohs(q->ipqe_ip->ip_len);
   1213 	}
   1214 	if (p->ipqe_mff)
   1215 		return (0);
   1216 
   1217 	/*
   1218 	 * Reassembly is complete.  Check for a bogus message size and
   1219 	 * concatenate fragments.
   1220 	 */
   1221 	q = TAILQ_FIRST(&fp->ipq_fragq);
   1222 	ip = q->ipqe_ip;
   1223 	if ((next + (ip->ip_hl << 2)) > IP_MAXPACKET) {
   1224 		IP_STATINC(IP_STAT_TOOLONG);
   1225 		ip_freef(fp);
   1226 		return (0);
   1227 	}
   1228 	m = q->ipqe_m;
   1229 	t = m->m_next;
   1230 	m->m_next = 0;
   1231 	m_cat(m, t);
   1232 	nq = TAILQ_NEXT(q, ipqe_q);
   1233 	s = splvm();
   1234 	pool_put(&ipqent_pool, q);
   1235 	splx(s);
   1236 	for (q = nq; q != NULL; q = nq) {
   1237 		t = q->ipqe_m;
   1238 		nq = TAILQ_NEXT(q, ipqe_q);
   1239 		s = splvm();
   1240 		pool_put(&ipqent_pool, q);
   1241 		splx(s);
   1242 		m_cat(m, t);
   1243 	}
   1244 	ip_nfrags -= fp->ipq_nfrags;
   1245 
   1246 	/*
   1247 	 * Create header for new ip packet by
   1248 	 * modifying header of first packet;
   1249 	 * dequeue and discard fragment reassembly header.
   1250 	 * Make header visible.
   1251 	 */
   1252 	ip->ip_len = htons(next);
   1253 	ip->ip_src = fp->ipq_src;
   1254 	ip->ip_dst = fp->ipq_dst;
   1255 	LIST_REMOVE(fp, ipq_q);
   1256 	FREE(fp, M_FTABLE);
   1257 	ip_nfragpackets--;
   1258 	m->m_len += (ip->ip_hl << 2);
   1259 	m->m_data -= (ip->ip_hl << 2);
   1260 	/* some debugging cruft by sklower, below, will go away soon */
   1261 	if (m->m_flags & M_PKTHDR) { /* XXX this should be done elsewhere */
   1262 		int plen = 0;
   1263 		for (t = m; t; t = t->m_next)
   1264 			plen += t->m_len;
   1265 		m->m_pkthdr.len = plen;
   1266 		m->m_pkthdr.csum_flags = 0;
   1267 	}
   1268 	return (m);
   1269 
   1270 dropfrag:
   1271 	if (fp != 0)
   1272 		fp->ipq_nfrags--;
   1273 	ip_nfrags--;
   1274 	IP_STATINC(IP_STAT_FRAGDROPPED);
   1275 	m_freem(m);
   1276 	s = splvm();
   1277 	pool_put(&ipqent_pool, ipqe);
   1278 	splx(s);
   1279 	return (0);
   1280 }
   1281 
   1282 /*
   1283  * Free a fragment reassembly header and all
   1284  * associated datagrams.
   1285  */
   1286 void
   1287 ip_freef(struct ipq *fp)
   1288 {
   1289 	struct ipqent *q, *p;
   1290 	u_int nfrags = 0;
   1291 	int s;
   1292 
   1293 	IPQ_LOCK_CHECK();
   1294 
   1295 	for (q = TAILQ_FIRST(&fp->ipq_fragq); q != NULL; q = p) {
   1296 		p = TAILQ_NEXT(q, ipqe_q);
   1297 		m_freem(q->ipqe_m);
   1298 		nfrags++;
   1299 		TAILQ_REMOVE(&fp->ipq_fragq, q, ipqe_q);
   1300 		s = splvm();
   1301 		pool_put(&ipqent_pool, q);
   1302 		splx(s);
   1303 	}
   1304 
   1305 	if (nfrags != fp->ipq_nfrags)
   1306 	    printf("ip_freef: nfrags %d != %d\n", fp->ipq_nfrags, nfrags);
   1307 	ip_nfrags -= nfrags;
   1308 	LIST_REMOVE(fp, ipq_q);
   1309 	FREE(fp, M_FTABLE);
   1310 	ip_nfragpackets--;
   1311 }
   1312 
   1313 /*
   1314  * IP reassembly TTL machinery for  multiplicative drop.
   1315  */
   1316 static u_int	fragttl_histo[(IPFRAGTTL+1)];
   1317 
   1318 
   1319 /*
   1320  * Decrement TTL of all reasembly queue entries by `ticks'.
   1321  * Count number of distinct fragments (as opposed to partial, fragmented
   1322  * datagrams) in the reassembly queue.  While we  traverse the entire
   1323  * reassembly queue, compute and return the median TTL over all fragments.
   1324  */
   1325 static u_int
   1326 ip_reass_ttl_decr(u_int ticks)
   1327 {
   1328 	u_int nfrags, median, dropfraction, keepfraction;
   1329 	struct ipq *fp, *nfp;
   1330 	int i;
   1331 
   1332 	nfrags = 0;
   1333 	memset(fragttl_histo, 0, sizeof fragttl_histo);
   1334 
   1335 	for (i = 0; i < IPREASS_NHASH; i++) {
   1336 		for (fp = LIST_FIRST(&ipq[i]); fp != NULL; fp = nfp) {
   1337 			fp->ipq_ttl = ((fp->ipq_ttl  <= ticks) ?
   1338 				       0 : fp->ipq_ttl - ticks);
   1339 			nfp = LIST_NEXT(fp, ipq_q);
   1340 			if (fp->ipq_ttl == 0) {
   1341 				IP_STATINC(IP_STAT_FRAGTIMEOUT);
   1342 				ip_freef(fp);
   1343 			} else {
   1344 				nfrags += fp->ipq_nfrags;
   1345 				fragttl_histo[fp->ipq_ttl] += fp->ipq_nfrags;
   1346 			}
   1347 		}
   1348 	}
   1349 
   1350 	KASSERT(ip_nfrags == nfrags);
   1351 
   1352 	/* Find median (or other drop fraction) in histogram. */
   1353 	dropfraction = (ip_nfrags / 2);
   1354 	keepfraction = ip_nfrags - dropfraction;
   1355 	for (i = IPFRAGTTL, median = 0; i >= 0; i--) {
   1356 		median +=  fragttl_histo[i];
   1357 		if (median >= keepfraction)
   1358 			break;
   1359 	}
   1360 
   1361 	/* Return TTL of median (or other fraction). */
   1362 	return (u_int)i;
   1363 }
   1364 
   1365 void
   1366 ip_reass_drophalf(void)
   1367 {
   1368 
   1369 	u_int median_ticks;
   1370 	/*
   1371 	 * Compute median TTL of all fragments, and count frags
   1372 	 * with that TTL or lower (roughly half of all fragments).
   1373 	 */
   1374 	median_ticks = ip_reass_ttl_decr(0);
   1375 
   1376 	/* Drop half. */
   1377 	median_ticks = ip_reass_ttl_decr(median_ticks);
   1378 
   1379 }
   1380 
   1381 /*
   1382  * IP timer processing;
   1383  * if a timer expires on a reassembly
   1384  * queue, discard it.
   1385  */
   1386 void
   1387 ip_slowtimo(void)
   1388 {
   1389 	static u_int dropscanidx = 0;
   1390 	u_int i;
   1391 	u_int median_ttl;
   1392 	int s = splsoftnet();
   1393 
   1394 	IPQ_LOCK();
   1395 
   1396 	/* Age TTL of all fragments by 1 tick .*/
   1397 	median_ttl = ip_reass_ttl_decr(1);
   1398 
   1399 	/* make sure fragment limit is up-to-date */
   1400 	CHECK_NMBCLUSTER_PARAMS();
   1401 
   1402 	/* If we have too many fragments, drop the older half. */
   1403 	if (ip_nfrags > ip_maxfrags)
   1404 		ip_reass_ttl_decr(median_ttl);
   1405 
   1406 	/*
   1407 	 * If we are over the maximum number of fragmented packets
   1408 	 * (due to the limit being lowered), drain off
   1409 	 * enough to get down to the new limit. Start draining
   1410 	 * from the reassembly hashqueue most recently drained.
   1411 	 */
   1412 	if (ip_maxfragpackets < 0)
   1413 		;
   1414 	else {
   1415 		int wrapped = 0;
   1416 
   1417 		i = dropscanidx;
   1418 		while (ip_nfragpackets > ip_maxfragpackets && wrapped == 0) {
   1419 			while (LIST_FIRST(&ipq[i]) != NULL)
   1420 				ip_freef(LIST_FIRST(&ipq[i]));
   1421 			if (++i >= IPREASS_NHASH) {
   1422 				i = 0;
   1423 			}
   1424 			/*
   1425 			 * Dont scan forever even if fragment counters are
   1426 			 * wrong: stop after scanning entire reassembly queue.
   1427 			 */
   1428 			if (i == dropscanidx)
   1429 			    wrapped = 1;
   1430 		}
   1431 		dropscanidx = i;
   1432 	}
   1433 	IPQ_UNLOCK();
   1434 	splx(s);
   1435 }
   1436 
   1437 /*
   1438  * Drain off all datagram fragments.
   1439  */
   1440 void
   1441 ip_drain(void)
   1442 {
   1443 
   1444 	/*
   1445 	 * We may be called from a device's interrupt context.  If
   1446 	 * the ipq is already busy, just bail out now.
   1447 	 */
   1448 	if (ipq_lock_try() == 0)
   1449 		return;
   1450 
   1451 	/*
   1452 	 * Drop half the total fragments now. If more mbufs are needed,
   1453 	 *  we will be called again soon.
   1454 	 */
   1455 	ip_reass_drophalf();
   1456 
   1457 	IPQ_UNLOCK();
   1458 }
   1459 
   1460 /*
   1461  * Do option processing on a datagram,
   1462  * possibly discarding it if bad options are encountered,
   1463  * or forwarding it if source-routed.
   1464  * Returns 1 if packet has been forwarded/freed,
   1465  * 0 if the packet should be processed further.
   1466  */
   1467 int
   1468 ip_dooptions(struct mbuf *m)
   1469 {
   1470 	struct ip *ip = mtod(m, struct ip *);
   1471 	u_char *cp, *cp0;
   1472 	struct ip_timestamp *ipt;
   1473 	struct in_ifaddr *ia;
   1474 	int opt, optlen, cnt, off, code, type = ICMP_PARAMPROB, forward = 0;
   1475 	struct in_addr dst;
   1476 	n_time ntime;
   1477 
   1478 	dst = ip->ip_dst;
   1479 	cp = (u_char *)(ip + 1);
   1480 	cnt = (ip->ip_hl << 2) - sizeof (struct ip);
   1481 	for (; cnt > 0; cnt -= optlen, cp += optlen) {
   1482 		opt = cp[IPOPT_OPTVAL];
   1483 		if (opt == IPOPT_EOL)
   1484 			break;
   1485 		if (opt == IPOPT_NOP)
   1486 			optlen = 1;
   1487 		else {
   1488 			if (cnt < IPOPT_OLEN + sizeof(*cp)) {
   1489 				code = &cp[IPOPT_OLEN] - (u_char *)ip;
   1490 				goto bad;
   1491 			}
   1492 			optlen = cp[IPOPT_OLEN];
   1493 			if (optlen < IPOPT_OLEN + sizeof(*cp) || optlen > cnt) {
   1494 				code = &cp[IPOPT_OLEN] - (u_char *)ip;
   1495 				goto bad;
   1496 			}
   1497 		}
   1498 		switch (opt) {
   1499 
   1500 		default:
   1501 			break;
   1502 
   1503 		/*
   1504 		 * Source routing with record.
   1505 		 * Find interface with current destination address.
   1506 		 * If none on this machine then drop if strictly routed,
   1507 		 * or do nothing if loosely routed.
   1508 		 * Record interface address and bring up next address
   1509 		 * component.  If strictly routed make sure next
   1510 		 * address is on directly accessible net.
   1511 		 */
   1512 		case IPOPT_LSRR:
   1513 		case IPOPT_SSRR:
   1514 			if (ip_allowsrcrt == 0) {
   1515 				type = ICMP_UNREACH;
   1516 				code = ICMP_UNREACH_NET_PROHIB;
   1517 				goto bad;
   1518 			}
   1519 			if (optlen < IPOPT_OFFSET + sizeof(*cp)) {
   1520 				code = &cp[IPOPT_OLEN] - (u_char *)ip;
   1521 				goto bad;
   1522 			}
   1523 			if ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {
   1524 				code = &cp[IPOPT_OFFSET] - (u_char *)ip;
   1525 				goto bad;
   1526 			}
   1527 			ipaddr.sin_addr = ip->ip_dst;
   1528 			ia = ifatoia(ifa_ifwithaddr(sintosa(&ipaddr)));
   1529 			if (ia == 0) {
   1530 				if (opt == IPOPT_SSRR) {
   1531 					type = ICMP_UNREACH;
   1532 					code = ICMP_UNREACH_SRCFAIL;
   1533 					goto bad;
   1534 				}
   1535 				/*
   1536 				 * Loose routing, and not at next destination
   1537 				 * yet; nothing to do except forward.
   1538 				 */
   1539 				break;
   1540 			}
   1541 			off--;			/* 0 origin */
   1542 			if ((off + sizeof(struct in_addr)) > optlen) {
   1543 				/*
   1544 				 * End of source route.  Should be for us.
   1545 				 */
   1546 				save_rte(cp, ip->ip_src);
   1547 				break;
   1548 			}
   1549 			/*
   1550 			 * locate outgoing interface
   1551 			 */
   1552 			bcopy((void *)(cp + off), (void *)&ipaddr.sin_addr,
   1553 			    sizeof(ipaddr.sin_addr));
   1554 			if (opt == IPOPT_SSRR)
   1555 				ia = ifatoia(ifa_ifwithladdr(sintosa(&ipaddr)));
   1556 			else
   1557 				ia = ip_rtaddr(ipaddr.sin_addr);
   1558 			if (ia == 0) {
   1559 				type = ICMP_UNREACH;
   1560 				code = ICMP_UNREACH_SRCFAIL;
   1561 				goto bad;
   1562 			}
   1563 			ip->ip_dst = ipaddr.sin_addr;
   1564 			bcopy((void *)&ia->ia_addr.sin_addr,
   1565 			    (void *)(cp + off), sizeof(struct in_addr));
   1566 			cp[IPOPT_OFFSET] += sizeof(struct in_addr);
   1567 			/*
   1568 			 * Let ip_intr's mcast routing check handle mcast pkts
   1569 			 */
   1570 			forward = !IN_MULTICAST(ip->ip_dst.s_addr);
   1571 			break;
   1572 
   1573 		case IPOPT_RR:
   1574 			if (optlen < IPOPT_OFFSET + sizeof(*cp)) {
   1575 				code = &cp[IPOPT_OLEN] - (u_char *)ip;
   1576 				goto bad;
   1577 			}
   1578 			if ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {
   1579 				code = &cp[IPOPT_OFFSET] - (u_char *)ip;
   1580 				goto bad;
   1581 			}
   1582 			/*
   1583 			 * If no space remains, ignore.
   1584 			 */
   1585 			off--;			/* 0 origin */
   1586 			if ((off + sizeof(struct in_addr)) > optlen)
   1587 				break;
   1588 			bcopy((void *)(&ip->ip_dst), (void *)&ipaddr.sin_addr,
   1589 			    sizeof(ipaddr.sin_addr));
   1590 			/*
   1591 			 * locate outgoing interface; if we're the destination,
   1592 			 * use the incoming interface (should be same).
   1593 			 */
   1594 			if ((ia = ifatoia(ifa_ifwithaddr(sintosa(&ipaddr))))
   1595 			    == NULL &&
   1596 			    (ia = ip_rtaddr(ipaddr.sin_addr)) == NULL) {
   1597 				type = ICMP_UNREACH;
   1598 				code = ICMP_UNREACH_HOST;
   1599 				goto bad;
   1600 			}
   1601 			bcopy((void *)&ia->ia_addr.sin_addr,
   1602 			    (void *)(cp + off), sizeof(struct in_addr));
   1603 			cp[IPOPT_OFFSET] += sizeof(struct in_addr);
   1604 			break;
   1605 
   1606 		case IPOPT_TS:
   1607 			code = cp - (u_char *)ip;
   1608 			ipt = (struct ip_timestamp *)cp;
   1609 			if (ipt->ipt_len < 4 || ipt->ipt_len > 40) {
   1610 				code = (u_char *)&ipt->ipt_len - (u_char *)ip;
   1611 				goto bad;
   1612 			}
   1613 			if (ipt->ipt_ptr < 5) {
   1614 				code = (u_char *)&ipt->ipt_ptr - (u_char *)ip;
   1615 				goto bad;
   1616 			}
   1617 			if (ipt->ipt_ptr > ipt->ipt_len - sizeof (int32_t)) {
   1618 				if (++ipt->ipt_oflw == 0) {
   1619 					code = (u_char *)&ipt->ipt_ptr -
   1620 					    (u_char *)ip;
   1621 					goto bad;
   1622 				}
   1623 				break;
   1624 			}
   1625 			cp0 = (cp + ipt->ipt_ptr - 1);
   1626 			switch (ipt->ipt_flg) {
   1627 
   1628 			case IPOPT_TS_TSONLY:
   1629 				break;
   1630 
   1631 			case IPOPT_TS_TSANDADDR:
   1632 				if (ipt->ipt_ptr - 1 + sizeof(n_time) +
   1633 				    sizeof(struct in_addr) > ipt->ipt_len) {
   1634 					code = (u_char *)&ipt->ipt_ptr -
   1635 					    (u_char *)ip;
   1636 					goto bad;
   1637 				}
   1638 				ipaddr.sin_addr = dst;
   1639 				ia = ifatoia(ifaof_ifpforaddr(sintosa(&ipaddr),
   1640 				    m->m_pkthdr.rcvif));
   1641 				if (ia == 0)
   1642 					continue;
   1643 				bcopy(&ia->ia_addr.sin_addr,
   1644 				    cp0, sizeof(struct in_addr));
   1645 				ipt->ipt_ptr += sizeof(struct in_addr);
   1646 				break;
   1647 
   1648 			case IPOPT_TS_PRESPEC:
   1649 				if (ipt->ipt_ptr - 1 + sizeof(n_time) +
   1650 				    sizeof(struct in_addr) > ipt->ipt_len) {
   1651 					code = (u_char *)&ipt->ipt_ptr -
   1652 					    (u_char *)ip;
   1653 					goto bad;
   1654 				}
   1655 				bcopy(cp0, &ipaddr.sin_addr,
   1656 				    sizeof(struct in_addr));
   1657 				if (ifatoia(ifa_ifwithaddr(sintosa(&ipaddr)))
   1658 				    == NULL)
   1659 					continue;
   1660 				ipt->ipt_ptr += sizeof(struct in_addr);
   1661 				break;
   1662 
   1663 			default:
   1664 				/* XXX can't take &ipt->ipt_flg */
   1665 				code = (u_char *)&ipt->ipt_ptr -
   1666 				    (u_char *)ip + 1;
   1667 				goto bad;
   1668 			}
   1669 			ntime = iptime();
   1670 			cp0 = (u_char *) &ntime; /* XXX grumble, GCC... */
   1671 			memmove((char *)cp + ipt->ipt_ptr - 1, cp0,
   1672 			    sizeof(n_time));
   1673 			ipt->ipt_ptr += sizeof(n_time);
   1674 		}
   1675 	}
   1676 	if (forward) {
   1677 		if (ip_forwsrcrt == 0) {
   1678 			type = ICMP_UNREACH;
   1679 			code = ICMP_UNREACH_SRCFAIL;
   1680 			goto bad;
   1681 		}
   1682 		ip_forward(m, 1);
   1683 		return (1);
   1684 	}
   1685 	return (0);
   1686 bad:
   1687 	icmp_error(m, type, code, 0, 0);
   1688 	IP_STATINC(IP_STAT_BADOPTIONS);
   1689 	return (1);
   1690 }
   1691 
   1692 /*
   1693  * Given address of next destination (final or next hop),
   1694  * return internet address info of interface to be used to get there.
   1695  */
   1696 struct in_ifaddr *
   1697 ip_rtaddr(struct in_addr dst)
   1698 {
   1699 	struct rtentry *rt;
   1700 	union {
   1701 		struct sockaddr		dst;
   1702 		struct sockaddr_in	dst4;
   1703 	} u;
   1704 
   1705 	sockaddr_in_init(&u.dst4, &dst, 0);
   1706 
   1707 	if ((rt = rtcache_lookup(&ipforward_rt, &u.dst)) == NULL)
   1708 		return NULL;
   1709 
   1710 	return ifatoia(rt->rt_ifa);
   1711 }
   1712 
   1713 /*
   1714  * Save incoming source route for use in replies,
   1715  * to be picked up later by ip_srcroute if the receiver is interested.
   1716  */
   1717 void
   1718 save_rte(u_char *option, struct in_addr dst)
   1719 {
   1720 	unsigned olen;
   1721 
   1722 	olen = option[IPOPT_OLEN];
   1723 #ifdef DIAGNOSTIC
   1724 	if (ipprintfs)
   1725 		printf("save_rte: olen %d\n", olen);
   1726 #endif /* 0 */
   1727 	if (olen > sizeof(ip_srcrt) - (1 + sizeof(dst)))
   1728 		return;
   1729 	bcopy((void *)option, (void *)ip_srcrt.srcopt, olen);
   1730 	ip_nhops = (olen - IPOPT_OFFSET - 1) / sizeof(struct in_addr);
   1731 	ip_srcrt.dst = dst;
   1732 }
   1733 
   1734 /*
   1735  * Retrieve incoming source route for use in replies,
   1736  * in the same form used by setsockopt.
   1737  * The first hop is placed before the options, will be removed later.
   1738  */
   1739 struct mbuf *
   1740 ip_srcroute(void)
   1741 {
   1742 	struct in_addr *p, *q;
   1743 	struct mbuf *m;
   1744 
   1745 	if (ip_nhops == 0)
   1746 		return NULL;
   1747 	m = m_get(M_DONTWAIT, MT_SOOPTS);
   1748 	if (m == 0)
   1749 		return NULL;
   1750 
   1751 	MCLAIM(m, &inetdomain.dom_mowner);
   1752 #define OPTSIZ	(sizeof(ip_srcrt.nop) + sizeof(ip_srcrt.srcopt))
   1753 
   1754 	/* length is (nhops+1)*sizeof(addr) + sizeof(nop + srcrt header) */
   1755 	m->m_len = ip_nhops * sizeof(struct in_addr) + sizeof(struct in_addr) +
   1756 	    OPTSIZ;
   1757 #ifdef DIAGNOSTIC
   1758 	if (ipprintfs)
   1759 		printf("ip_srcroute: nhops %d mlen %d", ip_nhops, m->m_len);
   1760 #endif
   1761 
   1762 	/*
   1763 	 * First save first hop for return route
   1764 	 */
   1765 	p = &ip_srcrt.route[ip_nhops - 1];
   1766 	*(mtod(m, struct in_addr *)) = *p--;
   1767 #ifdef DIAGNOSTIC
   1768 	if (ipprintfs)
   1769 		printf(" hops %x", ntohl(mtod(m, struct in_addr *)->s_addr));
   1770 #endif
   1771 
   1772 	/*
   1773 	 * Copy option fields and padding (nop) to mbuf.
   1774 	 */
   1775 	ip_srcrt.nop = IPOPT_NOP;
   1776 	ip_srcrt.srcopt[IPOPT_OFFSET] = IPOPT_MINOFF;
   1777 	memmove(mtod(m, char *) + sizeof(struct in_addr), &ip_srcrt.nop,
   1778 	    OPTSIZ);
   1779 	q = (struct in_addr *)(mtod(m, char *) +
   1780 	    sizeof(struct in_addr) + OPTSIZ);
   1781 #undef OPTSIZ
   1782 	/*
   1783 	 * Record return path as an IP source route,
   1784 	 * reversing the path (pointers are now aligned).
   1785 	 */
   1786 	while (p >= ip_srcrt.route) {
   1787 #ifdef DIAGNOSTIC
   1788 		if (ipprintfs)
   1789 			printf(" %x", ntohl(q->s_addr));
   1790 #endif
   1791 		*q++ = *p--;
   1792 	}
   1793 	/*
   1794 	 * Last hop goes to final destination.
   1795 	 */
   1796 	*q = ip_srcrt.dst;
   1797 #ifdef DIAGNOSTIC
   1798 	if (ipprintfs)
   1799 		printf(" %x\n", ntohl(q->s_addr));
   1800 #endif
   1801 	return (m);
   1802 }
   1803 
   1804 const int inetctlerrmap[PRC_NCMDS] = {
   1805 	[PRC_MSGSIZE] = EMSGSIZE,
   1806 	[PRC_HOSTDEAD] = EHOSTDOWN,
   1807 	[PRC_HOSTUNREACH] = EHOSTUNREACH,
   1808 	[PRC_UNREACH_NET] = EHOSTUNREACH,
   1809 	[PRC_UNREACH_HOST] = EHOSTUNREACH,
   1810 	[PRC_UNREACH_PROTOCOL] = ECONNREFUSED,
   1811 	[PRC_UNREACH_PORT] = ECONNREFUSED,
   1812 	[PRC_UNREACH_SRCFAIL] = EHOSTUNREACH,
   1813 	[PRC_PARAMPROB] = ENOPROTOOPT,
   1814 };
   1815 
   1816 /*
   1817  * Forward a packet.  If some error occurs return the sender
   1818  * an icmp packet.  Note we can't always generate a meaningful
   1819  * icmp message because icmp doesn't have a large enough repertoire
   1820  * of codes and types.
   1821  *
   1822  * If not forwarding, just drop the packet.  This could be confusing
   1823  * if ipforwarding was zero but some routing protocol was advancing
   1824  * us as a gateway to somewhere.  However, we must let the routing
   1825  * protocol deal with that.
   1826  *
   1827  * The srcrt parameter indicates whether the packet is being forwarded
   1828  * via a source route.
   1829  */
   1830 void
   1831 ip_forward(struct mbuf *m, int srcrt)
   1832 {
   1833 	struct ip *ip = mtod(m, struct ip *);
   1834 	struct rtentry *rt;
   1835 	int error, type = 0, code = 0, destmtu = 0;
   1836 	struct mbuf *mcopy;
   1837 	n_long dest;
   1838 	union {
   1839 		struct sockaddr		dst;
   1840 		struct sockaddr_in	dst4;
   1841 	} u;
   1842 
   1843 	/*
   1844 	 * We are now in the output path.
   1845 	 */
   1846 	MCLAIM(m, &ip_tx_mowner);
   1847 
   1848 	/*
   1849 	 * Clear any in-bound checksum flags for this packet.
   1850 	 */
   1851 	m->m_pkthdr.csum_flags = 0;
   1852 
   1853 	dest = 0;
   1854 #ifdef DIAGNOSTIC
   1855 	if (ipprintfs) {
   1856 		printf("forward: src %s ", inet_ntoa(ip->ip_src));
   1857 		printf("dst %s ttl %x\n", inet_ntoa(ip->ip_dst), ip->ip_ttl);
   1858 	}
   1859 #endif
   1860 	if (m->m_flags & (M_BCAST|M_MCAST) || in_canforward(ip->ip_dst) == 0) {
   1861 		IP_STATINC(IP_STAT_CANTFORWARD);
   1862 		m_freem(m);
   1863 		return;
   1864 	}
   1865 	if (ip->ip_ttl <= IPTTLDEC) {
   1866 		icmp_error(m, ICMP_TIMXCEED, ICMP_TIMXCEED_INTRANS, dest, 0);
   1867 		return;
   1868 	}
   1869 
   1870 	sockaddr_in_init(&u.dst4, &ip->ip_dst, 0);
   1871 	if ((rt = rtcache_lookup(&ipforward_rt, &u.dst)) == NULL) {
   1872 		icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_NET, dest, 0);
   1873 		return;
   1874 	}
   1875 
   1876 	/*
   1877 	 * Save at most 68 bytes of the packet in case
   1878 	 * we need to generate an ICMP message to the src.
   1879 	 * Pullup to avoid sharing mbuf cluster between m and mcopy.
   1880 	 */
   1881 	mcopy = m_copym(m, 0, imin(ntohs(ip->ip_len), 68), M_DONTWAIT);
   1882 	if (mcopy)
   1883 		mcopy = m_pullup(mcopy, ip->ip_hl << 2);
   1884 
   1885 	ip->ip_ttl -= IPTTLDEC;
   1886 
   1887 	/*
   1888 	 * If forwarding packet using same interface that it came in on,
   1889 	 * perhaps should send a redirect to sender to shortcut a hop.
   1890 	 * Only send redirect if source is sending directly to us,
   1891 	 * and if packet was not source routed (or has any options).
   1892 	 * Also, don't send redirect if forwarding using a default route
   1893 	 * or a route modified by a redirect.
   1894 	 */
   1895 	if (rt->rt_ifp == m->m_pkthdr.rcvif &&
   1896 	    (rt->rt_flags & (RTF_DYNAMIC|RTF_MODIFIED)) == 0 &&
   1897 	    !in_nullhost(satocsin(rt_getkey(rt))->sin_addr) &&
   1898 	    ipsendredirects && !srcrt) {
   1899 		if (rt->rt_ifa &&
   1900 		    (ip->ip_src.s_addr & ifatoia(rt->rt_ifa)->ia_subnetmask) ==
   1901 		    ifatoia(rt->rt_ifa)->ia_subnet) {
   1902 			if (rt->rt_flags & RTF_GATEWAY)
   1903 				dest = satosin(rt->rt_gateway)->sin_addr.s_addr;
   1904 			else
   1905 				dest = ip->ip_dst.s_addr;
   1906 			/*
   1907 			 * Router requirements says to only send host
   1908 			 * redirects.
   1909 			 */
   1910 			type = ICMP_REDIRECT;
   1911 			code = ICMP_REDIRECT_HOST;
   1912 #ifdef DIAGNOSTIC
   1913 			if (ipprintfs)
   1914 				printf("redirect (%d) to %x\n", code,
   1915 				    (u_int32_t)dest);
   1916 #endif
   1917 		}
   1918 	}
   1919 
   1920 	error = ip_output(m, NULL, &ipforward_rt,
   1921 	    (IP_FORWARDING | (ip_directedbcast ? IP_ALLOWBROADCAST : 0)),
   1922 	    (struct ip_moptions *)NULL, (struct socket *)NULL);
   1923 
   1924 	if (error)
   1925 		IP_STATINC(IP_STAT_CANTFORWARD);
   1926 	else {
   1927 		uint64_t *ips = IP_STAT_GETREF();
   1928 		ips[IP_STAT_FORWARD]++;
   1929 		if (type) {
   1930 			ips[IP_STAT_REDIRECTSENT]++;
   1931 			IP_STAT_PUTREF();
   1932 		} else {
   1933 			IP_STAT_PUTREF();
   1934 			if (mcopy) {
   1935 #ifdef GATEWAY
   1936 				if (mcopy->m_flags & M_CANFASTFWD)
   1937 					ipflow_create(&ipforward_rt, mcopy);
   1938 #endif
   1939 				m_freem(mcopy);
   1940 			}
   1941 			return;
   1942 		}
   1943 	}
   1944 	if (mcopy == NULL)
   1945 		return;
   1946 
   1947 	switch (error) {
   1948 
   1949 	case 0:				/* forwarded, but need redirect */
   1950 		/* type, code set above */
   1951 		break;
   1952 
   1953 	case ENETUNREACH:		/* shouldn't happen, checked above */
   1954 	case EHOSTUNREACH:
   1955 	case ENETDOWN:
   1956 	case EHOSTDOWN:
   1957 	default:
   1958 		type = ICMP_UNREACH;
   1959 		code = ICMP_UNREACH_HOST;
   1960 		break;
   1961 
   1962 	case EMSGSIZE:
   1963 		type = ICMP_UNREACH;
   1964 		code = ICMP_UNREACH_NEEDFRAG;
   1965 
   1966 		if ((rt = rtcache_validate(&ipforward_rt)) != NULL) {
   1967 
   1968 #if defined(IPSEC) || defined(FAST_IPSEC)
   1969 			/*
   1970 			 * If the packet is routed over IPsec tunnel, tell the
   1971 			 * originator the tunnel MTU.
   1972 			 *	tunnel MTU = if MTU - sizeof(IP) - ESP/AH hdrsiz
   1973 			 * XXX quickhack!!!
   1974 			 */
   1975 
   1976 			struct secpolicy *sp;
   1977 			int ipsecerror;
   1978 			size_t ipsechdr;
   1979 			struct route *ro;
   1980 
   1981 			sp = ipsec4_getpolicybyaddr(mcopy,
   1982 			    IPSEC_DIR_OUTBOUND, IP_FORWARDING,
   1983 			    &ipsecerror);
   1984 #endif
   1985 
   1986 			destmtu = rt->rt_ifp->if_mtu;
   1987 #if defined(IPSEC) || defined(FAST_IPSEC)
   1988 			if (sp != NULL) {
   1989 				/* count IPsec header size */
   1990 				ipsechdr = ipsec4_hdrsiz(mcopy,
   1991 				    IPSEC_DIR_OUTBOUND, NULL);
   1992 
   1993 				/*
   1994 				 * find the correct route for outer IPv4
   1995 				 * header, compute tunnel MTU.
   1996 				 */
   1997 
   1998 				if (sp->req != NULL
   1999 				 && sp->req->sav != NULL
   2000 				 && sp->req->sav->sah != NULL) {
   2001 					ro = &sp->req->sav->sah->sa_route;
   2002 					if (rt && rt->rt_ifp) {
   2003 						destmtu =
   2004 						    rt->rt_rmx.rmx_mtu ?
   2005 						    rt->rt_rmx.rmx_mtu :
   2006 						    rt->rt_ifp->if_mtu;
   2007 						destmtu -= ipsechdr;
   2008 					}
   2009 				}
   2010 
   2011 #ifdef	IPSEC
   2012 				key_freesp(sp);
   2013 #else
   2014 				KEY_FREESP(&sp);
   2015 #endif
   2016 			}
   2017 #endif /*defined(IPSEC) || defined(FAST_IPSEC)*/
   2018 		}
   2019 		IP_STATINC(IP_STAT_CANTFRAG);
   2020 		break;
   2021 
   2022 	case ENOBUFS:
   2023 #if 1
   2024 		/*
   2025 		 * a router should not generate ICMP_SOURCEQUENCH as
   2026 		 * required in RFC1812 Requirements for IP Version 4 Routers.
   2027 		 * source quench could be a big problem under DoS attacks,
   2028 		 * or if the underlying interface is rate-limited.
   2029 		 */
   2030 		if (mcopy)
   2031 			m_freem(mcopy);
   2032 		return;
   2033 #else
   2034 		type = ICMP_SOURCEQUENCH;
   2035 		code = 0;
   2036 		break;
   2037 #endif
   2038 	}
   2039 	icmp_error(mcopy, type, code, dest, destmtu);
   2040 }
   2041 
   2042 void
   2043 ip_savecontrol(struct inpcb *inp, struct mbuf **mp, struct ip *ip,
   2044     struct mbuf *m)
   2045 {
   2046 
   2047 	if (inp->inp_socket->so_options & SO_TIMESTAMP) {
   2048 		struct timeval tv;
   2049 
   2050 		microtime(&tv);
   2051 		*mp = sbcreatecontrol((void *) &tv, sizeof(tv),
   2052 		    SCM_TIMESTAMP, SOL_SOCKET);
   2053 		if (*mp)
   2054 			mp = &(*mp)->m_next;
   2055 	}
   2056 	if (inp->inp_flags & INP_RECVDSTADDR) {
   2057 		*mp = sbcreatecontrol((void *) &ip->ip_dst,
   2058 		    sizeof(struct in_addr), IP_RECVDSTADDR, IPPROTO_IP);
   2059 		if (*mp)
   2060 			mp = &(*mp)->m_next;
   2061 	}
   2062 #ifdef notyet
   2063 	/*
   2064 	 * XXX
   2065 	 * Moving these out of udp_input() made them even more broken
   2066 	 * than they already were.
   2067 	 *	- fenner (at) parc.xerox.com
   2068 	 */
   2069 	/* options were tossed already */
   2070 	if (inp->inp_flags & INP_RECVOPTS) {
   2071 		*mp = sbcreatecontrol((void *) opts_deleted_above,
   2072 		    sizeof(struct in_addr), IP_RECVOPTS, IPPROTO_IP);
   2073 		if (*mp)
   2074 			mp = &(*mp)->m_next;
   2075 	}
   2076 	/* ip_srcroute doesn't do what we want here, need to fix */
   2077 	if (inp->inp_flags & INP_RECVRETOPTS) {
   2078 		*mp = sbcreatecontrol((void *) ip_srcroute(),
   2079 		    sizeof(struct in_addr), IP_RECVRETOPTS, IPPROTO_IP);
   2080 		if (*mp)
   2081 			mp = &(*mp)->m_next;
   2082 	}
   2083 #endif
   2084 	if (inp->inp_flags & INP_RECVIF) {
   2085 		struct sockaddr_dl sdl;
   2086 
   2087 		sockaddr_dl_init(&sdl, sizeof(sdl),
   2088 		    (m->m_pkthdr.rcvif != NULL)
   2089 		        ?  m->m_pkthdr.rcvif->if_index
   2090 			: 0,
   2091 			0, NULL, 0, NULL, 0);
   2092 		*mp = sbcreatecontrol(&sdl, sdl.sdl_len, IP_RECVIF, IPPROTO_IP);
   2093 		if (*mp)
   2094 			mp = &(*mp)->m_next;
   2095 	}
   2096 }
   2097 
   2098 /*
   2099  * sysctl helper routine for net.inet.ip.forwsrcrt.
   2100  */
   2101 static int
   2102 sysctl_net_inet_ip_forwsrcrt(SYSCTLFN_ARGS)
   2103 {
   2104 	int error, tmp;
   2105 	struct sysctlnode node;
   2106 
   2107 	node = *rnode;
   2108 	tmp = ip_forwsrcrt;
   2109 	node.sysctl_data = &tmp;
   2110 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
   2111 	if (error || newp == NULL)
   2112 		return (error);
   2113 
   2114 	if (kauth_authorize_network(l->l_cred, KAUTH_NETWORK_FORWSRCRT,
   2115 	    0, NULL, NULL, NULL))
   2116 		return (EPERM);
   2117 
   2118 	ip_forwsrcrt = tmp;
   2119 
   2120 	return (0);
   2121 }
   2122 
   2123 /*
   2124  * sysctl helper routine for net.inet.ip.mtudisctimeout.  checks the
   2125  * range of the new value and tweaks timers if it changes.
   2126  */
   2127 static int
   2128 sysctl_net_inet_ip_pmtudto(SYSCTLFN_ARGS)
   2129 {
   2130 	int error, tmp;
   2131 	struct sysctlnode node;
   2132 
   2133 	node = *rnode;
   2134 	tmp = ip_mtudisc_timeout;
   2135 	node.sysctl_data = &tmp;
   2136 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
   2137 	if (error || newp == NULL)
   2138 		return (error);
   2139 	if (tmp < 0)
   2140 		return (EINVAL);
   2141 
   2142 	ip_mtudisc_timeout = tmp;
   2143 	rt_timer_queue_change(ip_mtudisc_timeout_q, ip_mtudisc_timeout);
   2144 
   2145 	return (0);
   2146 }
   2147 
   2148 #ifdef GATEWAY
   2149 /*
   2150  * sysctl helper routine for net.inet.ip.maxflows.
   2151  */
   2152 static int
   2153 sysctl_net_inet_ip_maxflows(SYSCTLFN_ARGS)
   2154 {
   2155 	int s;
   2156 
   2157 	s = sysctl_lookup(SYSCTLFN_CALL(rnode));
   2158 	if (s || newp == NULL)
   2159 		return (s);
   2160 
   2161 	s = splsoftnet();
   2162 	ipflow_prune();
   2163 	splx(s);
   2164 
   2165 	return (0);
   2166 }
   2167 
   2168 static int
   2169 sysctl_net_inet_ip_hashsize(SYSCTLFN_ARGS)
   2170 {
   2171 	int error, tmp;
   2172 	struct sysctlnode node;
   2173 
   2174 	node = *rnode;
   2175 	tmp = ip_hashsize;
   2176 	node.sysctl_data = &tmp;
   2177 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
   2178 	if (error || newp == NULL)
   2179 		return (error);
   2180 
   2181 	if ((tmp & (tmp - 1)) == 0 && tmp != 0) {
   2182 		/*
   2183 		 * Can only fail due to malloc()
   2184 		 */
   2185 		if (ipflow_invalidate_all(tmp))
   2186 			return ENOMEM;
   2187 	} else {
   2188 		/*
   2189 		 * EINVAL if not a power of 2
   2190 	         */
   2191 		return EINVAL;
   2192 	}
   2193 
   2194 	return (0);
   2195 }
   2196 #endif /* GATEWAY */
   2197 
   2198 static int
   2199 sysctl_net_inet_ip_stats(SYSCTLFN_ARGS)
   2200 {
   2201 	netstat_sysctl_context ctx;
   2202 	uint64_t ips[IP_NSTATS];
   2203 
   2204 	ctx.ctx_stat = ipstat_percpu;
   2205 	ctx.ctx_counters = ips;
   2206 	ctx.ctx_ncounters = IP_NSTATS;
   2207 	return (NETSTAT_SYSCTL(&ctx));
   2208 }
   2209 
   2210 SYSCTL_SETUP(sysctl_net_inet_ip_setup, "sysctl net.inet.ip subtree setup")
   2211 {
   2212 	extern int subnetsarelocal, hostzeroisbroadcast;
   2213 
   2214 	sysctl_createv(clog, 0, NULL, NULL,
   2215 		       CTLFLAG_PERMANENT,
   2216 		       CTLTYPE_NODE, "net", NULL,
   2217 		       NULL, 0, NULL, 0,
   2218 		       CTL_NET, CTL_EOL);
   2219 	sysctl_createv(clog, 0, NULL, NULL,
   2220 		       CTLFLAG_PERMANENT,
   2221 		       CTLTYPE_NODE, "inet",
   2222 		       SYSCTL_DESCR("PF_INET related settings"),
   2223 		       NULL, 0, NULL, 0,
   2224 		       CTL_NET, PF_INET, CTL_EOL);
   2225 	sysctl_createv(clog, 0, NULL, NULL,
   2226 		       CTLFLAG_PERMANENT,
   2227 		       CTLTYPE_NODE, "ip",
   2228 		       SYSCTL_DESCR("IPv4 related settings"),
   2229 		       NULL, 0, NULL, 0,
   2230 		       CTL_NET, PF_INET, IPPROTO_IP, CTL_EOL);
   2231 
   2232 	sysctl_createv(clog, 0, NULL, NULL,
   2233 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2234 		       CTLTYPE_INT, "forwarding",
   2235 		       SYSCTL_DESCR("Enable forwarding of INET datagrams"),
   2236 		       NULL, 0, &ipforwarding, 0,
   2237 		       CTL_NET, PF_INET, IPPROTO_IP,
   2238 		       IPCTL_FORWARDING, CTL_EOL);
   2239 	sysctl_createv(clog, 0, NULL, NULL,
   2240 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2241 		       CTLTYPE_INT, "redirect",
   2242 		       SYSCTL_DESCR("Enable sending of ICMP redirect messages"),
   2243 		       NULL, 0, &ipsendredirects, 0,
   2244 		       CTL_NET, PF_INET, IPPROTO_IP,
   2245 		       IPCTL_SENDREDIRECTS, CTL_EOL);
   2246 	sysctl_createv(clog, 0, NULL, NULL,
   2247 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2248 		       CTLTYPE_INT, "ttl",
   2249 		       SYSCTL_DESCR("Default TTL for an INET datagram"),
   2250 		       NULL, 0, &ip_defttl, 0,
   2251 		       CTL_NET, PF_INET, IPPROTO_IP,
   2252 		       IPCTL_DEFTTL, CTL_EOL);
   2253 #ifdef IPCTL_DEFMTU
   2254 	sysctl_createv(clog, 0, NULL, NULL,
   2255 		       CTLFLAG_PERMANENT /* |CTLFLAG_READWRITE? */,
   2256 		       CTLTYPE_INT, "mtu",
   2257 		       SYSCTL_DESCR("Default MTA for an INET route"),
   2258 		       NULL, 0, &ip_mtu, 0,
   2259 		       CTL_NET, PF_INET, IPPROTO_IP,
   2260 		       IPCTL_DEFMTU, CTL_EOL);
   2261 #endif /* IPCTL_DEFMTU */
   2262 	sysctl_createv(clog, 0, NULL, NULL,
   2263 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2264 		       CTLTYPE_INT, "forwsrcrt",
   2265 		       SYSCTL_DESCR("Enable forwarding of source-routed "
   2266 				    "datagrams"),
   2267 		       sysctl_net_inet_ip_forwsrcrt, 0, &ip_forwsrcrt, 0,
   2268 		       CTL_NET, PF_INET, IPPROTO_IP,
   2269 		       IPCTL_FORWSRCRT, CTL_EOL);
   2270 	sysctl_createv(clog, 0, NULL, NULL,
   2271 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2272 		       CTLTYPE_INT, "directed-broadcast",
   2273 		       SYSCTL_DESCR("Enable forwarding of broadcast datagrams"),
   2274 		       NULL, 0, &ip_directedbcast, 0,
   2275 		       CTL_NET, PF_INET, IPPROTO_IP,
   2276 		       IPCTL_DIRECTEDBCAST, CTL_EOL);
   2277 	sysctl_createv(clog, 0, NULL, NULL,
   2278 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2279 		       CTLTYPE_INT, "allowsrcrt",
   2280 		       SYSCTL_DESCR("Accept source-routed datagrams"),
   2281 		       NULL, 0, &ip_allowsrcrt, 0,
   2282 		       CTL_NET, PF_INET, IPPROTO_IP,
   2283 		       IPCTL_ALLOWSRCRT, CTL_EOL);
   2284 	sysctl_createv(clog, 0, NULL, NULL,
   2285 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2286 		       CTLTYPE_INT, "subnetsarelocal",
   2287 		       SYSCTL_DESCR("Whether logical subnets are considered "
   2288 				    "local"),
   2289 		       NULL, 0, &subnetsarelocal, 0,
   2290 		       CTL_NET, PF_INET, IPPROTO_IP,
   2291 		       IPCTL_SUBNETSARELOCAL, CTL_EOL);
   2292 	sysctl_createv(clog, 0, NULL, NULL,
   2293 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2294 		       CTLTYPE_INT, "mtudisc",
   2295 		       SYSCTL_DESCR("Use RFC1191 Path MTU Discovery"),
   2296 		       NULL, 0, &ip_mtudisc, 0,
   2297 		       CTL_NET, PF_INET, IPPROTO_IP,
   2298 		       IPCTL_MTUDISC, CTL_EOL);
   2299 	sysctl_createv(clog, 0, NULL, NULL,
   2300 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2301 		       CTLTYPE_INT, "anonportmin",
   2302 		       SYSCTL_DESCR("Lowest ephemeral port number to assign"),
   2303 		       sysctl_net_inet_ip_ports, 0, &anonportmin, 0,
   2304 		       CTL_NET, PF_INET, IPPROTO_IP,
   2305 		       IPCTL_ANONPORTMIN, CTL_EOL);
   2306 	sysctl_createv(clog, 0, NULL, NULL,
   2307 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2308 		       CTLTYPE_INT, "anonportmax",
   2309 		       SYSCTL_DESCR("Highest ephemeral port number to assign"),
   2310 		       sysctl_net_inet_ip_ports, 0, &anonportmax, 0,
   2311 		       CTL_NET, PF_INET, IPPROTO_IP,
   2312 		       IPCTL_ANONPORTMAX, CTL_EOL);
   2313 	sysctl_createv(clog, 0, NULL, NULL,
   2314 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2315 		       CTLTYPE_INT, "mtudisctimeout",
   2316 		       SYSCTL_DESCR("Lifetime of a Path MTU Discovered route"),
   2317 		       sysctl_net_inet_ip_pmtudto, 0, &ip_mtudisc_timeout, 0,
   2318 		       CTL_NET, PF_INET, IPPROTO_IP,
   2319 		       IPCTL_MTUDISCTIMEOUT, CTL_EOL);
   2320 #ifdef GATEWAY
   2321 	sysctl_createv(clog, 0, NULL, NULL,
   2322 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2323 		       CTLTYPE_INT, "maxflows",
   2324 		       SYSCTL_DESCR("Number of flows for fast forwarding"),
   2325 		       sysctl_net_inet_ip_maxflows, 0, &ip_maxflows, 0,
   2326 		       CTL_NET, PF_INET, IPPROTO_IP,
   2327 		       IPCTL_MAXFLOWS, CTL_EOL);
   2328 	sysctl_createv(clog, 0, NULL, NULL,
   2329 			CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2330 			CTLTYPE_INT, "hashsize",
   2331 			SYSCTL_DESCR("Size of hash table for fast forwarding (IPv4)"),
   2332 			sysctl_net_inet_ip_hashsize, 0, &ip_hashsize, 0,
   2333 			CTL_NET, PF_INET, IPPROTO_IP,
   2334 			CTL_CREATE, CTL_EOL);
   2335 #endif /* GATEWAY */
   2336 	sysctl_createv(clog, 0, NULL, NULL,
   2337 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2338 		       CTLTYPE_INT, "hostzerobroadcast",
   2339 		       SYSCTL_DESCR("All zeroes address is broadcast address"),
   2340 		       NULL, 0, &hostzeroisbroadcast, 0,
   2341 		       CTL_NET, PF_INET, IPPROTO_IP,
   2342 		       IPCTL_HOSTZEROBROADCAST, CTL_EOL);
   2343 #if NGIF > 0
   2344 	sysctl_createv(clog, 0, NULL, NULL,
   2345 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2346 		       CTLTYPE_INT, "gifttl",
   2347 		       SYSCTL_DESCR("Default TTL for a gif tunnel datagram"),
   2348 		       NULL, 0, &ip_gif_ttl, 0,
   2349 		       CTL_NET, PF_INET, IPPROTO_IP,
   2350 		       IPCTL_GIF_TTL, CTL_EOL);
   2351 #endif /* NGIF */
   2352 #ifndef IPNOPRIVPORTS
   2353 	sysctl_createv(clog, 0, NULL, NULL,
   2354 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2355 		       CTLTYPE_INT, "lowportmin",
   2356 		       SYSCTL_DESCR("Lowest privileged ephemeral port number "
   2357 				    "to assign"),
   2358 		       sysctl_net_inet_ip_ports, 0, &lowportmin, 0,
   2359 		       CTL_NET, PF_INET, IPPROTO_IP,
   2360 		       IPCTL_LOWPORTMIN, CTL_EOL);
   2361 	sysctl_createv(clog, 0, NULL, NULL,
   2362 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2363 		       CTLTYPE_INT, "lowportmax",
   2364 		       SYSCTL_DESCR("Highest privileged ephemeral port number "
   2365 				    "to assign"),
   2366 		       sysctl_net_inet_ip_ports, 0, &lowportmax, 0,
   2367 		       CTL_NET, PF_INET, IPPROTO_IP,
   2368 		       IPCTL_LOWPORTMAX, CTL_EOL);
   2369 #endif /* IPNOPRIVPORTS */
   2370 	sysctl_createv(clog, 0, NULL, NULL,
   2371 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2372 		       CTLTYPE_INT, "maxfragpackets",
   2373 		       SYSCTL_DESCR("Maximum number of fragments to retain for "
   2374 				    "possible reassembly"),
   2375 		       NULL, 0, &ip_maxfragpackets, 0,
   2376 		       CTL_NET, PF_INET, IPPROTO_IP,
   2377 		       IPCTL_MAXFRAGPACKETS, CTL_EOL);
   2378 #if NGRE > 0
   2379 	sysctl_createv(clog, 0, NULL, NULL,
   2380 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2381 		       CTLTYPE_INT, "grettl",
   2382 		       SYSCTL_DESCR("Default TTL for a gre tunnel datagram"),
   2383 		       NULL, 0, &ip_gre_ttl, 0,
   2384 		       CTL_NET, PF_INET, IPPROTO_IP,
   2385 		       IPCTL_GRE_TTL, CTL_EOL);
   2386 #endif /* NGRE */
   2387 	sysctl_createv(clog, 0, NULL, NULL,
   2388 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2389 		       CTLTYPE_INT, "checkinterface",
   2390 		       SYSCTL_DESCR("Enable receive side of Strong ES model "
   2391 				    "from RFC1122"),
   2392 		       NULL, 0, &ip_checkinterface, 0,
   2393 		       CTL_NET, PF_INET, IPPROTO_IP,
   2394 		       IPCTL_CHECKINTERFACE, CTL_EOL);
   2395 	sysctl_createv(clog, 0, NULL, NULL,
   2396 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2397 		       CTLTYPE_INT, "random_id",
   2398 		       SYSCTL_DESCR("Assign random ip_id values"),
   2399 		       NULL, 0, &ip_do_randomid, 0,
   2400 		       CTL_NET, PF_INET, IPPROTO_IP,
   2401 		       IPCTL_RANDOMID, CTL_EOL);
   2402 	sysctl_createv(clog, 0, NULL, NULL,
   2403 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2404 		       CTLTYPE_INT, "do_loopback_cksum",
   2405 		       SYSCTL_DESCR("Perform IP checksum on loopback"),
   2406 		       NULL, 0, &ip_do_loopback_cksum, 0,
   2407 		       CTL_NET, PF_INET, IPPROTO_IP,
   2408 		       IPCTL_LOOPBACKCKSUM, CTL_EOL);
   2409 	sysctl_createv(clog, 0, NULL, NULL,
   2410 		       CTLFLAG_PERMANENT,
   2411 		       CTLTYPE_STRUCT, "stats",
   2412 		       SYSCTL_DESCR("IP statistics"),
   2413 		       sysctl_net_inet_ip_stats, 0, NULL, 0,
   2414 		       CTL_NET, PF_INET, IPPROTO_IP, IPCTL_STATS,
   2415 		       CTL_EOL);
   2416 }
   2417 
   2418 void
   2419 ip_statinc(u_int stat)
   2420 {
   2421 
   2422 	KASSERT(stat < IP_NSTATS);
   2423 	IP_STATINC(stat);
   2424 }
   2425