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