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