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