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