ip_reass.c revision 153072
1/*-
2 * Copyright (c) 1982, 1986, 1988, 1993
3 *	The Regents of the University of California.  All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 * 4. Neither the name of the University nor the names of its contributors
14 *    may be used to endorse or promote products derived from this software
15 *    without specific prior written permission.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27 * SUCH DAMAGE.
28 *
29 *	@(#)ip_input.c	8.2 (Berkeley) 1/4/94
30 * $FreeBSD: head/sys/netinet/ip_input.c 153072 2005-12-04 02:12:43Z ru $
31 */
32
33#include "opt_bootp.h"
34#include "opt_ipfw.h"
35#include "opt_ipstealth.h"
36#include "opt_ipsec.h"
37#include "opt_mac.h"
38#include "opt_carp.h"
39
40#include <sys/param.h>
41#include <sys/systm.h>
42#include <sys/callout.h>
43#include <sys/mac.h>
44#include <sys/mbuf.h>
45#include <sys/malloc.h>
46#include <sys/domain.h>
47#include <sys/protosw.h>
48#include <sys/socket.h>
49#include <sys/time.h>
50#include <sys/kernel.h>
51#include <sys/syslog.h>
52#include <sys/sysctl.h>
53
54#include <net/pfil.h>
55#include <net/if.h>
56#include <net/if_types.h>
57#include <net/if_var.h>
58#include <net/if_dl.h>
59#include <net/route.h>
60#include <net/netisr.h>
61
62#include <netinet/in.h>
63#include <netinet/in_systm.h>
64#include <netinet/in_var.h>
65#include <netinet/ip.h>
66#include <netinet/in_pcb.h>
67#include <netinet/ip_var.h>
68#include <netinet/ip_icmp.h>
69#include <netinet/ip_options.h>
70#include <machine/in_cksum.h>
71#ifdef DEV_CARP
72#include <netinet/ip_carp.h>
73#endif
74
75#include <sys/socketvar.h>
76
77/* XXX: Temporary until ipfw_ether and ipfw_bridge are converted. */
78#include <netinet/ip_fw.h>
79#include <netinet/ip_dummynet.h>
80
81#ifdef IPSEC
82#include <netinet6/ipsec.h>
83#include <netkey/key.h>
84#endif
85
86#ifdef FAST_IPSEC
87#include <netipsec/ipsec.h>
88#include <netipsec/key.h>
89#endif
90
91int rsvp_on = 0;
92
93int	ipforwarding = 0;
94SYSCTL_INT(_net_inet_ip, IPCTL_FORWARDING, forwarding, CTLFLAG_RW,
95    &ipforwarding, 0, "Enable IP forwarding between interfaces");
96
97static int	ipsendredirects = 1; /* XXX */
98SYSCTL_INT(_net_inet_ip, IPCTL_SENDREDIRECTS, redirect, CTLFLAG_RW,
99    &ipsendredirects, 0, "Enable sending IP redirects");
100
101int	ip_defttl = IPDEFTTL;
102SYSCTL_INT(_net_inet_ip, IPCTL_DEFTTL, ttl, CTLFLAG_RW,
103    &ip_defttl, 0, "Maximum TTL on IP packets");
104
105static int	ip_keepfaith = 0;
106SYSCTL_INT(_net_inet_ip, IPCTL_KEEPFAITH, keepfaith, CTLFLAG_RW,
107	&ip_keepfaith,	0,
108	"Enable packet capture for FAITH IPv4->IPv6 translater daemon");
109
110static int    nipq = 0;         /* total # of reass queues */
111static int    maxnipq;
112SYSCTL_INT(_net_inet_ip, OID_AUTO, maxfragpackets, CTLFLAG_RW,
113	&maxnipq, 0,
114	"Maximum number of IPv4 fragment reassembly queue entries");
115
116static int    maxfragsperpacket;
117SYSCTL_INT(_net_inet_ip, OID_AUTO, maxfragsperpacket, CTLFLAG_RW,
118	&maxfragsperpacket, 0,
119	"Maximum number of IPv4 fragments allowed per packet");
120
121static int	ip_sendsourcequench = 0;
122SYSCTL_INT(_net_inet_ip, OID_AUTO, sendsourcequench, CTLFLAG_RW,
123	&ip_sendsourcequench, 0,
124	"Enable the transmission of source quench packets");
125
126int	ip_do_randomid = 0;
127SYSCTL_INT(_net_inet_ip, OID_AUTO, random_id, CTLFLAG_RW,
128	&ip_do_randomid, 0,
129	"Assign random ip_id values");
130
131/*
132 * XXX - Setting ip_checkinterface mostly implements the receive side of
133 * the Strong ES model described in RFC 1122, but since the routing table
134 * and transmit implementation do not implement the Strong ES model,
135 * setting this to 1 results in an odd hybrid.
136 *
137 * XXX - ip_checkinterface currently must be disabled if you use ipnat
138 * to translate the destination address to another local interface.
139 *
140 * XXX - ip_checkinterface must be disabled if you add IP aliases
141 * to the loopback interface instead of the interface where the
142 * packets for those addresses are received.
143 */
144static int	ip_checkinterface = 0;
145SYSCTL_INT(_net_inet_ip, OID_AUTO, check_interface, CTLFLAG_RW,
146    &ip_checkinterface, 0, "Verify packet arrives on correct interface");
147
148struct pfil_head inet_pfil_hook;	/* Packet filter hooks */
149
150static struct	ifqueue ipintrq;
151static int	ipqmaxlen = IFQ_MAXLEN;
152
153extern	struct domain inetdomain;
154extern	struct protosw inetsw[];
155u_char	ip_protox[IPPROTO_MAX];
156struct	in_ifaddrhead in_ifaddrhead; 		/* first inet address */
157struct	in_ifaddrhashhead *in_ifaddrhashtbl;	/* inet addr hash table  */
158u_long 	in_ifaddrhmask;				/* mask for hash table */
159
160SYSCTL_INT(_net_inet_ip, IPCTL_INTRQMAXLEN, intr_queue_maxlen, CTLFLAG_RW,
161    &ipintrq.ifq_maxlen, 0, "Maximum size of the IP input queue");
162SYSCTL_INT(_net_inet_ip, IPCTL_INTRQDROPS, intr_queue_drops, CTLFLAG_RD,
163    &ipintrq.ifq_drops, 0, "Number of packets dropped from the IP input queue");
164
165struct ipstat ipstat;
166SYSCTL_STRUCT(_net_inet_ip, IPCTL_STATS, stats, CTLFLAG_RW,
167    &ipstat, ipstat, "IP statistics (struct ipstat, netinet/ip_var.h)");
168
169/* Packet reassembly stuff */
170#define IPREASS_NHASH_LOG2      6
171#define IPREASS_NHASH           (1 << IPREASS_NHASH_LOG2)
172#define IPREASS_HMASK           (IPREASS_NHASH - 1)
173#define IPREASS_HASH(x,y) \
174	(((((x) & 0xF) | ((((x) >> 8) & 0xF) << 4)) ^ (y)) & IPREASS_HMASK)
175
176static TAILQ_HEAD(ipqhead, ipq) ipq[IPREASS_NHASH];
177struct mtx ipqlock;
178struct callout ipport_tick_callout;
179
180#define	IPQ_LOCK()	mtx_lock(&ipqlock)
181#define	IPQ_UNLOCK()	mtx_unlock(&ipqlock)
182#define	IPQ_LOCK_INIT()	mtx_init(&ipqlock, "ipqlock", NULL, MTX_DEF)
183#define	IPQ_LOCK_ASSERT()	mtx_assert(&ipqlock, MA_OWNED)
184
185#ifdef IPCTL_DEFMTU
186SYSCTL_INT(_net_inet_ip, IPCTL_DEFMTU, mtu, CTLFLAG_RW,
187    &ip_mtu, 0, "Default MTU");
188#endif
189
190#ifdef IPSTEALTH
191int	ipstealth = 0;
192SYSCTL_INT(_net_inet_ip, OID_AUTO, stealth, CTLFLAG_RW,
193    &ipstealth, 0, "");
194#endif
195
196/*
197 * ipfw_ether and ipfw_bridge hooks.
198 * XXX: Temporary until those are converted to pfil_hooks as well.
199 */
200ip_fw_chk_t *ip_fw_chk_ptr = NULL;
201ip_dn_io_t *ip_dn_io_ptr = NULL;
202int fw_enable = 1;
203int fw_one_pass = 1;
204
205static void	ip_freef(struct ipqhead *, struct ipq *);
206
207/*
208 * IP initialization: fill in IP protocol switch table.
209 * All protocols not implemented in kernel go to raw IP protocol handler.
210 */
211void
212ip_init()
213{
214	register struct protosw *pr;
215	register int i;
216
217	TAILQ_INIT(&in_ifaddrhead);
218	in_ifaddrhashtbl = hashinit(INADDR_NHASH, M_IFADDR, &in_ifaddrhmask);
219	pr = pffindproto(PF_INET, IPPROTO_RAW, SOCK_RAW);
220	if (pr == NULL)
221		panic("ip_init: PF_INET not found");
222
223	/* Initialize the entire ip_protox[] array to IPPROTO_RAW. */
224	for (i = 0; i < IPPROTO_MAX; i++)
225		ip_protox[i] = pr - inetsw;
226	/*
227	 * Cycle through IP protocols and put them into the appropriate place
228	 * in ip_protox[].
229	 */
230	for (pr = inetdomain.dom_protosw;
231	    pr < inetdomain.dom_protoswNPROTOSW; pr++)
232		if (pr->pr_domain->dom_family == PF_INET &&
233		    pr->pr_protocol && pr->pr_protocol != IPPROTO_RAW) {
234			/* Be careful to only index valid IP protocols. */
235			if (pr->pr_protocol < IPPROTO_MAX)
236				ip_protox[pr->pr_protocol] = pr - inetsw;
237		}
238
239	/* Initialize packet filter hooks. */
240	inet_pfil_hook.ph_type = PFIL_TYPE_AF;
241	inet_pfil_hook.ph_af = AF_INET;
242	if ((i = pfil_head_register(&inet_pfil_hook)) != 0)
243		printf("%s: WARNING: unable to register pfil hook, "
244			"error %d\n", __func__, i);
245
246	/* Initialize IP reassembly queue. */
247	IPQ_LOCK_INIT();
248	for (i = 0; i < IPREASS_NHASH; i++)
249	    TAILQ_INIT(&ipq[i]);
250	maxnipq = nmbclusters / 32;
251	maxfragsperpacket = 16;
252
253	/* Start ipport_tick. */
254	callout_init(&ipport_tick_callout, CALLOUT_MPSAFE);
255	ipport_tick(NULL);
256	EVENTHANDLER_REGISTER(shutdown_pre_sync, ip_fini, NULL,
257		SHUTDOWN_PRI_DEFAULT);
258
259	/* Initialize various other remaining things. */
260	ip_id = time_second & 0xffff;
261	ipintrq.ifq_maxlen = ipqmaxlen;
262	mtx_init(&ipintrq.ifq_mtx, "ip_inq", NULL, MTX_DEF);
263	netisr_register(NETISR_IP, ip_input, &ipintrq, NETISR_MPSAFE);
264}
265
266void ip_fini(xtp)
267	void *xtp;
268{
269	callout_stop(&ipport_tick_callout);
270}
271
272/*
273 * Ip input routine.  Checksum and byte swap header.  If fragmented
274 * try to reassemble.  Process options.  Pass to next level.
275 */
276void
277ip_input(struct mbuf *m)
278{
279	struct ip *ip = NULL;
280	struct in_ifaddr *ia = NULL;
281	struct ifaddr *ifa;
282	int    checkif, hlen = 0;
283	u_short sum;
284	int dchg = 0;				/* dest changed after fw */
285	struct in_addr odst;			/* original dst address */
286#ifdef FAST_IPSEC
287	struct m_tag *mtag;
288	struct tdb_ident *tdbi;
289	struct secpolicy *sp;
290	int s, error;
291#endif /* FAST_IPSEC */
292
293  	M_ASSERTPKTHDR(m);
294
295	if (m->m_flags & M_FASTFWD_OURS) {
296		/*
297		 * Firewall or NAT changed destination to local.
298		 * We expect ip_len and ip_off to be in host byte order.
299		 */
300		m->m_flags &= ~M_FASTFWD_OURS;
301		/* Set up some basics that will be used later. */
302		ip = mtod(m, struct ip *);
303		hlen = ip->ip_hl << 2;
304  		goto ours;
305  	}
306
307	ipstat.ips_total++;
308
309	if (m->m_pkthdr.len < sizeof(struct ip))
310		goto tooshort;
311
312	if (m->m_len < sizeof (struct ip) &&
313	    (m = m_pullup(m, sizeof (struct ip))) == NULL) {
314		ipstat.ips_toosmall++;
315		return;
316	}
317	ip = mtod(m, struct ip *);
318
319	if (ip->ip_v != IPVERSION) {
320		ipstat.ips_badvers++;
321		goto bad;
322	}
323
324	hlen = ip->ip_hl << 2;
325	if (hlen < sizeof(struct ip)) {	/* minimum header length */
326		ipstat.ips_badhlen++;
327		goto bad;
328	}
329	if (hlen > m->m_len) {
330		if ((m = m_pullup(m, hlen)) == NULL) {
331			ipstat.ips_badhlen++;
332			return;
333		}
334		ip = mtod(m, struct ip *);
335	}
336
337	/* 127/8 must not appear on wire - RFC1122 */
338	if ((ntohl(ip->ip_dst.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET ||
339	    (ntohl(ip->ip_src.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET) {
340		if ((m->m_pkthdr.rcvif->if_flags & IFF_LOOPBACK) == 0) {
341			ipstat.ips_badaddr++;
342			goto bad;
343		}
344	}
345
346	if (m->m_pkthdr.csum_flags & CSUM_IP_CHECKED) {
347		sum = !(m->m_pkthdr.csum_flags & CSUM_IP_VALID);
348	} else {
349		if (hlen == sizeof(struct ip)) {
350			sum = in_cksum_hdr(ip);
351		} else {
352			sum = in_cksum(m, hlen);
353		}
354	}
355	if (sum) {
356		ipstat.ips_badsum++;
357		goto bad;
358	}
359
360#ifdef ALTQ
361	if (altq_input != NULL && (*altq_input)(m, AF_INET) == 0)
362		/* packet is dropped by traffic conditioner */
363		return;
364#endif
365
366	/*
367	 * Convert fields to host representation.
368	 */
369	ip->ip_len = ntohs(ip->ip_len);
370	if (ip->ip_len < hlen) {
371		ipstat.ips_badlen++;
372		goto bad;
373	}
374	ip->ip_off = ntohs(ip->ip_off);
375
376	/*
377	 * Check that the amount of data in the buffers
378	 * is as at least much as the IP header would have us expect.
379	 * Trim mbufs if longer than we expect.
380	 * Drop packet if shorter than we expect.
381	 */
382	if (m->m_pkthdr.len < ip->ip_len) {
383tooshort:
384		ipstat.ips_tooshort++;
385		goto bad;
386	}
387	if (m->m_pkthdr.len > ip->ip_len) {
388		if (m->m_len == m->m_pkthdr.len) {
389			m->m_len = ip->ip_len;
390			m->m_pkthdr.len = ip->ip_len;
391		} else
392			m_adj(m, ip->ip_len - m->m_pkthdr.len);
393	}
394#if defined(IPSEC) && !defined(IPSEC_FILTERGIF)
395	/*
396	 * Bypass packet filtering for packets from a tunnel (gif).
397	 */
398	if (ipsec_getnhist(m))
399		goto passin;
400#endif
401#if defined(FAST_IPSEC) && !defined(IPSEC_FILTERGIF)
402	/*
403	 * Bypass packet filtering for packets from a tunnel (gif).
404	 */
405	if (m_tag_find(m, PACKET_TAG_IPSEC_IN_DONE, NULL) != NULL)
406		goto passin;
407#endif
408
409	/*
410	 * Run through list of hooks for input packets.
411	 *
412	 * NB: Beware of the destination address changing (e.g.
413	 *     by NAT rewriting).  When this happens, tell
414	 *     ip_forward to do the right thing.
415	 */
416
417	/* Jump over all PFIL processing if hooks are not active. */
418	if (inet_pfil_hook.ph_busy_count == -1)
419		goto passin;
420
421	odst = ip->ip_dst;
422	if (pfil_run_hooks(&inet_pfil_hook, &m, m->m_pkthdr.rcvif,
423	    PFIL_IN, NULL) != 0)
424		return;
425	if (m == NULL)			/* consumed by filter */
426		return;
427
428	ip = mtod(m, struct ip *);
429	dchg = (odst.s_addr != ip->ip_dst.s_addr);
430
431#ifdef IPFIREWALL_FORWARD
432	if (m->m_flags & M_FASTFWD_OURS) {
433		m->m_flags &= ~M_FASTFWD_OURS;
434		goto ours;
435	}
436#ifndef IPFIREWALL_FORWARD_EXTENDED
437	dchg = (m_tag_find(m, PACKET_TAG_IPFORWARD, NULL) != NULL);
438#else
439	if ((dchg = (m_tag_find(m, PACKET_TAG_IPFORWARD, NULL) != NULL)) != 0) {
440		/*
441		 * Directly ship on the packet.  This allows to forward packets
442		 * that were destined for us to some other directly connected
443		 * host.
444		 */
445		ip_forward(m, dchg);
446		return;
447	}
448#endif /* IPFIREWALL_FORWARD_EXTENDED */
449#endif /* IPFIREWALL_FORWARD */
450
451passin:
452	/*
453	 * Process options and, if not destined for us,
454	 * ship it on.  ip_dooptions returns 1 when an
455	 * error was detected (causing an icmp message
456	 * to be sent and the original packet to be freed).
457	 */
458	if (hlen > sizeof (struct ip) && ip_dooptions(m, 0))
459		return;
460
461        /* greedy RSVP, snatches any PATH packet of the RSVP protocol and no
462         * matter if it is destined to another node, or whether it is
463         * a multicast one, RSVP wants it! and prevents it from being forwarded
464         * anywhere else. Also checks if the rsvp daemon is running before
465	 * grabbing the packet.
466         */
467	if (rsvp_on && ip->ip_p==IPPROTO_RSVP)
468		goto ours;
469
470	/*
471	 * Check our list of addresses, to see if the packet is for us.
472	 * If we don't have any addresses, assume any unicast packet
473	 * we receive might be for us (and let the upper layers deal
474	 * with it).
475	 */
476	if (TAILQ_EMPTY(&in_ifaddrhead) &&
477	    (m->m_flags & (M_MCAST|M_BCAST)) == 0)
478		goto ours;
479
480	/*
481	 * Enable a consistency check between the destination address
482	 * and the arrival interface for a unicast packet (the RFC 1122
483	 * strong ES model) if IP forwarding is disabled and the packet
484	 * is not locally generated and the packet is not subject to
485	 * 'ipfw fwd'.
486	 *
487	 * XXX - Checking also should be disabled if the destination
488	 * address is ipnat'ed to a different interface.
489	 *
490	 * XXX - Checking is incompatible with IP aliases added
491	 * to the loopback interface instead of the interface where
492	 * the packets are received.
493	 *
494	 * XXX - This is the case for carp vhost IPs as well so we
495	 * insert a workaround. If the packet got here, we already
496	 * checked with carp_iamatch() and carp_forus().
497	 */
498	checkif = ip_checkinterface && (ipforwarding == 0) &&
499	    m->m_pkthdr.rcvif != NULL &&
500	    ((m->m_pkthdr.rcvif->if_flags & IFF_LOOPBACK) == 0) &&
501#ifdef DEV_CARP
502	    !m->m_pkthdr.rcvif->if_carp &&
503#endif
504	    (dchg == 0);
505
506	/*
507	 * Check for exact addresses in the hash bucket.
508	 */
509	LIST_FOREACH(ia, INADDR_HASH(ip->ip_dst.s_addr), ia_hash) {
510		/*
511		 * If the address matches, verify that the packet
512		 * arrived via the correct interface if checking is
513		 * enabled.
514		 */
515		if (IA_SIN(ia)->sin_addr.s_addr == ip->ip_dst.s_addr &&
516		    (!checkif || ia->ia_ifp == m->m_pkthdr.rcvif))
517			goto ours;
518	}
519	/*
520	 * Check for broadcast addresses.
521	 *
522	 * Only accept broadcast packets that arrive via the matching
523	 * interface.  Reception of forwarded directed broadcasts would
524	 * be handled via ip_forward() and ether_output() with the loopback
525	 * into the stack for SIMPLEX interfaces handled by ether_output().
526	 */
527	if (m->m_pkthdr.rcvif != NULL &&
528	    m->m_pkthdr.rcvif->if_flags & IFF_BROADCAST) {
529	        TAILQ_FOREACH(ifa, &m->m_pkthdr.rcvif->if_addrhead, ifa_link) {
530			if (ifa->ifa_addr->sa_family != AF_INET)
531				continue;
532			ia = ifatoia(ifa);
533			if (satosin(&ia->ia_broadaddr)->sin_addr.s_addr ==
534			    ip->ip_dst.s_addr)
535				goto ours;
536			if (ia->ia_netbroadcast.s_addr == ip->ip_dst.s_addr)
537				goto ours;
538#ifdef BOOTP_COMPAT
539			if (IA_SIN(ia)->sin_addr.s_addr == INADDR_ANY)
540				goto ours;
541#endif
542		}
543	}
544	if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr))) {
545		struct in_multi *inm;
546		if (ip_mrouter) {
547			/*
548			 * If we are acting as a multicast router, all
549			 * incoming multicast packets are passed to the
550			 * kernel-level multicast forwarding function.
551			 * The packet is returned (relatively) intact; if
552			 * ip_mforward() returns a non-zero value, the packet
553			 * must be discarded, else it may be accepted below.
554			 */
555			if (ip_mforward &&
556			    ip_mforward(ip, m->m_pkthdr.rcvif, m, 0) != 0) {
557				ipstat.ips_cantforward++;
558				m_freem(m);
559				return;
560			}
561
562			/*
563			 * The process-level routing daemon needs to receive
564			 * all multicast IGMP packets, whether or not this
565			 * host belongs to their destination groups.
566			 */
567			if (ip->ip_p == IPPROTO_IGMP)
568				goto ours;
569			ipstat.ips_forward++;
570		}
571		/*
572		 * See if we belong to the destination multicast group on the
573		 * arrival interface.
574		 */
575		IN_MULTI_LOCK();
576		IN_LOOKUP_MULTI(ip->ip_dst, m->m_pkthdr.rcvif, inm);
577		IN_MULTI_UNLOCK();
578		if (inm == NULL) {
579			ipstat.ips_notmember++;
580			m_freem(m);
581			return;
582		}
583		goto ours;
584	}
585	if (ip->ip_dst.s_addr == (u_long)INADDR_BROADCAST)
586		goto ours;
587	if (ip->ip_dst.s_addr == INADDR_ANY)
588		goto ours;
589
590	/*
591	 * FAITH(Firewall Aided Internet Translator)
592	 */
593	if (m->m_pkthdr.rcvif && m->m_pkthdr.rcvif->if_type == IFT_FAITH) {
594		if (ip_keepfaith) {
595			if (ip->ip_p == IPPROTO_TCP || ip->ip_p == IPPROTO_ICMP)
596				goto ours;
597		}
598		m_freem(m);
599		return;
600	}
601
602	/*
603	 * Not for us; forward if possible and desirable.
604	 */
605	if (ipforwarding == 0) {
606		ipstat.ips_cantforward++;
607		m_freem(m);
608	} else {
609#ifdef IPSEC
610		/*
611		 * Enforce inbound IPsec SPD.
612		 */
613		if (ipsec4_in_reject(m, NULL)) {
614			ipsecstat.in_polvio++;
615			goto bad;
616		}
617#endif /* IPSEC */
618#ifdef FAST_IPSEC
619		mtag = m_tag_find(m, PACKET_TAG_IPSEC_IN_DONE, NULL);
620		s = splnet();
621		if (mtag != NULL) {
622			tdbi = (struct tdb_ident *)(mtag + 1);
623			sp = ipsec_getpolicy(tdbi, IPSEC_DIR_INBOUND);
624		} else {
625			sp = ipsec_getpolicybyaddr(m, IPSEC_DIR_INBOUND,
626						   IP_FORWARDING, &error);
627		}
628		if (sp == NULL) {	/* NB: can happen if error */
629			splx(s);
630			/*XXX error stat???*/
631			DPRINTF(("ip_input: no SP for forwarding\n"));	/*XXX*/
632			goto bad;
633		}
634
635		/*
636		 * Check security policy against packet attributes.
637		 */
638		error = ipsec_in_reject(sp, m);
639		KEY_FREESP(&sp);
640		splx(s);
641		if (error) {
642			ipstat.ips_cantforward++;
643			goto bad;
644		}
645#endif /* FAST_IPSEC */
646		ip_forward(m, dchg);
647	}
648	return;
649
650ours:
651#ifdef IPSTEALTH
652	/*
653	 * IPSTEALTH: Process non-routing options only
654	 * if the packet is destined for us.
655	 */
656	if (ipstealth && hlen > sizeof (struct ip) &&
657	    ip_dooptions(m, 1))
658		return;
659#endif /* IPSTEALTH */
660
661	/* Count the packet in the ip address stats */
662	if (ia != NULL) {
663		ia->ia_ifa.if_ipackets++;
664		ia->ia_ifa.if_ibytes += m->m_pkthdr.len;
665	}
666
667	/*
668	 * Attempt reassembly; if it succeeds, proceed.
669	 * ip_reass() will return a different mbuf.
670	 */
671	if (ip->ip_off & (IP_MF | IP_OFFMASK)) {
672		m = ip_reass(m);
673		if (m == NULL)
674			return;
675		ip = mtod(m, struct ip *);
676		/* Get the header length of the reassembled packet */
677		hlen = ip->ip_hl << 2;
678	}
679
680	/*
681	 * Further protocols expect the packet length to be w/o the
682	 * IP header.
683	 */
684	ip->ip_len -= hlen;
685
686#ifdef IPSEC
687	/*
688	 * enforce IPsec policy checking if we are seeing last header.
689	 * note that we do not visit this with protocols with pcb layer
690	 * code - like udp/tcp/raw ip.
691	 */
692	if ((inetsw[ip_protox[ip->ip_p]].pr_flags & PR_LASTHDR) != 0 &&
693	    ipsec4_in_reject(m, NULL)) {
694		ipsecstat.in_polvio++;
695		goto bad;
696	}
697#endif
698#ifdef FAST_IPSEC
699	/*
700	 * enforce IPsec policy checking if we are seeing last header.
701	 * note that we do not visit this with protocols with pcb layer
702	 * code - like udp/tcp/raw ip.
703	 */
704	if ((inetsw[ip_protox[ip->ip_p]].pr_flags & PR_LASTHDR) != 0) {
705		/*
706		 * Check if the packet has already had IPsec processing
707		 * done.  If so, then just pass it along.  This tag gets
708		 * set during AH, ESP, etc. input handling, before the
709		 * packet is returned to the ip input queue for delivery.
710		 */
711		mtag = m_tag_find(m, PACKET_TAG_IPSEC_IN_DONE, NULL);
712		s = splnet();
713		if (mtag != NULL) {
714			tdbi = (struct tdb_ident *)(mtag + 1);
715			sp = ipsec_getpolicy(tdbi, IPSEC_DIR_INBOUND);
716		} else {
717			sp = ipsec_getpolicybyaddr(m, IPSEC_DIR_INBOUND,
718						   IP_FORWARDING, &error);
719		}
720		if (sp != NULL) {
721			/*
722			 * Check security policy against packet attributes.
723			 */
724			error = ipsec_in_reject(sp, m);
725			KEY_FREESP(&sp);
726		} else {
727			/* XXX error stat??? */
728			error = EINVAL;
729DPRINTF(("ip_input: no SP, packet discarded\n"));/*XXX*/
730			goto bad;
731		}
732		splx(s);
733		if (error)
734			goto bad;
735	}
736#endif /* FAST_IPSEC */
737
738	/*
739	 * Switch out to protocol's input routine.
740	 */
741	ipstat.ips_delivered++;
742
743	(*inetsw[ip_protox[ip->ip_p]].pr_input)(m, hlen);
744	return;
745bad:
746	m_freem(m);
747}
748
749/*
750 * Take incoming datagram fragment and try to reassemble it into
751 * whole datagram.  If the argument is the first fragment or one
752 * in between the function will return NULL and store the mbuf
753 * in the fragment chain.  If the argument is the last fragment
754 * the packet will be reassembled and the pointer to the new
755 * mbuf returned for further processing.  Only m_tags attached
756 * to the first packet/fragment are preserved.
757 * The IP header is *NOT* adjusted out of iplen.
758 */
759
760struct mbuf *
761ip_reass(struct mbuf *m)
762{
763	struct ip *ip;
764	struct mbuf *p, *q, *nq, *t;
765	struct ipq *fp = NULL;
766	struct ipqhead *head;
767	int i, hlen, next;
768	u_int8_t ecn, ecn0;
769	u_short hash;
770
771	/* If maxnipq or maxfragsperpacket are 0, never accept fragments. */
772	if (maxnipq == 0 || maxfragsperpacket == 0) {
773		ipstat.ips_fragments++;
774		ipstat.ips_fragdropped++;
775		m_freem(m);
776		return (NULL);
777	}
778
779	ip = mtod(m, struct ip *);
780	hlen = ip->ip_hl << 2;
781
782	hash = IPREASS_HASH(ip->ip_src.s_addr, ip->ip_id);
783	head = &ipq[hash];
784	IPQ_LOCK();
785
786	/*
787	 * Look for queue of fragments
788	 * of this datagram.
789	 */
790	TAILQ_FOREACH(fp, head, ipq_list)
791		if (ip->ip_id == fp->ipq_id &&
792		    ip->ip_src.s_addr == fp->ipq_src.s_addr &&
793		    ip->ip_dst.s_addr == fp->ipq_dst.s_addr &&
794#ifdef MAC
795		    mac_fragment_match(m, fp) &&
796#endif
797		    ip->ip_p == fp->ipq_p)
798			goto found;
799
800	fp = NULL;
801
802	/*
803	 * Enforce upper bound on number of fragmented packets
804	 * for which we attempt reassembly;
805	 * If maxnipq is -1, accept all fragments without limitation.
806	 */
807	if ((nipq > maxnipq) && (maxnipq > 0)) {
808		/*
809		 * drop something from the tail of the current queue
810		 * before proceeding further
811		 */
812		struct ipq *q = TAILQ_LAST(head, ipqhead);
813		if (q == NULL) {   /* gak */
814			for (i = 0; i < IPREASS_NHASH; i++) {
815				struct ipq *r = TAILQ_LAST(&ipq[i], ipqhead);
816				if (r) {
817					ipstat.ips_fragtimeout += r->ipq_nfrags;
818					ip_freef(&ipq[i], r);
819					break;
820				}
821			}
822		} else {
823			ipstat.ips_fragtimeout += q->ipq_nfrags;
824			ip_freef(head, q);
825		}
826	}
827
828found:
829	/*
830	 * Adjust ip_len to not reflect header,
831	 * convert offset of this to bytes.
832	 */
833	ip->ip_len -= hlen;
834	if (ip->ip_off & IP_MF) {
835		/*
836		 * Make sure that fragments have a data length
837		 * that's a non-zero multiple of 8 bytes.
838		 */
839		if (ip->ip_len == 0 || (ip->ip_len & 0x7) != 0) {
840			ipstat.ips_toosmall++; /* XXX */
841			goto dropfrag;
842		}
843		m->m_flags |= M_FRAG;
844	} else
845		m->m_flags &= ~M_FRAG;
846	ip->ip_off <<= 3;
847
848
849	/*
850	 * Attempt reassembly; if it succeeds, proceed.
851	 * ip_reass() will return a different mbuf.
852	 */
853	ipstat.ips_fragments++;
854	m->m_pkthdr.header = ip;
855
856	/* Previous ip_reass() started here. */
857	/*
858	 * Presence of header sizes in mbufs
859	 * would confuse code below.
860	 */
861	m->m_data += hlen;
862	m->m_len -= hlen;
863
864	/*
865	 * If first fragment to arrive, create a reassembly queue.
866	 */
867	if (fp == NULL) {
868		if ((t = m_get(M_DONTWAIT, MT_FTABLE)) == NULL)
869			goto dropfrag;
870		fp = mtod(t, struct ipq *);
871#ifdef MAC
872		if (mac_init_ipq(fp, M_NOWAIT) != 0) {
873			m_free(t);
874			goto dropfrag;
875		}
876		mac_create_ipq(m, fp);
877#endif
878		TAILQ_INSERT_HEAD(head, fp, ipq_list);
879		nipq++;
880		fp->ipq_nfrags = 1;
881		fp->ipq_ttl = IPFRAGTTL;
882		fp->ipq_p = ip->ip_p;
883		fp->ipq_id = ip->ip_id;
884		fp->ipq_src = ip->ip_src;
885		fp->ipq_dst = ip->ip_dst;
886		fp->ipq_frags = m;
887		m->m_nextpkt = NULL;
888		goto done;
889	} else {
890		fp->ipq_nfrags++;
891#ifdef MAC
892		mac_update_ipq(m, fp);
893#endif
894	}
895
896#define GETIP(m)	((struct ip*)((m)->m_pkthdr.header))
897
898	/*
899	 * Handle ECN by comparing this segment with the first one;
900	 * if CE is set, do not lose CE.
901	 * drop if CE and not-ECT are mixed for the same packet.
902	 */
903	ecn = ip->ip_tos & IPTOS_ECN_MASK;
904	ecn0 = GETIP(fp->ipq_frags)->ip_tos & IPTOS_ECN_MASK;
905	if (ecn == IPTOS_ECN_CE) {
906		if (ecn0 == IPTOS_ECN_NOTECT)
907			goto dropfrag;
908		if (ecn0 != IPTOS_ECN_CE)
909			GETIP(fp->ipq_frags)->ip_tos |= IPTOS_ECN_CE;
910	}
911	if (ecn == IPTOS_ECN_NOTECT && ecn0 != IPTOS_ECN_NOTECT)
912		goto dropfrag;
913
914	/*
915	 * Find a segment which begins after this one does.
916	 */
917	for (p = NULL, q = fp->ipq_frags; q; p = q, q = q->m_nextpkt)
918		if (GETIP(q)->ip_off > ip->ip_off)
919			break;
920
921	/*
922	 * If there is a preceding segment, it may provide some of
923	 * our data already.  If so, drop the data from the incoming
924	 * segment.  If it provides all of our data, drop us, otherwise
925	 * stick new segment in the proper place.
926	 *
927	 * If some of the data is dropped from the the preceding
928	 * segment, then it's checksum is invalidated.
929	 */
930	if (p) {
931		i = GETIP(p)->ip_off + GETIP(p)->ip_len - ip->ip_off;
932		if (i > 0) {
933			if (i >= ip->ip_len)
934				goto dropfrag;
935			m_adj(m, i);
936			m->m_pkthdr.csum_flags = 0;
937			ip->ip_off += i;
938			ip->ip_len -= i;
939		}
940		m->m_nextpkt = p->m_nextpkt;
941		p->m_nextpkt = m;
942	} else {
943		m->m_nextpkt = fp->ipq_frags;
944		fp->ipq_frags = m;
945	}
946
947	/*
948	 * While we overlap succeeding segments trim them or,
949	 * if they are completely covered, dequeue them.
950	 */
951	for (; q != NULL && ip->ip_off + ip->ip_len > GETIP(q)->ip_off;
952	     q = nq) {
953		i = (ip->ip_off + ip->ip_len) - GETIP(q)->ip_off;
954		if (i < GETIP(q)->ip_len) {
955			GETIP(q)->ip_len -= i;
956			GETIP(q)->ip_off += i;
957			m_adj(q, i);
958			q->m_pkthdr.csum_flags = 0;
959			break;
960		}
961		nq = q->m_nextpkt;
962		m->m_nextpkt = nq;
963		ipstat.ips_fragdropped++;
964		fp->ipq_nfrags--;
965		m_freem(q);
966	}
967
968	/*
969	 * Check for complete reassembly and perform frag per packet
970	 * limiting.
971	 *
972	 * Frag limiting is performed here so that the nth frag has
973	 * a chance to complete the packet before we drop the packet.
974	 * As a result, n+1 frags are actually allowed per packet, but
975	 * only n will ever be stored. (n = maxfragsperpacket.)
976	 *
977	 */
978	next = 0;
979	for (p = NULL, q = fp->ipq_frags; q; p = q, q = q->m_nextpkt) {
980		if (GETIP(q)->ip_off != next) {
981			if (fp->ipq_nfrags > maxfragsperpacket) {
982				ipstat.ips_fragdropped += fp->ipq_nfrags;
983				ip_freef(head, fp);
984			}
985			goto done;
986		}
987		next += GETIP(q)->ip_len;
988	}
989	/* Make sure the last packet didn't have the IP_MF flag */
990	if (p->m_flags & M_FRAG) {
991		if (fp->ipq_nfrags > maxfragsperpacket) {
992			ipstat.ips_fragdropped += fp->ipq_nfrags;
993			ip_freef(head, fp);
994		}
995		goto done;
996	}
997
998	/*
999	 * Reassembly is complete.  Make sure the packet is a sane size.
1000	 */
1001	q = fp->ipq_frags;
1002	ip = GETIP(q);
1003	if (next + (ip->ip_hl << 2) > IP_MAXPACKET) {
1004		ipstat.ips_toolong++;
1005		ipstat.ips_fragdropped += fp->ipq_nfrags;
1006		ip_freef(head, fp);
1007		goto done;
1008	}
1009
1010	/*
1011	 * Concatenate fragments.
1012	 */
1013	m = q;
1014	t = m->m_next;
1015	m->m_next = NULL;
1016	m_cat(m, t);
1017	nq = q->m_nextpkt;
1018	q->m_nextpkt = NULL;
1019	for (q = nq; q != NULL; q = nq) {
1020		nq = q->m_nextpkt;
1021		q->m_nextpkt = NULL;
1022		m->m_pkthdr.csum_flags &= q->m_pkthdr.csum_flags;
1023		m->m_pkthdr.csum_data += q->m_pkthdr.csum_data;
1024		m_cat(m, q);
1025	}
1026#ifdef MAC
1027	mac_create_datagram_from_ipq(fp, m);
1028	mac_destroy_ipq(fp);
1029#endif
1030
1031	/*
1032	 * Create header for new ip packet by modifying header of first
1033	 * packet;  dequeue and discard fragment reassembly header.
1034	 * Make header visible.
1035	 */
1036	ip->ip_len = (ip->ip_hl << 2) + next;
1037	ip->ip_src = fp->ipq_src;
1038	ip->ip_dst = fp->ipq_dst;
1039	TAILQ_REMOVE(head, fp, ipq_list);
1040	nipq--;
1041	(void) m_free(dtom(fp));
1042	m->m_len += (ip->ip_hl << 2);
1043	m->m_data -= (ip->ip_hl << 2);
1044	/* some debugging cruft by sklower, below, will go away soon */
1045	if (m->m_flags & M_PKTHDR)	/* XXX this should be done elsewhere */
1046		m_fixhdr(m);
1047	ipstat.ips_reassembled++;
1048	IPQ_UNLOCK();
1049	return (m);
1050
1051dropfrag:
1052	ipstat.ips_fragdropped++;
1053	if (fp != NULL)
1054		fp->ipq_nfrags--;
1055	m_freem(m);
1056done:
1057	IPQ_UNLOCK();
1058	return (NULL);
1059
1060#undef GETIP
1061}
1062
1063/*
1064 * Free a fragment reassembly header and all
1065 * associated datagrams.
1066 */
1067static void
1068ip_freef(fhp, fp)
1069	struct ipqhead *fhp;
1070	struct ipq *fp;
1071{
1072	register struct mbuf *q;
1073
1074	IPQ_LOCK_ASSERT();
1075
1076	while (fp->ipq_frags) {
1077		q = fp->ipq_frags;
1078		fp->ipq_frags = q->m_nextpkt;
1079		m_freem(q);
1080	}
1081	TAILQ_REMOVE(fhp, fp, ipq_list);
1082	(void) m_free(dtom(fp));
1083	nipq--;
1084}
1085
1086/*
1087 * IP timer processing;
1088 * if a timer expires on a reassembly
1089 * queue, discard it.
1090 */
1091void
1092ip_slowtimo()
1093{
1094	register struct ipq *fp;
1095	int i;
1096
1097	IPQ_LOCK();
1098	for (i = 0; i < IPREASS_NHASH; i++) {
1099		for(fp = TAILQ_FIRST(&ipq[i]); fp;) {
1100			struct ipq *fpp;
1101
1102			fpp = fp;
1103			fp = TAILQ_NEXT(fp, ipq_list);
1104			if(--fpp->ipq_ttl == 0) {
1105				ipstat.ips_fragtimeout += fpp->ipq_nfrags;
1106				ip_freef(&ipq[i], fpp);
1107			}
1108		}
1109	}
1110	/*
1111	 * If we are over the maximum number of fragments
1112	 * (due to the limit being lowered), drain off
1113	 * enough to get down to the new limit.
1114	 */
1115	if (maxnipq >= 0 && nipq > maxnipq) {
1116		for (i = 0; i < IPREASS_NHASH; i++) {
1117			while (nipq > maxnipq && !TAILQ_EMPTY(&ipq[i])) {
1118				ipstat.ips_fragdropped +=
1119				    TAILQ_FIRST(&ipq[i])->ipq_nfrags;
1120				ip_freef(&ipq[i], TAILQ_FIRST(&ipq[i]));
1121			}
1122		}
1123	}
1124	IPQ_UNLOCK();
1125}
1126
1127/*
1128 * Drain off all datagram fragments.
1129 */
1130void
1131ip_drain()
1132{
1133	int     i;
1134
1135	IPQ_LOCK();
1136	for (i = 0; i < IPREASS_NHASH; i++) {
1137		while(!TAILQ_EMPTY(&ipq[i])) {
1138			ipstat.ips_fragdropped +=
1139			    TAILQ_FIRST(&ipq[i])->ipq_nfrags;
1140			ip_freef(&ipq[i], TAILQ_FIRST(&ipq[i]));
1141		}
1142	}
1143	IPQ_UNLOCK();
1144	in_rtqdrain();
1145}
1146
1147/*
1148 * The protocol to be inserted into ip_protox[] must be already registered
1149 * in inetsw[], either statically or through pf_proto_register().
1150 */
1151int
1152ipproto_register(u_char ipproto)
1153{
1154	struct protosw *pr;
1155
1156	/* Sanity checks. */
1157	if (ipproto == 0)
1158		return (EPROTONOSUPPORT);
1159
1160	/*
1161	 * The protocol slot must not be occupied by another protocol
1162	 * already.  An index pointing to IPPROTO_RAW is unused.
1163	 */
1164	pr = pffindproto(PF_INET, IPPROTO_RAW, SOCK_RAW);
1165	if (pr == NULL)
1166		return (EPFNOSUPPORT);
1167	if (ip_protox[ipproto] != pr - inetsw)	/* IPPROTO_RAW */
1168		return (EEXIST);
1169
1170	/* Find the protocol position in inetsw[] and set the index. */
1171	for (pr = inetdomain.dom_protosw;
1172	     pr < inetdomain.dom_protoswNPROTOSW; pr++) {
1173		if (pr->pr_domain->dom_family == PF_INET &&
1174		    pr->pr_protocol && pr->pr_protocol == ipproto) {
1175			/* Be careful to only index valid IP protocols. */
1176			if (pr->pr_protocol < IPPROTO_MAX) {
1177				ip_protox[pr->pr_protocol] = pr - inetsw;
1178				return (0);
1179			} else
1180				return (EINVAL);
1181		}
1182	}
1183	return (EPROTONOSUPPORT);
1184}
1185
1186int
1187ipproto_unregister(u_char ipproto)
1188{
1189	struct protosw *pr;
1190
1191	/* Sanity checks. */
1192	if (ipproto == 0)
1193		return (EPROTONOSUPPORT);
1194
1195	/* Check if the protocol was indeed registered. */
1196	pr = pffindproto(PF_INET, IPPROTO_RAW, SOCK_RAW);
1197	if (pr == NULL)
1198		return (EPFNOSUPPORT);
1199	if (ip_protox[ipproto] == pr - inetsw)  /* IPPROTO_RAW */
1200		return (ENOENT);
1201
1202	/* Reset the protocol slot to IPPROTO_RAW. */
1203	ip_protox[ipproto] = pr - inetsw;
1204	return (0);
1205}
1206
1207/*
1208 * Given address of next destination (final or next hop),
1209 * return internet address info of interface to be used to get there.
1210 */
1211struct in_ifaddr *
1212ip_rtaddr(dst)
1213	struct in_addr dst;
1214{
1215	struct route sro;
1216	struct sockaddr_in *sin;
1217	struct in_ifaddr *ifa;
1218
1219	bzero(&sro, sizeof(sro));
1220	sin = (struct sockaddr_in *)&sro.ro_dst;
1221	sin->sin_family = AF_INET;
1222	sin->sin_len = sizeof(*sin);
1223	sin->sin_addr = dst;
1224	rtalloc_ign(&sro, RTF_CLONING);
1225
1226	if (sro.ro_rt == NULL)
1227		return (NULL);
1228
1229	ifa = ifatoia(sro.ro_rt->rt_ifa);
1230	RTFREE(sro.ro_rt);
1231	return (ifa);
1232}
1233
1234u_char inetctlerrmap[PRC_NCMDS] = {
1235	0,		0,		0,		0,
1236	0,		EMSGSIZE,	EHOSTDOWN,	EHOSTUNREACH,
1237	EHOSTUNREACH,	EHOSTUNREACH,	ECONNREFUSED,	ECONNREFUSED,
1238	EMSGSIZE,	EHOSTUNREACH,	0,		0,
1239	0,		0,		EHOSTUNREACH,	0,
1240	ENOPROTOOPT,	ECONNREFUSED
1241};
1242
1243/*
1244 * Forward a packet.  If some error occurs return the sender
1245 * an icmp packet.  Note we can't always generate a meaningful
1246 * icmp message because icmp doesn't have a large enough repertoire
1247 * of codes and types.
1248 *
1249 * If not forwarding, just drop the packet.  This could be confusing
1250 * if ipforwarding was zero but some routing protocol was advancing
1251 * us as a gateway to somewhere.  However, we must let the routing
1252 * protocol deal with that.
1253 *
1254 * The srcrt parameter indicates whether the packet is being forwarded
1255 * via a source route.
1256 */
1257void
1258ip_forward(struct mbuf *m, int srcrt)
1259{
1260	struct ip *ip = mtod(m, struct ip *);
1261	struct in_ifaddr *ia = NULL;
1262	struct mbuf *mcopy;
1263	struct in_addr dest;
1264	int error, type = 0, code = 0, mtu = 0;
1265
1266	if (m->m_flags & (M_BCAST|M_MCAST) || in_canforward(ip->ip_dst) == 0) {
1267		ipstat.ips_cantforward++;
1268		m_freem(m);
1269		return;
1270	}
1271#ifdef IPSTEALTH
1272	if (!ipstealth) {
1273#endif
1274		if (ip->ip_ttl <= IPTTLDEC) {
1275			icmp_error(m, ICMP_TIMXCEED, ICMP_TIMXCEED_INTRANS,
1276			    0, 0);
1277			return;
1278		}
1279#ifdef IPSTEALTH
1280	}
1281#endif
1282
1283	if (!srcrt && (ia = ip_rtaddr(ip->ip_dst)) == NULL) {
1284		icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_HOST, 0, 0);
1285		return;
1286	}
1287
1288	/*
1289	 * Save the IP header and at most 8 bytes of the payload,
1290	 * in case we need to generate an ICMP message to the src.
1291	 *
1292	 * XXX this can be optimized a lot by saving the data in a local
1293	 * buffer on the stack (72 bytes at most), and only allocating the
1294	 * mbuf if really necessary. The vast majority of the packets
1295	 * are forwarded without having to send an ICMP back (either
1296	 * because unnecessary, or because rate limited), so we are
1297	 * really we are wasting a lot of work here.
1298	 *
1299	 * We don't use m_copy() because it might return a reference
1300	 * to a shared cluster. Both this function and ip_output()
1301	 * assume exclusive access to the IP header in `m', so any
1302	 * data in a cluster may change before we reach icmp_error().
1303	 */
1304	MGETHDR(mcopy, M_DONTWAIT, m->m_type);
1305	if (mcopy != NULL && !m_dup_pkthdr(mcopy, m, M_DONTWAIT)) {
1306		/*
1307		 * It's probably ok if the pkthdr dup fails (because
1308		 * the deep copy of the tag chain failed), but for now
1309		 * be conservative and just discard the copy since
1310		 * code below may some day want the tags.
1311		 */
1312		m_free(mcopy);
1313		mcopy = NULL;
1314	}
1315	if (mcopy != NULL) {
1316		mcopy->m_len = min(ip->ip_len, M_TRAILINGSPACE(mcopy));
1317		mcopy->m_pkthdr.len = mcopy->m_len;
1318		m_copydata(m, 0, mcopy->m_len, mtod(mcopy, caddr_t));
1319	}
1320
1321#ifdef IPSTEALTH
1322	if (!ipstealth) {
1323#endif
1324		ip->ip_ttl -= IPTTLDEC;
1325#ifdef IPSTEALTH
1326	}
1327#endif
1328
1329	/*
1330	 * If forwarding packet using same interface that it came in on,
1331	 * perhaps should send a redirect to sender to shortcut a hop.
1332	 * Only send redirect if source is sending directly to us,
1333	 * and if packet was not source routed (or has any options).
1334	 * Also, don't send redirect if forwarding using a default route
1335	 * or a route modified by a redirect.
1336	 */
1337	dest.s_addr = 0;
1338	if (!srcrt && ipsendredirects && ia->ia_ifp == m->m_pkthdr.rcvif) {
1339		struct sockaddr_in *sin;
1340		struct route ro;
1341		struct rtentry *rt;
1342
1343		bzero(&ro, sizeof(ro));
1344		sin = (struct sockaddr_in *)&ro.ro_dst;
1345		sin->sin_family = AF_INET;
1346		sin->sin_len = sizeof(*sin);
1347		sin->sin_addr = ip->ip_dst;
1348		rtalloc_ign(&ro, RTF_CLONING);
1349
1350		rt = ro.ro_rt;
1351
1352		if (rt && (rt->rt_flags & (RTF_DYNAMIC|RTF_MODIFIED)) == 0 &&
1353		    satosin(rt_key(rt))->sin_addr.s_addr != 0) {
1354#define	RTA(rt)	((struct in_ifaddr *)(rt->rt_ifa))
1355			u_long src = ntohl(ip->ip_src.s_addr);
1356
1357			if (RTA(rt) &&
1358			    (src & RTA(rt)->ia_subnetmask) == RTA(rt)->ia_subnet) {
1359				if (rt->rt_flags & RTF_GATEWAY)
1360					dest.s_addr = satosin(rt->rt_gateway)->sin_addr.s_addr;
1361				else
1362					dest.s_addr = ip->ip_dst.s_addr;
1363				/* Router requirements says to only send host redirects */
1364				type = ICMP_REDIRECT;
1365				code = ICMP_REDIRECT_HOST;
1366			}
1367		}
1368		if (rt)
1369			RTFREE(rt);
1370	}
1371
1372	error = ip_output(m, NULL, NULL, IP_FORWARDING, NULL, NULL);
1373	if (error)
1374		ipstat.ips_cantforward++;
1375	else {
1376		ipstat.ips_forward++;
1377		if (type)
1378			ipstat.ips_redirectsent++;
1379		else {
1380			if (mcopy)
1381				m_freem(mcopy);
1382			return;
1383		}
1384	}
1385	if (mcopy == NULL)
1386		return;
1387
1388	switch (error) {
1389
1390	case 0:				/* forwarded, but need redirect */
1391		/* type, code set above */
1392		break;
1393
1394	case ENETUNREACH:		/* shouldn't happen, checked above */
1395	case EHOSTUNREACH:
1396	case ENETDOWN:
1397	case EHOSTDOWN:
1398	default:
1399		type = ICMP_UNREACH;
1400		code = ICMP_UNREACH_HOST;
1401		break;
1402
1403	case EMSGSIZE:
1404		type = ICMP_UNREACH;
1405		code = ICMP_UNREACH_NEEDFRAG;
1406#if defined(IPSEC) || defined(FAST_IPSEC)
1407		/*
1408		 * If the packet is routed over IPsec tunnel, tell the
1409		 * originator the tunnel MTU.
1410		 *	tunnel MTU = if MTU - sizeof(IP) - ESP/AH hdrsiz
1411		 * XXX quickhack!!!
1412		 */
1413		{
1414			struct secpolicy *sp = NULL;
1415			int ipsecerror;
1416			int ipsechdr;
1417			struct route *ro;
1418
1419#ifdef IPSEC
1420			sp = ipsec4_getpolicybyaddr(mcopy,
1421						    IPSEC_DIR_OUTBOUND,
1422						    IP_FORWARDING,
1423						    &ipsecerror);
1424#else /* FAST_IPSEC */
1425			sp = ipsec_getpolicybyaddr(mcopy,
1426						   IPSEC_DIR_OUTBOUND,
1427						   IP_FORWARDING,
1428						   &ipsecerror);
1429#endif
1430			if (sp != NULL) {
1431				/* count IPsec header size */
1432				ipsechdr = ipsec4_hdrsiz(mcopy,
1433							 IPSEC_DIR_OUTBOUND,
1434							 NULL);
1435
1436				/*
1437				 * find the correct route for outer IPv4
1438				 * header, compute tunnel MTU.
1439				 */
1440				if (sp->req != NULL
1441				 && sp->req->sav != NULL
1442				 && sp->req->sav->sah != NULL) {
1443					ro = &sp->req->sav->sah->sa_route;
1444					if (ro->ro_rt && ro->ro_rt->rt_ifp) {
1445						mtu =
1446						    ro->ro_rt->rt_rmx.rmx_mtu ?
1447						    ro->ro_rt->rt_rmx.rmx_mtu :
1448						    ro->ro_rt->rt_ifp->if_mtu;
1449						mtu -= ipsechdr;
1450					}
1451				}
1452
1453#ifdef IPSEC
1454				key_freesp(sp);
1455#else /* FAST_IPSEC */
1456				KEY_FREESP(&sp);
1457#endif
1458				ipstat.ips_cantfrag++;
1459				break;
1460			} else
1461#endif /*IPSEC || FAST_IPSEC*/
1462		/*
1463		 * When doing source routing 'ia' can be NULL.  Fall back
1464		 * to the minimum guaranteed routeable packet size and use
1465		 * the same hack as IPSEC to setup a dummyifp for icmp.
1466		 */
1467		if (ia == NULL)
1468			mtu = IP_MSS;
1469		else
1470			mtu = ia->ia_ifp->if_mtu;
1471#if defined(IPSEC) || defined(FAST_IPSEC)
1472		}
1473#endif /*IPSEC || FAST_IPSEC*/
1474		ipstat.ips_cantfrag++;
1475		break;
1476
1477	case ENOBUFS:
1478		/*
1479		 * A router should not generate ICMP_SOURCEQUENCH as
1480		 * required in RFC1812 Requirements for IP Version 4 Routers.
1481		 * Source quench could be a big problem under DoS attacks,
1482		 * or if the underlying interface is rate-limited.
1483		 * Those who need source quench packets may re-enable them
1484		 * via the net.inet.ip.sendsourcequench sysctl.
1485		 */
1486		if (ip_sendsourcequench == 0) {
1487			m_freem(mcopy);
1488			return;
1489		} else {
1490			type = ICMP_SOURCEQUENCH;
1491			code = 0;
1492		}
1493		break;
1494
1495	case EACCES:			/* ipfw denied packet */
1496		m_freem(mcopy);
1497		return;
1498	}
1499	icmp_error(mcopy, type, code, dest.s_addr, mtu);
1500}
1501
1502void
1503ip_savecontrol(inp, mp, ip, m)
1504	register struct inpcb *inp;
1505	register struct mbuf **mp;
1506	register struct ip *ip;
1507	register struct mbuf *m;
1508{
1509	if (inp->inp_socket->so_options & (SO_BINTIME | SO_TIMESTAMP)) {
1510		struct bintime bt;
1511
1512		bintime(&bt);
1513		if (inp->inp_socket->so_options & SO_BINTIME) {
1514			*mp = sbcreatecontrol((caddr_t) &bt, sizeof(bt),
1515			SCM_BINTIME, SOL_SOCKET);
1516			if (*mp)
1517				mp = &(*mp)->m_next;
1518		}
1519		if (inp->inp_socket->so_options & SO_TIMESTAMP) {
1520			struct timeval tv;
1521
1522			bintime2timeval(&bt, &tv);
1523			*mp = sbcreatecontrol((caddr_t) &tv, sizeof(tv),
1524				SCM_TIMESTAMP, SOL_SOCKET);
1525			if (*mp)
1526				mp = &(*mp)->m_next;
1527		}
1528	}
1529	if (inp->inp_flags & INP_RECVDSTADDR) {
1530		*mp = sbcreatecontrol((caddr_t) &ip->ip_dst,
1531		    sizeof(struct in_addr), IP_RECVDSTADDR, IPPROTO_IP);
1532		if (*mp)
1533			mp = &(*mp)->m_next;
1534	}
1535	if (inp->inp_flags & INP_RECVTTL) {
1536		*mp = sbcreatecontrol((caddr_t) &ip->ip_ttl,
1537		    sizeof(u_char), IP_RECVTTL, IPPROTO_IP);
1538		if (*mp)
1539			mp = &(*mp)->m_next;
1540	}
1541#ifdef notyet
1542	/* XXX
1543	 * Moving these out of udp_input() made them even more broken
1544	 * than they already were.
1545	 */
1546	/* options were tossed already */
1547	if (inp->inp_flags & INP_RECVOPTS) {
1548		*mp = sbcreatecontrol((caddr_t) opts_deleted_above,
1549		    sizeof(struct in_addr), IP_RECVOPTS, IPPROTO_IP);
1550		if (*mp)
1551			mp = &(*mp)->m_next;
1552	}
1553	/* ip_srcroute doesn't do what we want here, need to fix */
1554	if (inp->inp_flags & INP_RECVRETOPTS) {
1555		*mp = sbcreatecontrol((caddr_t) ip_srcroute(m),
1556		    sizeof(struct in_addr), IP_RECVRETOPTS, IPPROTO_IP);
1557		if (*mp)
1558			mp = &(*mp)->m_next;
1559	}
1560#endif
1561	if (inp->inp_flags & INP_RECVIF) {
1562		struct ifnet *ifp;
1563		struct sdlbuf {
1564			struct sockaddr_dl sdl;
1565			u_char	pad[32];
1566		} sdlbuf;
1567		struct sockaddr_dl *sdp;
1568		struct sockaddr_dl *sdl2 = &sdlbuf.sdl;
1569
1570		if (((ifp = m->m_pkthdr.rcvif))
1571		&& ( ifp->if_index && (ifp->if_index <= if_index))) {
1572			sdp = (struct sockaddr_dl *)ifp->if_addr->ifa_addr;
1573			/*
1574			 * Change our mind and don't try copy.
1575			 */
1576			if ((sdp->sdl_family != AF_LINK)
1577			|| (sdp->sdl_len > sizeof(sdlbuf))) {
1578				goto makedummy;
1579			}
1580			bcopy(sdp, sdl2, sdp->sdl_len);
1581		} else {
1582makedummy:
1583			sdl2->sdl_len
1584				= offsetof(struct sockaddr_dl, sdl_data[0]);
1585			sdl2->sdl_family = AF_LINK;
1586			sdl2->sdl_index = 0;
1587			sdl2->sdl_nlen = sdl2->sdl_alen = sdl2->sdl_slen = 0;
1588		}
1589		*mp = sbcreatecontrol((caddr_t) sdl2, sdl2->sdl_len,
1590			IP_RECVIF, IPPROTO_IP);
1591		if (*mp)
1592			mp = &(*mp)->m_next;
1593	}
1594}
1595
1596/*
1597 * XXX these routines are called from the upper part of the kernel.
1598 * They need to be locked when we remove Giant.
1599 *
1600 * They could also be moved to ip_mroute.c, since all the RSVP
1601 *  handling is done there already.
1602 */
1603static int ip_rsvp_on;
1604struct socket *ip_rsvpd;
1605int
1606ip_rsvp_init(struct socket *so)
1607{
1608	if (so->so_type != SOCK_RAW ||
1609	    so->so_proto->pr_protocol != IPPROTO_RSVP)
1610		return EOPNOTSUPP;
1611
1612	if (ip_rsvpd != NULL)
1613		return EADDRINUSE;
1614
1615	ip_rsvpd = so;
1616	/*
1617	 * This may seem silly, but we need to be sure we don't over-increment
1618	 * the RSVP counter, in case something slips up.
1619	 */
1620	if (!ip_rsvp_on) {
1621		ip_rsvp_on = 1;
1622		rsvp_on++;
1623	}
1624
1625	return 0;
1626}
1627
1628int
1629ip_rsvp_done(void)
1630{
1631	ip_rsvpd = NULL;
1632	/*
1633	 * This may seem silly, but we need to be sure we don't over-decrement
1634	 * the RSVP counter, in case something slips up.
1635	 */
1636	if (ip_rsvp_on) {
1637		ip_rsvp_on = 0;
1638		rsvp_on--;
1639	}
1640	return 0;
1641}
1642
1643void
1644rsvp_input(struct mbuf *m, int off)	/* XXX must fixup manually */
1645{
1646	if (rsvp_input_p) { /* call the real one if loaded */
1647		rsvp_input_p(m, off);
1648		return;
1649	}
1650
1651	/* Can still get packets with rsvp_on = 0 if there is a local member
1652	 * of the group to which the RSVP packet is addressed.  But in this
1653	 * case we want to throw the packet away.
1654	 */
1655
1656	if (!rsvp_on) {
1657		m_freem(m);
1658		return;
1659	}
1660
1661	if (ip_rsvpd != NULL) {
1662		rip_input(m, off);
1663		return;
1664	}
1665	/* Drop the packet */
1666	m_freem(m);
1667}
1668