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