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