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