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