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