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