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