ip_reass.c revision 122996
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 * 3. All advertising materials mentioning features or use of this software
14 *    must display the following acknowledgement:
15 *	This product includes software developed by the University of
16 *	California, Berkeley and its contributors.
17 * 4. Neither the name of the University nor the names of its contributors
18 *    may be used to endorse or promote products derived from this software
19 *    without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
32 *
33 *	@(#)ip_input.c	8.2 (Berkeley) 1/4/94
34 * $FreeBSD: head/sys/netinet/ip_input.c 122996 2003-11-26 20:31:13Z andre $
35 */
36
37#include "opt_bootp.h"
38#include "opt_ipfw.h"
39#include "opt_ipdn.h"
40#include "opt_ipdivert.h"
41#include "opt_ipfilter.h"
42#include "opt_ipstealth.h"
43#include "opt_ipsec.h"
44#include "opt_mac.h"
45#include "opt_pfil_hooks.h"
46#include "opt_random_ip_id.h"
47
48#include <sys/param.h>
49#include <sys/systm.h>
50#include <sys/mac.h>
51#include <sys/mbuf.h>
52#include <sys/malloc.h>
53#include <sys/domain.h>
54#include <sys/protosw.h>
55#include <sys/socket.h>
56#include <sys/time.h>
57#include <sys/kernel.h>
58#include <sys/syslog.h>
59#include <sys/sysctl.h>
60
61#include <net/pfil.h>
62#include <net/if.h>
63#include <net/if_types.h>
64#include <net/if_var.h>
65#include <net/if_dl.h>
66#include <net/route.h>
67#include <net/netisr.h>
68
69#include <netinet/in.h>
70#include <netinet/in_systm.h>
71#include <netinet/in_var.h>
72#include <netinet/ip.h>
73#include <netinet/in_pcb.h>
74#include <netinet/ip_var.h>
75#include <netinet/ip_icmp.h>
76#include <machine/in_cksum.h>
77
78#include <sys/socketvar.h>
79
80#include <netinet/ip_fw.h>
81#include <netinet/ip_dummynet.h>
82
83#ifdef IPSEC
84#include <netinet6/ipsec.h>
85#include <netkey/key.h>
86#endif
87
88#ifdef FAST_IPSEC
89#include <netipsec/ipsec.h>
90#include <netipsec/key.h>
91#endif
92
93int rsvp_on = 0;
94
95int	ipforwarding = 0;
96SYSCTL_INT(_net_inet_ip, IPCTL_FORWARDING, forwarding, CTLFLAG_RW,
97    &ipforwarding, 0, "Enable IP forwarding between interfaces");
98
99static int	ipsendredirects = 1; /* XXX */
100SYSCTL_INT(_net_inet_ip, IPCTL_SENDREDIRECTS, redirect, CTLFLAG_RW,
101    &ipsendredirects, 0, "Enable sending IP redirects");
102
103int	ip_defttl = IPDEFTTL;
104SYSCTL_INT(_net_inet_ip, IPCTL_DEFTTL, ttl, CTLFLAG_RW,
105    &ip_defttl, 0, "Maximum TTL on IP packets");
106
107static int	ip_dosourceroute = 0;
108SYSCTL_INT(_net_inet_ip, IPCTL_SOURCEROUTE, sourceroute, CTLFLAG_RW,
109    &ip_dosourceroute, 0, "Enable forwarding source routed IP packets");
110
111static int	ip_acceptsourceroute = 0;
112SYSCTL_INT(_net_inet_ip, IPCTL_ACCEPTSOURCEROUTE, accept_sourceroute,
113    CTLFLAG_RW, &ip_acceptsourceroute, 0,
114    "Enable accepting source routed IP packets");
115
116static int	ip_keepfaith = 0;
117SYSCTL_INT(_net_inet_ip, IPCTL_KEEPFAITH, keepfaith, CTLFLAG_RW,
118	&ip_keepfaith,	0,
119	"Enable packet capture for FAITH IPv4->IPv6 translater daemon");
120
121static int    nipq = 0;         /* total # of reass queues */
122static int    maxnipq;
123SYSCTL_INT(_net_inet_ip, OID_AUTO, maxfragpackets, CTLFLAG_RW,
124	&maxnipq, 0,
125	"Maximum number of IPv4 fragment reassembly queue entries");
126
127static int    maxfragsperpacket;
128SYSCTL_INT(_net_inet_ip, OID_AUTO, maxfragsperpacket, CTLFLAG_RW,
129	&maxfragsperpacket, 0,
130	"Maximum number of IPv4 fragments allowed per packet");
131
132static int	ip_sendsourcequench = 0;
133SYSCTL_INT(_net_inet_ip, OID_AUTO, sendsourcequench, CTLFLAG_RW,
134	&ip_sendsourcequench, 0,
135	"Enable the transmission of source quench packets");
136
137/*
138 * XXX - Setting ip_checkinterface mostly implements the receive side of
139 * the Strong ES model described in RFC 1122, but since the routing table
140 * and transmit implementation do not implement the Strong ES model,
141 * setting this to 1 results in an odd hybrid.
142 *
143 * XXX - ip_checkinterface currently must be disabled if you use ipnat
144 * to translate the destination address to another local interface.
145 *
146 * XXX - ip_checkinterface must be disabled if you add IP aliases
147 * to the loopback interface instead of the interface where the
148 * packets for those addresses are received.
149 */
150static int	ip_checkinterface = 1;
151SYSCTL_INT(_net_inet_ip, OID_AUTO, check_interface, CTLFLAG_RW,
152    &ip_checkinterface, 0, "Verify packet arrives on correct interface");
153
154#ifdef DIAGNOSTIC
155static int	ipprintfs = 0;
156#endif
157#ifdef PFIL_HOOKS
158struct pfil_head inet_pfil_hook;
159#endif
160
161static struct	ifqueue ipintrq;
162static int	ipqmaxlen = IFQ_MAXLEN;
163
164extern	struct domain inetdomain;
165extern	struct protosw inetsw[];
166u_char	ip_protox[IPPROTO_MAX];
167struct	in_ifaddrhead in_ifaddrhead; 		/* first inet address */
168struct	in_ifaddrhashhead *in_ifaddrhashtbl;	/* inet addr hash table  */
169u_long 	in_ifaddrhmask;				/* mask for hash table */
170
171SYSCTL_INT(_net_inet_ip, IPCTL_INTRQMAXLEN, intr_queue_maxlen, CTLFLAG_RW,
172    &ipintrq.ifq_maxlen, 0, "Maximum size of the IP input queue");
173SYSCTL_INT(_net_inet_ip, IPCTL_INTRQDROPS, intr_queue_drops, CTLFLAG_RD,
174    &ipintrq.ifq_drops, 0, "Number of packets dropped from the IP input queue");
175
176struct ipstat ipstat;
177SYSCTL_STRUCT(_net_inet_ip, IPCTL_STATS, stats, CTLFLAG_RW,
178    &ipstat, ipstat, "IP statistics (struct ipstat, netinet/ip_var.h)");
179
180/* Packet reassembly stuff */
181#define IPREASS_NHASH_LOG2      6
182#define IPREASS_NHASH           (1 << IPREASS_NHASH_LOG2)
183#define IPREASS_HMASK           (IPREASS_NHASH - 1)
184#define IPREASS_HASH(x,y) \
185	(((((x) & 0xF) | ((((x) >> 8) & 0xF) << 4)) ^ (y)) & IPREASS_HMASK)
186
187static TAILQ_HEAD(ipqhead, ipq) ipq[IPREASS_NHASH];
188struct mtx ipqlock;
189
190#define	IPQ_LOCK()	mtx_lock(&ipqlock)
191#define	IPQ_UNLOCK()	mtx_unlock(&ipqlock)
192#define	IPQ_LOCK_INIT()	mtx_init(&ipqlock, "ipqlock", NULL, MTX_DEF)
193#define	IPQ_LOCK_ASSERT()	mtx_assert(&ipqlock, MA_OWNED)
194
195#ifdef IPCTL_DEFMTU
196SYSCTL_INT(_net_inet_ip, IPCTL_DEFMTU, mtu, CTLFLAG_RW,
197    &ip_mtu, 0, "Default MTU");
198#endif
199
200#ifdef IPSTEALTH
201int	ipstealth = 0;
202SYSCTL_INT(_net_inet_ip, OID_AUTO, stealth, CTLFLAG_RW,
203    &ipstealth, 0, "");
204#endif
205
206
207/* Firewall hooks */
208ip_fw_chk_t *ip_fw_chk_ptr;
209int fw_enable = 1 ;
210int fw_one_pass = 1;
211
212/* Dummynet hooks */
213ip_dn_io_t *ip_dn_io_ptr;
214
215/*
216 * XXX this is ugly -- the following two global variables are
217 * used to store packet state while it travels through the stack.
218 * Note that the code even makes assumptions on the size and
219 * alignment of fields inside struct ip_srcrt so e.g. adding some
220 * fields will break the code. This needs to be fixed.
221 *
222 * We need to save the IP options in case a protocol wants to respond
223 * to an incoming packet over the same route if the packet got here
224 * using IP source routing.  This allows connection establishment and
225 * maintenance when the remote end is on a network that is not known
226 * to us.
227 */
228static int	ip_nhops = 0;
229static	struct ip_srcrt {
230	struct	in_addr dst;			/* final destination */
231	char	nop;				/* one NOP to align */
232	char	srcopt[IPOPT_OFFSET + 1];	/* OPTVAL, OLEN and OFFSET */
233	struct	in_addr route[MAX_IPOPTLEN/sizeof(struct in_addr)];
234} ip_srcrt;
235
236static void	save_rte(u_char *, struct in_addr);
237static int	ip_dooptions(struct mbuf *m, int,
238			struct sockaddr_in *next_hop);
239static void	ip_forward(struct mbuf *m, int srcrt,
240			struct sockaddr_in *next_hop);
241static void	ip_freef(struct ipqhead *, struct ipq *);
242static struct	mbuf *ip_reass(struct mbuf *, struct ipqhead *,
243		struct ipq *, u_int32_t *, u_int16_t *);
244
245/*
246 * IP initialization: fill in IP protocol switch table.
247 * All protocols not implemented in kernel go to raw IP protocol handler.
248 */
249void
250ip_init()
251{
252	register struct protosw *pr;
253	register int i;
254
255	TAILQ_INIT(&in_ifaddrhead);
256	in_ifaddrhashtbl = hashinit(INADDR_NHASH, M_IFADDR, &in_ifaddrhmask);
257	pr = pffindproto(PF_INET, IPPROTO_RAW, SOCK_RAW);
258	if (pr == 0)
259		panic("ip_init");
260	for (i = 0; i < IPPROTO_MAX; i++)
261		ip_protox[i] = pr - inetsw;
262	for (pr = inetdomain.dom_protosw;
263	    pr < inetdomain.dom_protoswNPROTOSW; pr++)
264		if (pr->pr_domain->dom_family == PF_INET &&
265		    pr->pr_protocol && pr->pr_protocol != IPPROTO_RAW)
266			ip_protox[pr->pr_protocol] = pr - inetsw;
267
268#ifdef PFIL_HOOKS
269	inet_pfil_hook.ph_type = PFIL_TYPE_AF;
270	inet_pfil_hook.ph_af = AF_INET;
271	if ((i = pfil_head_register(&inet_pfil_hook)) != 0)
272		printf("%s: WARNING: unable to register pfil hook, "
273			"error %d\n", __func__, i);
274#endif /* PFIL_HOOKS */
275
276	IPQ_LOCK_INIT();
277	for (i = 0; i < IPREASS_NHASH; i++)
278	    TAILQ_INIT(&ipq[i]);
279
280	maxnipq = nmbclusters / 32;
281	maxfragsperpacket = 16;
282
283#ifndef RANDOM_IP_ID
284	ip_id = time_second & 0xffff;
285#endif
286	ipintrq.ifq_maxlen = ipqmaxlen;
287	mtx_init(&ipintrq.ifq_mtx, "ip_inq", NULL, MTX_DEF);
288	netisr_register(NETISR_IP, ip_input, &ipintrq, NETISR_MPSAFE);
289}
290
291/*
292 * Ip input routine.  Checksum and byte swap header.  If fragmented
293 * try to reassemble.  Process options.  Pass to next level.
294 */
295void
296ip_input(struct mbuf *m)
297{
298	struct ip *ip = NULL;
299	struct ipq *fp;
300	struct in_ifaddr *ia = NULL;
301	struct ifaddr *ifa;
302	int    i, checkif, hlen = 0;
303	int    ours = 0;
304	u_short sum;
305	struct in_addr pkt_dst;
306	u_int32_t divert_info = 0;		/* packet divert/tee info */
307	struct ip_fw_args args;
308	int dchg = 0;				/* dest changed after fw */
309#ifdef PFIL_HOOKS
310	struct in_addr odst;			/* original dst address */
311#endif
312#ifdef FAST_IPSEC
313	struct m_tag *mtag;
314	struct tdb_ident *tdbi;
315	struct secpolicy *sp;
316	int s, error;
317#endif /* FAST_IPSEC */
318
319	args.eh = NULL;
320	args.oif = NULL;
321	args.rule = NULL;
322	args.divert_rule = 0;			/* divert cookie */
323	args.next_hop = NULL;
324
325	/*
326	 * Grab info from MT_TAG mbufs prepended to the chain.
327	 *
328	 * XXX: This is ugly. These pseudo mbuf prepend tags should really
329	 * be real m_tags.  Before these have always been allocated on the
330	 * callers stack, so we didn't have to free them.  Now with
331	 * ip_fastforward they are true mbufs and we have to free them
332	 * otherwise we have a leak.  Must rewrite ipfw to use m_tags.
333	 */
334	for (; m && m->m_type == MT_TAG;) {
335		struct mbuf *m0;
336
337		switch(m->_m_tag_id) {
338		default:
339			printf("ip_input: unrecognised MT_TAG tag %d\n",
340			    m->_m_tag_id);
341			break;
342
343		case PACKET_TAG_DUMMYNET:
344			args.rule = ((struct dn_pkt *)m)->rule;
345			break;
346
347		case PACKET_TAG_DIVERT:
348			args.divert_rule = (intptr_t)m->m_hdr.mh_data & 0xffff;
349			break;
350
351		case PACKET_TAG_IPFORWARD:
352			args.next_hop = (struct sockaddr_in *)m->m_hdr.mh_data;
353			break;
354
355		case PACKET_TAG_IPFASTFWD_OURS:
356			ours = 1;
357			break;
358		}
359
360		m0 = m;
361		m = m->m_next;
362		/* XXX: This is set by ip_fastforward */
363		if (m0->m_nextpkt == (struct mbuf *)1)
364			m_free(m0);
365	}
366
367	M_ASSERTPKTHDR(m);
368
369	if (ours)		/* ip_fastforward firewall changed dest to local */
370		goto ours;
371
372	if (args.rule) {	/* dummynet already filtered us */
373		ip = mtod(m, struct ip *);
374		hlen = ip->ip_hl << 2;
375		goto iphack ;
376	}
377
378	ipstat.ips_total++;
379
380	if (m->m_pkthdr.len < sizeof(struct ip))
381		goto tooshort;
382
383	if (m->m_len < sizeof (struct ip) &&
384	    (m = m_pullup(m, sizeof (struct ip))) == 0) {
385		ipstat.ips_toosmall++;
386		return;
387	}
388	ip = mtod(m, struct ip *);
389
390	if (ip->ip_v != IPVERSION) {
391		ipstat.ips_badvers++;
392		goto bad;
393	}
394
395	hlen = ip->ip_hl << 2;
396	if (hlen < sizeof(struct ip)) {	/* minimum header length */
397		ipstat.ips_badhlen++;
398		goto bad;
399	}
400	if (hlen > m->m_len) {
401		if ((m = m_pullup(m, hlen)) == 0) {
402			ipstat.ips_badhlen++;
403			return;
404		}
405		ip = mtod(m, struct ip *);
406	}
407
408	/* 127/8 must not appear on wire - RFC1122 */
409	if ((ntohl(ip->ip_dst.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET ||
410	    (ntohl(ip->ip_src.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET) {
411		if ((m->m_pkthdr.rcvif->if_flags & IFF_LOOPBACK) == 0) {
412			ipstat.ips_badaddr++;
413			goto bad;
414		}
415	}
416
417	if (m->m_pkthdr.csum_flags & CSUM_IP_CHECKED) {
418		sum = !(m->m_pkthdr.csum_flags & CSUM_IP_VALID);
419	} else {
420		if (hlen == sizeof(struct ip)) {
421			sum = in_cksum_hdr(ip);
422		} else {
423			sum = in_cksum(m, hlen);
424		}
425	}
426	if (sum) {
427		ipstat.ips_badsum++;
428		goto bad;
429	}
430
431	/*
432	 * Convert fields to host representation.
433	 */
434	ip->ip_len = ntohs(ip->ip_len);
435	if (ip->ip_len < hlen) {
436		ipstat.ips_badlen++;
437		goto bad;
438	}
439	ip->ip_off = ntohs(ip->ip_off);
440
441	/*
442	 * Check that the amount of data in the buffers
443	 * is as at least much as the IP header would have us expect.
444	 * Trim mbufs if longer than we expect.
445	 * Drop packet if shorter than we expect.
446	 */
447	if (m->m_pkthdr.len < ip->ip_len) {
448tooshort:
449		ipstat.ips_tooshort++;
450		goto bad;
451	}
452	if (m->m_pkthdr.len > ip->ip_len) {
453		if (m->m_len == m->m_pkthdr.len) {
454			m->m_len = ip->ip_len;
455			m->m_pkthdr.len = ip->ip_len;
456		} else
457			m_adj(m, ip->ip_len - m->m_pkthdr.len);
458	}
459#if defined(IPSEC) && !defined(IPSEC_FILTERGIF)
460	/*
461	 * Bypass packet filtering for packets from a tunnel (gif).
462	 */
463	if (ipsec_getnhist(m))
464		goto pass;
465#endif
466#if defined(FAST_IPSEC) && !defined(IPSEC_FILTERGIF)
467	/*
468	 * Bypass packet filtering for packets from a tunnel (gif).
469	 */
470	if (m_tag_find(m, PACKET_TAG_IPSEC_IN_DONE, NULL) != NULL)
471		goto pass;
472#endif
473
474	/*
475	 * IpHack's section.
476	 * Right now when no processing on packet has done
477	 * and it is still fresh out of network we do our black
478	 * deals with it.
479	 * - Firewall: deny/allow/divert
480	 * - Xlate: translate packet's addr/port (NAT).
481	 * - Pipe: pass pkt through dummynet.
482	 * - Wrap: fake packet's addr/port <unimpl.>
483	 * - Encapsulate: put it in another IP and send out. <unimp.>
484 	 */
485
486iphack:
487
488#ifdef PFIL_HOOKS
489	/*
490	 * Run through list of hooks for input packets.
491	 *
492	 * NB: Beware of the destination address changing (e.g.
493	 *     by NAT rewriting).  When this happens, tell
494	 *     ip_forward to do the right thing.
495	 */
496	odst = ip->ip_dst;
497	if (pfil_run_hooks(&inet_pfil_hook, &m, m->m_pkthdr.rcvif,
498	    PFIL_IN) != 0)
499		return;
500	if (m == NULL)			/* consumed by filter */
501		return;
502	ip = mtod(m, struct ip *);
503	dchg = (odst.s_addr != ip->ip_dst.s_addr);
504#endif /* PFIL_HOOKS */
505
506	if (fw_enable && IPFW_LOADED) {
507		/*
508		 * If we've been forwarded from the output side, then
509		 * skip the firewall a second time
510		 */
511		if (args.next_hop)
512			goto ours;
513
514		args.m = m;
515		i = ip_fw_chk_ptr(&args);
516		m = args.m;
517
518		if ( (i & IP_FW_PORT_DENY_FLAG) || m == NULL) { /* drop */
519			if (m)
520				m_freem(m);
521			return;
522		}
523		ip = mtod(m, struct ip *); /* just in case m changed */
524		if (i == 0 && args.next_hop == NULL)	/* common case */
525			goto pass;
526                if (DUMMYNET_LOADED && (i & IP_FW_PORT_DYNT_FLAG) != 0) {
527			/* Send packet to the appropriate pipe */
528			ip_dn_io_ptr(m, i&0xffff, DN_TO_IP_IN, &args);
529			return;
530		}
531#ifdef IPDIVERT
532		if (i != 0 && (i & IP_FW_PORT_DYNT_FLAG) == 0) {
533			/* Divert or tee packet */
534			divert_info = i;
535			goto ours;
536		}
537#endif
538		if (i == 0 && args.next_hop != NULL)
539			goto pass;
540		/*
541		 * if we get here, the packet must be dropped
542		 */
543		m_freem(m);
544		return;
545	}
546pass:
547
548	/*
549	 * Process options and, if not destined for us,
550	 * ship it on.  ip_dooptions returns 1 when an
551	 * error was detected (causing an icmp message
552	 * to be sent and the original packet to be freed).
553	 */
554	ip_nhops = 0;		/* for source routed packets */
555	if (hlen > sizeof (struct ip) && ip_dooptions(m, 0, args.next_hop))
556		return;
557
558        /* greedy RSVP, snatches any PATH packet of the RSVP protocol and no
559         * matter if it is destined to another node, or whether it is
560         * a multicast one, RSVP wants it! and prevents it from being forwarded
561         * anywhere else. Also checks if the rsvp daemon is running before
562	 * grabbing the packet.
563         */
564	if (rsvp_on && ip->ip_p==IPPROTO_RSVP)
565		goto ours;
566
567	/*
568	 * Check our list of addresses, to see if the packet is for us.
569	 * If we don't have any addresses, assume any unicast packet
570	 * we receive might be for us (and let the upper layers deal
571	 * with it).
572	 */
573	if (TAILQ_EMPTY(&in_ifaddrhead) &&
574	    (m->m_flags & (M_MCAST|M_BCAST)) == 0)
575		goto ours;
576
577	/*
578	 * Cache the destination address of the packet; this may be
579	 * changed by use of 'ipfw fwd'.
580	 */
581	pkt_dst = args.next_hop ? args.next_hop->sin_addr : ip->ip_dst;
582
583	/*
584	 * Enable a consistency check between the destination address
585	 * and the arrival interface for a unicast packet (the RFC 1122
586	 * strong ES model) if IP forwarding is disabled and the packet
587	 * is not locally generated and the packet is not subject to
588	 * 'ipfw fwd'.
589	 *
590	 * XXX - Checking also should be disabled if the destination
591	 * address is ipnat'ed to a different interface.
592	 *
593	 * XXX - Checking is incompatible with IP aliases added
594	 * to the loopback interface instead of the interface where
595	 * the packets are received.
596	 */
597	checkif = ip_checkinterface && (ipforwarding == 0) &&
598	    m->m_pkthdr.rcvif != NULL &&
599	    ((m->m_pkthdr.rcvif->if_flags & IFF_LOOPBACK) == 0) &&
600	    (args.next_hop == NULL);
601
602	/*
603	 * Check for exact addresses in the hash bucket.
604	 */
605	LIST_FOREACH(ia, INADDR_HASH(pkt_dst.s_addr), ia_hash) {
606		/*
607		 * If the address matches, verify that the packet
608		 * arrived via the correct interface if checking is
609		 * enabled.
610		 */
611		if (IA_SIN(ia)->sin_addr.s_addr == pkt_dst.s_addr &&
612		    (!checkif || ia->ia_ifp == m->m_pkthdr.rcvif))
613			goto ours;
614	}
615	/*
616	 * Check for broadcast addresses.
617	 *
618	 * Only accept broadcast packets that arrive via the matching
619	 * interface.  Reception of forwarded directed broadcasts would
620	 * be handled via ip_forward() and ether_output() with the loopback
621	 * into the stack for SIMPLEX interfaces handled by ether_output().
622	 */
623	if (m->m_pkthdr.rcvif->if_flags & IFF_BROADCAST) {
624	        TAILQ_FOREACH(ifa, &m->m_pkthdr.rcvif->if_addrhead, ifa_link) {
625			if (ifa->ifa_addr->sa_family != AF_INET)
626				continue;
627			ia = ifatoia(ifa);
628			if (satosin(&ia->ia_broadaddr)->sin_addr.s_addr ==
629			    pkt_dst.s_addr)
630				goto ours;
631			if (ia->ia_netbroadcast.s_addr == pkt_dst.s_addr)
632				goto ours;
633#ifdef BOOTP_COMPAT
634			if (IA_SIN(ia)->sin_addr.s_addr == INADDR_ANY)
635				goto ours;
636#endif
637		}
638	}
639	if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr))) {
640		struct in_multi *inm;
641		if (ip_mrouter) {
642			/*
643			 * If we are acting as a multicast router, all
644			 * incoming multicast packets are passed to the
645			 * kernel-level multicast forwarding function.
646			 * The packet is returned (relatively) intact; if
647			 * ip_mforward() returns a non-zero value, the packet
648			 * must be discarded, else it may be accepted below.
649			 */
650			if (ip_mforward &&
651			    ip_mforward(ip, m->m_pkthdr.rcvif, m, 0) != 0) {
652				ipstat.ips_cantforward++;
653				m_freem(m);
654				return;
655			}
656
657			/*
658			 * The process-level routing daemon needs to receive
659			 * all multicast IGMP packets, whether or not this
660			 * host belongs to their destination groups.
661			 */
662			if (ip->ip_p == IPPROTO_IGMP)
663				goto ours;
664			ipstat.ips_forward++;
665		}
666		/*
667		 * See if we belong to the destination multicast group on the
668		 * arrival interface.
669		 */
670		IN_LOOKUP_MULTI(ip->ip_dst, m->m_pkthdr.rcvif, inm);
671		if (inm == NULL) {
672			ipstat.ips_notmember++;
673			m_freem(m);
674			return;
675		}
676		goto ours;
677	}
678	if (ip->ip_dst.s_addr == (u_long)INADDR_BROADCAST)
679		goto ours;
680	if (ip->ip_dst.s_addr == INADDR_ANY)
681		goto ours;
682
683	/*
684	 * FAITH(Firewall Aided Internet Translator)
685	 */
686	if (m->m_pkthdr.rcvif && m->m_pkthdr.rcvif->if_type == IFT_FAITH) {
687		if (ip_keepfaith) {
688			if (ip->ip_p == IPPROTO_TCP || ip->ip_p == IPPROTO_ICMP)
689				goto ours;
690		}
691		m_freem(m);
692		return;
693	}
694
695	/*
696	 * Not for us; forward if possible and desirable.
697	 */
698	if (ipforwarding == 0) {
699		ipstat.ips_cantforward++;
700		m_freem(m);
701	} else {
702#ifdef IPSEC
703		/*
704		 * Enforce inbound IPsec SPD.
705		 */
706		if (ipsec4_in_reject(m, NULL)) {
707			ipsecstat.in_polvio++;
708			goto bad;
709		}
710#endif /* IPSEC */
711#ifdef FAST_IPSEC
712		mtag = m_tag_find(m, PACKET_TAG_IPSEC_IN_DONE, NULL);
713		s = splnet();
714		if (mtag != NULL) {
715			tdbi = (struct tdb_ident *)(mtag + 1);
716			sp = ipsec_getpolicy(tdbi, IPSEC_DIR_INBOUND);
717		} else {
718			sp = ipsec_getpolicybyaddr(m, IPSEC_DIR_INBOUND,
719						   IP_FORWARDING, &error);
720		}
721		if (sp == NULL) {	/* NB: can happen if error */
722			splx(s);
723			/*XXX error stat???*/
724			DPRINTF(("ip_input: no SP for forwarding\n"));	/*XXX*/
725			goto bad;
726		}
727
728		/*
729		 * Check security policy against packet attributes.
730		 */
731		error = ipsec_in_reject(sp, m);
732		KEY_FREESP(&sp);
733		splx(s);
734		if (error) {
735			ipstat.ips_cantforward++;
736			goto bad;
737		}
738#endif /* FAST_IPSEC */
739		ip_forward(m, dchg, args.next_hop);
740	}
741	return;
742
743ours:
744#ifdef IPSTEALTH
745	/*
746	 * IPSTEALTH: Process non-routing options only
747	 * if the packet is destined for us.
748	 */
749	if (ipstealth && hlen > sizeof (struct ip) &&
750	    ip_dooptions(m, 1, args.next_hop))
751		return;
752#endif /* IPSTEALTH */
753
754	/* Count the packet in the ip address stats */
755	if (ia != NULL) {
756		ia->ia_ifa.if_ipackets++;
757		ia->ia_ifa.if_ibytes += m->m_pkthdr.len;
758	}
759
760	/*
761	 * If offset or IP_MF are set, must reassemble.
762	 * Otherwise, nothing need be done.
763	 * (We could look in the reassembly queue to see
764	 * if the packet was previously fragmented,
765	 * but it's not worth the time; just let them time out.)
766	 */
767	if (ip->ip_off & (IP_MF | IP_OFFMASK)) {
768
769		/* If maxnipq is 0, never accept fragments. */
770		if (maxnipq == 0) {
771                	ipstat.ips_fragments++;
772			ipstat.ips_fragdropped++;
773			goto bad;
774		}
775
776		sum = IPREASS_HASH(ip->ip_src.s_addr, ip->ip_id);
777		IPQ_LOCK();
778		/*
779		 * Look for queue of fragments
780		 * of this datagram.
781		 */
782		TAILQ_FOREACH(fp, &ipq[sum], ipq_list)
783			if (ip->ip_id == fp->ipq_id &&
784			    ip->ip_src.s_addr == fp->ipq_src.s_addr &&
785			    ip->ip_dst.s_addr == fp->ipq_dst.s_addr &&
786#ifdef MAC
787			    mac_fragment_match(m, fp) &&
788#endif
789			    ip->ip_p == fp->ipq_p)
790				goto found;
791
792		fp = NULL;
793
794		/*
795		 * Enforce upper bound on number of fragmented packets
796		 * for which we attempt reassembly;
797		 * If maxnipq is -1, accept all fragments without limitation.
798		 */
799		if ((nipq > maxnipq) && (maxnipq > 0)) {
800		    /*
801		     * drop something from the tail of the current queue
802		     * before proceeding further
803		     */
804		    struct ipq *q = TAILQ_LAST(&ipq[sum], ipqhead);
805		    if (q == NULL) {   /* gak */
806			for (i = 0; i < IPREASS_NHASH; i++) {
807			    struct ipq *r = TAILQ_LAST(&ipq[i], ipqhead);
808			    if (r) {
809				ipstat.ips_fragtimeout += r->ipq_nfrags;
810				ip_freef(&ipq[i], r);
811				break;
812			    }
813			}
814		    } else {
815			ipstat.ips_fragtimeout += q->ipq_nfrags;
816			ip_freef(&ipq[sum], q);
817		    }
818		}
819found:
820		/*
821		 * Adjust ip_len to not reflect header,
822		 * convert offset of this to bytes.
823		 */
824		ip->ip_len -= hlen;
825		if (ip->ip_off & IP_MF) {
826		        /*
827		         * Make sure that fragments have a data length
828			 * that's a non-zero multiple of 8 bytes.
829		         */
830			if (ip->ip_len == 0 || (ip->ip_len & 0x7) != 0) {
831				IPQ_UNLOCK();
832				ipstat.ips_toosmall++; /* XXX */
833				goto bad;
834			}
835			m->m_flags |= M_FRAG;
836		} else
837			m->m_flags &= ~M_FRAG;
838		ip->ip_off <<= 3;
839
840		/*
841		 * Attempt reassembly; if it succeeds, proceed.
842		 * ip_reass() will return a different mbuf, and update
843		 * the divert info in divert_info and args.divert_rule.
844		 */
845		ipstat.ips_fragments++;
846		m->m_pkthdr.header = ip;
847		m = ip_reass(m,
848		    &ipq[sum], fp, &divert_info, &args.divert_rule);
849		IPQ_UNLOCK();
850		if (m == 0)
851			return;
852		ipstat.ips_reassembled++;
853		ip = mtod(m, struct ip *);
854		/* Get the header length of the reassembled packet */
855		hlen = ip->ip_hl << 2;
856#ifdef IPDIVERT
857		/* Restore original checksum before diverting packet */
858		if (divert_info != 0) {
859			ip->ip_len += hlen;
860			ip->ip_len = htons(ip->ip_len);
861			ip->ip_off = htons(ip->ip_off);
862			ip->ip_sum = 0;
863			if (hlen == sizeof(struct ip))
864				ip->ip_sum = in_cksum_hdr(ip);
865			else
866				ip->ip_sum = in_cksum(m, hlen);
867			ip->ip_off = ntohs(ip->ip_off);
868			ip->ip_len = ntohs(ip->ip_len);
869			ip->ip_len -= hlen;
870		}
871#endif
872	} else
873		ip->ip_len -= hlen;
874
875#ifdef IPDIVERT
876	/*
877	 * Divert or tee packet to the divert protocol if required.
878	 */
879	if (divert_info != 0) {
880		struct mbuf *clone = NULL;
881
882		/* Clone packet if we're doing a 'tee' */
883		if ((divert_info & IP_FW_PORT_TEE_FLAG) != 0)
884			clone = m_dup(m, M_DONTWAIT);
885
886		/* Restore packet header fields to original values */
887		ip->ip_len += hlen;
888		ip->ip_len = htons(ip->ip_len);
889		ip->ip_off = htons(ip->ip_off);
890
891		/* Deliver packet to divert input routine */
892		divert_packet(m, 1, divert_info & 0xffff, args.divert_rule);
893		ipstat.ips_delivered++;
894
895		/* If 'tee', continue with original packet */
896		if (clone == NULL)
897			return;
898		m = clone;
899		ip = mtod(m, struct ip *);
900		ip->ip_len += hlen;
901		/*
902		 * Jump backwards to complete processing of the
903		 * packet. But first clear divert_info to avoid
904		 * entering this block again.
905		 * We do not need to clear args.divert_rule
906		 * or args.next_hop as they will not be used.
907		 */
908		divert_info = 0;
909		goto pass;
910	}
911#endif
912
913#ifdef IPSEC
914	/*
915	 * enforce IPsec policy checking if we are seeing last header.
916	 * note that we do not visit this with protocols with pcb layer
917	 * code - like udp/tcp/raw ip.
918	 */
919	if ((inetsw[ip_protox[ip->ip_p]].pr_flags & PR_LASTHDR) != 0 &&
920	    ipsec4_in_reject(m, NULL)) {
921		ipsecstat.in_polvio++;
922		goto bad;
923	}
924#endif
925#if FAST_IPSEC
926	/*
927	 * enforce IPsec policy checking if we are seeing last header.
928	 * note that we do not visit this with protocols with pcb layer
929	 * code - like udp/tcp/raw ip.
930	 */
931	if ((inetsw[ip_protox[ip->ip_p]].pr_flags & PR_LASTHDR) != 0) {
932		/*
933		 * Check if the packet has already had IPsec processing
934		 * done.  If so, then just pass it along.  This tag gets
935		 * set during AH, ESP, etc. input handling, before the
936		 * packet is returned to the ip input queue for delivery.
937		 */
938		mtag = m_tag_find(m, PACKET_TAG_IPSEC_IN_DONE, NULL);
939		s = splnet();
940		if (mtag != NULL) {
941			tdbi = (struct tdb_ident *)(mtag + 1);
942			sp = ipsec_getpolicy(tdbi, IPSEC_DIR_INBOUND);
943		} else {
944			sp = ipsec_getpolicybyaddr(m, IPSEC_DIR_INBOUND,
945						   IP_FORWARDING, &error);
946		}
947		if (sp != NULL) {
948			/*
949			 * Check security policy against packet attributes.
950			 */
951			error = ipsec_in_reject(sp, m);
952			KEY_FREESP(&sp);
953		} else {
954			/* XXX error stat??? */
955			error = EINVAL;
956DPRINTF(("ip_input: no SP, packet discarded\n"));/*XXX*/
957			goto bad;
958		}
959		splx(s);
960		if (error)
961			goto bad;
962	}
963#endif /* FAST_IPSEC */
964
965	/*
966	 * Switch out to protocol's input routine.
967	 */
968	ipstat.ips_delivered++;
969	NET_PICKUP_GIANT();
970	if (args.next_hop && ip->ip_p == IPPROTO_TCP) {
971		/* TCP needs IPFORWARD info if available */
972		struct m_hdr tag;
973
974		tag.mh_type = MT_TAG;
975		tag.mh_flags = PACKET_TAG_IPFORWARD;
976		tag.mh_data = (caddr_t)args.next_hop;
977		tag.mh_next = m;
978		tag.mh_nextpkt = NULL;
979
980		(*inetsw[ip_protox[ip->ip_p]].pr_input)(
981			(struct mbuf *)&tag, hlen);
982	} else
983		(*inetsw[ip_protox[ip->ip_p]].pr_input)(m, hlen);
984	NET_DROP_GIANT();
985	return;
986bad:
987	m_freem(m);
988}
989
990/*
991 * Take incoming datagram fragment and try to reassemble it into
992 * whole datagram.  If a chain for reassembly of this datagram already
993 * exists, then it is given as fp; otherwise have to make a chain.
994 *
995 * When IPDIVERT enabled, keep additional state with each packet that
996 * tells us if we need to divert or tee the packet we're building.
997 * In particular, *divinfo includes the port and TEE flag,
998 * *divert_rule is the number of the matching rule.
999 */
1000
1001static struct mbuf *
1002ip_reass(struct mbuf *m, struct ipqhead *head, struct ipq *fp,
1003	u_int32_t *divinfo, u_int16_t *divert_rule)
1004{
1005	struct ip *ip = mtod(m, struct ip *);
1006	register struct mbuf *p, *q, *nq;
1007	struct mbuf *t;
1008	int hlen = ip->ip_hl << 2;
1009	int i, next;
1010	u_int8_t ecn, ecn0;
1011
1012	IPQ_LOCK_ASSERT();
1013
1014	/*
1015	 * Presence of header sizes in mbufs
1016	 * would confuse code below.
1017	 */
1018	m->m_data += hlen;
1019	m->m_len -= hlen;
1020
1021	/*
1022	 * If first fragment to arrive, create a reassembly queue.
1023	 */
1024	if (fp == NULL) {
1025		if ((t = m_get(M_DONTWAIT, MT_FTABLE)) == NULL)
1026			goto dropfrag;
1027		fp = mtod(t, struct ipq *);
1028#ifdef MAC
1029		if (mac_init_ipq(fp, M_NOWAIT) != 0) {
1030			m_free(t);
1031			goto dropfrag;
1032		}
1033		mac_create_ipq(m, fp);
1034#endif
1035		TAILQ_INSERT_HEAD(head, fp, ipq_list);
1036		nipq++;
1037		fp->ipq_nfrags = 1;
1038		fp->ipq_ttl = IPFRAGTTL;
1039		fp->ipq_p = ip->ip_p;
1040		fp->ipq_id = ip->ip_id;
1041		fp->ipq_src = ip->ip_src;
1042		fp->ipq_dst = ip->ip_dst;
1043		fp->ipq_frags = m;
1044		m->m_nextpkt = NULL;
1045#ifdef IPDIVERT
1046		fp->ipq_div_info = 0;
1047		fp->ipq_div_cookie = 0;
1048#endif
1049		goto inserted;
1050	} else {
1051		fp->ipq_nfrags++;
1052#ifdef MAC
1053		mac_update_ipq(m, fp);
1054#endif
1055	}
1056
1057#define GETIP(m)	((struct ip*)((m)->m_pkthdr.header))
1058
1059	/*
1060	 * Handle ECN by comparing this segment with the first one;
1061	 * if CE is set, do not lose CE.
1062	 * drop if CE and not-ECT are mixed for the same packet.
1063	 */
1064	ecn = ip->ip_tos & IPTOS_ECN_MASK;
1065	ecn0 = GETIP(fp->ipq_frags)->ip_tos & IPTOS_ECN_MASK;
1066	if (ecn == IPTOS_ECN_CE) {
1067		if (ecn0 == IPTOS_ECN_NOTECT)
1068			goto dropfrag;
1069		if (ecn0 != IPTOS_ECN_CE)
1070			GETIP(fp->ipq_frags)->ip_tos |= IPTOS_ECN_CE;
1071	}
1072	if (ecn == IPTOS_ECN_NOTECT && ecn0 != IPTOS_ECN_NOTECT)
1073		goto dropfrag;
1074
1075	/*
1076	 * Find a segment which begins after this one does.
1077	 */
1078	for (p = NULL, q = fp->ipq_frags; q; p = q, q = q->m_nextpkt)
1079		if (GETIP(q)->ip_off > ip->ip_off)
1080			break;
1081
1082	/*
1083	 * If there is a preceding segment, it may provide some of
1084	 * our data already.  If so, drop the data from the incoming
1085	 * segment.  If it provides all of our data, drop us, otherwise
1086	 * stick new segment in the proper place.
1087	 *
1088	 * If some of the data is dropped from the the preceding
1089	 * segment, then it's checksum is invalidated.
1090	 */
1091	if (p) {
1092		i = GETIP(p)->ip_off + GETIP(p)->ip_len - ip->ip_off;
1093		if (i > 0) {
1094			if (i >= ip->ip_len)
1095				goto dropfrag;
1096			m_adj(m, i);
1097			m->m_pkthdr.csum_flags = 0;
1098			ip->ip_off += i;
1099			ip->ip_len -= i;
1100		}
1101		m->m_nextpkt = p->m_nextpkt;
1102		p->m_nextpkt = m;
1103	} else {
1104		m->m_nextpkt = fp->ipq_frags;
1105		fp->ipq_frags = m;
1106	}
1107
1108	/*
1109	 * While we overlap succeeding segments trim them or,
1110	 * if they are completely covered, dequeue them.
1111	 */
1112	for (; q != NULL && ip->ip_off + ip->ip_len > GETIP(q)->ip_off;
1113	     q = nq) {
1114		i = (ip->ip_off + ip->ip_len) - GETIP(q)->ip_off;
1115		if (i < GETIP(q)->ip_len) {
1116			GETIP(q)->ip_len -= i;
1117			GETIP(q)->ip_off += i;
1118			m_adj(q, i);
1119			q->m_pkthdr.csum_flags = 0;
1120			break;
1121		}
1122		nq = q->m_nextpkt;
1123		m->m_nextpkt = nq;
1124		ipstat.ips_fragdropped++;
1125		fp->ipq_nfrags--;
1126		m_freem(q);
1127	}
1128
1129inserted:
1130
1131#ifdef IPDIVERT
1132	/*
1133	 * Transfer firewall instructions to the fragment structure.
1134	 * Only trust info in the fragment at offset 0.
1135	 */
1136	if (ip->ip_off == 0) {
1137		fp->ipq_div_info = *divinfo;
1138		fp->ipq_div_cookie = *divert_rule;
1139	}
1140	*divinfo = 0;
1141	*divert_rule = 0;
1142#endif
1143
1144	/*
1145	 * Check for complete reassembly and perform frag per packet
1146	 * limiting.
1147	 *
1148	 * Frag limiting is performed here so that the nth frag has
1149	 * a chance to complete the packet before we drop the packet.
1150	 * As a result, n+1 frags are actually allowed per packet, but
1151	 * only n will ever be stored. (n = maxfragsperpacket.)
1152	 *
1153	 */
1154	next = 0;
1155	for (p = NULL, q = fp->ipq_frags; q; p = q, q = q->m_nextpkt) {
1156		if (GETIP(q)->ip_off != next) {
1157			if (fp->ipq_nfrags > maxfragsperpacket) {
1158				ipstat.ips_fragdropped += fp->ipq_nfrags;
1159				ip_freef(head, fp);
1160			}
1161			return (0);
1162		}
1163		next += GETIP(q)->ip_len;
1164	}
1165	/* Make sure the last packet didn't have the IP_MF flag */
1166	if (p->m_flags & M_FRAG) {
1167		if (fp->ipq_nfrags > maxfragsperpacket) {
1168			ipstat.ips_fragdropped += fp->ipq_nfrags;
1169			ip_freef(head, fp);
1170		}
1171		return (0);
1172	}
1173
1174	/*
1175	 * Reassembly is complete.  Make sure the packet is a sane size.
1176	 */
1177	q = fp->ipq_frags;
1178	ip = GETIP(q);
1179	if (next + (ip->ip_hl << 2) > IP_MAXPACKET) {
1180		ipstat.ips_toolong++;
1181		ipstat.ips_fragdropped += fp->ipq_nfrags;
1182		ip_freef(head, fp);
1183		return (0);
1184	}
1185
1186	/*
1187	 * Concatenate fragments.
1188	 */
1189	m = q;
1190	t = m->m_next;
1191	m->m_next = 0;
1192	m_cat(m, t);
1193	nq = q->m_nextpkt;
1194	q->m_nextpkt = 0;
1195	for (q = nq; q != NULL; q = nq) {
1196		nq = q->m_nextpkt;
1197		q->m_nextpkt = NULL;
1198		m->m_pkthdr.csum_flags &= q->m_pkthdr.csum_flags;
1199		m->m_pkthdr.csum_data += q->m_pkthdr.csum_data;
1200		m_cat(m, q);
1201	}
1202#ifdef MAC
1203	mac_create_datagram_from_ipq(fp, m);
1204	mac_destroy_ipq(fp);
1205#endif
1206
1207#ifdef IPDIVERT
1208	/*
1209	 * Extract firewall instructions from the fragment structure.
1210	 */
1211	*divinfo = fp->ipq_div_info;
1212	*divert_rule = fp->ipq_div_cookie;
1213#endif
1214
1215	/*
1216	 * Create header for new ip packet by
1217	 * modifying header of first packet;
1218	 * dequeue and discard fragment reassembly header.
1219	 * Make header visible.
1220	 */
1221	ip->ip_len = next;
1222	ip->ip_src = fp->ipq_src;
1223	ip->ip_dst = fp->ipq_dst;
1224	TAILQ_REMOVE(head, fp, ipq_list);
1225	nipq--;
1226	(void) m_free(dtom(fp));
1227	m->m_len += (ip->ip_hl << 2);
1228	m->m_data -= (ip->ip_hl << 2);
1229	/* some debugging cruft by sklower, below, will go away soon */
1230	if (m->m_flags & M_PKTHDR)	/* XXX this should be done elsewhere */
1231		m_fixhdr(m);
1232	return (m);
1233
1234dropfrag:
1235#ifdef IPDIVERT
1236	*divinfo = 0;
1237	*divert_rule = 0;
1238#endif
1239	ipstat.ips_fragdropped++;
1240	if (fp != NULL)
1241		fp->ipq_nfrags--;
1242	m_freem(m);
1243	return (0);
1244
1245#undef GETIP
1246}
1247
1248/*
1249 * Free a fragment reassembly header and all
1250 * associated datagrams.
1251 */
1252static void
1253ip_freef(fhp, fp)
1254	struct ipqhead *fhp;
1255	struct ipq *fp;
1256{
1257	register struct mbuf *q;
1258
1259	IPQ_LOCK_ASSERT();
1260
1261	while (fp->ipq_frags) {
1262		q = fp->ipq_frags;
1263		fp->ipq_frags = q->m_nextpkt;
1264		m_freem(q);
1265	}
1266	TAILQ_REMOVE(fhp, fp, ipq_list);
1267	(void) m_free(dtom(fp));
1268	nipq--;
1269}
1270
1271/*
1272 * IP timer processing;
1273 * if a timer expires on a reassembly
1274 * queue, discard it.
1275 */
1276void
1277ip_slowtimo()
1278{
1279	register struct ipq *fp;
1280	int s = splnet();
1281	int i;
1282
1283	IPQ_LOCK();
1284	for (i = 0; i < IPREASS_NHASH; i++) {
1285		for(fp = TAILQ_FIRST(&ipq[i]); fp;) {
1286			struct ipq *fpp;
1287
1288			fpp = fp;
1289			fp = TAILQ_NEXT(fp, ipq_list);
1290			if(--fpp->ipq_ttl == 0) {
1291				ipstat.ips_fragtimeout += fpp->ipq_nfrags;
1292				ip_freef(&ipq[i], fpp);
1293			}
1294		}
1295	}
1296	/*
1297	 * If we are over the maximum number of fragments
1298	 * (due to the limit being lowered), drain off
1299	 * enough to get down to the new limit.
1300	 */
1301	if (maxnipq >= 0 && nipq > maxnipq) {
1302		for (i = 0; i < IPREASS_NHASH; i++) {
1303			while (nipq > maxnipq && !TAILQ_EMPTY(&ipq[i])) {
1304				ipstat.ips_fragdropped +=
1305				    TAILQ_FIRST(&ipq[i])->ipq_nfrags;
1306				ip_freef(&ipq[i], TAILQ_FIRST(&ipq[i]));
1307			}
1308		}
1309	}
1310	IPQ_UNLOCK();
1311	splx(s);
1312}
1313
1314/*
1315 * Drain off all datagram fragments.
1316 */
1317void
1318ip_drain()
1319{
1320	int     i;
1321
1322	IPQ_LOCK();
1323	for (i = 0; i < IPREASS_NHASH; i++) {
1324		while(!TAILQ_EMPTY(&ipq[i])) {
1325			ipstat.ips_fragdropped +=
1326			    TAILQ_FIRST(&ipq[i])->ipq_nfrags;
1327			ip_freef(&ipq[i], TAILQ_FIRST(&ipq[i]));
1328		}
1329	}
1330	IPQ_UNLOCK();
1331	in_rtqdrain();
1332}
1333
1334/*
1335 * Do option processing on a datagram,
1336 * possibly discarding it if bad options are encountered,
1337 * or forwarding it if source-routed.
1338 * The pass argument is used when operating in the IPSTEALTH
1339 * mode to tell what options to process:
1340 * [LS]SRR (pass 0) or the others (pass 1).
1341 * The reason for as many as two passes is that when doing IPSTEALTH,
1342 * non-routing options should be processed only if the packet is for us.
1343 * Returns 1 if packet has been forwarded/freed,
1344 * 0 if the packet should be processed further.
1345 */
1346static int
1347ip_dooptions(struct mbuf *m, int pass, struct sockaddr_in *next_hop)
1348{
1349	struct ip *ip = mtod(m, struct ip *);
1350	u_char *cp;
1351	struct in_ifaddr *ia;
1352	int opt, optlen, cnt, off, code, type = ICMP_PARAMPROB, forward = 0;
1353	struct in_addr *sin, dst;
1354	n_time ntime;
1355	struct	sockaddr_in ipaddr = { sizeof(ipaddr), AF_INET };
1356
1357	dst = ip->ip_dst;
1358	cp = (u_char *)(ip + 1);
1359	cnt = (ip->ip_hl << 2) - sizeof (struct ip);
1360	for (; cnt > 0; cnt -= optlen, cp += optlen) {
1361		opt = cp[IPOPT_OPTVAL];
1362		if (opt == IPOPT_EOL)
1363			break;
1364		if (opt == IPOPT_NOP)
1365			optlen = 1;
1366		else {
1367			if (cnt < IPOPT_OLEN + sizeof(*cp)) {
1368				code = &cp[IPOPT_OLEN] - (u_char *)ip;
1369				goto bad;
1370			}
1371			optlen = cp[IPOPT_OLEN];
1372			if (optlen < IPOPT_OLEN + sizeof(*cp) || optlen > cnt) {
1373				code = &cp[IPOPT_OLEN] - (u_char *)ip;
1374				goto bad;
1375			}
1376		}
1377		switch (opt) {
1378
1379		default:
1380			break;
1381
1382		/*
1383		 * Source routing with record.
1384		 * Find interface with current destination address.
1385		 * If none on this machine then drop if strictly routed,
1386		 * or do nothing if loosely routed.
1387		 * Record interface address and bring up next address
1388		 * component.  If strictly routed make sure next
1389		 * address is on directly accessible net.
1390		 */
1391		case IPOPT_LSRR:
1392		case IPOPT_SSRR:
1393#ifdef IPSTEALTH
1394			if (ipstealth && pass > 0)
1395				break;
1396#endif
1397			if (optlen < IPOPT_OFFSET + sizeof(*cp)) {
1398				code = &cp[IPOPT_OLEN] - (u_char *)ip;
1399				goto bad;
1400			}
1401			if ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {
1402				code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1403				goto bad;
1404			}
1405			ipaddr.sin_addr = ip->ip_dst;
1406			ia = (struct in_ifaddr *)
1407				ifa_ifwithaddr((struct sockaddr *)&ipaddr);
1408			if (ia == 0) {
1409				if (opt == IPOPT_SSRR) {
1410					type = ICMP_UNREACH;
1411					code = ICMP_UNREACH_SRCFAIL;
1412					goto bad;
1413				}
1414				if (!ip_dosourceroute)
1415					goto nosourcerouting;
1416				/*
1417				 * Loose routing, and not at next destination
1418				 * yet; nothing to do except forward.
1419				 */
1420				break;
1421			}
1422			off--;			/* 0 origin */
1423			if (off > optlen - (int)sizeof(struct in_addr)) {
1424				/*
1425				 * End of source route.  Should be for us.
1426				 */
1427				if (!ip_acceptsourceroute)
1428					goto nosourcerouting;
1429				save_rte(cp, ip->ip_src);
1430				break;
1431			}
1432#ifdef IPSTEALTH
1433			if (ipstealth)
1434				goto dropit;
1435#endif
1436			if (!ip_dosourceroute) {
1437				if (ipforwarding) {
1438					char buf[16]; /* aaa.bbb.ccc.ddd\0 */
1439					/*
1440					 * Acting as a router, so generate ICMP
1441					 */
1442nosourcerouting:
1443					strcpy(buf, inet_ntoa(ip->ip_dst));
1444					log(LOG_WARNING,
1445					    "attempted source route from %s to %s\n",
1446					    inet_ntoa(ip->ip_src), buf);
1447					type = ICMP_UNREACH;
1448					code = ICMP_UNREACH_SRCFAIL;
1449					goto bad;
1450				} else {
1451					/*
1452					 * Not acting as a router, so silently drop.
1453					 */
1454#ifdef IPSTEALTH
1455dropit:
1456#endif
1457					ipstat.ips_cantforward++;
1458					m_freem(m);
1459					return (1);
1460				}
1461			}
1462
1463			/*
1464			 * locate outgoing interface
1465			 */
1466			(void)memcpy(&ipaddr.sin_addr, cp + off,
1467			    sizeof(ipaddr.sin_addr));
1468
1469			if (opt == IPOPT_SSRR) {
1470#define	INA	struct in_ifaddr *
1471#define	SA	struct sockaddr *
1472			    if ((ia = (INA)ifa_ifwithdstaddr((SA)&ipaddr)) == 0)
1473				ia = (INA)ifa_ifwithnet((SA)&ipaddr);
1474			} else
1475				ia = ip_rtaddr(ipaddr.sin_addr);
1476			if (ia == 0) {
1477				type = ICMP_UNREACH;
1478				code = ICMP_UNREACH_SRCFAIL;
1479				goto bad;
1480			}
1481			ip->ip_dst = ipaddr.sin_addr;
1482			(void)memcpy(cp + off, &(IA_SIN(ia)->sin_addr),
1483			    sizeof(struct in_addr));
1484			cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1485			/*
1486			 * Let ip_intr's mcast routing check handle mcast pkts
1487			 */
1488			forward = !IN_MULTICAST(ntohl(ip->ip_dst.s_addr));
1489			break;
1490
1491		case IPOPT_RR:
1492#ifdef IPSTEALTH
1493			if (ipstealth && pass == 0)
1494				break;
1495#endif
1496			if (optlen < IPOPT_OFFSET + sizeof(*cp)) {
1497				code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1498				goto bad;
1499			}
1500			if ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {
1501				code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1502				goto bad;
1503			}
1504			/*
1505			 * If no space remains, ignore.
1506			 */
1507			off--;			/* 0 origin */
1508			if (off > optlen - (int)sizeof(struct in_addr))
1509				break;
1510			(void)memcpy(&ipaddr.sin_addr, &ip->ip_dst,
1511			    sizeof(ipaddr.sin_addr));
1512			/*
1513			 * locate outgoing interface; if we're the destination,
1514			 * use the incoming interface (should be same).
1515			 */
1516			if ((ia = (INA)ifa_ifwithaddr((SA)&ipaddr)) == 0 &&
1517			    (ia = ip_rtaddr(ipaddr.sin_addr)) == 0) {
1518				type = ICMP_UNREACH;
1519				code = ICMP_UNREACH_HOST;
1520				goto bad;
1521			}
1522			(void)memcpy(cp + off, &(IA_SIN(ia)->sin_addr),
1523			    sizeof(struct in_addr));
1524			cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1525			break;
1526
1527		case IPOPT_TS:
1528#ifdef IPSTEALTH
1529			if (ipstealth && pass == 0)
1530				break;
1531#endif
1532			code = cp - (u_char *)ip;
1533			if (optlen < 4 || optlen > 40) {
1534				code = &cp[IPOPT_OLEN] - (u_char *)ip;
1535				goto bad;
1536			}
1537			if ((off = cp[IPOPT_OFFSET]) < 5) {
1538				code = &cp[IPOPT_OLEN] - (u_char *)ip;
1539				goto bad;
1540			}
1541			if (off > optlen - (int)sizeof(int32_t)) {
1542				cp[IPOPT_OFFSET + 1] += (1 << 4);
1543				if ((cp[IPOPT_OFFSET + 1] & 0xf0) == 0) {
1544					code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1545					goto bad;
1546				}
1547				break;
1548			}
1549			off--;				/* 0 origin */
1550			sin = (struct in_addr *)(cp + off);
1551			switch (cp[IPOPT_OFFSET + 1] & 0x0f) {
1552
1553			case IPOPT_TS_TSONLY:
1554				break;
1555
1556			case IPOPT_TS_TSANDADDR:
1557				if (off + sizeof(n_time) +
1558				    sizeof(struct in_addr) > optlen) {
1559					code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1560					goto bad;
1561				}
1562				ipaddr.sin_addr = dst;
1563				ia = (INA)ifaof_ifpforaddr((SA)&ipaddr,
1564							    m->m_pkthdr.rcvif);
1565				if (ia == 0)
1566					continue;
1567				(void)memcpy(sin, &IA_SIN(ia)->sin_addr,
1568				    sizeof(struct in_addr));
1569				cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1570				off += sizeof(struct in_addr);
1571				break;
1572
1573			case IPOPT_TS_PRESPEC:
1574				if (off + sizeof(n_time) +
1575				    sizeof(struct in_addr) > optlen) {
1576					code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1577					goto bad;
1578				}
1579				(void)memcpy(&ipaddr.sin_addr, sin,
1580				    sizeof(struct in_addr));
1581				if (ifa_ifwithaddr((SA)&ipaddr) == 0)
1582					continue;
1583				cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1584				off += sizeof(struct in_addr);
1585				break;
1586
1587			default:
1588				code = &cp[IPOPT_OFFSET + 1] - (u_char *)ip;
1589				goto bad;
1590			}
1591			ntime = iptime();
1592			(void)memcpy(cp + off, &ntime, sizeof(n_time));
1593			cp[IPOPT_OFFSET] += sizeof(n_time);
1594		}
1595	}
1596	if (forward && ipforwarding) {
1597		ip_forward(m, 1, next_hop);
1598		return (1);
1599	}
1600	return (0);
1601bad:
1602	icmp_error(m, type, code, 0, 0);
1603	ipstat.ips_badoptions++;
1604	return (1);
1605}
1606
1607/*
1608 * Given address of next destination (final or next hop),
1609 * return internet address info of interface to be used to get there.
1610 */
1611struct in_ifaddr *
1612ip_rtaddr(dst)
1613	struct in_addr dst;
1614{
1615	struct route sro;
1616	struct sockaddr_in *sin;
1617	struct in_ifaddr *ifa;
1618
1619	bzero(&sro, sizeof(sro));
1620	sin = (struct sockaddr_in *)&sro.ro_dst;
1621	sin->sin_family = AF_INET;
1622	sin->sin_len = sizeof(*sin);
1623	sin->sin_addr = dst;
1624	rtalloc_ign(&sro, RTF_CLONING);
1625
1626	if (sro.ro_rt == NULL)
1627		return ((struct in_ifaddr *)0);
1628
1629	ifa = ifatoia(sro.ro_rt->rt_ifa);
1630	RTFREE(sro.ro_rt);
1631	return ifa;
1632}
1633
1634/*
1635 * Save incoming source route for use in replies,
1636 * to be picked up later by ip_srcroute if the receiver is interested.
1637 */
1638static void
1639save_rte(option, dst)
1640	u_char *option;
1641	struct in_addr dst;
1642{
1643	unsigned olen;
1644
1645	olen = option[IPOPT_OLEN];
1646#ifdef DIAGNOSTIC
1647	if (ipprintfs)
1648		printf("save_rte: olen %d\n", olen);
1649#endif
1650	if (olen > sizeof(ip_srcrt) - (1 + sizeof(dst)))
1651		return;
1652	bcopy(option, ip_srcrt.srcopt, olen);
1653	ip_nhops = (olen - IPOPT_OFFSET - 1) / sizeof(struct in_addr);
1654	ip_srcrt.dst = dst;
1655}
1656
1657/*
1658 * Retrieve incoming source route for use in replies,
1659 * in the same form used by setsockopt.
1660 * The first hop is placed before the options, will be removed later.
1661 */
1662struct mbuf *
1663ip_srcroute()
1664{
1665	register struct in_addr *p, *q;
1666	register struct mbuf *m;
1667
1668	if (ip_nhops == 0)
1669		return ((struct mbuf *)0);
1670	m = m_get(M_DONTWAIT, MT_HEADER);
1671	if (m == 0)
1672		return ((struct mbuf *)0);
1673
1674#define OPTSIZ	(sizeof(ip_srcrt.nop) + sizeof(ip_srcrt.srcopt))
1675
1676	/* length is (nhops+1)*sizeof(addr) + sizeof(nop + srcrt header) */
1677	m->m_len = ip_nhops * sizeof(struct in_addr) + sizeof(struct in_addr) +
1678	    OPTSIZ;
1679#ifdef DIAGNOSTIC
1680	if (ipprintfs)
1681		printf("ip_srcroute: nhops %d mlen %d", ip_nhops, m->m_len);
1682#endif
1683
1684	/*
1685	 * First save first hop for return route
1686	 */
1687	p = &ip_srcrt.route[ip_nhops - 1];
1688	*(mtod(m, struct in_addr *)) = *p--;
1689#ifdef DIAGNOSTIC
1690	if (ipprintfs)
1691		printf(" hops %lx", (u_long)ntohl(mtod(m, struct in_addr *)->s_addr));
1692#endif
1693
1694	/*
1695	 * Copy option fields and padding (nop) to mbuf.
1696	 */
1697	ip_srcrt.nop = IPOPT_NOP;
1698	ip_srcrt.srcopt[IPOPT_OFFSET] = IPOPT_MINOFF;
1699	(void)memcpy(mtod(m, caddr_t) + sizeof(struct in_addr),
1700	    &ip_srcrt.nop, OPTSIZ);
1701	q = (struct in_addr *)(mtod(m, caddr_t) +
1702	    sizeof(struct in_addr) + OPTSIZ);
1703#undef OPTSIZ
1704	/*
1705	 * Record return path as an IP source route,
1706	 * reversing the path (pointers are now aligned).
1707	 */
1708	while (p >= ip_srcrt.route) {
1709#ifdef DIAGNOSTIC
1710		if (ipprintfs)
1711			printf(" %lx", (u_long)ntohl(q->s_addr));
1712#endif
1713		*q++ = *p--;
1714	}
1715	/*
1716	 * Last hop goes to final destination.
1717	 */
1718	*q = ip_srcrt.dst;
1719#ifdef DIAGNOSTIC
1720	if (ipprintfs)
1721		printf(" %lx\n", (u_long)ntohl(q->s_addr));
1722#endif
1723	return (m);
1724}
1725
1726/*
1727 * Strip out IP options, at higher
1728 * level protocol in the kernel.
1729 * Second argument is buffer to which options
1730 * will be moved, and return value is their length.
1731 * XXX should be deleted; last arg currently ignored.
1732 */
1733void
1734ip_stripoptions(m, mopt)
1735	register struct mbuf *m;
1736	struct mbuf *mopt;
1737{
1738	register int i;
1739	struct ip *ip = mtod(m, struct ip *);
1740	register caddr_t opts;
1741	int olen;
1742
1743	olen = (ip->ip_hl << 2) - sizeof (struct ip);
1744	opts = (caddr_t)(ip + 1);
1745	i = m->m_len - (sizeof (struct ip) + olen);
1746	bcopy(opts + olen, opts, (unsigned)i);
1747	m->m_len -= olen;
1748	if (m->m_flags & M_PKTHDR)
1749		m->m_pkthdr.len -= olen;
1750	ip->ip_v = IPVERSION;
1751	ip->ip_hl = sizeof(struct ip) >> 2;
1752}
1753
1754u_char inetctlerrmap[PRC_NCMDS] = {
1755	0,		0,		0,		0,
1756	0,		EMSGSIZE,	EHOSTDOWN,	EHOSTUNREACH,
1757	EHOSTUNREACH,	EHOSTUNREACH,	ECONNREFUSED,	ECONNREFUSED,
1758	EMSGSIZE,	EHOSTUNREACH,	0,		0,
1759	0,		0,		EHOSTUNREACH,	0,
1760	ENOPROTOOPT,	ECONNREFUSED
1761};
1762
1763/*
1764 * Forward a packet.  If some error occurs return the sender
1765 * an icmp packet.  Note we can't always generate a meaningful
1766 * icmp message because icmp doesn't have a large enough repertoire
1767 * of codes and types.
1768 *
1769 * If not forwarding, just drop the packet.  This could be confusing
1770 * if ipforwarding was zero but some routing protocol was advancing
1771 * us as a gateway to somewhere.  However, we must let the routing
1772 * protocol deal with that.
1773 *
1774 * The srcrt parameter indicates whether the packet is being forwarded
1775 * via a source route.
1776 */
1777static void
1778ip_forward(struct mbuf *m, int srcrt, struct sockaddr_in *next_hop)
1779{
1780	struct ip *ip = mtod(m, struct ip *);
1781	struct in_ifaddr *ia;
1782	int error, type = 0, code = 0;
1783	struct mbuf *mcopy;
1784	n_long dest;
1785	struct in_addr pkt_dst;
1786	struct ifnet *destifp;
1787#if defined(IPSEC) || defined(FAST_IPSEC)
1788	struct ifnet dummyifp;
1789#endif
1790
1791	/*
1792	 * Cache the destination address of the packet; this may be
1793	 * changed by use of 'ipfw fwd'.
1794	 */
1795	pkt_dst = next_hop ? next_hop->sin_addr : ip->ip_dst;
1796
1797#ifdef DIAGNOSTIC
1798	if (ipprintfs)
1799		printf("forward: src %lx dst %lx ttl %x\n",
1800		    (u_long)ip->ip_src.s_addr, (u_long)pkt_dst.s_addr,
1801		    ip->ip_ttl);
1802#endif
1803
1804
1805	if (m->m_flags & (M_BCAST|M_MCAST) || in_canforward(pkt_dst) == 0) {
1806		ipstat.ips_cantforward++;
1807		m_freem(m);
1808		return;
1809	}
1810#ifdef IPSTEALTH
1811	if (!ipstealth) {
1812#endif
1813		if (ip->ip_ttl <= IPTTLDEC) {
1814			icmp_error(m, ICMP_TIMXCEED, ICMP_TIMXCEED_INTRANS,
1815			    0, 0);
1816			return;
1817		}
1818#ifdef IPSTEALTH
1819	}
1820#endif
1821
1822	if ((ia = ip_rtaddr(pkt_dst)) == 0) {
1823		icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_HOST, 0, 0);
1824		return;
1825	}
1826
1827	/*
1828	 * Save the IP header and at most 8 bytes of the payload,
1829	 * in case we need to generate an ICMP message to the src.
1830	 *
1831	 * XXX this can be optimized a lot by saving the data in a local
1832	 * buffer on the stack (72 bytes at most), and only allocating the
1833	 * mbuf if really necessary. The vast majority of the packets
1834	 * are forwarded without having to send an ICMP back (either
1835	 * because unnecessary, or because rate limited), so we are
1836	 * really we are wasting a lot of work here.
1837	 *
1838	 * We don't use m_copy() because it might return a reference
1839	 * to a shared cluster. Both this function and ip_output()
1840	 * assume exclusive access to the IP header in `m', so any
1841	 * data in a cluster may change before we reach icmp_error().
1842	 */
1843	MGET(mcopy, M_DONTWAIT, m->m_type);
1844	if (mcopy != NULL && !m_dup_pkthdr(mcopy, m, M_DONTWAIT)) {
1845		/*
1846		 * It's probably ok if the pkthdr dup fails (because
1847		 * the deep copy of the tag chain failed), but for now
1848		 * be conservative and just discard the copy since
1849		 * code below may some day want the tags.
1850		 */
1851		m_free(mcopy);
1852		mcopy = NULL;
1853	}
1854	if (mcopy != NULL) {
1855		mcopy->m_len = imin((ip->ip_hl << 2) + 8,
1856		    (int)ip->ip_len);
1857		m_copydata(m, 0, mcopy->m_len, mtod(mcopy, caddr_t));
1858	}
1859
1860#ifdef IPSTEALTH
1861	if (!ipstealth) {
1862#endif
1863		ip->ip_ttl -= IPTTLDEC;
1864#ifdef IPSTEALTH
1865	}
1866#endif
1867
1868	/*
1869	 * If forwarding packet using same interface that it came in on,
1870	 * perhaps should send a redirect to sender to shortcut a hop.
1871	 * Only send redirect if source is sending directly to us,
1872	 * and if packet was not source routed (or has any options).
1873	 * Also, don't send redirect if forwarding using a default route
1874	 * or a route modified by a redirect.
1875	 */
1876	dest = 0;
1877	if (ipsendredirects && ia->ia_ifp == m->m_pkthdr.rcvif) {
1878		struct sockaddr_in *sin;
1879		struct route ro;
1880		struct rtentry *rt;
1881
1882		bzero(&ro, sizeof(ro));
1883		sin = (struct sockaddr_in *)&ro.ro_dst;
1884		sin->sin_family = AF_INET;
1885		sin->sin_len = sizeof(*sin);
1886		sin->sin_addr = pkt_dst;
1887		rtalloc_ign(&ro, RTF_CLONING);
1888
1889		rt = ro.ro_rt;
1890
1891		if (rt && (rt->rt_flags & (RTF_DYNAMIC|RTF_MODIFIED)) == 0 &&
1892		    satosin(rt_key(rt))->sin_addr.s_addr != 0 &&
1893		    ipsendredirects && !srcrt && !next_hop) {
1894#define	RTA(rt)	((struct in_ifaddr *)(rt->rt_ifa))
1895			u_long src = ntohl(ip->ip_src.s_addr);
1896
1897			if (RTA(rt) &&
1898			    (src & RTA(rt)->ia_subnetmask) == RTA(rt)->ia_subnet) {
1899				if (rt->rt_flags & RTF_GATEWAY)
1900					dest = satosin(rt->rt_gateway)->sin_addr.s_addr;
1901				else
1902					dest = pkt_dst.s_addr;
1903				/* Router requirements says to only send host redirects */
1904				type = ICMP_REDIRECT;
1905				code = ICMP_REDIRECT_HOST;
1906#ifdef DIAGNOSTIC
1907				if (ipprintfs)
1908					printf("redirect (%d) to %lx\n", code, (u_long)dest);
1909#endif
1910			}
1911		}
1912		if (rt)
1913			RTFREE(rt);
1914	}
1915
1916    {
1917	struct m_hdr tag;
1918
1919	if (next_hop) {
1920		/* Pass IPFORWARD info if available */
1921
1922		tag.mh_type = MT_TAG;
1923		tag.mh_flags = PACKET_TAG_IPFORWARD;
1924		tag.mh_data = (caddr_t)next_hop;
1925		tag.mh_next = m;
1926		tag.mh_nextpkt = NULL;
1927		m = (struct mbuf *)&tag;
1928	}
1929	error = ip_output(m, (struct mbuf *)0, NULL, IP_FORWARDING, 0, NULL);
1930    }
1931	if (error)
1932		ipstat.ips_cantforward++;
1933	else {
1934		ipstat.ips_forward++;
1935		if (type)
1936			ipstat.ips_redirectsent++;
1937		else {
1938			if (mcopy)
1939				m_freem(mcopy);
1940			return;
1941		}
1942	}
1943	if (mcopy == NULL)
1944		return;
1945	destifp = NULL;
1946
1947	switch (error) {
1948
1949	case 0:				/* forwarded, but need redirect */
1950		/* type, code set above */
1951		break;
1952
1953	case ENETUNREACH:		/* shouldn't happen, checked above */
1954	case EHOSTUNREACH:
1955	case ENETDOWN:
1956	case EHOSTDOWN:
1957	default:
1958		type = ICMP_UNREACH;
1959		code = ICMP_UNREACH_HOST;
1960		break;
1961
1962	case EMSGSIZE:
1963		type = ICMP_UNREACH;
1964		code = ICMP_UNREACH_NEEDFRAG;
1965#if defined(IPSEC) || defined(FAST_IPSEC)
1966		/*
1967		 * If the packet is routed over IPsec tunnel, tell the
1968		 * originator the tunnel MTU.
1969		 *	tunnel MTU = if MTU - sizeof(IP) - ESP/AH hdrsiz
1970		 * XXX quickhack!!!
1971		 */
1972		{
1973			struct secpolicy *sp = NULL;
1974			int ipsecerror;
1975			int ipsechdr;
1976			struct route *ro;
1977
1978#ifdef IPSEC
1979			sp = ipsec4_getpolicybyaddr(mcopy,
1980						    IPSEC_DIR_OUTBOUND,
1981						    IP_FORWARDING,
1982						    &ipsecerror);
1983#else /* FAST_IPSEC */
1984			sp = ipsec_getpolicybyaddr(mcopy,
1985						   IPSEC_DIR_OUTBOUND,
1986						   IP_FORWARDING,
1987						   &ipsecerror);
1988#endif
1989			if (sp != NULL) {
1990				/* count IPsec header size */
1991				ipsechdr = ipsec4_hdrsiz(mcopy,
1992							 IPSEC_DIR_OUTBOUND,
1993							 NULL);
1994
1995				/*
1996				 * find the correct route for outer IPv4
1997				 * header, compute tunnel MTU.
1998				 *
1999				 * XXX BUG ALERT
2000				 * The "dummyifp" code relies upon the fact
2001				 * that icmp_error() touches only ifp->if_mtu.
2002				 */
2003				/*XXX*/
2004				destifp = NULL;
2005				if (sp->req != NULL
2006				 && sp->req->sav != NULL
2007				 && sp->req->sav->sah != NULL) {
2008					ro = &sp->req->sav->sah->sa_route;
2009					if (ro->ro_rt && ro->ro_rt->rt_ifp) {
2010						dummyifp.if_mtu =
2011						    ro->ro_rt->rt_ifp->if_mtu;
2012						dummyifp.if_mtu -= ipsechdr;
2013						destifp = &dummyifp;
2014					}
2015				}
2016
2017#ifdef IPSEC
2018				key_freesp(sp);
2019#else /* FAST_IPSEC */
2020				KEY_FREESP(&sp);
2021#endif
2022				ipstat.ips_cantfrag++;
2023				break;
2024			} else
2025#endif /*IPSEC || FAST_IPSEC*/
2026		destifp = ia->ia_ifp;
2027#if defined(IPSEC) || defined(FAST_IPSEC)
2028		}
2029#endif /*IPSEC || FAST_IPSEC*/
2030		ipstat.ips_cantfrag++;
2031		break;
2032
2033	case ENOBUFS:
2034		/*
2035		 * A router should not generate ICMP_SOURCEQUENCH as
2036		 * required in RFC1812 Requirements for IP Version 4 Routers.
2037		 * Source quench could be a big problem under DoS attacks,
2038		 * or if the underlying interface is rate-limited.
2039		 * Those who need source quench packets may re-enable them
2040		 * via the net.inet.ip.sendsourcequench sysctl.
2041		 */
2042		if (ip_sendsourcequench == 0) {
2043			m_freem(mcopy);
2044			return;
2045		} else {
2046			type = ICMP_SOURCEQUENCH;
2047			code = 0;
2048		}
2049		break;
2050
2051	case EACCES:			/* ipfw denied packet */
2052		m_freem(mcopy);
2053		return;
2054	}
2055	icmp_error(mcopy, type, code, dest, destifp);
2056}
2057
2058void
2059ip_savecontrol(inp, mp, ip, m)
2060	register struct inpcb *inp;
2061	register struct mbuf **mp;
2062	register struct ip *ip;
2063	register struct mbuf *m;
2064{
2065	if (inp->inp_socket->so_options & SO_TIMESTAMP) {
2066		struct timeval tv;
2067
2068		microtime(&tv);
2069		*mp = sbcreatecontrol((caddr_t) &tv, sizeof(tv),
2070			SCM_TIMESTAMP, SOL_SOCKET);
2071		if (*mp)
2072			mp = &(*mp)->m_next;
2073	}
2074	if (inp->inp_flags & INP_RECVDSTADDR) {
2075		*mp = sbcreatecontrol((caddr_t) &ip->ip_dst,
2076		    sizeof(struct in_addr), IP_RECVDSTADDR, IPPROTO_IP);
2077		if (*mp)
2078			mp = &(*mp)->m_next;
2079	}
2080	if (inp->inp_flags & INP_RECVTTL) {
2081		*mp = sbcreatecontrol((caddr_t) &ip->ip_ttl,
2082		    sizeof(u_char), IP_RECVTTL, IPPROTO_IP);
2083		if (*mp)
2084			mp = &(*mp)->m_next;
2085	}
2086#ifdef notyet
2087	/* XXX
2088	 * Moving these out of udp_input() made them even more broken
2089	 * than they already were.
2090	 */
2091	/* options were tossed already */
2092	if (inp->inp_flags & INP_RECVOPTS) {
2093		*mp = sbcreatecontrol((caddr_t) opts_deleted_above,
2094		    sizeof(struct in_addr), IP_RECVOPTS, IPPROTO_IP);
2095		if (*mp)
2096			mp = &(*mp)->m_next;
2097	}
2098	/* ip_srcroute doesn't do what we want here, need to fix */
2099	if (inp->inp_flags & INP_RECVRETOPTS) {
2100		*mp = sbcreatecontrol((caddr_t) ip_srcroute(),
2101		    sizeof(struct in_addr), IP_RECVRETOPTS, IPPROTO_IP);
2102		if (*mp)
2103			mp = &(*mp)->m_next;
2104	}
2105#endif
2106	if (inp->inp_flags & INP_RECVIF) {
2107		struct ifnet *ifp;
2108		struct sdlbuf {
2109			struct sockaddr_dl sdl;
2110			u_char	pad[32];
2111		} sdlbuf;
2112		struct sockaddr_dl *sdp;
2113		struct sockaddr_dl *sdl2 = &sdlbuf.sdl;
2114
2115		if (((ifp = m->m_pkthdr.rcvif))
2116		&& ( ifp->if_index && (ifp->if_index <= if_index))) {
2117			sdp = (struct sockaddr_dl *)
2118			    (ifaddr_byindex(ifp->if_index)->ifa_addr);
2119			/*
2120			 * Change our mind and don't try copy.
2121			 */
2122			if ((sdp->sdl_family != AF_LINK)
2123			|| (sdp->sdl_len > sizeof(sdlbuf))) {
2124				goto makedummy;
2125			}
2126			bcopy(sdp, sdl2, sdp->sdl_len);
2127		} else {
2128makedummy:
2129			sdl2->sdl_len
2130				= offsetof(struct sockaddr_dl, sdl_data[0]);
2131			sdl2->sdl_family = AF_LINK;
2132			sdl2->sdl_index = 0;
2133			sdl2->sdl_nlen = sdl2->sdl_alen = sdl2->sdl_slen = 0;
2134		}
2135		*mp = sbcreatecontrol((caddr_t) sdl2, sdl2->sdl_len,
2136			IP_RECVIF, IPPROTO_IP);
2137		if (*mp)
2138			mp = &(*mp)->m_next;
2139	}
2140}
2141
2142/*
2143 * XXX these routines are called from the upper part of the kernel.
2144 * They need to be locked when we remove Giant.
2145 *
2146 * They could also be moved to ip_mroute.c, since all the RSVP
2147 *  handling is done there already.
2148 */
2149static int ip_rsvp_on;
2150struct socket *ip_rsvpd;
2151int
2152ip_rsvp_init(struct socket *so)
2153{
2154	if (so->so_type != SOCK_RAW ||
2155	    so->so_proto->pr_protocol != IPPROTO_RSVP)
2156		return EOPNOTSUPP;
2157
2158	if (ip_rsvpd != NULL)
2159		return EADDRINUSE;
2160
2161	ip_rsvpd = so;
2162	/*
2163	 * This may seem silly, but we need to be sure we don't over-increment
2164	 * the RSVP counter, in case something slips up.
2165	 */
2166	if (!ip_rsvp_on) {
2167		ip_rsvp_on = 1;
2168		rsvp_on++;
2169	}
2170
2171	return 0;
2172}
2173
2174int
2175ip_rsvp_done(void)
2176{
2177	ip_rsvpd = NULL;
2178	/*
2179	 * This may seem silly, but we need to be sure we don't over-decrement
2180	 * the RSVP counter, in case something slips up.
2181	 */
2182	if (ip_rsvp_on) {
2183		ip_rsvp_on = 0;
2184		rsvp_on--;
2185	}
2186	return 0;
2187}
2188
2189void
2190rsvp_input(struct mbuf *m, int off)	/* XXX must fixup manually */
2191{
2192	if (rsvp_input_p) { /* call the real one if loaded */
2193		rsvp_input_p(m, off);
2194		return;
2195	}
2196
2197	/* Can still get packets with rsvp_on = 0 if there is a local member
2198	 * of the group to which the RSVP packet is addressed.  But in this
2199	 * case we want to throw the packet away.
2200	 */
2201
2202	if (!rsvp_on) {
2203		m_freem(m);
2204		return;
2205	}
2206
2207	if (ip_rsvpd != NULL) {
2208		rip_input(m, off);
2209		return;
2210	}
2211	/* Drop the packet */
2212	m_freem(m);
2213}
2214