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