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