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