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