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