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