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