tcp_input.c revision 50015
1/*
2 * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994, 1995
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 *	@(#)tcp_input.c	8.12 (Berkeley) 5/24/95
34 *	$Id: tcp_input.c,v 1.88 1999/08/17 12:17:52 csgr Exp $
35 */
36
37#include "opt_ipfw.h"		/* for ipfw_fwd		*/
38#include "opt_tcpdebug.h"
39
40#include <sys/param.h>
41#include <sys/systm.h>
42#include <sys/kernel.h>
43#include <sys/sysctl.h>
44#include <sys/malloc.h>
45#include <sys/mbuf.h>
46#include <sys/proc.h>		/* for proc0 declaration */
47#include <sys/protosw.h>
48#include <sys/socket.h>
49#include <sys/socketvar.h>
50#include <sys/syslog.h>
51
52#include <machine/cpu.h>	/* before tcp_seq.h, for tcp_random18() */
53
54#include <net/if.h>
55#include <net/route.h>
56
57#include <netinet/in.h>
58#include <netinet/in_systm.h>
59#include <netinet/ip.h>
60#include <netinet/ip_icmp.h>	/* for ICMP_BANDLIM		*/
61#include <netinet/in_pcb.h>
62#include <netinet/ip_var.h>
63#include <netinet/icmp_var.h>	/* for ICMP_BANDLIM		*/
64#include <netinet/tcp.h>
65#include <netinet/tcp_fsm.h>
66#include <netinet/tcp_seq.h>
67#include <netinet/tcp_timer.h>
68#include <netinet/tcp_var.h>
69#include <netinet/tcpip.h>
70#ifdef TCPDEBUG
71#include <netinet/tcp_debug.h>
72static struct	tcpiphdr tcp_saveti;
73#endif
74
75static int	tcprexmtthresh = 3;
76tcp_seq	tcp_iss;
77tcp_cc	tcp_ccgen;
78
79struct	tcpstat tcpstat;
80SYSCTL_STRUCT(_net_inet_tcp, TCPCTL_STATS, stats, CTLFLAG_RD,
81    &tcpstat , tcpstat, "TCP statistics (struct tcpstat, netinet/tcp_var.h)");
82
83static int log_in_vain = 0;
84SYSCTL_INT(_net_inet_tcp, OID_AUTO, log_in_vain, CTLFLAG_RW,
85    &log_in_vain, 0, "Log all incoming TCP connections");
86
87static int blackhole = 0;
88SYSCTL_INT(_net_inet_tcp, OID_AUTO, blackhole, CTLFLAG_RW,
89	&blackhole, 0, "Do not send RST when dropping refused connections");
90
91int tcp_delack_enabled = 1;
92SYSCTL_INT(_net_inet_tcp, OID_AUTO, delayed_ack, CTLFLAG_RW,
93    &tcp_delack_enabled, 0,
94    "Delay ACK to try and piggyback it onto a data packet");
95
96u_long	tcp_now;
97struct inpcbhead tcb;
98struct inpcbinfo tcbinfo;
99
100static void	 tcp_dooptions __P((struct tcpcb *,
101	    u_char *, int, struct tcpiphdr *, struct tcpopt *));
102static void	 tcp_pulloutofband __P((struct socket *,
103	    struct tcpiphdr *, struct mbuf *));
104static int	 tcp_reass __P((struct tcpcb *, struct tcpiphdr *, struct mbuf *));
105static void	 tcp_xmit_timer __P((struct tcpcb *, int));
106
107
108/*
109 * Insert segment ti into reassembly queue of tcp with
110 * control block tp.  Return TH_FIN if reassembly now includes
111 * a segment with FIN.  The macro form does the common case inline
112 * (segment is the next to be received on an established connection,
113 * and the queue is empty), avoiding linkage into and removal
114 * from the queue and repetition of various conversions.
115 * Set DELACK for segments received in order, but ack immediately
116 * when segments are out of order (so fast retransmit can work).
117 */
118#define	TCP_REASS(tp, ti, m, so, flags) { \
119	if ((ti)->ti_seq == (tp)->rcv_nxt && \
120	    (tp)->t_segq == NULL && \
121	    (tp)->t_state == TCPS_ESTABLISHED) { \
122		if (tcp_delack_enabled) \
123			tp->t_flags |= TF_DELACK; \
124		else \
125			tp->t_flags |= TF_ACKNOW; \
126		(tp)->rcv_nxt += (ti)->ti_len; \
127		flags = (ti)->ti_flags & TH_FIN; \
128		tcpstat.tcps_rcvpack++;\
129		tcpstat.tcps_rcvbyte += (ti)->ti_len;\
130		sbappend(&(so)->so_rcv, (m)); \
131		sorwakeup(so); \
132	} else { \
133		(flags) = tcp_reass((tp), (ti), (m)); \
134		tp->t_flags |= TF_ACKNOW; \
135	} \
136}
137
138static int
139tcp_reass(tp, ti, m)
140	register struct tcpcb *tp;
141	register struct tcpiphdr *ti;
142	struct mbuf *m;
143{
144	struct mbuf *q;
145	struct mbuf *p;
146	struct mbuf *nq;
147	struct socket *so = tp->t_inpcb->inp_socket;
148	int flags;
149
150#define GETTCP(m)	((struct tcpiphdr *)m->m_pkthdr.header)
151
152	/*
153	 * Call with ti==0 after become established to
154	 * force pre-ESTABLISHED data up to user socket.
155	 */
156	if (ti == 0)
157		goto present;
158
159	m->m_pkthdr.header = ti;
160
161	/*
162	 * Find a segment which begins after this one does.
163	 */
164	for (q = tp->t_segq, p = NULL; q; p = q, q = q->m_nextpkt)
165		if (SEQ_GT(GETTCP(q)->ti_seq, ti->ti_seq))
166			break;
167
168	/*
169	 * If there is a preceding segment, it may provide some of
170	 * our data already.  If so, drop the data from the incoming
171	 * segment.  If it provides all of our data, drop us.
172	 */
173	if (p != NULL) {
174		register int i;
175		/* conversion to int (in i) handles seq wraparound */
176		i = GETTCP(p)->ti_seq + GETTCP(p)->ti_len - ti->ti_seq;
177		if (i > 0) {
178			if (i >= ti->ti_len) {
179				tcpstat.tcps_rcvduppack++;
180				tcpstat.tcps_rcvdupbyte += ti->ti_len;
181				m_freem(m);
182				/*
183				 * Try to present any queued data
184				 * at the left window edge to the user.
185				 * This is needed after the 3-WHS
186				 * completes.
187				 */
188				goto present;	/* ??? */
189			}
190			m_adj(m, i);
191			ti->ti_len -= i;
192			ti->ti_seq += i;
193		}
194	}
195	tcpstat.tcps_rcvoopack++;
196	tcpstat.tcps_rcvoobyte += ti->ti_len;
197
198	/*
199	 * While we overlap succeeding segments trim them or,
200	 * if they are completely covered, dequeue them.
201	 */
202	while (q) {
203		register int i = (ti->ti_seq + ti->ti_len) - GETTCP(q)->ti_seq;
204		if (i <= 0)
205			break;
206		if (i < GETTCP(q)->ti_len) {
207			GETTCP(q)->ti_seq += i;
208			GETTCP(q)->ti_len -= i;
209			m_adj(q, i);
210			break;
211		}
212
213		nq = q->m_nextpkt;
214		if (p)
215			p->m_nextpkt = nq;
216		else
217			tp->t_segq = nq;
218		m_freem(q);
219		q = nq;
220	}
221
222	if (p == NULL) {
223		m->m_nextpkt = tp->t_segq;
224		tp->t_segq = m;
225	} else {
226		m->m_nextpkt = p->m_nextpkt;
227		p->m_nextpkt = m;
228	}
229
230present:
231	/*
232	 * Present data to user, advancing rcv_nxt through
233	 * completed sequence space.
234	 */
235	if (!TCPS_HAVEESTABLISHED(tp->t_state))
236		return (0);
237	q = tp->t_segq;
238	if (!q || GETTCP(q)->ti_seq != tp->rcv_nxt)
239		return (0);
240	do {
241		tp->rcv_nxt += GETTCP(q)->ti_len;
242		flags = GETTCP(q)->ti_flags & TH_FIN;
243		nq = q->m_nextpkt;
244		tp->t_segq = nq;
245		q->m_nextpkt = NULL;
246		if (so->so_state & SS_CANTRCVMORE)
247			m_freem(q);
248		else
249			sbappend(&so->so_rcv, q);
250		q = nq;
251	} while (q && GETTCP(q)->ti_seq == tp->rcv_nxt);
252	sorwakeup(so);
253	return (flags);
254
255#undef GETTCP
256}
257
258/*
259 * TCP input routine, follows pages 65-76 of the
260 * protocol specification dated September, 1981 very closely.
261 */
262void
263tcp_input(m, iphlen)
264	register struct mbuf *m;
265	int iphlen;
266{
267	register struct tcpiphdr *ti;
268	register struct inpcb *inp;
269	u_char *optp = NULL;
270	int optlen = 0;
271	int len, tlen, off;
272	register struct tcpcb *tp = 0;
273	register int tiflags;
274	struct socket *so = 0;
275	int todrop, acked, ourfinisacked, needoutput = 0;
276	struct in_addr laddr;
277	int dropsocket = 0;
278	int iss = 0;
279	u_long tiwin;
280	struct tcpopt to;		/* options in this segment */
281	struct rmxp_tao *taop;		/* pointer to our TAO cache entry */
282	struct rmxp_tao	tao_noncached;	/* in case there's no cached entry */
283#ifdef TCPDEBUG
284	short ostate = 0;
285#endif
286
287	bzero((char *)&to, sizeof(to));
288
289	tcpstat.tcps_rcvtotal++;
290	/*
291	 * Get IP and TCP header together in first mbuf.
292	 * Note: IP leaves IP header in first mbuf.
293	 */
294	ti = mtod(m, struct tcpiphdr *);
295	if (iphlen > sizeof (struct ip))
296		ip_stripoptions(m, (struct mbuf *)0);
297	if (m->m_len < sizeof (struct tcpiphdr)) {
298		if ((m = m_pullup(m, sizeof (struct tcpiphdr))) == 0) {
299			tcpstat.tcps_rcvshort++;
300			return;
301		}
302		ti = mtod(m, struct tcpiphdr *);
303	}
304
305	/*
306	 * Checksum extended TCP header and data.
307	 */
308	tlen = ((struct ip *)ti)->ip_len;
309	len = sizeof (struct ip) + tlen;
310	bzero(ti->ti_x1, sizeof(ti->ti_x1));
311	ti->ti_len = (u_short)tlen;
312	HTONS(ti->ti_len);
313	ti->ti_sum = in_cksum(m, len);
314	if (ti->ti_sum) {
315		tcpstat.tcps_rcvbadsum++;
316		goto drop;
317	}
318
319	/*
320	 * Check that TCP offset makes sense,
321	 * pull out TCP options and adjust length.		XXX
322	 */
323	off = ti->ti_off << 2;
324	if (off < sizeof (struct tcphdr) || off > tlen) {
325		tcpstat.tcps_rcvbadoff++;
326		goto drop;
327	}
328	tlen -= off;
329	ti->ti_len = tlen;
330	if (off > sizeof (struct tcphdr)) {
331		if (m->m_len < sizeof(struct ip) + off) {
332			if ((m = m_pullup(m, sizeof (struct ip) + off)) == 0) {
333				tcpstat.tcps_rcvshort++;
334				return;
335			}
336			ti = mtod(m, struct tcpiphdr *);
337		}
338		optlen = off - sizeof (struct tcphdr);
339		optp = mtod(m, u_char *) + sizeof (struct tcpiphdr);
340	}
341	tiflags = ti->ti_flags;
342
343	/*
344	 * Convert TCP protocol specific fields to host format.
345	 */
346	NTOHL(ti->ti_seq);
347	NTOHL(ti->ti_ack);
348	NTOHS(ti->ti_win);
349	NTOHS(ti->ti_urp);
350
351	/*
352	 * Drop TCP, IP headers and TCP options.
353	 */
354	m->m_data += sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr);
355	m->m_len  -= sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr);
356
357	/*
358	 * Locate pcb for segment.
359	 */
360findpcb:
361#ifdef IPFIREWALL_FORWARD
362	if (ip_fw_fwd_addr != NULL) {
363		/*
364		 * Diverted. Pretend to be the destination.
365		 * already got one like this?
366		 */
367		inp = in_pcblookup_hash(&tcbinfo, ti->ti_src, ti->ti_sport,
368			ti->ti_dst, ti->ti_dport, 0);
369		if (!inp) {
370			/*
371			 * No, then it's new. Try find the ambushing socket
372			 */
373			if (!ip_fw_fwd_addr->sin_port) {
374				inp = in_pcblookup_hash(&tcbinfo, ti->ti_src,
375				    ti->ti_sport, ip_fw_fwd_addr->sin_addr,
376				    ti->ti_dport, 1);
377			} else {
378				inp = in_pcblookup_hash(&tcbinfo,
379				    ti->ti_src, ti->ti_sport,
380	    			    ip_fw_fwd_addr->sin_addr,
381				    ntohs(ip_fw_fwd_addr->sin_port), 1);
382			}
383		}
384		ip_fw_fwd_addr = NULL;
385	} else
386#endif	/* IPFIREWALL_FORWARD */
387
388	inp = in_pcblookup_hash(&tcbinfo, ti->ti_src, ti->ti_sport,
389	    ti->ti_dst, ti->ti_dport, 1);
390
391	/*
392	 * If the state is CLOSED (i.e., TCB does not exist) then
393	 * all data in the incoming segment is discarded.
394	 * If the TCB exists but is in CLOSED state, it is embryonic,
395	 * but should either do a listen or a connect soon.
396	 */
397	if (inp == NULL) {
398		if (log_in_vain) {
399			char buf[4*sizeof "123"];
400
401			strcpy(buf, inet_ntoa(ti->ti_dst));
402			switch (log_in_vain) {
403			case 1:
404				if(tiflags & TH_SYN)
405					log(LOG_INFO,
406			    		"Connection attempt to TCP %s:%d from %s:%d\n",
407			    		buf, ntohs(ti->ti_dport), inet_ntoa(ti->ti_src),
408			    		ntohs(ti->ti_sport));
409						break;
410			case 2:
411				log(LOG_INFO,
412			    	"Connection attempt to TCP %s:%d from %s:%d flags:0x%x\n",
413			    	buf, ntohs(ti->ti_dport), inet_ntoa(ti->ti_src),
414			    	ntohs(ti->ti_sport), tiflags);
415					break;
416			default:
417				break;
418			}
419		}
420#ifdef ICMP_BANDLIM
421		if (badport_bandlim(1) < 0)
422			goto drop;
423#endif
424		if(blackhole) {
425			switch (blackhole) {
426				case 1: if(tiflags & TH_SYN) goto drop;
427				case 2: goto drop ;
428				default : goto drop ;
429			}
430		} else
431			goto dropwithreset;
432	}
433	tp = intotcpcb(inp);
434	if (tp == 0)
435		goto dropwithreset;
436	if (tp->t_state == TCPS_CLOSED)
437		goto drop;
438
439	/* Unscale the window into a 32-bit value. */
440	if ((tiflags & TH_SYN) == 0)
441		tiwin = ti->ti_win << tp->snd_scale;
442	else
443		tiwin = ti->ti_win;
444
445	so = inp->inp_socket;
446	if (so->so_options & (SO_DEBUG|SO_ACCEPTCONN)) {
447#ifdef TCPDEBUG
448		if (so->so_options & SO_DEBUG) {
449			ostate = tp->t_state;
450			tcp_saveti = *ti;
451		}
452#endif
453		if (so->so_options & SO_ACCEPTCONN) {
454			register struct tcpcb *tp0 = tp;
455			struct socket *so2;
456			if ((tiflags & (TH_RST|TH_ACK|TH_SYN)) != TH_SYN) {
457				/*
458				 * Note: dropwithreset makes sure we don't
459				 * send a RST in response to a RST.
460				 */
461				if (tiflags & TH_ACK) {
462					tcpstat.tcps_badsyn++;
463					goto dropwithreset;
464				}
465				goto drop;
466			}
467			so2 = sonewconn(so, 0);
468			if (so2 == 0) {
469				tcpstat.tcps_listendrop++;
470				so2 = sodropablereq(so);
471				if (so2) {
472					tcp_drop(sototcpcb(so2), ETIMEDOUT);
473					so2 = sonewconn(so, 0);
474				}
475				if (!so2)
476					goto drop;
477			}
478			so = so2;
479			/*
480			 * This is ugly, but ....
481			 *
482			 * Mark socket as temporary until we're
483			 * committed to keeping it.  The code at
484			 * ``drop'' and ``dropwithreset'' check the
485			 * flag dropsocket to see if the temporary
486			 * socket created here should be discarded.
487			 * We mark the socket as discardable until
488			 * we're committed to it below in TCPS_LISTEN.
489			 */
490			dropsocket++;
491			inp = (struct inpcb *)so->so_pcb;
492			inp->inp_laddr = ti->ti_dst;
493			inp->inp_lport = ti->ti_dport;
494			if (in_pcbinshash(inp) != 0) {
495				/*
496				 * Undo the assignments above if we failed to put
497				 * the PCB on the hash lists.
498				 */
499				inp->inp_laddr.s_addr = INADDR_ANY;
500				inp->inp_lport = 0;
501				goto drop;
502			}
503			inp->inp_options = ip_srcroute();
504			tp = intotcpcb(inp);
505			tp->t_state = TCPS_LISTEN;
506			tp->t_flags |= tp0->t_flags & (TF_NOPUSH|TF_NOOPT);
507
508			/* Compute proper scaling value from buffer space */
509			while (tp->request_r_scale < TCP_MAX_WINSHIFT &&
510			   TCP_MAXWIN << tp->request_r_scale < so->so_rcv.sb_hiwat)
511				tp->request_r_scale++;
512		}
513	}
514
515	/*
516	 * Segment received on connection.
517	 * Reset idle time and keep-alive timer.
518	 */
519	tp->t_idle = 0;
520	if (TCPS_HAVEESTABLISHED(tp->t_state))
521		tp->t_timer[TCPT_KEEP] = tcp_keepidle;
522
523	/*
524	 * Process options if not in LISTEN state,
525	 * else do it below (after getting remote address).
526	 */
527	if (tp->t_state != TCPS_LISTEN)
528		tcp_dooptions(tp, optp, optlen, ti, &to);
529
530	/*
531	 * Header prediction: check for the two common cases
532	 * of a uni-directional data xfer.  If the packet has
533	 * no control flags, is in-sequence, the window didn't
534	 * change and we're not retransmitting, it's a
535	 * candidate.  If the length is zero and the ack moved
536	 * forward, we're the sender side of the xfer.  Just
537	 * free the data acked & wake any higher level process
538	 * that was blocked waiting for space.  If the length
539	 * is non-zero and the ack didn't move, we're the
540	 * receiver side.  If we're getting packets in-order
541	 * (the reassembly queue is empty), add the data to
542	 * the socket buffer and note that we need a delayed ack.
543	 * Make sure that the hidden state-flags are also off.
544	 * Since we check for TCPS_ESTABLISHED above, it can only
545	 * be TH_NEEDSYN.
546	 */
547	if (tp->t_state == TCPS_ESTABLISHED &&
548	    (tiflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
549	    ((tp->t_flags & (TF_NEEDSYN|TF_NEEDFIN)) == 0) &&
550	    ((to.to_flag & TOF_TS) == 0 ||
551	     TSTMP_GEQ(to.to_tsval, tp->ts_recent)) &&
552	    /*
553	     * Using the CC option is compulsory if once started:
554	     *   the segment is OK if no T/TCP was negotiated or
555	     *   if the segment has a CC option equal to CCrecv
556	     */
557	    ((tp->t_flags & (TF_REQ_CC|TF_RCVD_CC)) != (TF_REQ_CC|TF_RCVD_CC) ||
558	     ((to.to_flag & TOF_CC) != 0 && to.to_cc == tp->cc_recv)) &&
559	    ti->ti_seq == tp->rcv_nxt &&
560	    tiwin && tiwin == tp->snd_wnd &&
561	    tp->snd_nxt == tp->snd_max) {
562
563		/*
564		 * If last ACK falls within this segment's sequence numbers,
565		 * record the timestamp.
566		 * NOTE that the test is modified according to the latest
567		 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
568		 */
569		if ((to.to_flag & TOF_TS) != 0 &&
570		   SEQ_LEQ(ti->ti_seq, tp->last_ack_sent)) {
571			tp->ts_recent_age = tcp_now;
572			tp->ts_recent = to.to_tsval;
573		}
574
575		if (ti->ti_len == 0) {
576			if (SEQ_GT(ti->ti_ack, tp->snd_una) &&
577			    SEQ_LEQ(ti->ti_ack, tp->snd_max) &&
578			    tp->snd_cwnd >= tp->snd_wnd &&
579			    tp->t_dupacks < tcprexmtthresh) {
580				/*
581				 * this is a pure ack for outstanding data.
582				 */
583				++tcpstat.tcps_predack;
584				if ((to.to_flag & TOF_TS) != 0)
585					tcp_xmit_timer(tp,
586					    tcp_now - to.to_tsecr + 1);
587				else if (tp->t_rtt &&
588					    SEQ_GT(ti->ti_ack, tp->t_rtseq))
589					tcp_xmit_timer(tp, tp->t_rtt);
590				acked = ti->ti_ack - tp->snd_una;
591				tcpstat.tcps_rcvackpack++;
592				tcpstat.tcps_rcvackbyte += acked;
593				sbdrop(&so->so_snd, acked);
594				tp->snd_una = ti->ti_ack;
595				m_freem(m);
596
597				/*
598				 * If all outstanding data are acked, stop
599				 * retransmit timer, otherwise restart timer
600				 * using current (possibly backed-off) value.
601				 * If process is waiting for space,
602				 * wakeup/selwakeup/signal.  If data
603				 * are ready to send, let tcp_output
604				 * decide between more output or persist.
605				 */
606				if (tp->snd_una == tp->snd_max)
607					tp->t_timer[TCPT_REXMT] = 0;
608				else if (tp->t_timer[TCPT_PERSIST] == 0)
609					tp->t_timer[TCPT_REXMT] = tp->t_rxtcur;
610
611				sowwakeup(so);
612				if (so->so_snd.sb_cc)
613					(void) tcp_output(tp);
614				return;
615			}
616		} else if (ti->ti_ack == tp->snd_una &&
617		    tp->t_segq == NULL &&
618		    ti->ti_len <= sbspace(&so->so_rcv)) {
619			/*
620			 * this is a pure, in-sequence data packet
621			 * with nothing on the reassembly queue and
622			 * we have enough buffer space to take it.
623			 */
624			++tcpstat.tcps_preddat;
625			tp->rcv_nxt += ti->ti_len;
626			tcpstat.tcps_rcvpack++;
627			tcpstat.tcps_rcvbyte += ti->ti_len;
628			/*
629			 * Add data to socket buffer.
630			 */
631			sbappend(&so->so_rcv, m);
632			sorwakeup(so);
633			if (tcp_delack_enabled) {
634				tp->t_flags |= TF_DELACK;
635			} else {
636				tp->t_flags |= TF_ACKNOW;
637				tcp_output(tp);
638			}
639			return;
640		}
641	}
642
643	/*
644	 * Calculate amount of space in receive window,
645	 * and then do TCP input processing.
646	 * Receive window is amount of space in rcv queue,
647	 * but not less than advertised window.
648	 */
649	{ int win;
650
651	win = sbspace(&so->so_rcv);
652	if (win < 0)
653		win = 0;
654	tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
655	}
656
657	switch (tp->t_state) {
658
659	/*
660	 * If the state is LISTEN then ignore segment if it contains an RST.
661	 * If the segment contains an ACK then it is bad and send a RST.
662	 * If it does not contain a SYN then it is not interesting; drop it.
663	 * If it is from this socket, drop it, it must be forged.
664	 * Don't bother responding if the destination was a broadcast.
665	 * Otherwise initialize tp->rcv_nxt, and tp->irs, select an initial
666	 * tp->iss, and send a segment:
667	 *     <SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK>
668	 * Also initialize tp->snd_nxt to tp->iss+1 and tp->snd_una to tp->iss.
669	 * Fill in remote peer address fields if not previously specified.
670	 * Enter SYN_RECEIVED state, and process any other fields of this
671	 * segment in this state.
672	 */
673	case TCPS_LISTEN: {
674		register struct sockaddr_in *sin;
675
676		if (tiflags & TH_RST)
677			goto drop;
678		if (tiflags & TH_ACK)
679			goto dropwithreset;
680		if ((tiflags & TH_SYN) == 0)
681			goto drop;
682		if ((ti->ti_dport == ti->ti_sport) &&
683		    (ti->ti_dst.s_addr == ti->ti_src.s_addr))
684			goto drop;
685		/*
686		 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
687		 * in_broadcast() should never return true on a received
688		 * packet with M_BCAST not set.
689		 */
690		if (m->m_flags & (M_BCAST|M_MCAST) ||
691		    IN_MULTICAST(ntohl(ti->ti_dst.s_addr)))
692			goto drop;
693		MALLOC(sin, struct sockaddr_in *, sizeof *sin, M_SONAME,
694		       M_NOWAIT);
695		if (sin == NULL)
696			goto drop;
697		sin->sin_family = AF_INET;
698		sin->sin_len = sizeof(*sin);
699		sin->sin_addr = ti->ti_src;
700		sin->sin_port = ti->ti_sport;
701		bzero((caddr_t)sin->sin_zero, sizeof(sin->sin_zero));
702		laddr = inp->inp_laddr;
703		if (inp->inp_laddr.s_addr == INADDR_ANY)
704			inp->inp_laddr = ti->ti_dst;
705		if (in_pcbconnect(inp, (struct sockaddr *)sin, &proc0)) {
706			inp->inp_laddr = laddr;
707			FREE(sin, M_SONAME);
708			goto drop;
709		}
710		FREE(sin, M_SONAME);
711		tp->t_template = tcp_template(tp);
712		if (tp->t_template == 0) {
713			tp = tcp_drop(tp, ENOBUFS);
714			dropsocket = 0;		/* socket is already gone */
715			goto drop;
716		}
717		if ((taop = tcp_gettaocache(inp)) == NULL) {
718			taop = &tao_noncached;
719			bzero(taop, sizeof(*taop));
720		}
721		tcp_dooptions(tp, optp, optlen, ti, &to);
722		if (iss)
723			tp->iss = iss;
724		else
725			tp->iss = tcp_iss;
726		tcp_iss += TCP_ISSINCR/4;
727		tp->irs = ti->ti_seq;
728		tcp_sendseqinit(tp);
729		tcp_rcvseqinit(tp);
730		/*
731		 * Initialization of the tcpcb for transaction;
732		 *   set SND.WND = SEG.WND,
733		 *   initialize CCsend and CCrecv.
734		 */
735		tp->snd_wnd = tiwin;	/* initial send-window */
736		tp->cc_send = CC_INC(tcp_ccgen);
737		tp->cc_recv = to.to_cc;
738		/*
739		 * Perform TAO test on incoming CC (SEG.CC) option, if any.
740		 * - compare SEG.CC against cached CC from the same host,
741		 *	if any.
742		 * - if SEG.CC > chached value, SYN must be new and is accepted
743		 *	immediately: save new CC in the cache, mark the socket
744		 *	connected, enter ESTABLISHED state, turn on flag to
745		 *	send a SYN in the next segment.
746		 *	A virtual advertised window is set in rcv_adv to
747		 *	initialize SWS prevention.  Then enter normal segment
748		 *	processing: drop SYN, process data and FIN.
749		 * - otherwise do a normal 3-way handshake.
750		 */
751		if ((to.to_flag & TOF_CC) != 0) {
752		    if (((tp->t_flags & TF_NOPUSH) != 0) &&
753			taop->tao_cc != 0 && CC_GT(to.to_cc, taop->tao_cc)) {
754
755			taop->tao_cc = to.to_cc;
756			tp->t_state = TCPS_ESTABLISHED;
757
758			/*
759			 * If there is a FIN, or if there is data and the
760			 * connection is local, then delay SYN,ACK(SYN) in
761			 * the hope of piggy-backing it on a response
762			 * segment.  Otherwise must send ACK now in case
763			 * the other side is slow starting.
764			 */
765			if (tcp_delack_enabled && ((tiflags & TH_FIN) || (ti->ti_len != 0 &&
766			    in_localaddr(inp->inp_faddr))))
767				tp->t_flags |= (TF_DELACK | TF_NEEDSYN);
768			else
769				tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
770
771			/*
772			 * Limit the `virtual advertised window' to TCP_MAXWIN
773			 * here.  Even if we requested window scaling, it will
774			 * become effective only later when our SYN is acked.
775			 */
776			tp->rcv_adv += min(tp->rcv_wnd, TCP_MAXWIN);
777			tcpstat.tcps_connects++;
778			soisconnected(so);
779			tp->t_timer[TCPT_KEEP] = tcp_keepinit;
780			dropsocket = 0;		/* committed to socket */
781			tcpstat.tcps_accepts++;
782			goto trimthenstep6;
783		    }
784		/* else do standard 3-way handshake */
785		} else {
786		    /*
787		     * No CC option, but maybe CC.NEW:
788		     *   invalidate cached value.
789		     */
790		     taop->tao_cc = 0;
791		}
792		/*
793		 * TAO test failed or there was no CC option,
794		 *    do a standard 3-way handshake.
795		 */
796		tp->t_flags |= TF_ACKNOW;
797		tp->t_state = TCPS_SYN_RECEIVED;
798		tp->t_timer[TCPT_KEEP] = tcp_keepinit;
799		dropsocket = 0;		/* committed to socket */
800		tcpstat.tcps_accepts++;
801		goto trimthenstep6;
802		}
803
804	/*
805	 * If the state is SYN_RECEIVED:
806	 *	if seg contains an ACK, but not for our SYN/ACK, send a RST.
807	 */
808	case TCPS_SYN_RECEIVED:
809		if ((tiflags & TH_ACK) &&
810		    (SEQ_LEQ(ti->ti_ack, tp->snd_una) ||
811		     SEQ_GT(ti->ti_ack, tp->snd_max)))
812				goto dropwithreset;
813		break;
814
815	/*
816	 * If the state is SYN_SENT:
817	 *	if seg contains an ACK, but not for our SYN, drop the input.
818	 *	if seg contains a RST, then drop the connection.
819	 *	if seg does not contain SYN, then drop it.
820	 * Otherwise this is an acceptable SYN segment
821	 *	initialize tp->rcv_nxt and tp->irs
822	 *	if seg contains ack then advance tp->snd_una
823	 *	if SYN has been acked change to ESTABLISHED else SYN_RCVD state
824	 *	arrange for segment to be acked (eventually)
825	 *	continue processing rest of data/controls, beginning with URG
826	 */
827	case TCPS_SYN_SENT:
828		if ((taop = tcp_gettaocache(inp)) == NULL) {
829			taop = &tao_noncached;
830			bzero(taop, sizeof(*taop));
831		}
832
833		if ((tiflags & TH_ACK) &&
834		    (SEQ_LEQ(ti->ti_ack, tp->iss) ||
835		     SEQ_GT(ti->ti_ack, tp->snd_max))) {
836			/*
837			 * If we have a cached CCsent for the remote host,
838			 * hence we haven't just crashed and restarted,
839			 * do not send a RST.  This may be a retransmission
840			 * from the other side after our earlier ACK was lost.
841			 * Our new SYN, when it arrives, will serve as the
842			 * needed ACK.
843			 */
844			if (taop->tao_ccsent != 0)
845				goto drop;
846			else
847				goto dropwithreset;
848		}
849		if (tiflags & TH_RST) {
850			if (tiflags & TH_ACK)
851				tp = tcp_drop(tp, ECONNREFUSED);
852			goto drop;
853		}
854		if ((tiflags & TH_SYN) == 0)
855			goto drop;
856		tp->snd_wnd = ti->ti_win;	/* initial send window */
857		tp->cc_recv = to.to_cc;		/* foreign CC */
858
859		tp->irs = ti->ti_seq;
860		tcp_rcvseqinit(tp);
861		if (tiflags & TH_ACK) {
862			/*
863			 * Our SYN was acked.  If segment contains CC.ECHO
864			 * option, check it to make sure this segment really
865			 * matches our SYN.  If not, just drop it as old
866			 * duplicate, but send an RST if we're still playing
867			 * by the old rules.  If no CC.ECHO option, make sure
868			 * we don't get fooled into using T/TCP.
869			 */
870			if (to.to_flag & TOF_CCECHO) {
871				if (tp->cc_send != to.to_ccecho) {
872					if (taop->tao_ccsent != 0)
873						goto drop;
874					else
875						goto dropwithreset;
876				}
877			} else
878				tp->t_flags &= ~TF_RCVD_CC;
879			tcpstat.tcps_connects++;
880			soisconnected(so);
881			/* Do window scaling on this connection? */
882			if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
883				(TF_RCVD_SCALE|TF_REQ_SCALE)) {
884				tp->snd_scale = tp->requested_s_scale;
885				tp->rcv_scale = tp->request_r_scale;
886			}
887			/* Segment is acceptable, update cache if undefined. */
888			if (taop->tao_ccsent == 0)
889				taop->tao_ccsent = to.to_ccecho;
890
891			tp->rcv_adv += tp->rcv_wnd;
892			tp->snd_una++;		/* SYN is acked */
893			/*
894			 * If there's data, delay ACK; if there's also a FIN
895			 * ACKNOW will be turned on later.
896			 */
897			if (tcp_delack_enabled && ti->ti_len != 0)
898				tp->t_flags |= TF_DELACK;
899			else
900				tp->t_flags |= TF_ACKNOW;
901			/*
902			 * Received <SYN,ACK> in SYN_SENT[*] state.
903			 * Transitions:
904			 *	SYN_SENT  --> ESTABLISHED
905			 *	SYN_SENT* --> FIN_WAIT_1
906			 */
907			if (tp->t_flags & TF_NEEDFIN) {
908				tp->t_state = TCPS_FIN_WAIT_1;
909				tp->t_flags &= ~TF_NEEDFIN;
910				tiflags &= ~TH_SYN;
911			} else {
912				tp->t_state = TCPS_ESTABLISHED;
913				tp->t_timer[TCPT_KEEP] = tcp_keepidle;
914			}
915		} else {
916		/*
917		 *  Received initial SYN in SYN-SENT[*] state => simul-
918		 *  taneous open.  If segment contains CC option and there is
919		 *  a cached CC, apply TAO test; if it succeeds, connection is
920		 *  half-synchronized.  Otherwise, do 3-way handshake:
921		 *        SYN-SENT -> SYN-RECEIVED
922		 *        SYN-SENT* -> SYN-RECEIVED*
923		 *  If there was no CC option, clear cached CC value.
924		 */
925			tp->t_flags |= TF_ACKNOW;
926			tp->t_timer[TCPT_REXMT] = 0;
927			if (to.to_flag & TOF_CC) {
928				if (taop->tao_cc != 0 &&
929				    CC_GT(to.to_cc, taop->tao_cc)) {
930					/*
931					 * update cache and make transition:
932					 *        SYN-SENT -> ESTABLISHED*
933					 *        SYN-SENT* -> FIN-WAIT-1*
934					 */
935					taop->tao_cc = to.to_cc;
936					if (tp->t_flags & TF_NEEDFIN) {
937						tp->t_state = TCPS_FIN_WAIT_1;
938						tp->t_flags &= ~TF_NEEDFIN;
939					} else {
940						tp->t_state = TCPS_ESTABLISHED;
941						tp->t_timer[TCPT_KEEP] = tcp_keepidle;
942					}
943					tp->t_flags |= TF_NEEDSYN;
944				} else
945					tp->t_state = TCPS_SYN_RECEIVED;
946			} else {
947				/* CC.NEW or no option => invalidate cache */
948				taop->tao_cc = 0;
949				tp->t_state = TCPS_SYN_RECEIVED;
950			}
951		}
952
953trimthenstep6:
954		/*
955		 * Advance ti->ti_seq to correspond to first data byte.
956		 * If data, trim to stay within window,
957		 * dropping FIN if necessary.
958		 */
959		ti->ti_seq++;
960		if (ti->ti_len > tp->rcv_wnd) {
961			todrop = ti->ti_len - tp->rcv_wnd;
962			m_adj(m, -todrop);
963			ti->ti_len = tp->rcv_wnd;
964			tiflags &= ~TH_FIN;
965			tcpstat.tcps_rcvpackafterwin++;
966			tcpstat.tcps_rcvbyteafterwin += todrop;
967		}
968		tp->snd_wl1 = ti->ti_seq - 1;
969		tp->rcv_up = ti->ti_seq;
970		/*
971		 *  Client side of transaction: already sent SYN and data.
972		 *  If the remote host used T/TCP to validate the SYN,
973		 *  our data will be ACK'd; if so, enter normal data segment
974		 *  processing in the middle of step 5, ack processing.
975		 *  Otherwise, goto step 6.
976		 */
977 		if (tiflags & TH_ACK)
978			goto process_ACK;
979		goto step6;
980	/*
981	 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
982	 *	if segment contains a SYN and CC [not CC.NEW] option:
983	 *              if state == TIME_WAIT and connection duration > MSL,
984	 *                  drop packet and send RST;
985	 *
986	 *		if SEG.CC > CCrecv then is new SYN, and can implicitly
987	 *		    ack the FIN (and data) in retransmission queue.
988	 *                  Complete close and delete TCPCB.  Then reprocess
989	 *                  segment, hoping to find new TCPCB in LISTEN state;
990	 *
991	 *		else must be old SYN; drop it.
992	 *      else do normal processing.
993	 */
994	case TCPS_LAST_ACK:
995	case TCPS_CLOSING:
996	case TCPS_TIME_WAIT:
997		if ((tiflags & TH_SYN) &&
998		    (to.to_flag & TOF_CC) && tp->cc_recv != 0) {
999			if (tp->t_state == TCPS_TIME_WAIT &&
1000					tp->t_duration > TCPTV_MSL)
1001				goto dropwithreset;
1002			if (CC_GT(to.to_cc, tp->cc_recv)) {
1003				tp = tcp_close(tp);
1004				goto findpcb;
1005			}
1006			else
1007				goto drop;
1008		}
1009 		break;  /* continue normal processing */
1010	}
1011
1012	/*
1013	 * States other than LISTEN or SYN_SENT.
1014	 * First check the RST flag and sequence number since reset segments
1015	 * are exempt from the timestamp and connection count tests.  This
1016	 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
1017	 * below which allowed reset segments in half the sequence space
1018	 * to fall though and be processed (which gives forged reset
1019	 * segments with a random sequence number a 50 percent chance of
1020	 * killing a connection).
1021	 * Then check timestamp, if present.
1022	 * Then check the connection count, if present.
1023	 * Then check that at least some bytes of segment are within
1024	 * receive window.  If segment begins before rcv_nxt,
1025	 * drop leading data (and SYN); if nothing left, just ack.
1026	 *
1027	 *
1028	 * If the RST bit is set, check the sequence number to see
1029	 * if this is a valid reset segment.
1030	 * RFC 793 page 37:
1031	 *   In all states except SYN-SENT, all reset (RST) segments
1032	 *   are validated by checking their SEQ-fields.  A reset is
1033	 *   valid if its sequence number is in the window.
1034	 * Note: this does not take into account delayed ACKs, so
1035	 *   we should test against last_ack_sent instead of rcv_nxt.
1036	 *   Also, it does not make sense to allow reset segments with
1037	 *   sequence numbers greater than last_ack_sent to be processed
1038	 *   since these sequence numbers are just the acknowledgement
1039	 *   numbers in our outgoing packets being echoed back at us,
1040	 *   and these acknowledgement numbers are monotonically
1041	 *   increasing.
1042	 * If we have multiple segments in flight, the intial reset
1043	 * segment sequence numbers will be to the left of last_ack_sent,
1044	 * but they will eventually catch up.
1045	 * In any case, it never made sense to trim reset segments to
1046	 * fit the receive window since RFC 1122 says:
1047	 *   4.2.2.12  RST Segment: RFC-793 Section 3.4
1048	 *
1049	 *    A TCP SHOULD allow a received RST segment to include data.
1050	 *
1051	 *    DISCUSSION
1052	 *         It has been suggested that a RST segment could contain
1053	 *         ASCII text that encoded and explained the cause of the
1054	 *         RST.  No standard has yet been established for such
1055	 *         data.
1056	 *
1057	 * If the reset segment passes the sequence number test examine
1058	 * the state:
1059	 *    SYN_RECEIVED STATE:
1060	 *	If passive open, return to LISTEN state.
1061	 *	If active open, inform user that connection was refused.
1062	 *    ESTABLISHED, FIN_WAIT_1, FIN_WAIT2, CLOSE_WAIT STATES:
1063	 *	Inform user that connection was reset, and close tcb.
1064	 *    CLOSING, LAST_ACK STATES:
1065	 *	Close the tcb.
1066	 *    TIME_WAIT STATE:
1067	 *	Drop the segment - see Stevens, vol. 2, p. 964 and
1068	 *      RFC 1337.
1069	 */
1070	if (tiflags & TH_RST) {
1071		if (tp->last_ack_sent == ti->ti_seq) {
1072			switch (tp->t_state) {
1073
1074			case TCPS_SYN_RECEIVED:
1075				so->so_error = ECONNREFUSED;
1076				goto close;
1077
1078			case TCPS_ESTABLISHED:
1079			case TCPS_FIN_WAIT_1:
1080			case TCPS_FIN_WAIT_2:
1081			case TCPS_CLOSE_WAIT:
1082				so->so_error = ECONNRESET;
1083			close:
1084				tp->t_state = TCPS_CLOSED;
1085				tcpstat.tcps_drops++;
1086				tp = tcp_close(tp);
1087				break;
1088
1089			case TCPS_CLOSING:
1090			case TCPS_LAST_ACK:
1091				tp = tcp_close(tp);
1092				break;
1093
1094			case TCPS_TIME_WAIT:
1095				break;
1096			}
1097		}
1098		goto drop;
1099	}
1100
1101	/*
1102	 * RFC 1323 PAWS: If we have a timestamp reply on this segment
1103	 * and it's less than ts_recent, drop it.
1104	 */
1105	if ((to.to_flag & TOF_TS) != 0 && tp->ts_recent &&
1106	    TSTMP_LT(to.to_tsval, tp->ts_recent)) {
1107
1108		/* Check to see if ts_recent is over 24 days old.  */
1109		if ((int)(tcp_now - tp->ts_recent_age) > TCP_PAWS_IDLE) {
1110			/*
1111			 * Invalidate ts_recent.  If this segment updates
1112			 * ts_recent, the age will be reset later and ts_recent
1113			 * will get a valid value.  If it does not, setting
1114			 * ts_recent to zero will at least satisfy the
1115			 * requirement that zero be placed in the timestamp
1116			 * echo reply when ts_recent isn't valid.  The
1117			 * age isn't reset until we get a valid ts_recent
1118			 * because we don't want out-of-order segments to be
1119			 * dropped when ts_recent is old.
1120			 */
1121			tp->ts_recent = 0;
1122		} else {
1123			tcpstat.tcps_rcvduppack++;
1124			tcpstat.tcps_rcvdupbyte += ti->ti_len;
1125			tcpstat.tcps_pawsdrop++;
1126			goto dropafterack;
1127		}
1128	}
1129
1130	/*
1131	 * T/TCP mechanism
1132	 *   If T/TCP was negotiated and the segment doesn't have CC,
1133	 *   or if its CC is wrong then drop the segment.
1134	 *   RST segments do not have to comply with this.
1135	 */
1136	if ((tp->t_flags & (TF_REQ_CC|TF_RCVD_CC)) == (TF_REQ_CC|TF_RCVD_CC) &&
1137	    ((to.to_flag & TOF_CC) == 0 || tp->cc_recv != to.to_cc))
1138 		goto dropafterack;
1139
1140	/*
1141	 * In the SYN-RECEIVED state, validate that the packet belongs to
1142	 * this connection before trimming the data to fit the receive
1143	 * window.  Check the sequence number versus IRS since we know
1144	 * the sequence numbers haven't wrapped.  This is a partial fix
1145	 * for the "LAND" DoS attack.
1146	 */
1147	if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(ti->ti_seq, tp->irs))
1148		goto dropwithreset;
1149
1150	todrop = tp->rcv_nxt - ti->ti_seq;
1151	if (todrop > 0) {
1152		if (tiflags & TH_SYN) {
1153			tiflags &= ~TH_SYN;
1154			ti->ti_seq++;
1155			if (ti->ti_urp > 1)
1156				ti->ti_urp--;
1157			else
1158				tiflags &= ~TH_URG;
1159			todrop--;
1160		}
1161		/*
1162		 * Following if statement from Stevens, vol. 2, p. 960.
1163		 */
1164		if (todrop > ti->ti_len
1165		    || (todrop == ti->ti_len && (tiflags & TH_FIN) == 0)) {
1166			/*
1167			 * Any valid FIN must be to the left of the window.
1168			 * At this point the FIN must be a duplicate or out
1169			 * of sequence; drop it.
1170			 */
1171			tiflags &= ~TH_FIN;
1172
1173			/*
1174			 * Send an ACK to resynchronize and drop any data.
1175			 * But keep on processing for RST or ACK.
1176			 */
1177			tp->t_flags |= TF_ACKNOW;
1178			todrop = ti->ti_len;
1179			tcpstat.tcps_rcvduppack++;
1180			tcpstat.tcps_rcvdupbyte += todrop;
1181		} else {
1182			tcpstat.tcps_rcvpartduppack++;
1183			tcpstat.tcps_rcvpartdupbyte += todrop;
1184		}
1185		m_adj(m, todrop);
1186		ti->ti_seq += todrop;
1187		ti->ti_len -= todrop;
1188		if (ti->ti_urp > todrop)
1189			ti->ti_urp -= todrop;
1190		else {
1191			tiflags &= ~TH_URG;
1192			ti->ti_urp = 0;
1193		}
1194	}
1195
1196	/*
1197	 * If new data are received on a connection after the
1198	 * user processes are gone, then RST the other end.
1199	 */
1200	if ((so->so_state & SS_NOFDREF) &&
1201	    tp->t_state > TCPS_CLOSE_WAIT && ti->ti_len) {
1202		tp = tcp_close(tp);
1203		tcpstat.tcps_rcvafterclose++;
1204		goto dropwithreset;
1205	}
1206
1207	/*
1208	 * If segment ends after window, drop trailing data
1209	 * (and PUSH and FIN); if nothing left, just ACK.
1210	 */
1211	todrop = (ti->ti_seq+ti->ti_len) - (tp->rcv_nxt+tp->rcv_wnd);
1212	if (todrop > 0) {
1213		tcpstat.tcps_rcvpackafterwin++;
1214		if (todrop >= ti->ti_len) {
1215			tcpstat.tcps_rcvbyteafterwin += ti->ti_len;
1216			/*
1217			 * If a new connection request is received
1218			 * while in TIME_WAIT, drop the old connection
1219			 * and start over if the sequence numbers
1220			 * are above the previous ones.
1221			 */
1222			if (tiflags & TH_SYN &&
1223			    tp->t_state == TCPS_TIME_WAIT &&
1224			    SEQ_GT(ti->ti_seq, tp->rcv_nxt)) {
1225				iss = tp->snd_nxt + TCP_ISSINCR;
1226				tp = tcp_close(tp);
1227				goto findpcb;
1228			}
1229			/*
1230			 * If window is closed can only take segments at
1231			 * window edge, and have to drop data and PUSH from
1232			 * incoming segments.  Continue processing, but
1233			 * remember to ack.  Otherwise, drop segment
1234			 * and ack.
1235			 */
1236			if (tp->rcv_wnd == 0 && ti->ti_seq == tp->rcv_nxt) {
1237				tp->t_flags |= TF_ACKNOW;
1238				tcpstat.tcps_rcvwinprobe++;
1239			} else
1240				goto dropafterack;
1241		} else
1242			tcpstat.tcps_rcvbyteafterwin += todrop;
1243		m_adj(m, -todrop);
1244		ti->ti_len -= todrop;
1245		tiflags &= ~(TH_PUSH|TH_FIN);
1246	}
1247
1248	/*
1249	 * If last ACK falls within this segment's sequence numbers,
1250	 * record its timestamp.
1251	 * NOTE that the test is modified according to the latest
1252	 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1253	 */
1254	if ((to.to_flag & TOF_TS) != 0 &&
1255	    SEQ_LEQ(ti->ti_seq, tp->last_ack_sent)) {
1256		tp->ts_recent_age = tcp_now;
1257		tp->ts_recent = to.to_tsval;
1258	}
1259
1260	/*
1261	 * If a SYN is in the window, then this is an
1262	 * error and we send an RST and drop the connection.
1263	 */
1264	if (tiflags & TH_SYN) {
1265		tp = tcp_drop(tp, ECONNRESET);
1266		goto dropwithreset;
1267	}
1268
1269	/*
1270	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN
1271	 * flag is on (half-synchronized state), then queue data for
1272	 * later processing; else drop segment and return.
1273	 */
1274	if ((tiflags & TH_ACK) == 0) {
1275		if (tp->t_state == TCPS_SYN_RECEIVED ||
1276		    (tp->t_flags & TF_NEEDSYN))
1277			goto step6;
1278		else
1279			goto drop;
1280	}
1281
1282	/*
1283	 * Ack processing.
1284	 */
1285	switch (tp->t_state) {
1286
1287	/*
1288	 * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
1289	 * ESTABLISHED state and continue processing.
1290	 * The ACK was checked above.
1291	 */
1292	case TCPS_SYN_RECEIVED:
1293
1294		tcpstat.tcps_connects++;
1295		soisconnected(so);
1296		/* Do window scaling? */
1297		if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1298			(TF_RCVD_SCALE|TF_REQ_SCALE)) {
1299			tp->snd_scale = tp->requested_s_scale;
1300			tp->rcv_scale = tp->request_r_scale;
1301		}
1302		/*
1303		 * Upon successful completion of 3-way handshake,
1304		 * update cache.CC if it was undefined, pass any queued
1305		 * data to the user, and advance state appropriately.
1306		 */
1307		if ((taop = tcp_gettaocache(inp)) != NULL &&
1308		    taop->tao_cc == 0)
1309			taop->tao_cc = tp->cc_recv;
1310
1311		/*
1312		 * Make transitions:
1313		 *      SYN-RECEIVED  -> ESTABLISHED
1314		 *      SYN-RECEIVED* -> FIN-WAIT-1
1315		 */
1316		if (tp->t_flags & TF_NEEDFIN) {
1317			tp->t_state = TCPS_FIN_WAIT_1;
1318			tp->t_flags &= ~TF_NEEDFIN;
1319		} else {
1320			tp->t_state = TCPS_ESTABLISHED;
1321			tp->t_timer[TCPT_KEEP] = tcp_keepidle;
1322		}
1323		/*
1324		 * If segment contains data or ACK, will call tcp_reass()
1325		 * later; if not, do so now to pass queued data to user.
1326		 */
1327		if (ti->ti_len == 0 && (tiflags & TH_FIN) == 0)
1328			(void) tcp_reass(tp, (struct tcpiphdr *)0,
1329			    (struct mbuf *)0);
1330		tp->snd_wl1 = ti->ti_seq - 1;
1331		/* fall into ... */
1332
1333	/*
1334	 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
1335	 * ACKs.  If the ack is in the range
1336	 *	tp->snd_una < ti->ti_ack <= tp->snd_max
1337	 * then advance tp->snd_una to ti->ti_ack and drop
1338	 * data from the retransmission queue.  If this ACK reflects
1339	 * more up to date window information we update our window information.
1340	 */
1341	case TCPS_ESTABLISHED:
1342	case TCPS_FIN_WAIT_1:
1343	case TCPS_FIN_WAIT_2:
1344	case TCPS_CLOSE_WAIT:
1345	case TCPS_CLOSING:
1346	case TCPS_LAST_ACK:
1347	case TCPS_TIME_WAIT:
1348
1349		if (SEQ_LEQ(ti->ti_ack, tp->snd_una)) {
1350			if (ti->ti_len == 0 && tiwin == tp->snd_wnd) {
1351				tcpstat.tcps_rcvdupack++;
1352				/*
1353				 * If we have outstanding data (other than
1354				 * a window probe), this is a completely
1355				 * duplicate ack (ie, window info didn't
1356				 * change), the ack is the biggest we've
1357				 * seen and we've seen exactly our rexmt
1358				 * threshhold of them, assume a packet
1359				 * has been dropped and retransmit it.
1360				 * Kludge snd_nxt & the congestion
1361				 * window so we send only this one
1362				 * packet.
1363				 *
1364				 * We know we're losing at the current
1365				 * window size so do congestion avoidance
1366				 * (set ssthresh to half the current window
1367				 * and pull our congestion window back to
1368				 * the new ssthresh).
1369				 *
1370				 * Dup acks mean that packets have left the
1371				 * network (they're now cached at the receiver)
1372				 * so bump cwnd by the amount in the receiver
1373				 * to keep a constant cwnd packets in the
1374				 * network.
1375				 */
1376				if (tp->t_timer[TCPT_REXMT] == 0 ||
1377				    ti->ti_ack != tp->snd_una)
1378					tp->t_dupacks = 0;
1379				else if (++tp->t_dupacks == tcprexmtthresh) {
1380					tcp_seq onxt = tp->snd_nxt;
1381					u_int win =
1382					    min(tp->snd_wnd, tp->snd_cwnd) / 2 /
1383						tp->t_maxseg;
1384
1385					if (win < 2)
1386						win = 2;
1387					tp->snd_ssthresh = win * tp->t_maxseg;
1388					tp->t_timer[TCPT_REXMT] = 0;
1389					tp->t_rtt = 0;
1390					tp->snd_nxt = ti->ti_ack;
1391					tp->snd_cwnd = tp->t_maxseg;
1392					(void) tcp_output(tp);
1393					tp->snd_cwnd = tp->snd_ssthresh +
1394					       tp->t_maxseg * tp->t_dupacks;
1395					if (SEQ_GT(onxt, tp->snd_nxt))
1396						tp->snd_nxt = onxt;
1397					goto drop;
1398				} else if (tp->t_dupacks > tcprexmtthresh) {
1399					tp->snd_cwnd += tp->t_maxseg;
1400					(void) tcp_output(tp);
1401					goto drop;
1402				}
1403			} else
1404				tp->t_dupacks = 0;
1405			break;
1406		}
1407		/*
1408		 * If the congestion window was inflated to account
1409		 * for the other side's cached packets, retract it.
1410		 */
1411		if (tp->t_dupacks >= tcprexmtthresh &&
1412		    tp->snd_cwnd > tp->snd_ssthresh)
1413			tp->snd_cwnd = tp->snd_ssthresh;
1414		tp->t_dupacks = 0;
1415		if (SEQ_GT(ti->ti_ack, tp->snd_max)) {
1416			tcpstat.tcps_rcvacktoomuch++;
1417			goto dropafterack;
1418		}
1419		/*
1420		 *  If we reach this point, ACK is not a duplicate,
1421		 *     i.e., it ACKs something we sent.
1422		 */
1423		if (tp->t_flags & TF_NEEDSYN) {
1424			/*
1425			 * T/TCP: Connection was half-synchronized, and our
1426			 * SYN has been ACK'd (so connection is now fully
1427			 * synchronized).  Go to non-starred state,
1428			 * increment snd_una for ACK of SYN, and check if
1429			 * we can do window scaling.
1430			 */
1431			tp->t_flags &= ~TF_NEEDSYN;
1432			tp->snd_una++;
1433			/* Do window scaling? */
1434			if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1435				(TF_RCVD_SCALE|TF_REQ_SCALE)) {
1436				tp->snd_scale = tp->requested_s_scale;
1437				tp->rcv_scale = tp->request_r_scale;
1438			}
1439		}
1440
1441process_ACK:
1442		acked = ti->ti_ack - tp->snd_una;
1443		tcpstat.tcps_rcvackpack++;
1444		tcpstat.tcps_rcvackbyte += acked;
1445
1446		/*
1447		 * If we have a timestamp reply, update smoothed
1448		 * round trip time.  If no timestamp is present but
1449		 * transmit timer is running and timed sequence
1450		 * number was acked, update smoothed round trip time.
1451		 * Since we now have an rtt measurement, cancel the
1452		 * timer backoff (cf., Phil Karn's retransmit alg.).
1453		 * Recompute the initial retransmit timer.
1454		 */
1455		if (to.to_flag & TOF_TS)
1456			tcp_xmit_timer(tp, tcp_now - to.to_tsecr + 1);
1457		else if (tp->t_rtt && SEQ_GT(ti->ti_ack, tp->t_rtseq))
1458			tcp_xmit_timer(tp,tp->t_rtt);
1459
1460		/*
1461		 * If all outstanding data is acked, stop retransmit
1462		 * timer and remember to restart (more output or persist).
1463		 * If there is more data to be acked, restart retransmit
1464		 * timer, using current (possibly backed-off) value.
1465		 */
1466		if (ti->ti_ack == tp->snd_max) {
1467			tp->t_timer[TCPT_REXMT] = 0;
1468			needoutput = 1;
1469		} else if (tp->t_timer[TCPT_PERSIST] == 0)
1470			tp->t_timer[TCPT_REXMT] = tp->t_rxtcur;
1471
1472		/*
1473		 * If no data (only SYN) was ACK'd,
1474		 *    skip rest of ACK processing.
1475		 */
1476		if (acked == 0)
1477			goto step6;
1478
1479		/*
1480		 * When new data is acked, open the congestion window.
1481		 * If the window gives us less than ssthresh packets
1482		 * in flight, open exponentially (maxseg per packet).
1483		 * Otherwise open linearly: maxseg per window
1484		 * (maxseg^2 / cwnd per packet).
1485		 */
1486		{
1487		register u_int cw = tp->snd_cwnd;
1488		register u_int incr = tp->t_maxseg;
1489
1490		if (cw > tp->snd_ssthresh)
1491			incr = incr * incr / cw;
1492		tp->snd_cwnd = min(cw + incr, TCP_MAXWIN<<tp->snd_scale);
1493		}
1494		if (acked > so->so_snd.sb_cc) {
1495			tp->snd_wnd -= so->so_snd.sb_cc;
1496			sbdrop(&so->so_snd, (int)so->so_snd.sb_cc);
1497			ourfinisacked = 1;
1498		} else {
1499			sbdrop(&so->so_snd, acked);
1500			tp->snd_wnd -= acked;
1501			ourfinisacked = 0;
1502		}
1503		sowwakeup(so);
1504		tp->snd_una = ti->ti_ack;
1505		if (SEQ_LT(tp->snd_nxt, tp->snd_una))
1506			tp->snd_nxt = tp->snd_una;
1507
1508		switch (tp->t_state) {
1509
1510		/*
1511		 * In FIN_WAIT_1 STATE in addition to the processing
1512		 * for the ESTABLISHED state if our FIN is now acknowledged
1513		 * then enter FIN_WAIT_2.
1514		 */
1515		case TCPS_FIN_WAIT_1:
1516			if (ourfinisacked) {
1517				/*
1518				 * If we can't receive any more
1519				 * data, then closing user can proceed.
1520				 * Starting the timer is contrary to the
1521				 * specification, but if we don't get a FIN
1522				 * we'll hang forever.
1523				 */
1524				if (so->so_state & SS_CANTRCVMORE) {
1525					soisdisconnected(so);
1526					tp->t_timer[TCPT_2MSL] = tcp_maxidle;
1527				}
1528				tp->t_state = TCPS_FIN_WAIT_2;
1529			}
1530			break;
1531
1532	 	/*
1533		 * In CLOSING STATE in addition to the processing for
1534		 * the ESTABLISHED state if the ACK acknowledges our FIN
1535		 * then enter the TIME-WAIT state, otherwise ignore
1536		 * the segment.
1537		 */
1538		case TCPS_CLOSING:
1539			if (ourfinisacked) {
1540				tp->t_state = TCPS_TIME_WAIT;
1541				tcp_canceltimers(tp);
1542				/* Shorten TIME_WAIT [RFC-1644, p.28] */
1543				if (tp->cc_recv != 0 &&
1544				    tp->t_duration < TCPTV_MSL)
1545					tp->t_timer[TCPT_2MSL] =
1546					    tp->t_rxtcur * TCPTV_TWTRUNC;
1547				else
1548					tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
1549				soisdisconnected(so);
1550			}
1551			break;
1552
1553		/*
1554		 * In LAST_ACK, we may still be waiting for data to drain
1555		 * and/or to be acked, as well as for the ack of our FIN.
1556		 * If our FIN is now acknowledged, delete the TCB,
1557		 * enter the closed state and return.
1558		 */
1559		case TCPS_LAST_ACK:
1560			if (ourfinisacked) {
1561				tp = tcp_close(tp);
1562				goto drop;
1563			}
1564			break;
1565
1566		/*
1567		 * In TIME_WAIT state the only thing that should arrive
1568		 * is a retransmission of the remote FIN.  Acknowledge
1569		 * it and restart the finack timer.
1570		 */
1571		case TCPS_TIME_WAIT:
1572			tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
1573			goto dropafterack;
1574		}
1575	}
1576
1577step6:
1578	/*
1579	 * Update window information.
1580	 * Don't look at window if no ACK: TAC's send garbage on first SYN.
1581	 */
1582	if ((tiflags & TH_ACK) &&
1583	    (SEQ_LT(tp->snd_wl1, ti->ti_seq) ||
1584	    (tp->snd_wl1 == ti->ti_seq && (SEQ_LT(tp->snd_wl2, ti->ti_ack) ||
1585	     (tp->snd_wl2 == ti->ti_ack && tiwin > tp->snd_wnd))))) {
1586		/* keep track of pure window updates */
1587		if (ti->ti_len == 0 &&
1588		    tp->snd_wl2 == ti->ti_ack && tiwin > tp->snd_wnd)
1589			tcpstat.tcps_rcvwinupd++;
1590		tp->snd_wnd = tiwin;
1591		tp->snd_wl1 = ti->ti_seq;
1592		tp->snd_wl2 = ti->ti_ack;
1593		if (tp->snd_wnd > tp->max_sndwnd)
1594			tp->max_sndwnd = tp->snd_wnd;
1595		needoutput = 1;
1596	}
1597
1598	/*
1599	 * Process segments with URG.
1600	 */
1601	if ((tiflags & TH_URG) && ti->ti_urp &&
1602	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
1603		/*
1604		 * This is a kludge, but if we receive and accept
1605		 * random urgent pointers, we'll crash in
1606		 * soreceive.  It's hard to imagine someone
1607		 * actually wanting to send this much urgent data.
1608		 */
1609		if (ti->ti_urp + so->so_rcv.sb_cc > sb_max) {
1610			ti->ti_urp = 0;			/* XXX */
1611			tiflags &= ~TH_URG;		/* XXX */
1612			goto dodata;			/* XXX */
1613		}
1614		/*
1615		 * If this segment advances the known urgent pointer,
1616		 * then mark the data stream.  This should not happen
1617		 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
1618		 * a FIN has been received from the remote side.
1619		 * In these states we ignore the URG.
1620		 *
1621		 * According to RFC961 (Assigned Protocols),
1622		 * the urgent pointer points to the last octet
1623		 * of urgent data.  We continue, however,
1624		 * to consider it to indicate the first octet
1625		 * of data past the urgent section as the original
1626		 * spec states (in one of two places).
1627		 */
1628		if (SEQ_GT(ti->ti_seq+ti->ti_urp, tp->rcv_up)) {
1629			tp->rcv_up = ti->ti_seq + ti->ti_urp;
1630			so->so_oobmark = so->so_rcv.sb_cc +
1631			    (tp->rcv_up - tp->rcv_nxt) - 1;
1632			if (so->so_oobmark == 0)
1633				so->so_state |= SS_RCVATMARK;
1634			sohasoutofband(so);
1635			tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
1636		}
1637		/*
1638		 * Remove out of band data so doesn't get presented to user.
1639		 * This can happen independent of advancing the URG pointer,
1640		 * but if two URG's are pending at once, some out-of-band
1641		 * data may creep in... ick.
1642		 */
1643		if (ti->ti_urp <= (u_long)ti->ti_len
1644#ifdef SO_OOBINLINE
1645		     && (so->so_options & SO_OOBINLINE) == 0
1646#endif
1647		     )
1648			tcp_pulloutofband(so, ti, m);
1649	} else
1650		/*
1651		 * If no out of band data is expected,
1652		 * pull receive urgent pointer along
1653		 * with the receive window.
1654		 */
1655		if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
1656			tp->rcv_up = tp->rcv_nxt;
1657dodata:							/* XXX */
1658
1659	/*
1660	 * Process the segment text, merging it into the TCP sequencing queue,
1661	 * and arranging for acknowledgment of receipt if necessary.
1662	 * This process logically involves adjusting tp->rcv_wnd as data
1663	 * is presented to the user (this happens in tcp_usrreq.c,
1664	 * case PRU_RCVD).  If a FIN has already been received on this
1665	 * connection then we just ignore the text.
1666	 */
1667	if ((ti->ti_len || (tiflags&TH_FIN)) &&
1668	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
1669		TCP_REASS(tp, ti, m, so, tiflags);
1670		/*
1671		 * Note the amount of data that peer has sent into
1672		 * our window, in order to estimate the sender's
1673		 * buffer size.
1674		 */
1675		len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
1676	} else {
1677		m_freem(m);
1678		tiflags &= ~TH_FIN;
1679	}
1680
1681	/*
1682	 * If FIN is received ACK the FIN and let the user know
1683	 * that the connection is closing.
1684	 */
1685	if (tiflags & TH_FIN) {
1686		if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
1687			socantrcvmore(so);
1688			/*
1689			 *  If connection is half-synchronized
1690			 *  (ie NEEDSYN flag on) then delay ACK,
1691			 *  so it may be piggybacked when SYN is sent.
1692			 *  Otherwise, since we received a FIN then no
1693			 *  more input can be expected, send ACK now.
1694			 */
1695			if (tcp_delack_enabled && (tp->t_flags & TF_NEEDSYN))
1696				tp->t_flags |= TF_DELACK;
1697			else
1698				tp->t_flags |= TF_ACKNOW;
1699			tp->rcv_nxt++;
1700		}
1701		switch (tp->t_state) {
1702
1703	 	/*
1704		 * In SYN_RECEIVED and ESTABLISHED STATES
1705		 * enter the CLOSE_WAIT state.
1706		 */
1707		case TCPS_SYN_RECEIVED:
1708		case TCPS_ESTABLISHED:
1709			tp->t_state = TCPS_CLOSE_WAIT;
1710			break;
1711
1712	 	/*
1713		 * If still in FIN_WAIT_1 STATE FIN has not been acked so
1714		 * enter the CLOSING state.
1715		 */
1716		case TCPS_FIN_WAIT_1:
1717			tp->t_state = TCPS_CLOSING;
1718			break;
1719
1720	 	/*
1721		 * In FIN_WAIT_2 state enter the TIME_WAIT state,
1722		 * starting the time-wait timer, turning off the other
1723		 * standard timers.
1724		 */
1725		case TCPS_FIN_WAIT_2:
1726			tp->t_state = TCPS_TIME_WAIT;
1727			tcp_canceltimers(tp);
1728			/* Shorten TIME_WAIT [RFC-1644, p.28] */
1729			if (tp->cc_recv != 0 &&
1730			    tp->t_duration < TCPTV_MSL) {
1731				tp->t_timer[TCPT_2MSL] =
1732				    tp->t_rxtcur * TCPTV_TWTRUNC;
1733				/* For transaction client, force ACK now. */
1734				tp->t_flags |= TF_ACKNOW;
1735			}
1736			else
1737				tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
1738			soisdisconnected(so);
1739			break;
1740
1741		/*
1742		 * In TIME_WAIT state restart the 2 MSL time_wait timer.
1743		 */
1744		case TCPS_TIME_WAIT:
1745			tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
1746			break;
1747		}
1748	}
1749#ifdef TCPDEBUG
1750	if (so->so_options & SO_DEBUG)
1751		tcp_trace(TA_INPUT, ostate, tp, &tcp_saveti, 0);
1752#endif
1753
1754	/*
1755	 * Return any desired output.
1756	 */
1757	if (needoutput || (tp->t_flags & TF_ACKNOW))
1758		(void) tcp_output(tp);
1759	return;
1760
1761dropafterack:
1762	/*
1763	 * Generate an ACK dropping incoming segment if it occupies
1764	 * sequence space, where the ACK reflects our state.
1765	 *
1766	 * We can now skip the test for the RST flag since all
1767	 * paths to this code happen after packets containing
1768	 * RST have been dropped.
1769	 *
1770	 * In the SYN-RECEIVED state, don't send an ACK unless the
1771	 * segment we received passes the SYN-RECEIVED ACK test.
1772	 * If it fails send a RST.  This breaks the loop in the
1773	 * "LAND" DoS attack, and also prevents an ACK storm
1774	 * between two listening ports that have been sent forged
1775	 * SYN segments, each with the source address of the other.
1776	 */
1777	if (tp->t_state == TCPS_SYN_RECEIVED && (tiflags & TH_ACK) &&
1778	    (SEQ_GT(tp->snd_una, ti->ti_ack) ||
1779	     SEQ_GT(ti->ti_ack, tp->snd_max)) )
1780		goto dropwithreset;
1781#ifdef TCPDEBUG
1782	if (so->so_options & SO_DEBUG)
1783		tcp_trace(TA_DROP, ostate, tp, &tcp_saveti, 0);
1784#endif
1785	m_freem(m);
1786	tp->t_flags |= TF_ACKNOW;
1787	(void) tcp_output(tp);
1788	return;
1789
1790dropwithreset:
1791	/*
1792	 * Generate a RST, dropping incoming segment.
1793	 * Make ACK acceptable to originator of segment.
1794	 * Don't bother to respond if destination was broadcast/multicast.
1795	 */
1796	if ((tiflags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST) ||
1797	    IN_MULTICAST(ntohl(ti->ti_dst.s_addr)))
1798		goto drop;
1799#ifdef TCPDEBUG
1800	if (tp == 0 || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
1801		tcp_trace(TA_DROP, ostate, tp, &tcp_saveti, 0);
1802#endif
1803	if (tiflags & TH_ACK)
1804		tcp_respond(tp, ti, m, (tcp_seq)0, ti->ti_ack, TH_RST);
1805	else {
1806		if (tiflags & TH_SYN)
1807			ti->ti_len++;
1808		tcp_respond(tp, ti, m, ti->ti_seq+ti->ti_len, (tcp_seq)0,
1809		    TH_RST|TH_ACK);
1810	}
1811	/* destroy temporarily created socket */
1812	if (dropsocket)
1813		(void) soabort(so);
1814	return;
1815
1816drop:
1817	/*
1818	 * Drop space held by incoming segment and return.
1819	 */
1820#ifdef TCPDEBUG
1821	if (tp == 0 || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
1822		tcp_trace(TA_DROP, ostate, tp, &tcp_saveti, 0);
1823#endif
1824	m_freem(m);
1825	/* destroy temporarily created socket */
1826	if (dropsocket)
1827		(void) soabort(so);
1828	return;
1829}
1830
1831static void
1832tcp_dooptions(tp, cp, cnt, ti, to)
1833	struct tcpcb *tp;
1834	u_char *cp;
1835	int cnt;
1836	struct tcpiphdr *ti;
1837	struct tcpopt *to;
1838{
1839	u_short mss = 0;
1840	int opt, optlen;
1841
1842	for (; cnt > 0; cnt -= optlen, cp += optlen) {
1843		opt = cp[0];
1844		if (opt == TCPOPT_EOL)
1845			break;
1846		if (opt == TCPOPT_NOP)
1847			optlen = 1;
1848		else {
1849			optlen = cp[1];
1850			if (optlen <= 0)
1851				break;
1852		}
1853		switch (opt) {
1854
1855		default:
1856			continue;
1857
1858		case TCPOPT_MAXSEG:
1859			if (optlen != TCPOLEN_MAXSEG)
1860				continue;
1861			if (!(ti->ti_flags & TH_SYN))
1862				continue;
1863			bcopy((char *) cp + 2, (char *) &mss, sizeof(mss));
1864			NTOHS(mss);
1865			break;
1866
1867		case TCPOPT_WINDOW:
1868			if (optlen != TCPOLEN_WINDOW)
1869				continue;
1870			if (!(ti->ti_flags & TH_SYN))
1871				continue;
1872			tp->t_flags |= TF_RCVD_SCALE;
1873			tp->requested_s_scale = min(cp[2], TCP_MAX_WINSHIFT);
1874			break;
1875
1876		case TCPOPT_TIMESTAMP:
1877			if (optlen != TCPOLEN_TIMESTAMP)
1878				continue;
1879			to->to_flag |= TOF_TS;
1880			bcopy((char *)cp + 2,
1881			    (char *)&to->to_tsval, sizeof(to->to_tsval));
1882			NTOHL(to->to_tsval);
1883			bcopy((char *)cp + 6,
1884			    (char *)&to->to_tsecr, sizeof(to->to_tsecr));
1885			NTOHL(to->to_tsecr);
1886
1887			/*
1888			 * A timestamp received in a SYN makes
1889			 * it ok to send timestamp requests and replies.
1890			 */
1891			if (ti->ti_flags & TH_SYN) {
1892				tp->t_flags |= TF_RCVD_TSTMP;
1893				tp->ts_recent = to->to_tsval;
1894				tp->ts_recent_age = tcp_now;
1895			}
1896			break;
1897		case TCPOPT_CC:
1898			if (optlen != TCPOLEN_CC)
1899				continue;
1900			to->to_flag |= TOF_CC;
1901			bcopy((char *)cp + 2,
1902			    (char *)&to->to_cc, sizeof(to->to_cc));
1903			NTOHL(to->to_cc);
1904			/*
1905			 * A CC or CC.new option received in a SYN makes
1906			 * it ok to send CC in subsequent segments.
1907			 */
1908			if (ti->ti_flags & TH_SYN)
1909				tp->t_flags |= TF_RCVD_CC;
1910			break;
1911		case TCPOPT_CCNEW:
1912			if (optlen != TCPOLEN_CC)
1913				continue;
1914			if (!(ti->ti_flags & TH_SYN))
1915				continue;
1916			to->to_flag |= TOF_CCNEW;
1917			bcopy((char *)cp + 2,
1918			    (char *)&to->to_cc, sizeof(to->to_cc));
1919			NTOHL(to->to_cc);
1920			/*
1921			 * A CC or CC.new option received in a SYN makes
1922			 * it ok to send CC in subsequent segments.
1923			 */
1924			tp->t_flags |= TF_RCVD_CC;
1925			break;
1926		case TCPOPT_CCECHO:
1927			if (optlen != TCPOLEN_CC)
1928				continue;
1929			if (!(ti->ti_flags & TH_SYN))
1930				continue;
1931			to->to_flag |= TOF_CCECHO;
1932			bcopy((char *)cp + 2,
1933			    (char *)&to->to_ccecho, sizeof(to->to_ccecho));
1934			NTOHL(to->to_ccecho);
1935			break;
1936		}
1937	}
1938	if (ti->ti_flags & TH_SYN)
1939		tcp_mss(tp, mss);	/* sets t_maxseg */
1940}
1941
1942/*
1943 * Pull out of band byte out of a segment so
1944 * it doesn't appear in the user's data queue.
1945 * It is still reflected in the segment length for
1946 * sequencing purposes.
1947 */
1948static void
1949tcp_pulloutofband(so, ti, m)
1950	struct socket *so;
1951	struct tcpiphdr *ti;
1952	register struct mbuf *m;
1953{
1954	int cnt = ti->ti_urp - 1;
1955
1956	while (cnt >= 0) {
1957		if (m->m_len > cnt) {
1958			char *cp = mtod(m, caddr_t) + cnt;
1959			struct tcpcb *tp = sototcpcb(so);
1960
1961			tp->t_iobc = *cp;
1962			tp->t_oobflags |= TCPOOB_HAVEDATA;
1963			bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
1964			m->m_len--;
1965			return;
1966		}
1967		cnt -= m->m_len;
1968		m = m->m_next;
1969		if (m == 0)
1970			break;
1971	}
1972	panic("tcp_pulloutofband");
1973}
1974
1975/*
1976 * Collect new round-trip time estimate
1977 * and update averages and current timeout.
1978 */
1979static void
1980tcp_xmit_timer(tp, rtt)
1981	register struct tcpcb *tp;
1982	short rtt;
1983{
1984	register int delta;
1985
1986	tcpstat.tcps_rttupdated++;
1987	tp->t_rttupdated++;
1988	if (tp->t_srtt != 0) {
1989		/*
1990		 * srtt is stored as fixed point with 5 bits after the
1991		 * binary point (i.e., scaled by 8).  The following magic
1992		 * is equivalent to the smoothing algorithm in rfc793 with
1993		 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
1994		 * point).  Adjust rtt to origin 0.
1995		 */
1996		delta = ((rtt - 1) << TCP_DELTA_SHIFT)
1997			- (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
1998
1999		if ((tp->t_srtt += delta) <= 0)
2000			tp->t_srtt = 1;
2001
2002		/*
2003		 * We accumulate a smoothed rtt variance (actually, a
2004		 * smoothed mean difference), then set the retransmit
2005		 * timer to smoothed rtt + 4 times the smoothed variance.
2006		 * rttvar is stored as fixed point with 4 bits after the
2007		 * binary point (scaled by 16).  The following is
2008		 * equivalent to rfc793 smoothing with an alpha of .75
2009		 * (rttvar = rttvar*3/4 + |delta| / 4).  This replaces
2010		 * rfc793's wired-in beta.
2011		 */
2012		if (delta < 0)
2013			delta = -delta;
2014		delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
2015		if ((tp->t_rttvar += delta) <= 0)
2016			tp->t_rttvar = 1;
2017	} else {
2018		/*
2019		 * No rtt measurement yet - use the unsmoothed rtt.
2020		 * Set the variance to half the rtt (so our first
2021		 * retransmit happens at 3*rtt).
2022		 */
2023		tp->t_srtt = rtt << TCP_RTT_SHIFT;
2024		tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
2025	}
2026	tp->t_rtt = 0;
2027	tp->t_rxtshift = 0;
2028
2029	/*
2030	 * the retransmit should happen at rtt + 4 * rttvar.
2031	 * Because of the way we do the smoothing, srtt and rttvar
2032	 * will each average +1/2 tick of bias.  When we compute
2033	 * the retransmit timer, we want 1/2 tick of rounding and
2034	 * 1 extra tick because of +-1/2 tick uncertainty in the
2035	 * firing of the timer.  The bias will give us exactly the
2036	 * 1.5 tick we need.  But, because the bias is
2037	 * statistical, we have to test that we don't drop below
2038	 * the minimum feasible timer (which is 2 ticks).
2039	 */
2040	TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
2041		      max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
2042
2043	/*
2044	 * We received an ack for a packet that wasn't retransmitted;
2045	 * it is probably safe to discard any error indications we've
2046	 * received recently.  This isn't quite right, but close enough
2047	 * for now (a route might have failed after we sent a segment,
2048	 * and the return path might not be symmetrical).
2049	 */
2050	tp->t_softerror = 0;
2051}
2052
2053/*
2054 * Determine a reasonable value for maxseg size.
2055 * If the route is known, check route for mtu.
2056 * If none, use an mss that can be handled on the outgoing
2057 * interface without forcing IP to fragment; if bigger than
2058 * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
2059 * to utilize large mbufs.  If no route is found, route has no mtu,
2060 * or the destination isn't local, use a default, hopefully conservative
2061 * size (usually 512 or the default IP max size, but no more than the mtu
2062 * of the interface), as we can't discover anything about intervening
2063 * gateways or networks.  We also initialize the congestion/slow start
2064 * window to be a single segment if the destination isn't local.
2065 * While looking at the routing entry, we also initialize other path-dependent
2066 * parameters from pre-set or cached values in the routing entry.
2067 *
2068 * Also take into account the space needed for options that we
2069 * send regularly.  Make maxseg shorter by that amount to assure
2070 * that we can send maxseg amount of data even when the options
2071 * are present.  Store the upper limit of the length of options plus
2072 * data in maxopd.
2073 *
2074 * NOTE that this routine is only called when we process an incoming
2075 * segment, for outgoing segments only tcp_mssopt is called.
2076 *
2077 * In case of T/TCP, we call this routine during implicit connection
2078 * setup as well (offer = -1), to initialize maxseg from the cached
2079 * MSS of our peer.
2080 */
2081void
2082tcp_mss(tp, offer)
2083	struct tcpcb *tp;
2084	int offer;
2085{
2086	register struct rtentry *rt;
2087	struct ifnet *ifp;
2088	register int rtt, mss;
2089	u_long bufsize;
2090	struct inpcb *inp;
2091	struct socket *so;
2092	struct rmxp_tao *taop;
2093	int origoffer = offer;
2094
2095	inp = tp->t_inpcb;
2096	if ((rt = tcp_rtlookup(inp)) == NULL) {
2097		tp->t_maxopd = tp->t_maxseg = tcp_mssdflt;
2098		return;
2099	}
2100	ifp = rt->rt_ifp;
2101	so = inp->inp_socket;
2102
2103	taop = rmx_taop(rt->rt_rmx);
2104	/*
2105	 * Offer == -1 means that we didn't receive SYN yet,
2106	 * use cached value in that case;
2107	 */
2108	if (offer == -1)
2109		offer = taop->tao_mssopt;
2110	/*
2111	 * Offer == 0 means that there was no MSS on the SYN segment,
2112	 * in this case we use tcp_mssdflt.
2113	 */
2114	if (offer == 0)
2115		offer = tcp_mssdflt;
2116	else
2117		/*
2118		 * Sanity check: make sure that maxopd will be large
2119		 * enough to allow some data on segments even is the
2120		 * all the option space is used (40bytes).  Otherwise
2121		 * funny things may happen in tcp_output.
2122		 */
2123		offer = max(offer, 64);
2124	taop->tao_mssopt = offer;
2125
2126	/*
2127	 * While we're here, check if there's an initial rtt
2128	 * or rttvar.  Convert from the route-table units
2129	 * to scaled multiples of the slow timeout timer.
2130	 */
2131	if (tp->t_srtt == 0 && (rtt = rt->rt_rmx.rmx_rtt)) {
2132		/*
2133		 * XXX the lock bit for RTT indicates that the value
2134		 * is also a minimum value; this is subject to time.
2135		 */
2136		if (rt->rt_rmx.rmx_locks & RTV_RTT)
2137			tp->t_rttmin = rtt / (RTM_RTTUNIT / PR_SLOWHZ);
2138		tp->t_srtt = rtt / (RTM_RTTUNIT / (PR_SLOWHZ * TCP_RTT_SCALE));
2139		tcpstat.tcps_usedrtt++;
2140		if (rt->rt_rmx.rmx_rttvar) {
2141			tp->t_rttvar = rt->rt_rmx.rmx_rttvar /
2142			    (RTM_RTTUNIT / (PR_SLOWHZ * TCP_RTTVAR_SCALE));
2143			tcpstat.tcps_usedrttvar++;
2144		} else {
2145			/* default variation is +- 1 rtt */
2146			tp->t_rttvar =
2147			    tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
2148		}
2149		TCPT_RANGESET(tp->t_rxtcur,
2150		    ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
2151		    tp->t_rttmin, TCPTV_REXMTMAX);
2152	}
2153	/*
2154	 * if there's an mtu associated with the route, use it
2155	 */
2156	if (rt->rt_rmx.rmx_mtu)
2157		mss = rt->rt_rmx.rmx_mtu - sizeof(struct tcpiphdr);
2158	else
2159	{
2160		mss = ifp->if_mtu - sizeof(struct tcpiphdr);
2161		if (!in_localaddr(inp->inp_faddr))
2162			mss = min(mss, tcp_mssdflt);
2163	}
2164	mss = min(mss, offer);
2165	/*
2166	 * maxopd stores the maximum length of data AND options
2167	 * in a segment; maxseg is the amount of data in a normal
2168	 * segment.  We need to store this value (maxopd) apart
2169	 * from maxseg, because now every segment carries options
2170	 * and thus we normally have somewhat less data in segments.
2171	 */
2172	tp->t_maxopd = mss;
2173
2174	/*
2175	 * In case of T/TCP, origoffer==-1 indicates, that no segments
2176	 * were received yet.  In this case we just guess, otherwise
2177	 * we do the same as before T/TCP.
2178	 */
2179 	if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
2180	    (origoffer == -1 ||
2181	     (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP))
2182		mss -= TCPOLEN_TSTAMP_APPA;
2183 	if ((tp->t_flags & (TF_REQ_CC|TF_NOOPT)) == TF_REQ_CC &&
2184	    (origoffer == -1 ||
2185	     (tp->t_flags & TF_RCVD_CC) == TF_RCVD_CC))
2186		mss -= TCPOLEN_CC_APPA;
2187
2188#if	(MCLBYTES & (MCLBYTES - 1)) == 0
2189		if (mss > MCLBYTES)
2190			mss &= ~(MCLBYTES-1);
2191#else
2192		if (mss > MCLBYTES)
2193			mss = mss / MCLBYTES * MCLBYTES;
2194#endif
2195	/*
2196	 * If there's a pipesize, change the socket buffer
2197	 * to that size.  Make the socket buffers an integral
2198	 * number of mss units; if the mss is larger than
2199	 * the socket buffer, decrease the mss.
2200	 */
2201#ifdef RTV_SPIPE
2202	if ((bufsize = rt->rt_rmx.rmx_sendpipe) == 0)
2203#endif
2204		bufsize = so->so_snd.sb_hiwat;
2205	if (bufsize < mss)
2206		mss = bufsize;
2207	else {
2208		bufsize = roundup(bufsize, mss);
2209		if (bufsize > sb_max)
2210			bufsize = sb_max;
2211		(void)sbreserve(&so->so_snd, bufsize);
2212	}
2213	tp->t_maxseg = mss;
2214
2215#ifdef RTV_RPIPE
2216	if ((bufsize = rt->rt_rmx.rmx_recvpipe) == 0)
2217#endif
2218		bufsize = so->so_rcv.sb_hiwat;
2219	if (bufsize > mss) {
2220		bufsize = roundup(bufsize, mss);
2221		if (bufsize > sb_max)
2222			bufsize = sb_max;
2223		(void)sbreserve(&so->so_rcv, bufsize);
2224	}
2225	/*
2226	 * Don't force slow-start on local network.
2227	 */
2228	if (!in_localaddr(inp->inp_faddr))
2229		tp->snd_cwnd = mss;
2230
2231	if (rt->rt_rmx.rmx_ssthresh) {
2232		/*
2233		 * There's some sort of gateway or interface
2234		 * buffer limit on the path.  Use this to set
2235		 * the slow start threshhold, but set the
2236		 * threshold to no less than 2*mss.
2237		 */
2238		tp->snd_ssthresh = max(2 * mss, rt->rt_rmx.rmx_ssthresh);
2239		tcpstat.tcps_usedssthresh++;
2240	}
2241}
2242
2243/*
2244 * Determine the MSS option to send on an outgoing SYN.
2245 */
2246int
2247tcp_mssopt(tp)
2248	struct tcpcb *tp;
2249{
2250	struct rtentry *rt;
2251
2252	rt = tcp_rtlookup(tp->t_inpcb);
2253	if (rt == NULL)
2254		return tcp_mssdflt;
2255
2256	return rt->rt_ifp->if_mtu - sizeof(struct tcpiphdr);
2257}
2258