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