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