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