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