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