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