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