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