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