ip_input.c revision 122708
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 122708 2003-11-14 21:48:57Z 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
201static int	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
979		(*inetsw[ip_protox[ip->ip_p]].pr_input)(
980			(struct mbuf *)&tag, hlen);
981	} else
982		(*inetsw[ip_protox[ip->ip_p]].pr_input)(m, hlen);
983	NET_DROP_GIANT();
984	return;
985bad:
986	m_freem(m);
987}
988
989/*
990 * Take incoming datagram fragment and try to reassemble it into
991 * whole datagram.  If a chain for reassembly of this datagram already
992 * exists, then it is given as fp; otherwise have to make a chain.
993 *
994 * When IPDIVERT enabled, keep additional state with each packet that
995 * tells us if we need to divert or tee the packet we're building.
996 * In particular, *divinfo includes the port and TEE flag,
997 * *divert_rule is the number of the matching rule.
998 */
999
1000static struct mbuf *
1001ip_reass(struct mbuf *m, struct ipqhead *head, struct ipq *fp,
1002	u_int32_t *divinfo, u_int16_t *divert_rule)
1003{
1004	struct ip *ip = mtod(m, struct ip *);
1005	register struct mbuf *p, *q, *nq;
1006	struct mbuf *t;
1007	int hlen = ip->ip_hl << 2;
1008	int i, next;
1009	u_int8_t ecn, ecn0;
1010
1011	IPQ_LOCK_ASSERT();
1012
1013	/*
1014	 * Presence of header sizes in mbufs
1015	 * would confuse code below.
1016	 */
1017	m->m_data += hlen;
1018	m->m_len -= hlen;
1019
1020	/*
1021	 * If first fragment to arrive, create a reassembly queue.
1022	 */
1023	if (fp == NULL) {
1024		if ((t = m_get(M_DONTWAIT, MT_FTABLE)) == NULL)
1025			goto dropfrag;
1026		fp = mtod(t, struct ipq *);
1027#ifdef MAC
1028		if (mac_init_ipq(fp, M_NOWAIT) != 0) {
1029			m_free(t);
1030			goto dropfrag;
1031		}
1032		mac_create_ipq(m, fp);
1033#endif
1034		TAILQ_INSERT_HEAD(head, fp, ipq_list);
1035		nipq++;
1036		fp->ipq_nfrags = 1;
1037		fp->ipq_ttl = IPFRAGTTL;
1038		fp->ipq_p = ip->ip_p;
1039		fp->ipq_id = ip->ip_id;
1040		fp->ipq_src = ip->ip_src;
1041		fp->ipq_dst = ip->ip_dst;
1042		fp->ipq_frags = m;
1043		m->m_nextpkt = NULL;
1044#ifdef IPDIVERT
1045		fp->ipq_div_info = 0;
1046		fp->ipq_div_cookie = 0;
1047#endif
1048		goto inserted;
1049	} else {
1050		fp->ipq_nfrags++;
1051#ifdef MAC
1052		mac_update_ipq(m, fp);
1053#endif
1054	}
1055
1056#define GETIP(m)	((struct ip*)((m)->m_pkthdr.header))
1057
1058	/*
1059	 * Handle ECN by comparing this segment with the first one;
1060	 * if CE is set, do not lose CE.
1061	 * drop if CE and not-ECT are mixed for the same packet.
1062	 */
1063	ecn = ip->ip_tos & IPTOS_ECN_MASK;
1064	ecn0 = GETIP(fp->ipq_frags)->ip_tos & IPTOS_ECN_MASK;
1065	if (ecn == IPTOS_ECN_CE) {
1066		if (ecn0 == IPTOS_ECN_NOTECT)
1067			goto dropfrag;
1068		if (ecn0 != IPTOS_ECN_CE)
1069			GETIP(fp->ipq_frags)->ip_tos |= IPTOS_ECN_CE;
1070	}
1071	if (ecn == IPTOS_ECN_NOTECT && ecn0 != IPTOS_ECN_NOTECT)
1072		goto dropfrag;
1073
1074	/*
1075	 * Find a segment which begins after this one does.
1076	 */
1077	for (p = NULL, q = fp->ipq_frags; q; p = q, q = q->m_nextpkt)
1078		if (GETIP(q)->ip_off > ip->ip_off)
1079			break;
1080
1081	/*
1082	 * If there is a preceding segment, it may provide some of
1083	 * our data already.  If so, drop the data from the incoming
1084	 * segment.  If it provides all of our data, drop us, otherwise
1085	 * stick new segment in the proper place.
1086	 *
1087	 * If some of the data is dropped from the the preceding
1088	 * segment, then it's checksum is invalidated.
1089	 */
1090	if (p) {
1091		i = GETIP(p)->ip_off + GETIP(p)->ip_len - ip->ip_off;
1092		if (i > 0) {
1093			if (i >= ip->ip_len)
1094				goto dropfrag;
1095			m_adj(m, i);
1096			m->m_pkthdr.csum_flags = 0;
1097			ip->ip_off += i;
1098			ip->ip_len -= i;
1099		}
1100		m->m_nextpkt = p->m_nextpkt;
1101		p->m_nextpkt = m;
1102	} else {
1103		m->m_nextpkt = fp->ipq_frags;
1104		fp->ipq_frags = m;
1105	}
1106
1107	/*
1108	 * While we overlap succeeding segments trim them or,
1109	 * if they are completely covered, dequeue them.
1110	 */
1111	for (; q != NULL && ip->ip_off + ip->ip_len > GETIP(q)->ip_off;
1112	     q = nq) {
1113		i = (ip->ip_off + ip->ip_len) - GETIP(q)->ip_off;
1114		if (i < GETIP(q)->ip_len) {
1115			GETIP(q)->ip_len -= i;
1116			GETIP(q)->ip_off += i;
1117			m_adj(q, i);
1118			q->m_pkthdr.csum_flags = 0;
1119			break;
1120		}
1121		nq = q->m_nextpkt;
1122		m->m_nextpkt = nq;
1123		ipstat.ips_fragdropped++;
1124		fp->ipq_nfrags--;
1125		m_freem(q);
1126	}
1127
1128inserted:
1129
1130#ifdef IPDIVERT
1131	/*
1132	 * Transfer firewall instructions to the fragment structure.
1133	 * Only trust info in the fragment at offset 0.
1134	 */
1135	if (ip->ip_off == 0) {
1136		fp->ipq_div_info = *divinfo;
1137		fp->ipq_div_cookie = *divert_rule;
1138	}
1139	*divinfo = 0;
1140	*divert_rule = 0;
1141#endif
1142
1143	/*
1144	 * Check for complete reassembly and perform frag per packet
1145	 * limiting.
1146	 *
1147	 * Frag limiting is performed here so that the nth frag has
1148	 * a chance to complete the packet before we drop the packet.
1149	 * As a result, n+1 frags are actually allowed per packet, but
1150	 * only n will ever be stored. (n = maxfragsperpacket.)
1151	 *
1152	 */
1153	next = 0;
1154	for (p = NULL, q = fp->ipq_frags; q; p = q, q = q->m_nextpkt) {
1155		if (GETIP(q)->ip_off != next) {
1156			if (fp->ipq_nfrags > maxfragsperpacket) {
1157				ipstat.ips_fragdropped += fp->ipq_nfrags;
1158				ip_freef(head, fp);
1159			}
1160			return (0);
1161		}
1162		next += GETIP(q)->ip_len;
1163	}
1164	/* Make sure the last packet didn't have the IP_MF flag */
1165	if (p->m_flags & M_FRAG) {
1166		if (fp->ipq_nfrags > maxfragsperpacket) {
1167			ipstat.ips_fragdropped += fp->ipq_nfrags;
1168			ip_freef(head, fp);
1169		}
1170		return (0);
1171	}
1172
1173	/*
1174	 * Reassembly is complete.  Make sure the packet is a sane size.
1175	 */
1176	q = fp->ipq_frags;
1177	ip = GETIP(q);
1178	if (next + (ip->ip_hl << 2) > IP_MAXPACKET) {
1179		ipstat.ips_toolong++;
1180		ipstat.ips_fragdropped += fp->ipq_nfrags;
1181		ip_freef(head, fp);
1182		return (0);
1183	}
1184
1185	/*
1186	 * Concatenate fragments.
1187	 */
1188	m = q;
1189	t = m->m_next;
1190	m->m_next = 0;
1191	m_cat(m, t);
1192	nq = q->m_nextpkt;
1193	q->m_nextpkt = 0;
1194	for (q = nq; q != NULL; q = nq) {
1195		nq = q->m_nextpkt;
1196		q->m_nextpkt = NULL;
1197		m->m_pkthdr.csum_flags &= q->m_pkthdr.csum_flags;
1198		m->m_pkthdr.csum_data += q->m_pkthdr.csum_data;
1199		m_cat(m, q);
1200	}
1201#ifdef MAC
1202	mac_create_datagram_from_ipq(fp, m);
1203	mac_destroy_ipq(fp);
1204#endif
1205
1206#ifdef IPDIVERT
1207	/*
1208	 * Extract firewall instructions from the fragment structure.
1209	 */
1210	*divinfo = fp->ipq_div_info;
1211	*divert_rule = fp->ipq_div_cookie;
1212#endif
1213
1214	/*
1215	 * Create header for new ip packet by
1216	 * modifying header of first packet;
1217	 * dequeue and discard fragment reassembly header.
1218	 * Make header visible.
1219	 */
1220	ip->ip_len = next;
1221	ip->ip_src = fp->ipq_src;
1222	ip->ip_dst = fp->ipq_dst;
1223	TAILQ_REMOVE(head, fp, ipq_list);
1224	nipq--;
1225	(void) m_free(dtom(fp));
1226	m->m_len += (ip->ip_hl << 2);
1227	m->m_data -= (ip->ip_hl << 2);
1228	/* some debugging cruft by sklower, below, will go away soon */
1229	if (m->m_flags & M_PKTHDR)	/* XXX this should be done elsewhere */
1230		m_fixhdr(m);
1231	return (m);
1232
1233dropfrag:
1234#ifdef IPDIVERT
1235	*divinfo = 0;
1236	*divert_rule = 0;
1237#endif
1238	ipstat.ips_fragdropped++;
1239	if (fp != NULL)
1240		fp->ipq_nfrags--;
1241	m_freem(m);
1242	return (0);
1243
1244#undef GETIP
1245}
1246
1247/*
1248 * Free a fragment reassembly header and all
1249 * associated datagrams.
1250 */
1251static void
1252ip_freef(fhp, fp)
1253	struct ipqhead *fhp;
1254	struct ipq *fp;
1255{
1256	register struct mbuf *q;
1257
1258	IPQ_LOCK_ASSERT();
1259
1260	while (fp->ipq_frags) {
1261		q = fp->ipq_frags;
1262		fp->ipq_frags = q->m_nextpkt;
1263		m_freem(q);
1264	}
1265	TAILQ_REMOVE(fhp, fp, ipq_list);
1266	(void) m_free(dtom(fp));
1267	nipq--;
1268}
1269
1270/*
1271 * IP timer processing;
1272 * if a timer expires on a reassembly
1273 * queue, discard it.
1274 */
1275void
1276ip_slowtimo()
1277{
1278	register struct ipq *fp;
1279	int s = splnet();
1280	int i;
1281
1282	IPQ_LOCK();
1283	for (i = 0; i < IPREASS_NHASH; i++) {
1284		for(fp = TAILQ_FIRST(&ipq[i]); fp;) {
1285			struct ipq *fpp;
1286
1287			fpp = fp;
1288			fp = TAILQ_NEXT(fp, ipq_list);
1289			if(--fpp->ipq_ttl == 0) {
1290				ipstat.ips_fragtimeout += fpp->ipq_nfrags;
1291				ip_freef(&ipq[i], fpp);
1292			}
1293		}
1294	}
1295	/*
1296	 * If we are over the maximum number of fragments
1297	 * (due to the limit being lowered), drain off
1298	 * enough to get down to the new limit.
1299	 */
1300	if (maxnipq >= 0 && nipq > maxnipq) {
1301		for (i = 0; i < IPREASS_NHASH; i++) {
1302			while (nipq > maxnipq && !TAILQ_EMPTY(&ipq[i])) {
1303				ipstat.ips_fragdropped +=
1304				    TAILQ_FIRST(&ipq[i])->ipq_nfrags;
1305				ip_freef(&ipq[i], TAILQ_FIRST(&ipq[i]));
1306			}
1307		}
1308	}
1309	IPQ_UNLOCK();
1310	splx(s);
1311}
1312
1313/*
1314 * Drain off all datagram fragments.
1315 */
1316void
1317ip_drain()
1318{
1319	int     i;
1320
1321	IPQ_LOCK();
1322	for (i = 0; i < IPREASS_NHASH; i++) {
1323		while(!TAILQ_EMPTY(&ipq[i])) {
1324			ipstat.ips_fragdropped +=
1325			    TAILQ_FIRST(&ipq[i])->ipq_nfrags;
1326			ip_freef(&ipq[i], TAILQ_FIRST(&ipq[i]));
1327		}
1328	}
1329	IPQ_UNLOCK();
1330	in_rtqdrain();
1331}
1332
1333/*
1334 * Do option processing on a datagram,
1335 * possibly discarding it if bad options are encountered,
1336 * or forwarding it if source-routed.
1337 * The pass argument is used when operating in the IPSTEALTH
1338 * mode to tell what options to process:
1339 * [LS]SRR (pass 0) or the others (pass 1).
1340 * The reason for as many as two passes is that when doing IPSTEALTH,
1341 * non-routing options should be processed only if the packet is for us.
1342 * Returns 1 if packet has been forwarded/freed,
1343 * 0 if the packet should be processed further.
1344 */
1345static int
1346ip_dooptions(struct mbuf *m, int pass, struct sockaddr_in *next_hop)
1347{
1348	struct ip *ip = mtod(m, struct ip *);
1349	u_char *cp;
1350	struct in_ifaddr *ia;
1351	int opt, optlen, cnt, off, code, type = ICMP_PARAMPROB, forward = 0;
1352	struct in_addr *sin, dst;
1353	n_time ntime;
1354	struct	sockaddr_in ipaddr = { sizeof(ipaddr), AF_INET };
1355
1356	dst = ip->ip_dst;
1357	cp = (u_char *)(ip + 1);
1358	cnt = (ip->ip_hl << 2) - sizeof (struct ip);
1359	for (; cnt > 0; cnt -= optlen, cp += optlen) {
1360		opt = cp[IPOPT_OPTVAL];
1361		if (opt == IPOPT_EOL)
1362			break;
1363		if (opt == IPOPT_NOP)
1364			optlen = 1;
1365		else {
1366			if (cnt < IPOPT_OLEN + sizeof(*cp)) {
1367				code = &cp[IPOPT_OLEN] - (u_char *)ip;
1368				goto bad;
1369			}
1370			optlen = cp[IPOPT_OLEN];
1371			if (optlen < IPOPT_OLEN + sizeof(*cp) || optlen > cnt) {
1372				code = &cp[IPOPT_OLEN] - (u_char *)ip;
1373				goto bad;
1374			}
1375		}
1376		switch (opt) {
1377
1378		default:
1379			break;
1380
1381		/*
1382		 * Source routing with record.
1383		 * Find interface with current destination address.
1384		 * If none on this machine then drop if strictly routed,
1385		 * or do nothing if loosely routed.
1386		 * Record interface address and bring up next address
1387		 * component.  If strictly routed make sure next
1388		 * address is on directly accessible net.
1389		 */
1390		case IPOPT_LSRR:
1391		case IPOPT_SSRR:
1392#ifdef IPSTEALTH
1393			if (ipstealth && pass > 0)
1394				break;
1395#endif
1396			if (optlen < IPOPT_OFFSET + sizeof(*cp)) {
1397				code = &cp[IPOPT_OLEN] - (u_char *)ip;
1398				goto bad;
1399			}
1400			if ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {
1401				code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1402				goto bad;
1403			}
1404			ipaddr.sin_addr = ip->ip_dst;
1405			ia = (struct in_ifaddr *)
1406				ifa_ifwithaddr((struct sockaddr *)&ipaddr);
1407			if (ia == 0) {
1408				if (opt == IPOPT_SSRR) {
1409					type = ICMP_UNREACH;
1410					code = ICMP_UNREACH_SRCFAIL;
1411					goto bad;
1412				}
1413				if (!ip_dosourceroute)
1414					goto nosourcerouting;
1415				/*
1416				 * Loose routing, and not at next destination
1417				 * yet; nothing to do except forward.
1418				 */
1419				break;
1420			}
1421			off--;			/* 0 origin */
1422			if (off > optlen - (int)sizeof(struct in_addr)) {
1423				/*
1424				 * End of source route.  Should be for us.
1425				 */
1426				if (!ip_acceptsourceroute)
1427					goto nosourcerouting;
1428				save_rte(cp, ip->ip_src);
1429				break;
1430			}
1431#ifdef IPSTEALTH
1432			if (ipstealth)
1433				goto dropit;
1434#endif
1435			if (!ip_dosourceroute) {
1436				if (ipforwarding) {
1437					char buf[16]; /* aaa.bbb.ccc.ddd\0 */
1438					/*
1439					 * Acting as a router, so generate ICMP
1440					 */
1441nosourcerouting:
1442					strcpy(buf, inet_ntoa(ip->ip_dst));
1443					log(LOG_WARNING,
1444					    "attempted source route from %s to %s\n",
1445					    inet_ntoa(ip->ip_src), buf);
1446					type = ICMP_UNREACH;
1447					code = ICMP_UNREACH_SRCFAIL;
1448					goto bad;
1449				} else {
1450					/*
1451					 * Not acting as a router, so silently drop.
1452					 */
1453#ifdef IPSTEALTH
1454dropit:
1455#endif
1456					ipstat.ips_cantforward++;
1457					m_freem(m);
1458					return (1);
1459				}
1460			}
1461
1462			/*
1463			 * locate outgoing interface
1464			 */
1465			(void)memcpy(&ipaddr.sin_addr, cp + off,
1466			    sizeof(ipaddr.sin_addr));
1467
1468			if (opt == IPOPT_SSRR) {
1469#define	INA	struct in_ifaddr *
1470#define	SA	struct sockaddr *
1471			    if ((ia = (INA)ifa_ifwithdstaddr((SA)&ipaddr)) == 0)
1472				ia = (INA)ifa_ifwithnet((SA)&ipaddr);
1473			} else
1474				ia = ip_rtaddr(ipaddr.sin_addr);
1475			if (ia == 0) {
1476				type = ICMP_UNREACH;
1477				code = ICMP_UNREACH_SRCFAIL;
1478				goto bad;
1479			}
1480			ip->ip_dst = ipaddr.sin_addr;
1481			(void)memcpy(cp + off, &(IA_SIN(ia)->sin_addr),
1482			    sizeof(struct in_addr));
1483			cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1484			/*
1485			 * Let ip_intr's mcast routing check handle mcast pkts
1486			 */
1487			forward = !IN_MULTICAST(ntohl(ip->ip_dst.s_addr));
1488			break;
1489
1490		case IPOPT_RR:
1491#ifdef IPSTEALTH
1492			if (ipstealth && pass == 0)
1493				break;
1494#endif
1495			if (optlen < IPOPT_OFFSET + sizeof(*cp)) {
1496				code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1497				goto bad;
1498			}
1499			if ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {
1500				code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1501				goto bad;
1502			}
1503			/*
1504			 * If no space remains, ignore.
1505			 */
1506			off--;			/* 0 origin */
1507			if (off > optlen - (int)sizeof(struct in_addr))
1508				break;
1509			(void)memcpy(&ipaddr.sin_addr, &ip->ip_dst,
1510			    sizeof(ipaddr.sin_addr));
1511			/*
1512			 * locate outgoing interface; if we're the destination,
1513			 * use the incoming interface (should be same).
1514			 */
1515			if ((ia = (INA)ifa_ifwithaddr((SA)&ipaddr)) == 0 &&
1516			    (ia = ip_rtaddr(ipaddr.sin_addr)) == 0) {
1517				type = ICMP_UNREACH;
1518				code = ICMP_UNREACH_HOST;
1519				goto bad;
1520			}
1521			(void)memcpy(cp + off, &(IA_SIN(ia)->sin_addr),
1522			    sizeof(struct in_addr));
1523			cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1524			break;
1525
1526		case IPOPT_TS:
1527#ifdef IPSTEALTH
1528			if (ipstealth && pass == 0)
1529				break;
1530#endif
1531			code = cp - (u_char *)ip;
1532			if (optlen < 4 || optlen > 40) {
1533				code = &cp[IPOPT_OLEN] - (u_char *)ip;
1534				goto bad;
1535			}
1536			if ((off = cp[IPOPT_OFFSET]) < 5) {
1537				code = &cp[IPOPT_OLEN] - (u_char *)ip;
1538				goto bad;
1539			}
1540			if (off > optlen - (int)sizeof(int32_t)) {
1541				cp[IPOPT_OFFSET + 1] += (1 << 4);
1542				if ((cp[IPOPT_OFFSET + 1] & 0xf0) == 0) {
1543					code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1544					goto bad;
1545				}
1546				break;
1547			}
1548			off--;				/* 0 origin */
1549			sin = (struct in_addr *)(cp + off);
1550			switch (cp[IPOPT_OFFSET + 1] & 0x0f) {
1551
1552			case IPOPT_TS_TSONLY:
1553				break;
1554
1555			case IPOPT_TS_TSANDADDR:
1556				if (off + sizeof(n_time) +
1557				    sizeof(struct in_addr) > optlen) {
1558					code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1559					goto bad;
1560				}
1561				ipaddr.sin_addr = dst;
1562				ia = (INA)ifaof_ifpforaddr((SA)&ipaddr,
1563							    m->m_pkthdr.rcvif);
1564				if (ia == 0)
1565					continue;
1566				(void)memcpy(sin, &IA_SIN(ia)->sin_addr,
1567				    sizeof(struct in_addr));
1568				cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1569				off += sizeof(struct in_addr);
1570				break;
1571
1572			case IPOPT_TS_PRESPEC:
1573				if (off + sizeof(n_time) +
1574				    sizeof(struct in_addr) > optlen) {
1575					code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1576					goto bad;
1577				}
1578				(void)memcpy(&ipaddr.sin_addr, sin,
1579				    sizeof(struct in_addr));
1580				if (ifa_ifwithaddr((SA)&ipaddr) == 0)
1581					continue;
1582				cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1583				off += sizeof(struct in_addr);
1584				break;
1585
1586			default:
1587				code = &cp[IPOPT_OFFSET + 1] - (u_char *)ip;
1588				goto bad;
1589			}
1590			ntime = iptime();
1591			(void)memcpy(cp + off, &ntime, sizeof(n_time));
1592			cp[IPOPT_OFFSET] += sizeof(n_time);
1593		}
1594	}
1595	if (forward && ipforwarding) {
1596		ip_forward(m, 1, next_hop);
1597		return (1);
1598	}
1599	return (0);
1600bad:
1601	icmp_error(m, type, code, 0, 0);
1602	ipstat.ips_badoptions++;
1603	return (1);
1604}
1605
1606/*
1607 * Given address of next destination (final or next hop),
1608 * return internet address info of interface to be used to get there.
1609 */
1610struct in_ifaddr *
1611ip_rtaddr(dst)
1612	struct in_addr dst;
1613{
1614	struct sockaddr_in *sin;
1615	struct in_ifaddr *ifa;
1616	struct route ro;
1617
1618	bzero(&ro, sizeof(ro));
1619	sin = (struct sockaddr_in *)&ro.ro_dst;
1620	sin->sin_family = AF_INET;
1621	sin->sin_len = sizeof(*sin);
1622	sin->sin_addr = dst;
1623	rtalloc_ign(&ro, (RTF_PRCLONING | RTF_CLONING));
1624
1625	if (ro.ro_rt == 0)
1626		return ((struct in_ifaddr *)0);
1627
1628	ifa = ifatoia(ro.ro_rt->rt_ifa);
1629	RTFREE(ro.ro_rt);
1630	return ifa;
1631}
1632
1633/*
1634 * Save incoming source route for use in replies,
1635 * to be picked up later by ip_srcroute if the receiver is interested.
1636 */
1637static void
1638save_rte(option, dst)
1639	u_char *option;
1640	struct in_addr dst;
1641{
1642	unsigned olen;
1643
1644	olen = option[IPOPT_OLEN];
1645#ifdef DIAGNOSTIC
1646	if (ipprintfs)
1647		printf("save_rte: olen %d\n", olen);
1648#endif
1649	if (olen > sizeof(ip_srcrt) - (1 + sizeof(dst)))
1650		return;
1651	bcopy(option, ip_srcrt.srcopt, olen);
1652	ip_nhops = (olen - IPOPT_OFFSET - 1) / sizeof(struct in_addr);
1653	ip_srcrt.dst = dst;
1654}
1655
1656/*
1657 * Retrieve incoming source route for use in replies,
1658 * in the same form used by setsockopt.
1659 * The first hop is placed before the options, will be removed later.
1660 */
1661struct mbuf *
1662ip_srcroute()
1663{
1664	register struct in_addr *p, *q;
1665	register struct mbuf *m;
1666
1667	if (ip_nhops == 0)
1668		return ((struct mbuf *)0);
1669	m = m_get(M_DONTWAIT, MT_HEADER);
1670	if (m == 0)
1671		return ((struct mbuf *)0);
1672
1673#define OPTSIZ	(sizeof(ip_srcrt.nop) + sizeof(ip_srcrt.srcopt))
1674
1675	/* length is (nhops+1)*sizeof(addr) + sizeof(nop + srcrt header) */
1676	m->m_len = ip_nhops * sizeof(struct in_addr) + sizeof(struct in_addr) +
1677	    OPTSIZ;
1678#ifdef DIAGNOSTIC
1679	if (ipprintfs)
1680		printf("ip_srcroute: nhops %d mlen %d", ip_nhops, m->m_len);
1681#endif
1682
1683	/*
1684	 * First save first hop for return route
1685	 */
1686	p = &ip_srcrt.route[ip_nhops - 1];
1687	*(mtod(m, struct in_addr *)) = *p--;
1688#ifdef DIAGNOSTIC
1689	if (ipprintfs)
1690		printf(" hops %lx", (u_long)ntohl(mtod(m, struct in_addr *)->s_addr));
1691#endif
1692
1693	/*
1694	 * Copy option fields and padding (nop) to mbuf.
1695	 */
1696	ip_srcrt.nop = IPOPT_NOP;
1697	ip_srcrt.srcopt[IPOPT_OFFSET] = IPOPT_MINOFF;
1698	(void)memcpy(mtod(m, caddr_t) + sizeof(struct in_addr),
1699	    &ip_srcrt.nop, OPTSIZ);
1700	q = (struct in_addr *)(mtod(m, caddr_t) +
1701	    sizeof(struct in_addr) + OPTSIZ);
1702#undef OPTSIZ
1703	/*
1704	 * Record return path as an IP source route,
1705	 * reversing the path (pointers are now aligned).
1706	 */
1707	while (p >= ip_srcrt.route) {
1708#ifdef DIAGNOSTIC
1709		if (ipprintfs)
1710			printf(" %lx", (u_long)ntohl(q->s_addr));
1711#endif
1712		*q++ = *p--;
1713	}
1714	/*
1715	 * Last hop goes to final destination.
1716	 */
1717	*q = ip_srcrt.dst;
1718#ifdef DIAGNOSTIC
1719	if (ipprintfs)
1720		printf(" %lx\n", (u_long)ntohl(q->s_addr));
1721#endif
1722	return (m);
1723}
1724
1725/*
1726 * Strip out IP options, at higher
1727 * level protocol in the kernel.
1728 * Second argument is buffer to which options
1729 * will be moved, and return value is their length.
1730 * XXX should be deleted; last arg currently ignored.
1731 */
1732void
1733ip_stripoptions(m, mopt)
1734	register struct mbuf *m;
1735	struct mbuf *mopt;
1736{
1737	register int i;
1738	struct ip *ip = mtod(m, struct ip *);
1739	register caddr_t opts;
1740	int olen;
1741
1742	olen = (ip->ip_hl << 2) - sizeof (struct ip);
1743	opts = (caddr_t)(ip + 1);
1744	i = m->m_len - (sizeof (struct ip) + olen);
1745	bcopy(opts + olen, opts, (unsigned)i);
1746	m->m_len -= olen;
1747	if (m->m_flags & M_PKTHDR)
1748		m->m_pkthdr.len -= olen;
1749	ip->ip_v = IPVERSION;
1750	ip->ip_hl = sizeof(struct ip) >> 2;
1751}
1752
1753u_char inetctlerrmap[PRC_NCMDS] = {
1754	0,		0,		0,		0,
1755	0,		EMSGSIZE,	EHOSTDOWN,	EHOSTUNREACH,
1756	EHOSTUNREACH,	EHOSTUNREACH,	ECONNREFUSED,	ECONNREFUSED,
1757	EMSGSIZE,	EHOSTUNREACH,	0,		0,
1758	0,		0,		EHOSTUNREACH,	0,
1759	ENOPROTOOPT,	ECONNREFUSED
1760};
1761
1762/*
1763 * Forward a packet.  If some error occurs return the sender
1764 * an icmp packet.  Note we can't always generate a meaningful
1765 * icmp message because icmp doesn't have a large enough repertoire
1766 * of codes and types.
1767 *
1768 * If not forwarding, just drop the packet.  This could be confusing
1769 * if ipforwarding was zero but some routing protocol was advancing
1770 * us as a gateway to somewhere.  However, we must let the routing
1771 * protocol deal with that.
1772 *
1773 * The srcrt parameter indicates whether the packet is being forwarded
1774 * via a source route.
1775 */
1776static void
1777ip_forward(struct mbuf *m, int srcrt, struct sockaddr_in *next_hop)
1778{
1779	struct ip *ip = mtod(m, struct ip *);
1780	struct in_ifaddr *ia;
1781	int error, type = 0, code = 0;
1782	struct mbuf *mcopy;
1783	n_long dest;
1784	struct in_addr pkt_dst;
1785	struct ifnet *destifp;
1786#if defined(IPSEC) || defined(FAST_IPSEC)
1787	struct ifnet dummyifp;
1788#endif
1789
1790	/*
1791	 * Cache the destination address of the packet; this may be
1792	 * changed by use of 'ipfw fwd'.
1793	 */
1794	pkt_dst = next_hop ? next_hop->sin_addr : ip->ip_dst;
1795
1796#ifdef DIAGNOSTIC
1797	if (ipprintfs)
1798		printf("forward: src %lx dst %lx ttl %x\n",
1799		    (u_long)ip->ip_src.s_addr, (u_long)pkt_dst.s_addr,
1800		    ip->ip_ttl);
1801#endif
1802
1803
1804	if (m->m_flags & (M_BCAST|M_MCAST) || in_canforward(pkt_dst) == 0) {
1805		ipstat.ips_cantforward++;
1806		m_freem(m);
1807		return;
1808	}
1809#ifdef IPSTEALTH
1810	if (!ipstealth) {
1811#endif
1812		if (ip->ip_ttl <= IPTTLDEC) {
1813			icmp_error(m, ICMP_TIMXCEED, ICMP_TIMXCEED_INTRANS,
1814			    0, 0);
1815			return;
1816		}
1817#ifdef IPSTEALTH
1818	}
1819#endif
1820
1821	if ((ia = ip_rtaddr(pkt_dst)) == 0) {
1822		icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_HOST, 0, 0);
1823		return;
1824	}
1825
1826	/*
1827	 * Save the IP header and at most 8 bytes of the payload,
1828	 * in case we need to generate an ICMP message to the src.
1829	 *
1830	 * XXX this can be optimized a lot by saving the data in a local
1831	 * buffer on the stack (72 bytes at most), and only allocating the
1832	 * mbuf if really necessary. The vast majority of the packets
1833	 * are forwarded without having to send an ICMP back (either
1834	 * because unnecessary, or because rate limited), so we are
1835	 * really we are wasting a lot of work here.
1836	 *
1837	 * We don't use m_copy() because it might return a reference
1838	 * to a shared cluster. Both this function and ip_output()
1839	 * assume exclusive access to the IP header in `m', so any
1840	 * data in a cluster may change before we reach icmp_error().
1841	 */
1842	MGET(mcopy, M_DONTWAIT, m->m_type);
1843	if (mcopy != NULL && !m_dup_pkthdr(mcopy, m, M_DONTWAIT)) {
1844		/*
1845		 * It's probably ok if the pkthdr dup fails (because
1846		 * the deep copy of the tag chain failed), but for now
1847		 * be conservative and just discard the copy since
1848		 * code below may some day want the tags.
1849		 */
1850		m_free(mcopy);
1851		mcopy = NULL;
1852	}
1853	if (mcopy != NULL) {
1854		mcopy->m_len = imin((ip->ip_hl << 2) + 8,
1855		    (int)ip->ip_len);
1856		m_copydata(m, 0, mcopy->m_len, mtod(mcopy, caddr_t));
1857	}
1858
1859#ifdef IPSTEALTH
1860	if (!ipstealth) {
1861#endif
1862		ip->ip_ttl -= IPTTLDEC;
1863#ifdef IPSTEALTH
1864	}
1865#endif
1866
1867	/*
1868	 * If forwarding packet using same interface that it came in on,
1869	 * perhaps should send a redirect to sender to shortcut a hop.
1870	 * Only send redirect if source is sending directly to us,
1871	 * and if packet was not source routed (or has any options).
1872	 * Also, don't send redirect if forwarding using a default route
1873	 * or a route modified by a redirect.
1874	 */
1875	dest = 0;
1876	if (ipsendredirects && ia->ia_ifp == m->m_pkthdr.rcvif) {
1877		struct sockaddr_in *sin;
1878		struct route ro;
1879		struct rtentry *rt;
1880
1881		bzero(&ro, sizeof(ro));
1882		sin = (struct sockaddr_in *)&ro.ro_dst;
1883		sin->sin_family = AF_INET;
1884		sin->sin_len = sizeof(*sin);
1885		sin->sin_addr = pkt_dst;
1886		rtalloc_ign(&ro, (RTF_PRCLONING | RTF_CLONING));
1887
1888		rt = ro.ro_rt;
1889
1890		if (rt && (rt->rt_flags & (RTF_DYNAMIC|RTF_MODIFIED)) == 0 &&
1891		    satosin(rt_key(rt))->sin_addr.s_addr != 0 &&
1892		    ipsendredirects && !srcrt && !next_hop) {
1893#define	RTA(rt)	((struct in_ifaddr *)(rt->rt_ifa))
1894			u_long src = ntohl(ip->ip_src.s_addr);
1895
1896			if (RTA(rt) &&
1897			    (src & RTA(rt)->ia_subnetmask) == RTA(rt)->ia_subnet) {
1898				if (rt->rt_flags & RTF_GATEWAY)
1899					dest = satosin(rt->rt_gateway)->sin_addr.s_addr;
1900				else
1901					dest = pkt_dst.s_addr;
1902				/* Router requirements says to only send host redirects */
1903				type = ICMP_REDIRECT;
1904				code = ICMP_REDIRECT_HOST;
1905#ifdef DIAGNOSTIC
1906				if (ipprintfs)
1907					printf("redirect (%d) to %lx\n", code, (u_long)dest);
1908#endif
1909			}
1910		}
1911		if (rt)
1912			RTFREE(rt);
1913	}
1914
1915    {
1916	struct m_hdr tag;
1917
1918	if (next_hop) {
1919		/* Pass IPFORWARD info if available */
1920
1921		tag.mh_type = MT_TAG;
1922		tag.mh_flags = PACKET_TAG_IPFORWARD;
1923		tag.mh_data = (caddr_t)next_hop;
1924		tag.mh_next = m;
1925		m = (struct mbuf *)&tag;
1926	}
1927	error = ip_output(m, (struct mbuf *)0, NULL, IP_FORWARDING, 0, NULL);
1928    }
1929	if (error)
1930		ipstat.ips_cantforward++;
1931	else {
1932		ipstat.ips_forward++;
1933		if (type)
1934			ipstat.ips_redirectsent++;
1935		else {
1936			if (mcopy)
1937				m_freem(mcopy);
1938			return;
1939		}
1940	}
1941	if (mcopy == NULL)
1942		return;
1943	destifp = NULL;
1944
1945	switch (error) {
1946
1947	case 0:				/* forwarded, but need redirect */
1948		/* type, code set above */
1949		break;
1950
1951	case ENETUNREACH:		/* shouldn't happen, checked above */
1952	case EHOSTUNREACH:
1953	case ENETDOWN:
1954	case EHOSTDOWN:
1955	default:
1956		type = ICMP_UNREACH;
1957		code = ICMP_UNREACH_HOST;
1958		break;
1959
1960	case EMSGSIZE:
1961		type = ICMP_UNREACH;
1962		code = ICMP_UNREACH_NEEDFRAG;
1963#if defined(IPSEC) || defined(FAST_IPSEC)
1964		/*
1965		 * If the packet is routed over IPsec tunnel, tell the
1966		 * originator the tunnel MTU.
1967		 *	tunnel MTU = if MTU - sizeof(IP) - ESP/AH hdrsiz
1968		 * XXX quickhack!!!
1969		 */
1970		{
1971			struct secpolicy *sp = NULL;
1972			int ipsecerror;
1973			int ipsechdr;
1974			struct route *ro;
1975
1976#ifdef IPSEC
1977			sp = ipsec4_getpolicybyaddr(mcopy,
1978						    IPSEC_DIR_OUTBOUND,
1979						    IP_FORWARDING,
1980						    &ipsecerror);
1981#else /* FAST_IPSEC */
1982			sp = ipsec_getpolicybyaddr(mcopy,
1983						   IPSEC_DIR_OUTBOUND,
1984						   IP_FORWARDING,
1985						   &ipsecerror);
1986#endif
1987			if (sp != NULL) {
1988				/* count IPsec header size */
1989				ipsechdr = ipsec4_hdrsiz(mcopy,
1990							 IPSEC_DIR_OUTBOUND,
1991							 NULL);
1992
1993				/*
1994				 * find the correct route for outer IPv4
1995				 * header, compute tunnel MTU.
1996				 *
1997				 * XXX BUG ALERT
1998				 * The "dummyifp" code relies upon the fact
1999				 * that icmp_error() touches only ifp->if_mtu.
2000				 */
2001				/*XXX*/
2002				destifp = NULL;
2003				if (sp->req != NULL
2004				 && sp->req->sav != NULL
2005				 && sp->req->sav->sah != NULL) {
2006					ro = &sp->req->sav->sah->sa_route;
2007					if (ro->ro_rt && ro->ro_rt->rt_ifp) {
2008						dummyifp.if_mtu =
2009						    ro->ro_rt->rt_ifp->if_mtu;
2010						dummyifp.if_mtu -= ipsechdr;
2011						destifp = &dummyifp;
2012					}
2013				}
2014
2015#ifdef IPSEC
2016				key_freesp(sp);
2017#else /* FAST_IPSEC */
2018				KEY_FREESP(&sp);
2019#endif
2020				ipstat.ips_cantfrag++;
2021				break;
2022			} else
2023#endif /*IPSEC || FAST_IPSEC*/
2024		destifp = ia->ia_ifp;
2025#if defined(IPSEC) || defined(FAST_IPSEC)
2026		}
2027#endif /*IPSEC || FAST_IPSEC*/
2028		ipstat.ips_cantfrag++;
2029		break;
2030
2031	case ENOBUFS:
2032		/*
2033		 * A router should not generate ICMP_SOURCEQUENCH as
2034		 * required in RFC1812 Requirements for IP Version 4 Routers.
2035		 * Source quench could be a big problem under DoS attacks,
2036		 * or if the underlying interface is rate-limited.
2037		 * Those who need source quench packets may re-enable them
2038		 * via the net.inet.ip.sendsourcequench sysctl.
2039		 */
2040		if (ip_sendsourcequench == 0) {
2041			m_freem(mcopy);
2042			return;
2043		} else {
2044			type = ICMP_SOURCEQUENCH;
2045			code = 0;
2046		}
2047		break;
2048
2049	case EACCES:			/* ipfw denied packet */
2050		m_freem(mcopy);
2051		return;
2052	}
2053	icmp_error(mcopy, type, code, dest, destifp);
2054}
2055
2056void
2057ip_savecontrol(inp, mp, ip, m)
2058	register struct inpcb *inp;
2059	register struct mbuf **mp;
2060	register struct ip *ip;
2061	register struct mbuf *m;
2062{
2063	if (inp->inp_socket->so_options & SO_TIMESTAMP) {
2064		struct timeval tv;
2065
2066		microtime(&tv);
2067		*mp = sbcreatecontrol((caddr_t) &tv, sizeof(tv),
2068			SCM_TIMESTAMP, SOL_SOCKET);
2069		if (*mp)
2070			mp = &(*mp)->m_next;
2071	}
2072	if (inp->inp_flags & INP_RECVDSTADDR) {
2073		*mp = sbcreatecontrol((caddr_t) &ip->ip_dst,
2074		    sizeof(struct in_addr), IP_RECVDSTADDR, IPPROTO_IP);
2075		if (*mp)
2076			mp = &(*mp)->m_next;
2077	}
2078	if (inp->inp_flags & INP_RECVTTL) {
2079		*mp = sbcreatecontrol((caddr_t) &ip->ip_ttl,
2080		    sizeof(u_char), IP_RECVTTL, IPPROTO_IP);
2081		if (*mp)
2082			mp = &(*mp)->m_next;
2083	}
2084#ifdef notyet
2085	/* XXX
2086	 * Moving these out of udp_input() made them even more broken
2087	 * than they already were.
2088	 */
2089	/* options were tossed already */
2090	if (inp->inp_flags & INP_RECVOPTS) {
2091		*mp = sbcreatecontrol((caddr_t) opts_deleted_above,
2092		    sizeof(struct in_addr), IP_RECVOPTS, IPPROTO_IP);
2093		if (*mp)
2094			mp = &(*mp)->m_next;
2095	}
2096	/* ip_srcroute doesn't do what we want here, need to fix */
2097	if (inp->inp_flags & INP_RECVRETOPTS) {
2098		*mp = sbcreatecontrol((caddr_t) ip_srcroute(),
2099		    sizeof(struct in_addr), IP_RECVRETOPTS, IPPROTO_IP);
2100		if (*mp)
2101			mp = &(*mp)->m_next;
2102	}
2103#endif
2104	if (inp->inp_flags & INP_RECVIF) {
2105		struct ifnet *ifp;
2106		struct sdlbuf {
2107			struct sockaddr_dl sdl;
2108			u_char	pad[32];
2109		} sdlbuf;
2110		struct sockaddr_dl *sdp;
2111		struct sockaddr_dl *sdl2 = &sdlbuf.sdl;
2112
2113		if (((ifp = m->m_pkthdr.rcvif))
2114		&& ( ifp->if_index && (ifp->if_index <= if_index))) {
2115			sdp = (struct sockaddr_dl *)
2116			    (ifaddr_byindex(ifp->if_index)->ifa_addr);
2117			/*
2118			 * Change our mind and don't try copy.
2119			 */
2120			if ((sdp->sdl_family != AF_LINK)
2121			|| (sdp->sdl_len > sizeof(sdlbuf))) {
2122				goto makedummy;
2123			}
2124			bcopy(sdp, sdl2, sdp->sdl_len);
2125		} else {
2126makedummy:
2127			sdl2->sdl_len
2128				= offsetof(struct sockaddr_dl, sdl_data[0]);
2129			sdl2->sdl_family = AF_LINK;
2130			sdl2->sdl_index = 0;
2131			sdl2->sdl_nlen = sdl2->sdl_alen = sdl2->sdl_slen = 0;
2132		}
2133		*mp = sbcreatecontrol((caddr_t) sdl2, sdl2->sdl_len,
2134			IP_RECVIF, IPPROTO_IP);
2135		if (*mp)
2136			mp = &(*mp)->m_next;
2137	}
2138}
2139
2140/*
2141 * XXX these routines are called from the upper part of the kernel.
2142 * They need to be locked when we remove Giant.
2143 *
2144 * They could also be moved to ip_mroute.c, since all the RSVP
2145 *  handling is done there already.
2146 */
2147static int ip_rsvp_on;
2148struct socket *ip_rsvpd;
2149int
2150ip_rsvp_init(struct socket *so)
2151{
2152	if (so->so_type != SOCK_RAW ||
2153	    so->so_proto->pr_protocol != IPPROTO_RSVP)
2154		return EOPNOTSUPP;
2155
2156	if (ip_rsvpd != NULL)
2157		return EADDRINUSE;
2158
2159	ip_rsvpd = so;
2160	/*
2161	 * This may seem silly, but we need to be sure we don't over-increment
2162	 * the RSVP counter, in case something slips up.
2163	 */
2164	if (!ip_rsvp_on) {
2165		ip_rsvp_on = 1;
2166		rsvp_on++;
2167	}
2168
2169	return 0;
2170}
2171
2172int
2173ip_rsvp_done(void)
2174{
2175	ip_rsvpd = NULL;
2176	/*
2177	 * This may seem silly, but we need to be sure we don't over-decrement
2178	 * the RSVP counter, in case something slips up.
2179	 */
2180	if (ip_rsvp_on) {
2181		ip_rsvp_on = 0;
2182		rsvp_on--;
2183	}
2184	return 0;
2185}
2186
2187void
2188rsvp_input(struct mbuf *m, int off)	/* XXX must fixup manually */
2189{
2190	if (rsvp_input_p) { /* call the real one if loaded */
2191		rsvp_input_p(m, off);
2192		return;
2193	}
2194
2195	/* Can still get packets with rsvp_on = 0 if there is a local member
2196	 * of the group to which the RSVP packet is addressed.  But in this
2197	 * case we want to throw the packet away.
2198	 */
2199
2200	if (!rsvp_on) {
2201		m_freem(m);
2202		return;
2203	}
2204
2205	if (ip_rsvpd != NULL) {
2206		rip_input(m, off);
2207		return;
2208	}
2209	/* Drop the packet */
2210	m_freem(m);
2211}
2212