ip_input.c revision 74454
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 74454 2001-03-19 09:16:16Z ru $
35 */
36
37#define	_IP_VHL
38
39#include "opt_bootp.h"
40#include "opt_ipfw.h"
41#include "opt_ipdn.h"
42#include "opt_ipdivert.h"
43#include "opt_ipfilter.h"
44#include "opt_ipstealth.h"
45#include "opt_ipsec.h"
46#include "opt_pfil_hooks.h"
47
48#include <sys/param.h>
49#include <sys/systm.h>
50#include <sys/mbuf.h>
51#include <sys/malloc.h>
52#include <sys/domain.h>
53#include <sys/protosw.h>
54#include <sys/socket.h>
55#include <sys/time.h>
56#include <sys/kernel.h>
57#include <sys/syslog.h>
58#include <sys/sysctl.h>
59
60#include <net/pfil.h>
61#include <net/if.h>
62#include <net/if_var.h>
63#include <net/if_dl.h>
64#include <net/route.h>
65#include <net/netisr.h>
66#include <net/intrq.h>
67
68#include <netinet/in.h>
69#include <netinet/in_systm.h>
70#include <netinet/in_var.h>
71#include <netinet/ip.h>
72#include <netinet/in_pcb.h>
73#include <netinet/ip_var.h>
74#include <netinet/ip_icmp.h>
75#include <machine/in_cksum.h>
76
77#include <netinet/ipprotosw.h>
78
79#include <sys/socketvar.h>
80
81#include <netinet/ip_fw.h>
82
83#ifdef IPSEC
84#include <netinet6/ipsec.h>
85#include <netkey/key.h>
86#endif
87
88#include "faith.h"
89#if defined(NFAITH) && NFAITH > 0
90#include <net/if_types.h>
91#endif
92
93#ifdef DUMMYNET
94#include <netinet/ip_dummynet.h>
95#endif
96
97int rsvp_on = 0;
98static int ip_rsvp_on;
99struct socket *ip_rsvpd;
100
101int	ipforwarding = 0;
102SYSCTL_INT(_net_inet_ip, IPCTL_FORWARDING, forwarding, CTLFLAG_RW,
103    &ipforwarding, 0, "Enable IP forwarding between interfaces");
104
105static int	ipsendredirects = 1; /* XXX */
106SYSCTL_INT(_net_inet_ip, IPCTL_SENDREDIRECTS, redirect, CTLFLAG_RW,
107    &ipsendredirects, 0, "Enable sending IP redirects");
108
109int	ip_defttl = IPDEFTTL;
110SYSCTL_INT(_net_inet_ip, IPCTL_DEFTTL, ttl, CTLFLAG_RW,
111    &ip_defttl, 0, "Maximum TTL on IP packets");
112
113static int	ip_dosourceroute = 0;
114SYSCTL_INT(_net_inet_ip, IPCTL_SOURCEROUTE, sourceroute, CTLFLAG_RW,
115    &ip_dosourceroute, 0, "Enable forwarding source routed IP packets");
116
117static int	ip_acceptsourceroute = 0;
118SYSCTL_INT(_net_inet_ip, IPCTL_ACCEPTSOURCEROUTE, accept_sourceroute,
119    CTLFLAG_RW, &ip_acceptsourceroute, 0,
120    "Enable accepting source routed IP packets");
121
122static int	ip_keepfaith = 0;
123SYSCTL_INT(_net_inet_ip, IPCTL_KEEPFAITH, keepfaith, CTLFLAG_RW,
124	&ip_keepfaith,	0,
125	"Enable packet capture for FAITH IPv4->IPv6 translater daemon");
126
127/*
128 * XXX - Setting ip_checkinterface mostly implements the receive side of
129 * the Strong ES model described in RFC 1122, but since the routing table
130 * and transmit implementation do not implement the Strong ES model,
131 * setting this to 1 results in an odd hybrid.
132 *
133 * XXX - ip_checkinterface currently must be disabled if you use ipnat
134 * to translate the destination address to another local interface.
135 *
136 * XXX - ip_checkinterface must be disabled if you add IP aliases
137 * to the loopback interface instead of the interface where the
138 * packets for those addresses are received.
139 */
140static int	ip_checkinterface = 1;
141SYSCTL_INT(_net_inet_ip, OID_AUTO, check_interface, CTLFLAG_RW,
142    &ip_checkinterface, 0, "Verify packet arrives on correct interface");
143
144#ifdef DIAGNOSTIC
145static int	ipprintfs = 0;
146#endif
147
148extern	struct domain inetdomain;
149extern	struct ipprotosw inetsw[];
150u_char	ip_protox[IPPROTO_MAX];
151static int	ipqmaxlen = IFQ_MAXLEN;
152struct	in_ifaddrhead in_ifaddrhead; /* first inet address */
153SYSCTL_INT(_net_inet_ip, IPCTL_INTRQMAXLEN, intr_queue_maxlen, CTLFLAG_RW,
154    &ipintrq.ifq_maxlen, 0, "Maximum size of the IP input queue");
155SYSCTL_INT(_net_inet_ip, IPCTL_INTRQDROPS, intr_queue_drops, CTLFLAG_RD,
156    &ipintrq.ifq_drops, 0, "Number of packets dropped from the IP input queue");
157
158struct ipstat ipstat;
159SYSCTL_STRUCT(_net_inet_ip, IPCTL_STATS, stats, CTLFLAG_RD,
160    &ipstat, ipstat, "IP statistics (struct ipstat, netinet/ip_var.h)");
161
162/* Packet reassembly stuff */
163#define IPREASS_NHASH_LOG2      6
164#define IPREASS_NHASH           (1 << IPREASS_NHASH_LOG2)
165#define IPREASS_HMASK           (IPREASS_NHASH - 1)
166#define IPREASS_HASH(x,y) \
167	(((((x) & 0xF) | ((((x) >> 8) & 0xF) << 4)) ^ (y)) & IPREASS_HMASK)
168
169static TAILQ_HEAD(ipqhead, ipq) ipq[IPREASS_NHASH];
170static int    nipq = 0;         /* total # of reass queues */
171static int    maxnipq;
172const  int    ipintrq_present = 1;
173
174#ifdef IPCTL_DEFMTU
175SYSCTL_INT(_net_inet_ip, IPCTL_DEFMTU, mtu, CTLFLAG_RW,
176    &ip_mtu, 0, "Default MTU");
177#endif
178
179#ifdef IPSTEALTH
180static int	ipstealth = 0;
181SYSCTL_INT(_net_inet_ip, OID_AUTO, stealth, CTLFLAG_RW,
182    &ipstealth, 0, "");
183#endif
184
185
186/* Firewall hooks */
187ip_fw_chk_t *ip_fw_chk_ptr;
188ip_fw_ctl_t *ip_fw_ctl_ptr;
189int fw_enable = 1 ;
190
191#ifdef DUMMYNET
192ip_dn_ctl_t *ip_dn_ctl_ptr;
193#endif
194
195
196/*
197 * We need to save the IP options in case a protocol wants to respond
198 * to an incoming packet over the same route if the packet got here
199 * using IP source routing.  This allows connection establishment and
200 * maintenance when the remote end is on a network that is not known
201 * to us.
202 */
203static int	ip_nhops = 0;
204static	struct ip_srcrt {
205	struct	in_addr dst;			/* final destination */
206	char	nop;				/* one NOP to align */
207	char	srcopt[IPOPT_OFFSET + 1];	/* OPTVAL, OLEN and OFFSET */
208	struct	in_addr route[MAX_IPOPTLEN/sizeof(struct in_addr)];
209} ip_srcrt;
210
211struct sockaddr_in *ip_fw_fwd_addr;
212
213static void	save_rte __P((u_char *, struct in_addr));
214static int	ip_dooptions __P((struct mbuf *));
215static void	ip_forward __P((struct mbuf *, int));
216static void	ip_freef __P((struct ipqhead *, struct ipq *));
217#ifdef IPDIVERT
218static struct	mbuf *ip_reass __P((struct mbuf *, struct ipqhead *, struct ipq *, u_int32_t *, u_int16_t *));
219#else
220static struct	mbuf *ip_reass __P((struct mbuf *, struct ipqhead *, struct ipq *));
221#endif
222static struct	in_ifaddr *ip_rtaddr __P((struct in_addr));
223static void	ipintr __P((void));
224
225/*
226 * IP initialization: fill in IP protocol switch table.
227 * All protocols not implemented in kernel go to raw IP protocol handler.
228 */
229void
230ip_init()
231{
232	register struct ipprotosw *pr;
233	register int i;
234
235	TAILQ_INIT(&in_ifaddrhead);
236	pr = (struct ipprotosw *)pffindproto(PF_INET, IPPROTO_RAW, SOCK_RAW);
237	if (pr == 0)
238		panic("ip_init");
239	for (i = 0; i < IPPROTO_MAX; i++)
240		ip_protox[i] = pr - inetsw;
241	for (pr = (struct ipprotosw *)inetdomain.dom_protosw;
242	    pr < (struct ipprotosw *)inetdomain.dom_protoswNPROTOSW; pr++)
243		if (pr->pr_domain->dom_family == PF_INET &&
244		    pr->pr_protocol && pr->pr_protocol != IPPROTO_RAW)
245			ip_protox[pr->pr_protocol] = pr - inetsw;
246
247	for (i = 0; i < IPREASS_NHASH; i++)
248	    TAILQ_INIT(&ipq[i]);
249
250	maxnipq = nmbclusters/4;
251
252	ip_id = time_second & 0xffff;
253	ipintrq.ifq_maxlen = ipqmaxlen;
254	mtx_init(&ipintrq.ifq_mtx, "ip_inq", MTX_DEF);
255
256	register_netisr(NETISR_IP, ipintr);
257}
258
259static struct	sockaddr_in ipaddr = { sizeof(ipaddr), AF_INET };
260struct	route ipforward_rt;
261
262/*
263 * Ip input routine.  Checksum and byte swap header.  If fragmented
264 * try to reassemble.  Process options.  Pass to next level.
265 */
266void
267ip_input(struct mbuf *m)
268{
269	struct ip *ip;
270	struct ipq *fp;
271	struct in_ifaddr *ia = NULL;
272	int    i, hlen, checkif;
273	u_short sum;
274	u_int16_t divert_cookie;		/* firewall cookie */
275	struct in_addr pkt_dst;
276#ifdef IPDIVERT
277	u_int32_t divert_info = 0;		/* packet divert/tee info */
278#endif
279	struct ip_fw_chain *rule = NULL;
280#ifdef PFIL_HOOKS
281	struct packet_filter_hook *pfh;
282	struct mbuf *m0;
283	int rv;
284#endif /* PFIL_HOOKS */
285
286#ifdef IPDIVERT
287	/* Get and reset firewall cookie */
288	divert_cookie = ip_divert_cookie;
289	ip_divert_cookie = 0;
290#else
291	divert_cookie = 0;
292#endif
293
294#if defined(IPFIREWALL) && defined(DUMMYNET)
295        /*
296         * dummynet packet are prepended a vestigial mbuf with
297         * m_type = MT_DUMMYNET and m_data pointing to the matching
298         * rule.
299         */
300        if (m->m_type == MT_DUMMYNET) {
301            rule = (struct ip_fw_chain *)(m->m_data) ;
302            m = m->m_next ;
303            ip = mtod(m, struct ip *);
304            hlen = IP_VHL_HL(ip->ip_vhl) << 2;
305            goto iphack ;
306        } else
307            rule = NULL ;
308#endif
309
310#ifdef	DIAGNOSTIC
311	if (m == NULL || (m->m_flags & M_PKTHDR) == 0)
312		panic("ip_input no HDR");
313#endif
314	ipstat.ips_total++;
315
316	if (m->m_pkthdr.len < sizeof(struct ip))
317		goto tooshort;
318
319	if (m->m_len < sizeof (struct ip) &&
320	    (m = m_pullup(m, sizeof (struct ip))) == 0) {
321		ipstat.ips_toosmall++;
322		return;
323	}
324	ip = mtod(m, struct ip *);
325
326	if (IP_VHL_V(ip->ip_vhl) != IPVERSION) {
327		ipstat.ips_badvers++;
328		goto bad;
329	}
330
331	hlen = IP_VHL_HL(ip->ip_vhl) << 2;
332	if (hlen < sizeof(struct ip)) {	/* minimum header length */
333		ipstat.ips_badhlen++;
334		goto bad;
335	}
336	if (hlen > m->m_len) {
337		if ((m = m_pullup(m, hlen)) == 0) {
338			ipstat.ips_badhlen++;
339			return;
340		}
341		ip = mtod(m, struct ip *);
342	}
343	if (m->m_pkthdr.csum_flags & CSUM_IP_CHECKED) {
344		sum = !(m->m_pkthdr.csum_flags & CSUM_IP_VALID);
345	} else {
346		if (hlen == sizeof(struct ip)) {
347			sum = in_cksum_hdr(ip);
348		} else {
349			sum = in_cksum(m, hlen);
350		}
351	}
352	if (sum) {
353		ipstat.ips_badsum++;
354		goto bad;
355	}
356
357	/*
358	 * Convert fields to host representation.
359	 */
360	NTOHS(ip->ip_len);
361	if (ip->ip_len < hlen) {
362		ipstat.ips_badlen++;
363		goto bad;
364	}
365	NTOHS(ip->ip_off);
366
367	/*
368	 * Check that the amount of data in the buffers
369	 * is as at least much as the IP header would have us expect.
370	 * Trim mbufs if longer than we expect.
371	 * Drop packet if shorter than we expect.
372	 */
373	if (m->m_pkthdr.len < ip->ip_len) {
374tooshort:
375		ipstat.ips_tooshort++;
376		goto bad;
377	}
378	if (m->m_pkthdr.len > ip->ip_len) {
379		if (m->m_len == m->m_pkthdr.len) {
380			m->m_len = ip->ip_len;
381			m->m_pkthdr.len = ip->ip_len;
382		} else
383			m_adj(m, ip->ip_len - m->m_pkthdr.len);
384	}
385
386	/*
387	 * Don't accept packets with a loopback destination address
388	 * unless they arrived via the loopback interface.
389	 */
390	if ((ntohl(ip->ip_dst.s_addr) & IN_CLASSA_NET) ==
391	    (IN_LOOPBACKNET << IN_CLASSA_NSHIFT) &&
392	    (m->m_pkthdr.rcvif->if_flags & IFF_LOOPBACK) == 0) {
393		goto bad;
394	}
395
396	/*
397	 * IpHack's section.
398	 * Right now when no processing on packet has done
399	 * and it is still fresh out of network we do our black
400	 * deals with it.
401	 * - Firewall: deny/allow/divert
402	 * - Xlate: translate packet's addr/port (NAT).
403	 * - Pipe: pass pkt through dummynet.
404	 * - Wrap: fake packet's addr/port <unimpl.>
405	 * - Encapsulate: put it in another IP and send out. <unimp.>
406 	 */
407
408#if defined(IPFIREWALL) && defined(DUMMYNET)
409iphack:
410#endif
411
412#ifdef PFIL_HOOKS
413	/*
414	 * Run through list of hooks for input packets.  If there are any
415	 * filters which require that additional packets in the flow are
416	 * not fast-forwarded, they must clear the M_CANFASTFWD flag.
417	 * Note that filters must _never_ set this flag, as another filter
418	 * in the list may have previously cleared it.
419	 */
420	m0 = m;
421	pfh = pfil_hook_get(PFIL_IN, &inetsw[ip_protox[IPPROTO_IP]].pr_pfh);
422	for (; pfh; pfh = TAILQ_NEXT(pfh, pfil_link))
423		if (pfh->pfil_func) {
424			rv = pfh->pfil_func(ip, hlen,
425					    m->m_pkthdr.rcvif, 0, &m0);
426			if (rv)
427				return;
428			m = m0;
429			if (m == NULL)
430				return;
431			ip = mtod(m, struct ip *);
432		}
433#endif /* PFIL_HOOKS */
434
435	if (fw_enable && ip_fw_chk_ptr) {
436#ifdef IPFIREWALL_FORWARD
437		/*
438		 * If we've been forwarded from the output side, then
439		 * skip the firewall a second time
440		 */
441		if (ip_fw_fwd_addr)
442			goto ours;
443#endif	/* IPFIREWALL_FORWARD */
444		/*
445		 * See the comment in ip_output for the return values
446		 * produced by the firewall.
447		 */
448		i = (*ip_fw_chk_ptr)(&ip,
449		    hlen, NULL, &divert_cookie, &m, &rule, &ip_fw_fwd_addr);
450		if (i & IP_FW_PORT_DENY_FLAG) { /* XXX new interface-denied */
451		    if (m)
452			m_freem(m);
453		    return ;
454		}
455		if (m == NULL) {	/* Packet discarded by firewall */
456		    static int __debug=10;
457		    if (__debug >0) {
458			printf("firewall returns NULL, please update!\n");
459			__debug-- ;
460		    }
461		    return;
462		}
463		if (i == 0 && ip_fw_fwd_addr == NULL)	/* common case */
464			goto pass;
465#ifdef DUMMYNET
466                if ((i & IP_FW_PORT_DYNT_FLAG) != 0) {
467                        /* Send packet to the appropriate pipe */
468                        dummynet_io(i&0xffff,DN_TO_IP_IN,m,NULL,NULL,0, rule,
469				    0);
470			return;
471		}
472#endif
473#ifdef IPDIVERT
474		if (i != 0 && (i & IP_FW_PORT_DYNT_FLAG) == 0) {
475			/* Divert or tee packet */
476			divert_info = i;
477			goto ours;
478		}
479#endif
480#ifdef IPFIREWALL_FORWARD
481		if (i == 0 && ip_fw_fwd_addr != NULL)
482			goto pass;
483#endif
484		/*
485		 * if we get here, the packet must be dropped
486		 */
487		m_freem(m);
488		return;
489	}
490pass:
491
492	/*
493	 * Process options and, if not destined for us,
494	 * ship it on.  ip_dooptions returns 1 when an
495	 * error was detected (causing an icmp message
496	 * to be sent and the original packet to be freed).
497	 */
498	ip_nhops = 0;		/* for source routed packets */
499	if (hlen > sizeof (struct ip) && ip_dooptions(m)) {
500#ifdef IPFIREWALL_FORWARD
501		ip_fw_fwd_addr = NULL;
502#endif
503		return;
504	}
505
506        /* greedy RSVP, snatches any PATH packet of the RSVP protocol and no
507         * matter if it is destined to another node, or whether it is
508         * a multicast one, RSVP wants it! and prevents it from being forwarded
509         * anywhere else. Also checks if the rsvp daemon is running before
510	 * grabbing the packet.
511         */
512	if (rsvp_on && ip->ip_p==IPPROTO_RSVP)
513		goto ours;
514
515	/*
516	 * Check our list of addresses, to see if the packet is for us.
517	 * If we don't have any addresses, assume any unicast packet
518	 * we receive might be for us (and let the upper layers deal
519	 * with it).
520	 */
521	if (TAILQ_EMPTY(&in_ifaddrhead) &&
522	    (m->m_flags & (M_MCAST|M_BCAST)) == 0)
523		goto ours;
524
525	/*
526	 * Cache the destination address of the packet; this may be
527	 * changed by use of 'ipfw fwd'.
528	 */
529	pkt_dst = ip_fw_fwd_addr == NULL ?
530	    ip->ip_dst : ip_fw_fwd_addr->sin_addr;
531
532	/*
533	 * Enable a consistency check between the destination address
534	 * and the arrival interface for a unicast packet (the RFC 1122
535	 * strong ES model) if IP forwarding is disabled and the packet
536	 * is not locally generated and the packet is not subject to
537	 * 'ipfw fwd'.
538	 *
539         * XXX - Checking also should be disabled if the destination
540	 * address is ipnat'ed to a different interface.
541	 *
542	 * XXX - Checking is incompatible with IP aliases added
543	 * to the loopback interface instead of the interface where
544	 * the packets are received.
545	 */
546	checkif = ip_checkinterface && (ipforwarding == 0) &&
547	    ((m->m_pkthdr.rcvif->if_flags & IFF_LOOPBACK) == 0) &&
548	    (ip_fw_fwd_addr == NULL);
549
550	TAILQ_FOREACH(ia, &in_ifaddrhead, ia_link) {
551#define	satosin(sa)	((struct sockaddr_in *)(sa))
552
553#ifdef BOOTP_COMPAT
554		if (IA_SIN(ia)->sin_addr.s_addr == INADDR_ANY)
555			goto ours;
556#endif
557		/*
558		 * If the address matches, verify that the packet
559		 * arrived via the correct interface if checking is
560		 * enabled.
561		 */
562		if (IA_SIN(ia)->sin_addr.s_addr == pkt_dst.s_addr &&
563		    (!checkif || ia->ia_ifp == m->m_pkthdr.rcvif))
564			goto ours;
565		/*
566		 * Only accept broadcast packets that arrive via the
567		 * matching interface.  Reception of forwarded directed
568		 * broadcasts would be handled via ip_forward() and
569		 * ether_output() with the loopback into the stack for
570		 * SIMPLEX interfaces handled by ether_output().
571		 */
572		if (ia->ia_ifp == m->m_pkthdr.rcvif &&
573		    ia->ia_ifp && ia->ia_ifp->if_flags & IFF_BROADCAST) {
574			if (satosin(&ia->ia_broadaddr)->sin_addr.s_addr ==
575			    pkt_dst.s_addr)
576				goto ours;
577			if (ia->ia_netbroadcast.s_addr == pkt_dst.s_addr)
578				goto ours;
579		}
580	}
581	if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr))) {
582		struct in_multi *inm;
583		if (ip_mrouter) {
584			/*
585			 * If we are acting as a multicast router, all
586			 * incoming multicast packets are passed to the
587			 * kernel-level multicast forwarding function.
588			 * The packet is returned (relatively) intact; if
589			 * ip_mforward() returns a non-zero value, the packet
590			 * must be discarded, else it may be accepted below.
591			 */
592			if (ip_mforward(ip, m->m_pkthdr.rcvif, m, 0) != 0) {
593				ipstat.ips_cantforward++;
594				m_freem(m);
595				return;
596			}
597
598			/*
599			 * The process-level routing demon needs to receive
600			 * all multicast IGMP packets, whether or not this
601			 * host belongs to their destination groups.
602			 */
603			if (ip->ip_p == IPPROTO_IGMP)
604				goto ours;
605			ipstat.ips_forward++;
606		}
607		/*
608		 * See if we belong to the destination multicast group on the
609		 * arrival interface.
610		 */
611		IN_LOOKUP_MULTI(ip->ip_dst, m->m_pkthdr.rcvif, inm);
612		if (inm == NULL) {
613			ipstat.ips_notmember++;
614			m_freem(m);
615			return;
616		}
617		goto ours;
618	}
619	if (ip->ip_dst.s_addr == (u_long)INADDR_BROADCAST)
620		goto ours;
621	if (ip->ip_dst.s_addr == INADDR_ANY)
622		goto ours;
623
624#if defined(NFAITH) && 0 < NFAITH
625	/*
626	 * FAITH(Firewall Aided Internet Translator)
627	 */
628	if (m->m_pkthdr.rcvif && m->m_pkthdr.rcvif->if_type == IFT_FAITH) {
629		if (ip_keepfaith) {
630			if (ip->ip_p == IPPROTO_TCP || ip->ip_p == IPPROTO_ICMP)
631				goto ours;
632		}
633		m_freem(m);
634		return;
635	}
636#endif
637	/*
638	 * Not for us; forward if possible and desirable.
639	 */
640	if (ipforwarding == 0) {
641		ipstat.ips_cantforward++;
642		m_freem(m);
643	} else
644		ip_forward(m, 0);
645#ifdef IPFIREWALL_FORWARD
646	ip_fw_fwd_addr = NULL;
647#endif
648	return;
649
650ours:
651	/* Count the packet in the ip address stats */
652	if (ia != NULL) {
653		ia->ia_ifa.if_ipackets++;
654		ia->ia_ifa.if_ibytes += m->m_pkthdr.len;
655	}
656
657	/*
658	 * If offset or IP_MF are set, must reassemble.
659	 * Otherwise, nothing need be done.
660	 * (We could look in the reassembly queue to see
661	 * if the packet was previously fragmented,
662	 * but it's not worth the time; just let them time out.)
663	 */
664	if (ip->ip_off & (IP_MF | IP_OFFMASK)) {
665
666		sum = IPREASS_HASH(ip->ip_src.s_addr, ip->ip_id);
667		/*
668		 * Look for queue of fragments
669		 * of this datagram.
670		 */
671		TAILQ_FOREACH(fp, &ipq[sum], ipq_list)
672			if (ip->ip_id == fp->ipq_id &&
673			    ip->ip_src.s_addr == fp->ipq_src.s_addr &&
674			    ip->ip_dst.s_addr == fp->ipq_dst.s_addr &&
675			    ip->ip_p == fp->ipq_p)
676				goto found;
677
678		fp = 0;
679
680		/* check if there's a place for the new queue */
681		if (nipq > maxnipq) {
682		    /*
683		     * drop something from the tail of the current queue
684		     * before proceeding further
685		     */
686		    struct ipq *q = TAILQ_LAST(&ipq[sum], ipqhead);
687		    if (q == NULL) {   /* gak */
688			for (i = 0; i < IPREASS_NHASH; i++) {
689			    struct ipq *r = TAILQ_LAST(&ipq[i], ipqhead);
690			    if (r) {
691				ip_freef(&ipq[i], r);
692				break;
693			    }
694			}
695		    } else
696			ip_freef(&ipq[sum], q);
697		}
698found:
699		/*
700		 * Adjust ip_len to not reflect header,
701		 * convert offset of this to bytes.
702		 */
703		ip->ip_len -= hlen;
704		if (ip->ip_off & IP_MF) {
705		        /*
706		         * Make sure that fragments have a data length
707			 * that's a non-zero multiple of 8 bytes.
708		         */
709			if (ip->ip_len == 0 || (ip->ip_len & 0x7) != 0) {
710				ipstat.ips_toosmall++; /* XXX */
711				goto bad;
712			}
713			m->m_flags |= M_FRAG;
714		}
715		ip->ip_off <<= 3;
716
717		/*
718		 * Attempt reassembly; if it succeeds, proceed.
719		 */
720		ipstat.ips_fragments++;
721		m->m_pkthdr.header = ip;
722#ifdef IPDIVERT
723		m = ip_reass(m,
724		    &ipq[sum], fp, &divert_info, &divert_cookie);
725#else
726		m = ip_reass(m, &ipq[sum], fp);
727#endif
728		if (m == 0) {
729#ifdef IPFIREWALL_FORWARD
730			ip_fw_fwd_addr = NULL;
731#endif
732			return;
733		}
734		ipstat.ips_reassembled++;
735		ip = mtod(m, struct ip *);
736		/* Get the header length of the reassembled packet */
737		hlen = IP_VHL_HL(ip->ip_vhl) << 2;
738#ifdef IPDIVERT
739		/* Restore original checksum before diverting packet */
740		if (divert_info != 0) {
741			ip->ip_len += hlen;
742			HTONS(ip->ip_len);
743			HTONS(ip->ip_off);
744			ip->ip_sum = 0;
745			if (hlen == sizeof(struct ip))
746				ip->ip_sum = in_cksum_hdr(ip);
747			else
748				ip->ip_sum = in_cksum(m, hlen);
749			NTOHS(ip->ip_off);
750			NTOHS(ip->ip_len);
751			ip->ip_len -= hlen;
752		}
753#endif
754	} else
755		ip->ip_len -= hlen;
756
757#ifdef IPDIVERT
758	/*
759	 * Divert or tee packet to the divert protocol if required.
760	 *
761	 * If divert_info is zero then cookie should be too, so we shouldn't
762	 * need to clear them here.  Assume divert_packet() does so also.
763	 */
764	if (divert_info != 0) {
765		struct mbuf *clone = NULL;
766
767		/* Clone packet if we're doing a 'tee' */
768		if ((divert_info & IP_FW_PORT_TEE_FLAG) != 0)
769			clone = m_dup(m, M_DONTWAIT);
770
771		/* Restore packet header fields to original values */
772		ip->ip_len += hlen;
773		HTONS(ip->ip_len);
774		HTONS(ip->ip_off);
775
776		/* Deliver packet to divert input routine */
777		ip_divert_cookie = divert_cookie;
778		divert_packet(m, 1, divert_info & 0xffff);
779		ipstat.ips_delivered++;
780
781		/* If 'tee', continue with original packet */
782		if (clone == NULL)
783			return;
784		m = clone;
785		ip = mtod(m, struct ip *);
786	}
787#endif
788
789	/*
790	 * Switch out to protocol's input routine.
791	 */
792	ipstat.ips_delivered++;
793    {
794	int off = hlen, nh = ip->ip_p;
795
796	(*inetsw[ip_protox[ip->ip_p]].pr_input)(m, off, nh);
797#ifdef	IPFIREWALL_FORWARD
798	ip_fw_fwd_addr = NULL;	/* tcp needed it */
799#endif
800	return;
801    }
802bad:
803#ifdef	IPFIREWALL_FORWARD
804	ip_fw_fwd_addr = NULL;
805#endif
806	m_freem(m);
807}
808
809/*
810 * IP software interrupt routine - to go away sometime soon
811 */
812static void
813ipintr(void)
814{
815	struct mbuf *m;
816
817	while (1) {
818		IF_DEQUEUE(&ipintrq, m);
819		if (m == 0)
820			return;
821		ip_input(m);
822	}
823}
824
825/*
826 * Take incoming datagram fragment and try to reassemble it into
827 * whole datagram.  If a chain for reassembly of this datagram already
828 * exists, then it is given as fp; otherwise have to make a chain.
829 *
830 * When IPDIVERT enabled, keep additional state with each packet that
831 * tells us if we need to divert or tee the packet we're building.
832 */
833
834static struct mbuf *
835#ifdef IPDIVERT
836ip_reass(m, head, fp, divinfo, divcookie)
837#else
838ip_reass(m, head, fp)
839#endif
840	struct mbuf *m;
841	struct ipqhead *head;
842	struct ipq *fp;
843#ifdef IPDIVERT
844	u_int32_t *divinfo;
845	u_int16_t *divcookie;
846#endif
847{
848	struct ip *ip = mtod(m, struct ip *);
849	register struct mbuf *p, *q, *nq;
850	struct mbuf *t;
851	int hlen = IP_VHL_HL(ip->ip_vhl) << 2;
852	int i, next;
853
854	/*
855	 * Presence of header sizes in mbufs
856	 * would confuse code below.
857	 */
858	m->m_data += hlen;
859	m->m_len -= hlen;
860
861	/*
862	 * If first fragment to arrive, create a reassembly queue.
863	 */
864	if (fp == 0) {
865		if ((t = m_get(M_DONTWAIT, MT_FTABLE)) == NULL)
866			goto dropfrag;
867		fp = mtod(t, struct ipq *);
868		TAILQ_INSERT_HEAD(head, fp, ipq_list);
869		nipq++;
870		fp->ipq_ttl = IPFRAGTTL;
871		fp->ipq_p = ip->ip_p;
872		fp->ipq_id = ip->ip_id;
873		fp->ipq_src = ip->ip_src;
874		fp->ipq_dst = ip->ip_dst;
875		fp->ipq_frags = m;
876		m->m_nextpkt = NULL;
877#ifdef IPDIVERT
878		fp->ipq_div_info = 0;
879		fp->ipq_div_cookie = 0;
880#endif
881		goto inserted;
882	}
883
884#define GETIP(m)	((struct ip*)((m)->m_pkthdr.header))
885
886	/*
887	 * Find a segment which begins after this one does.
888	 */
889	for (p = NULL, q = fp->ipq_frags; q; p = q, q = q->m_nextpkt)
890		if (GETIP(q)->ip_off > ip->ip_off)
891			break;
892
893	/*
894	 * If there is a preceding segment, it may provide some of
895	 * our data already.  If so, drop the data from the incoming
896	 * segment.  If it provides all of our data, drop us, otherwise
897	 * stick new segment in the proper place.
898	 *
899	 * If some of the data is dropped from the the preceding
900	 * segment, then it's checksum is invalidated.
901	 */
902	if (p) {
903		i = GETIP(p)->ip_off + GETIP(p)->ip_len - ip->ip_off;
904		if (i > 0) {
905			if (i >= ip->ip_len)
906				goto dropfrag;
907			m_adj(m, i);
908			m->m_pkthdr.csum_flags = 0;
909			ip->ip_off += i;
910			ip->ip_len -= i;
911		}
912		m->m_nextpkt = p->m_nextpkt;
913		p->m_nextpkt = m;
914	} else {
915		m->m_nextpkt = fp->ipq_frags;
916		fp->ipq_frags = m;
917	}
918
919	/*
920	 * While we overlap succeeding segments trim them or,
921	 * if they are completely covered, dequeue them.
922	 */
923	for (; q != NULL && ip->ip_off + ip->ip_len > GETIP(q)->ip_off;
924	     q = nq) {
925		i = (ip->ip_off + ip->ip_len) -
926		    GETIP(q)->ip_off;
927		if (i < GETIP(q)->ip_len) {
928			GETIP(q)->ip_len -= i;
929			GETIP(q)->ip_off += i;
930			m_adj(q, i);
931			q->m_pkthdr.csum_flags = 0;
932			break;
933		}
934		nq = q->m_nextpkt;
935		m->m_nextpkt = nq;
936		m_freem(q);
937	}
938
939inserted:
940
941#ifdef IPDIVERT
942	/*
943	 * Transfer firewall instructions to the fragment structure.
944	 * Any fragment diverting causes the whole packet to divert.
945	 */
946	fp->ipq_div_info = *divinfo;
947	fp->ipq_div_cookie = *divcookie;
948	*divinfo = 0;
949	*divcookie = 0;
950#endif
951
952	/*
953	 * Check for complete reassembly.
954	 */
955	next = 0;
956	for (p = NULL, q = fp->ipq_frags; q; p = q, q = q->m_nextpkt) {
957		if (GETIP(q)->ip_off != next)
958			return (0);
959		next += GETIP(q)->ip_len;
960	}
961	/* Make sure the last packet didn't have the IP_MF flag */
962	if (p->m_flags & M_FRAG)
963		return (0);
964
965	/*
966	 * Reassembly is complete.  Make sure the packet is a sane size.
967	 */
968	q = fp->ipq_frags;
969	ip = GETIP(q);
970	if (next + (IP_VHL_HL(ip->ip_vhl) << 2) > IP_MAXPACKET) {
971		ipstat.ips_toolong++;
972		ip_freef(head, fp);
973		return (0);
974	}
975
976	/*
977	 * Concatenate fragments.
978	 */
979	m = q;
980	t = m->m_next;
981	m->m_next = 0;
982	m_cat(m, t);
983	nq = q->m_nextpkt;
984	q->m_nextpkt = 0;
985	for (q = nq; q != NULL; q = nq) {
986		nq = q->m_nextpkt;
987		q->m_nextpkt = NULL;
988		m->m_pkthdr.csum_flags &= q->m_pkthdr.csum_flags;
989		m->m_pkthdr.csum_data += q->m_pkthdr.csum_data;
990		m_cat(m, q);
991	}
992
993#ifdef IPDIVERT
994	/*
995	 * Extract firewall instructions from the fragment structure.
996	 */
997	*divinfo = fp->ipq_div_info;
998	*divcookie = fp->ipq_div_cookie;
999#endif
1000
1001	/*
1002	 * Create header for new ip packet by
1003	 * modifying header of first packet;
1004	 * dequeue and discard fragment reassembly header.
1005	 * Make header visible.
1006	 */
1007	ip->ip_len = next;
1008	ip->ip_src = fp->ipq_src;
1009	ip->ip_dst = fp->ipq_dst;
1010	TAILQ_REMOVE(head, fp, ipq_list);
1011	nipq--;
1012	(void) m_free(dtom(fp));
1013	m->m_len += (IP_VHL_HL(ip->ip_vhl) << 2);
1014	m->m_data -= (IP_VHL_HL(ip->ip_vhl) << 2);
1015	/* some debugging cruft by sklower, below, will go away soon */
1016	if (m->m_flags & M_PKTHDR) { /* XXX this should be done elsewhere */
1017		register int plen = 0;
1018		for (t = m; t; t = t->m_next)
1019			plen += t->m_len;
1020		m->m_pkthdr.len = plen;
1021	}
1022	return (m);
1023
1024dropfrag:
1025#ifdef IPDIVERT
1026	*divinfo = 0;
1027	*divcookie = 0;
1028#endif
1029	ipstat.ips_fragdropped++;
1030	m_freem(m);
1031	return (0);
1032
1033#undef GETIP
1034}
1035
1036/*
1037 * Free a fragment reassembly header and all
1038 * associated datagrams.
1039 */
1040static void
1041ip_freef(fhp, fp)
1042	struct ipqhead *fhp;
1043	struct ipq *fp;
1044{
1045	register struct mbuf *q;
1046
1047	while (fp->ipq_frags) {
1048		q = fp->ipq_frags;
1049		fp->ipq_frags = q->m_nextpkt;
1050		m_freem(q);
1051	}
1052	TAILQ_REMOVE(fhp, fp, ipq_list);
1053	(void) m_free(dtom(fp));
1054	nipq--;
1055}
1056
1057/*
1058 * IP timer processing;
1059 * if a timer expires on a reassembly
1060 * queue, discard it.
1061 */
1062void
1063ip_slowtimo()
1064{
1065	register struct ipq *fp;
1066	int s = splnet();
1067	int i;
1068
1069	for (i = 0; i < IPREASS_NHASH; i++) {
1070		for(fp = TAILQ_FIRST(&ipq[i]); fp;) {
1071			struct ipq *fpp;
1072
1073			fpp = fp;
1074			fp = TAILQ_NEXT(fp, ipq_list);
1075			if(--fpp->ipq_ttl == 0) {
1076				ipstat.ips_fragtimeout++;
1077				ip_freef(&ipq[i], fpp);
1078			}
1079		}
1080	}
1081	ipflow_slowtimo();
1082	splx(s);
1083}
1084
1085/*
1086 * Drain off all datagram fragments.
1087 */
1088void
1089ip_drain()
1090{
1091	int     i;
1092
1093	for (i = 0; i < IPREASS_NHASH; i++) {
1094		while(!TAILQ_EMPTY(&ipq[i])) {
1095			ipstat.ips_fragdropped++;
1096			ip_freef(&ipq[i], TAILQ_FIRST(&ipq[i]));
1097		}
1098	}
1099	in_rtqdrain();
1100}
1101
1102/*
1103 * Do option processing on a datagram,
1104 * possibly discarding it if bad options are encountered,
1105 * or forwarding it if source-routed.
1106 * Returns 1 if packet has been forwarded/freed,
1107 * 0 if the packet should be processed further.
1108 */
1109static int
1110ip_dooptions(m)
1111	struct mbuf *m;
1112{
1113	register struct ip *ip = mtod(m, struct ip *);
1114	register u_char *cp;
1115	register struct ip_timestamp *ipt;
1116	register struct in_ifaddr *ia;
1117	int opt, optlen, cnt, off, code, type = ICMP_PARAMPROB, forward = 0;
1118	struct in_addr *sin, dst;
1119	n_time ntime;
1120
1121	dst = ip->ip_dst;
1122	cp = (u_char *)(ip + 1);
1123	cnt = (IP_VHL_HL(ip->ip_vhl) << 2) - sizeof (struct ip);
1124	for (; cnt > 0; cnt -= optlen, cp += optlen) {
1125		opt = cp[IPOPT_OPTVAL];
1126		if (opt == IPOPT_EOL)
1127			break;
1128		if (opt == IPOPT_NOP)
1129			optlen = 1;
1130		else {
1131			if (cnt < IPOPT_OLEN + sizeof(*cp)) {
1132				code = &cp[IPOPT_OLEN] - (u_char *)ip;
1133				goto bad;
1134			}
1135			optlen = cp[IPOPT_OLEN];
1136			if (optlen < IPOPT_OLEN + sizeof(*cp) || optlen > cnt) {
1137				code = &cp[IPOPT_OLEN] - (u_char *)ip;
1138				goto bad;
1139			}
1140		}
1141		switch (opt) {
1142
1143		default:
1144			break;
1145
1146		/*
1147		 * Source routing with record.
1148		 * Find interface with current destination address.
1149		 * If none on this machine then drop if strictly routed,
1150		 * or do nothing if loosely routed.
1151		 * Record interface address and bring up next address
1152		 * component.  If strictly routed make sure next
1153		 * address is on directly accessible net.
1154		 */
1155		case IPOPT_LSRR:
1156		case IPOPT_SSRR:
1157			if ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {
1158				code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1159				goto bad;
1160			}
1161			ipaddr.sin_addr = ip->ip_dst;
1162			ia = (struct in_ifaddr *)
1163				ifa_ifwithaddr((struct sockaddr *)&ipaddr);
1164			if (ia == 0) {
1165				if (opt == IPOPT_SSRR) {
1166					type = ICMP_UNREACH;
1167					code = ICMP_UNREACH_SRCFAIL;
1168					goto bad;
1169				}
1170				if (!ip_dosourceroute)
1171					goto nosourcerouting;
1172				/*
1173				 * Loose routing, and not at next destination
1174				 * yet; nothing to do except forward.
1175				 */
1176				break;
1177			}
1178			off--;			/* 0 origin */
1179			if (off > optlen - (int)sizeof(struct in_addr)) {
1180				/*
1181				 * End of source route.  Should be for us.
1182				 */
1183				if (!ip_acceptsourceroute)
1184					goto nosourcerouting;
1185				save_rte(cp, ip->ip_src);
1186				break;
1187			}
1188
1189			if (!ip_dosourceroute) {
1190				if (ipforwarding) {
1191					char buf[16]; /* aaa.bbb.ccc.ddd\0 */
1192					/*
1193					 * Acting as a router, so generate ICMP
1194					 */
1195nosourcerouting:
1196					strcpy(buf, inet_ntoa(ip->ip_dst));
1197					log(LOG_WARNING,
1198					    "attempted source route from %s to %s\n",
1199					    inet_ntoa(ip->ip_src), buf);
1200					type = ICMP_UNREACH;
1201					code = ICMP_UNREACH_SRCFAIL;
1202					goto bad;
1203				} else {
1204					/*
1205					 * Not acting as a router, so silently drop.
1206					 */
1207					ipstat.ips_cantforward++;
1208					m_freem(m);
1209					return (1);
1210				}
1211			}
1212
1213			/*
1214			 * locate outgoing interface
1215			 */
1216			(void)memcpy(&ipaddr.sin_addr, cp + off,
1217			    sizeof(ipaddr.sin_addr));
1218
1219			if (opt == IPOPT_SSRR) {
1220#define	INA	struct in_ifaddr *
1221#define	SA	struct sockaddr *
1222			    if ((ia = (INA)ifa_ifwithdstaddr((SA)&ipaddr)) == 0)
1223				ia = (INA)ifa_ifwithnet((SA)&ipaddr);
1224			} else
1225				ia = ip_rtaddr(ipaddr.sin_addr);
1226			if (ia == 0) {
1227				type = ICMP_UNREACH;
1228				code = ICMP_UNREACH_SRCFAIL;
1229				goto bad;
1230			}
1231			ip->ip_dst = ipaddr.sin_addr;
1232			(void)memcpy(cp + off, &(IA_SIN(ia)->sin_addr),
1233			    sizeof(struct in_addr));
1234			cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1235			/*
1236			 * Let ip_intr's mcast routing check handle mcast pkts
1237			 */
1238			forward = !IN_MULTICAST(ntohl(ip->ip_dst.s_addr));
1239			break;
1240
1241		case IPOPT_RR:
1242			if (optlen < IPOPT_OFFSET + sizeof(*cp)) {
1243				code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1244				goto bad;
1245			}
1246			if ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {
1247				code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1248				goto bad;
1249			}
1250			/*
1251			 * If no space remains, ignore.
1252			 */
1253			off--;			/* 0 origin */
1254			if (off > optlen - (int)sizeof(struct in_addr))
1255				break;
1256			(void)memcpy(&ipaddr.sin_addr, &ip->ip_dst,
1257			    sizeof(ipaddr.sin_addr));
1258			/*
1259			 * locate outgoing interface; if we're the destination,
1260			 * use the incoming interface (should be same).
1261			 */
1262			if ((ia = (INA)ifa_ifwithaddr((SA)&ipaddr)) == 0 &&
1263			    (ia = ip_rtaddr(ipaddr.sin_addr)) == 0) {
1264				type = ICMP_UNREACH;
1265				code = ICMP_UNREACH_HOST;
1266				goto bad;
1267			}
1268			(void)memcpy(cp + off, &(IA_SIN(ia)->sin_addr),
1269			    sizeof(struct in_addr));
1270			cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1271			break;
1272
1273		case IPOPT_TS:
1274			code = cp - (u_char *)ip;
1275			ipt = (struct ip_timestamp *)cp;
1276			if (ipt->ipt_len < 5)
1277				goto bad;
1278			if (ipt->ipt_ptr >
1279			    ipt->ipt_len - (int)sizeof(int32_t)) {
1280				if (++ipt->ipt_oflw == 0)
1281					goto bad;
1282				break;
1283			}
1284			sin = (struct in_addr *)(cp + ipt->ipt_ptr - 1);
1285			switch (ipt->ipt_flg) {
1286
1287			case IPOPT_TS_TSONLY:
1288				break;
1289
1290			case IPOPT_TS_TSANDADDR:
1291				if (ipt->ipt_ptr - 1 + sizeof(n_time) +
1292				    sizeof(struct in_addr) > ipt->ipt_len)
1293					goto bad;
1294				ipaddr.sin_addr = dst;
1295				ia = (INA)ifaof_ifpforaddr((SA)&ipaddr,
1296							    m->m_pkthdr.rcvif);
1297				if (ia == 0)
1298					continue;
1299				(void)memcpy(sin, &IA_SIN(ia)->sin_addr,
1300				    sizeof(struct in_addr));
1301				ipt->ipt_ptr += sizeof(struct in_addr);
1302				break;
1303
1304			case IPOPT_TS_PRESPEC:
1305				if (ipt->ipt_ptr - 1 + sizeof(n_time) +
1306				    sizeof(struct in_addr) > ipt->ipt_len)
1307					goto bad;
1308				(void)memcpy(&ipaddr.sin_addr, sin,
1309				    sizeof(struct in_addr));
1310				if (ifa_ifwithaddr((SA)&ipaddr) == 0)
1311					continue;
1312				ipt->ipt_ptr += sizeof(struct in_addr);
1313				break;
1314
1315			default:
1316				goto bad;
1317			}
1318			ntime = iptime();
1319			(void)memcpy(cp + ipt->ipt_ptr - 1, &ntime,
1320			    sizeof(n_time));
1321			ipt->ipt_ptr += sizeof(n_time);
1322		}
1323	}
1324	if (forward && ipforwarding) {
1325		ip_forward(m, 1);
1326		return (1);
1327	}
1328	return (0);
1329bad:
1330	icmp_error(m, type, code, 0, 0);
1331	ipstat.ips_badoptions++;
1332	return (1);
1333}
1334
1335/*
1336 * Given address of next destination (final or next hop),
1337 * return internet address info of interface to be used to get there.
1338 */
1339static struct in_ifaddr *
1340ip_rtaddr(dst)
1341	 struct in_addr dst;
1342{
1343	register struct sockaddr_in *sin;
1344
1345	sin = (struct sockaddr_in *) &ipforward_rt.ro_dst;
1346
1347	if (ipforward_rt.ro_rt == 0 ||
1348	    !(ipforward_rt.ro_rt->rt_flags & RTF_UP) ||
1349	    dst.s_addr != sin->sin_addr.s_addr) {
1350		if (ipforward_rt.ro_rt) {
1351			RTFREE(ipforward_rt.ro_rt);
1352			ipforward_rt.ro_rt = 0;
1353		}
1354		sin->sin_family = AF_INET;
1355		sin->sin_len = sizeof(*sin);
1356		sin->sin_addr = dst;
1357
1358		rtalloc_ign(&ipforward_rt, RTF_PRCLONING);
1359	}
1360	if (ipforward_rt.ro_rt == 0)
1361		return ((struct in_ifaddr *)0);
1362	return ((struct in_ifaddr *) ipforward_rt.ro_rt->rt_ifa);
1363}
1364
1365/*
1366 * Save incoming source route for use in replies,
1367 * to be picked up later by ip_srcroute if the receiver is interested.
1368 */
1369void
1370save_rte(option, dst)
1371	u_char *option;
1372	struct in_addr dst;
1373{
1374	unsigned olen;
1375
1376	olen = option[IPOPT_OLEN];
1377#ifdef DIAGNOSTIC
1378	if (ipprintfs)
1379		printf("save_rte: olen %d\n", olen);
1380#endif
1381	if (olen > sizeof(ip_srcrt) - (1 + sizeof(dst)))
1382		return;
1383	bcopy(option, ip_srcrt.srcopt, olen);
1384	ip_nhops = (olen - IPOPT_OFFSET - 1) / sizeof(struct in_addr);
1385	ip_srcrt.dst = dst;
1386}
1387
1388/*
1389 * Retrieve incoming source route for use in replies,
1390 * in the same form used by setsockopt.
1391 * The first hop is placed before the options, will be removed later.
1392 */
1393struct mbuf *
1394ip_srcroute()
1395{
1396	register struct in_addr *p, *q;
1397	register struct mbuf *m;
1398
1399	if (ip_nhops == 0)
1400		return ((struct mbuf *)0);
1401	m = m_get(M_DONTWAIT, MT_HEADER);
1402	if (m == 0)
1403		return ((struct mbuf *)0);
1404
1405#define OPTSIZ	(sizeof(ip_srcrt.nop) + sizeof(ip_srcrt.srcopt))
1406
1407	/* length is (nhops+1)*sizeof(addr) + sizeof(nop + srcrt header) */
1408	m->m_len = ip_nhops * sizeof(struct in_addr) + sizeof(struct in_addr) +
1409	    OPTSIZ;
1410#ifdef DIAGNOSTIC
1411	if (ipprintfs)
1412		printf("ip_srcroute: nhops %d mlen %d", ip_nhops, m->m_len);
1413#endif
1414
1415	/*
1416	 * First save first hop for return route
1417	 */
1418	p = &ip_srcrt.route[ip_nhops - 1];
1419	*(mtod(m, struct in_addr *)) = *p--;
1420#ifdef DIAGNOSTIC
1421	if (ipprintfs)
1422		printf(" hops %lx", (u_long)ntohl(mtod(m, struct in_addr *)->s_addr));
1423#endif
1424
1425	/*
1426	 * Copy option fields and padding (nop) to mbuf.
1427	 */
1428	ip_srcrt.nop = IPOPT_NOP;
1429	ip_srcrt.srcopt[IPOPT_OFFSET] = IPOPT_MINOFF;
1430	(void)memcpy(mtod(m, caddr_t) + sizeof(struct in_addr),
1431	    &ip_srcrt.nop, OPTSIZ);
1432	q = (struct in_addr *)(mtod(m, caddr_t) +
1433	    sizeof(struct in_addr) + OPTSIZ);
1434#undef OPTSIZ
1435	/*
1436	 * Record return path as an IP source route,
1437	 * reversing the path (pointers are now aligned).
1438	 */
1439	while (p >= ip_srcrt.route) {
1440#ifdef DIAGNOSTIC
1441		if (ipprintfs)
1442			printf(" %lx", (u_long)ntohl(q->s_addr));
1443#endif
1444		*q++ = *p--;
1445	}
1446	/*
1447	 * Last hop goes to final destination.
1448	 */
1449	*q = ip_srcrt.dst;
1450#ifdef DIAGNOSTIC
1451	if (ipprintfs)
1452		printf(" %lx\n", (u_long)ntohl(q->s_addr));
1453#endif
1454	return (m);
1455}
1456
1457/*
1458 * Strip out IP options, at higher
1459 * level protocol in the kernel.
1460 * Second argument is buffer to which options
1461 * will be moved, and return value is their length.
1462 * XXX should be deleted; last arg currently ignored.
1463 */
1464void
1465ip_stripoptions(m, mopt)
1466	register struct mbuf *m;
1467	struct mbuf *mopt;
1468{
1469	register int i;
1470	struct ip *ip = mtod(m, struct ip *);
1471	register caddr_t opts;
1472	int olen;
1473
1474	olen = (IP_VHL_HL(ip->ip_vhl) << 2) - sizeof (struct ip);
1475	opts = (caddr_t)(ip + 1);
1476	i = m->m_len - (sizeof (struct ip) + olen);
1477	bcopy(opts + olen, opts, (unsigned)i);
1478	m->m_len -= olen;
1479	if (m->m_flags & M_PKTHDR)
1480		m->m_pkthdr.len -= olen;
1481	ip->ip_vhl = IP_MAKE_VHL(IPVERSION, sizeof(struct ip) >> 2);
1482}
1483
1484u_char inetctlerrmap[PRC_NCMDS] = {
1485	0,		0,		0,		0,
1486	0,		EMSGSIZE,	EHOSTDOWN,	EHOSTUNREACH,
1487	EHOSTUNREACH,	EHOSTUNREACH,	ECONNREFUSED,	ECONNREFUSED,
1488	EMSGSIZE,	EHOSTUNREACH,	0,		0,
1489	0,		0,		0,		0,
1490	ENOPROTOOPT,	ENETRESET
1491};
1492
1493/*
1494 * Forward a packet.  If some error occurs return the sender
1495 * an icmp packet.  Note we can't always generate a meaningful
1496 * icmp message because icmp doesn't have a large enough repertoire
1497 * of codes and types.
1498 *
1499 * If not forwarding, just drop the packet.  This could be confusing
1500 * if ipforwarding was zero but some routing protocol was advancing
1501 * us as a gateway to somewhere.  However, we must let the routing
1502 * protocol deal with that.
1503 *
1504 * The srcrt parameter indicates whether the packet is being forwarded
1505 * via a source route.
1506 */
1507static void
1508ip_forward(m, srcrt)
1509	struct mbuf *m;
1510	int srcrt;
1511{
1512	register struct ip *ip = mtod(m, struct ip *);
1513	register struct rtentry *rt;
1514	int error, type = 0, code = 0;
1515	struct mbuf *mcopy;
1516	n_long dest;
1517	struct ifnet *destifp;
1518#ifdef IPSEC
1519	struct ifnet dummyifp;
1520#endif
1521
1522	dest = 0;
1523#ifdef DIAGNOSTIC
1524	if (ipprintfs)
1525		printf("forward: src %lx dst %lx ttl %x\n",
1526		    (u_long)ip->ip_src.s_addr, (u_long)ip->ip_dst.s_addr,
1527		    ip->ip_ttl);
1528#endif
1529
1530
1531	if (m->m_flags & (M_BCAST|M_MCAST) || in_canforward(ip->ip_dst) == 0) {
1532		ipstat.ips_cantforward++;
1533		m_freem(m);
1534		return;
1535	}
1536#ifdef IPSTEALTH
1537	if (!ipstealth) {
1538#endif
1539		if (ip->ip_ttl <= IPTTLDEC) {
1540			icmp_error(m, ICMP_TIMXCEED, ICMP_TIMXCEED_INTRANS,
1541			    dest, 0);
1542			return;
1543		}
1544#ifdef IPSTEALTH
1545	}
1546#endif
1547
1548	if (ip_rtaddr(ip->ip_dst) == 0) {
1549		icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_HOST, dest, 0);
1550		return;
1551	} else
1552		rt = ipforward_rt.ro_rt;
1553
1554	/*
1555	 * Save the IP header and at most 8 bytes of the payload,
1556	 * in case we need to generate an ICMP message to the src.
1557	 *
1558	 * We don't use m_copy() because it might return a reference
1559	 * to a shared cluster. Both this function and ip_output()
1560	 * assume exclusive access to the IP header in `m', so any
1561	 * data in a cluster may change before we reach icmp_error().
1562	 */
1563	MGET(mcopy, M_DONTWAIT, m->m_type);
1564	if (mcopy != NULL) {
1565		M_COPY_PKTHDR(mcopy, m);
1566		mcopy->m_len = imin((IP_VHL_HL(ip->ip_vhl) << 2) + 8,
1567		    (int)ip->ip_len);
1568		m_copydata(m, 0, mcopy->m_len, mtod(mcopy, caddr_t));
1569	}
1570
1571#ifdef IPSTEALTH
1572	if (!ipstealth) {
1573#endif
1574		ip->ip_ttl -= IPTTLDEC;
1575#ifdef IPSTEALTH
1576	}
1577#endif
1578
1579	/*
1580	 * If forwarding packet using same interface that it came in on,
1581	 * perhaps should send a redirect to sender to shortcut a hop.
1582	 * Only send redirect if source is sending directly to us,
1583	 * and if packet was not source routed (or has any options).
1584	 * Also, don't send redirect if forwarding using a default route
1585	 * or a route modified by a redirect.
1586	 */
1587#define	satosin(sa)	((struct sockaddr_in *)(sa))
1588	if (rt->rt_ifp == m->m_pkthdr.rcvif &&
1589	    (rt->rt_flags & (RTF_DYNAMIC|RTF_MODIFIED)) == 0 &&
1590	    satosin(rt_key(rt))->sin_addr.s_addr != 0 &&
1591	    ipsendredirects && !srcrt) {
1592#define	RTA(rt)	((struct in_ifaddr *)(rt->rt_ifa))
1593		u_long src = ntohl(ip->ip_src.s_addr);
1594
1595		if (RTA(rt) &&
1596		    (src & RTA(rt)->ia_subnetmask) == RTA(rt)->ia_subnet) {
1597		    if (rt->rt_flags & RTF_GATEWAY)
1598			dest = satosin(rt->rt_gateway)->sin_addr.s_addr;
1599		    else
1600			dest = ip->ip_dst.s_addr;
1601		    /* Router requirements says to only send host redirects */
1602		    type = ICMP_REDIRECT;
1603		    code = ICMP_REDIRECT_HOST;
1604#ifdef DIAGNOSTIC
1605		    if (ipprintfs)
1606		        printf("redirect (%d) to %lx\n", code, (u_long)dest);
1607#endif
1608		}
1609	}
1610
1611	error = ip_output(m, (struct mbuf *)0, &ipforward_rt,
1612			  IP_FORWARDING, 0);
1613	if (error)
1614		ipstat.ips_cantforward++;
1615	else {
1616		ipstat.ips_forward++;
1617		if (type)
1618			ipstat.ips_redirectsent++;
1619		else {
1620			if (mcopy) {
1621				ipflow_create(&ipforward_rt, mcopy);
1622				m_freem(mcopy);
1623			}
1624			return;
1625		}
1626	}
1627	if (mcopy == NULL)
1628		return;
1629	destifp = NULL;
1630
1631	switch (error) {
1632
1633	case 0:				/* forwarded, but need redirect */
1634		/* type, code set above */
1635		break;
1636
1637	case ENETUNREACH:		/* shouldn't happen, checked above */
1638	case EHOSTUNREACH:
1639	case ENETDOWN:
1640	case EHOSTDOWN:
1641	default:
1642		type = ICMP_UNREACH;
1643		code = ICMP_UNREACH_HOST;
1644		break;
1645
1646	case EMSGSIZE:
1647		type = ICMP_UNREACH;
1648		code = ICMP_UNREACH_NEEDFRAG;
1649#ifndef IPSEC
1650		if (ipforward_rt.ro_rt)
1651			destifp = ipforward_rt.ro_rt->rt_ifp;
1652#else
1653		/*
1654		 * If the packet is routed over IPsec tunnel, tell the
1655		 * originator the tunnel MTU.
1656		 *	tunnel MTU = if MTU - sizeof(IP) - ESP/AH hdrsiz
1657		 * XXX quickhack!!!
1658		 */
1659		if (ipforward_rt.ro_rt) {
1660			struct secpolicy *sp = NULL;
1661			int ipsecerror;
1662			int ipsechdr;
1663			struct route *ro;
1664
1665			sp = ipsec4_getpolicybyaddr(mcopy,
1666						    IPSEC_DIR_OUTBOUND,
1667			                            IP_FORWARDING,
1668			                            &ipsecerror);
1669
1670			if (sp == NULL)
1671				destifp = ipforward_rt.ro_rt->rt_ifp;
1672			else {
1673				/* count IPsec header size */
1674				ipsechdr = ipsec4_hdrsiz(mcopy,
1675							 IPSEC_DIR_OUTBOUND,
1676							 NULL);
1677
1678				/*
1679				 * find the correct route for outer IPv4
1680				 * header, compute tunnel MTU.
1681				 *
1682				 * XXX BUG ALERT
1683				 * The "dummyifp" code relies upon the fact
1684				 * that icmp_error() touches only ifp->if_mtu.
1685				 */
1686				/*XXX*/
1687				destifp = NULL;
1688				if (sp->req != NULL
1689				 && sp->req->sav != NULL
1690				 && sp->req->sav->sah != NULL) {
1691					ro = &sp->req->sav->sah->sa_route;
1692					if (ro->ro_rt && ro->ro_rt->rt_ifp) {
1693						dummyifp.if_mtu =
1694						    ro->ro_rt->rt_ifp->if_mtu;
1695						dummyifp.if_mtu -= ipsechdr;
1696						destifp = &dummyifp;
1697					}
1698				}
1699
1700				key_freesp(sp);
1701			}
1702		}
1703#endif /*IPSEC*/
1704		ipstat.ips_cantfrag++;
1705		break;
1706
1707	case ENOBUFS:
1708		type = ICMP_SOURCEQUENCH;
1709		code = 0;
1710		break;
1711
1712	case EACCES:			/* ipfw denied packet */
1713		m_freem(mcopy);
1714		return;
1715	}
1716	icmp_error(mcopy, type, code, dest, destifp);
1717}
1718
1719void
1720ip_savecontrol(inp, mp, ip, m)
1721	register struct inpcb *inp;
1722	register struct mbuf **mp;
1723	register struct ip *ip;
1724	register struct mbuf *m;
1725{
1726	if (inp->inp_socket->so_options & SO_TIMESTAMP) {
1727		struct timeval tv;
1728
1729		microtime(&tv);
1730		*mp = sbcreatecontrol((caddr_t) &tv, sizeof(tv),
1731			SCM_TIMESTAMP, SOL_SOCKET);
1732		if (*mp)
1733			mp = &(*mp)->m_next;
1734	}
1735	if (inp->inp_flags & INP_RECVDSTADDR) {
1736		*mp = sbcreatecontrol((caddr_t) &ip->ip_dst,
1737		    sizeof(struct in_addr), IP_RECVDSTADDR, IPPROTO_IP);
1738		if (*mp)
1739			mp = &(*mp)->m_next;
1740	}
1741#ifdef notyet
1742	/* XXX
1743	 * Moving these out of udp_input() made them even more broken
1744	 * than they already were.
1745	 */
1746	/* options were tossed already */
1747	if (inp->inp_flags & INP_RECVOPTS) {
1748		*mp = sbcreatecontrol((caddr_t) opts_deleted_above,
1749		    sizeof(struct in_addr), IP_RECVOPTS, IPPROTO_IP);
1750		if (*mp)
1751			mp = &(*mp)->m_next;
1752	}
1753	/* ip_srcroute doesn't do what we want here, need to fix */
1754	if (inp->inp_flags & INP_RECVRETOPTS) {
1755		*mp = sbcreatecontrol((caddr_t) ip_srcroute(),
1756		    sizeof(struct in_addr), IP_RECVRETOPTS, IPPROTO_IP);
1757		if (*mp)
1758			mp = &(*mp)->m_next;
1759	}
1760#endif
1761	if (inp->inp_flags & INP_RECVIF) {
1762		struct ifnet *ifp;
1763		struct sdlbuf {
1764			struct sockaddr_dl sdl;
1765			u_char	pad[32];
1766		} sdlbuf;
1767		struct sockaddr_dl *sdp;
1768		struct sockaddr_dl *sdl2 = &sdlbuf.sdl;
1769
1770		if (((ifp = m->m_pkthdr.rcvif))
1771		&& ( ifp->if_index && (ifp->if_index <= if_index))) {
1772			sdp = (struct sockaddr_dl *)(ifnet_addrs
1773					[ifp->if_index - 1]->ifa_addr);
1774			/*
1775			 * Change our mind and don't try copy.
1776			 */
1777			if ((sdp->sdl_family != AF_LINK)
1778			|| (sdp->sdl_len > sizeof(sdlbuf))) {
1779				goto makedummy;
1780			}
1781			bcopy(sdp, sdl2, sdp->sdl_len);
1782		} else {
1783makedummy:
1784			sdl2->sdl_len
1785				= offsetof(struct sockaddr_dl, sdl_data[0]);
1786			sdl2->sdl_family = AF_LINK;
1787			sdl2->sdl_index = 0;
1788			sdl2->sdl_nlen = sdl2->sdl_alen = sdl2->sdl_slen = 0;
1789		}
1790		*mp = sbcreatecontrol((caddr_t) sdl2, sdl2->sdl_len,
1791			IP_RECVIF, IPPROTO_IP);
1792		if (*mp)
1793			mp = &(*mp)->m_next;
1794	}
1795}
1796
1797int
1798ip_rsvp_init(struct socket *so)
1799{
1800	if (so->so_type != SOCK_RAW ||
1801	    so->so_proto->pr_protocol != IPPROTO_RSVP)
1802	  return EOPNOTSUPP;
1803
1804	if (ip_rsvpd != NULL)
1805	  return EADDRINUSE;
1806
1807	ip_rsvpd = so;
1808	/*
1809	 * This may seem silly, but we need to be sure we don't over-increment
1810	 * the RSVP counter, in case something slips up.
1811	 */
1812	if (!ip_rsvp_on) {
1813		ip_rsvp_on = 1;
1814		rsvp_on++;
1815	}
1816
1817	return 0;
1818}
1819
1820int
1821ip_rsvp_done(void)
1822{
1823	ip_rsvpd = NULL;
1824	/*
1825	 * This may seem silly, but we need to be sure we don't over-decrement
1826	 * the RSVP counter, in case something slips up.
1827	 */
1828	if (ip_rsvp_on) {
1829		ip_rsvp_on = 0;
1830		rsvp_on--;
1831	}
1832	return 0;
1833}
1834