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