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