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