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