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