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