tcp_input.c revision 1817
1/*
2 * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994
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.5 (Berkeley) 4/10/94
34 * $Id$
35 */
36
37#ifndef TUBA_INCLUDE
38#include <sys/param.h>
39#include <sys/systm.h>
40#include <sys/malloc.h>
41#include <sys/mbuf.h>
42#include <sys/protosw.h>
43#include <sys/socket.h>
44#include <sys/socketvar.h>
45#include <sys/errno.h>
46
47#include <net/if.h>
48#include <net/route.h>
49
50#include <netinet/in.h>
51#include <netinet/in_systm.h>
52#include <netinet/ip.h>
53#include <netinet/in_pcb.h>
54#include <netinet/ip_var.h>
55#include <netinet/tcp.h>
56#include <netinet/tcp_fsm.h>
57#include <netinet/tcp_seq.h>
58#include <netinet/tcp_timer.h>
59#include <netinet/tcp_var.h>
60#include <netinet/tcpip.h>
61#include <netinet/tcp_debug.h>
62
63int	tcprexmtthresh = 3;
64struct	tcpiphdr tcp_saveti;
65struct	inpcb *tcp_last_inpcb = &tcb;
66
67extern u_long sb_max;
68
69#endif /* TUBA_INCLUDE */
70#define TCP_PAWS_IDLE	(24 * 24 * 60 * 60 * PR_SLOWHZ)
71
72/* for modulo comparisons of timestamps */
73#define TSTMP_LT(a,b)	((int)((a)-(b)) < 0)
74#define TSTMP_GEQ(a,b)	((int)((a)-(b)) >= 0)
75
76
77/*
78 * Insert segment ti into reassembly queue of tcp with
79 * control block tp.  Return TH_FIN if reassembly now includes
80 * a segment with FIN.  The macro form does the common case inline
81 * (segment is the next to be received on an established connection,
82 * and the queue is empty), avoiding linkage into and removal
83 * from the queue and repetition of various conversions.
84 * Set DELACK for segments received in order, but ack immediately
85 * when segments are out of order (so fast retransmit can work).
86 */
87#define	TCP_REASS(tp, ti, m, so, flags) { \
88	if ((ti)->ti_seq == (tp)->rcv_nxt && \
89	    (tp)->seg_next == (struct tcpiphdr *)(tp) && \
90	    (tp)->t_state == TCPS_ESTABLISHED) { \
91		tp->t_flags |= TF_DELACK; \
92		(tp)->rcv_nxt += (ti)->ti_len; \
93		flags = (ti)->ti_flags & TH_FIN; \
94		tcpstat.tcps_rcvpack++;\
95		tcpstat.tcps_rcvbyte += (ti)->ti_len;\
96		sbappend(&(so)->so_rcv, (m)); \
97		sorwakeup(so); \
98	} else { \
99		(flags) = tcp_reass((tp), (ti), (m)); \
100		tp->t_flags |= TF_ACKNOW; \
101	} \
102}
103#ifndef TUBA_INCLUDE
104
105int
106tcp_reass(tp, ti, m)
107	register struct tcpcb *tp;
108	register struct tcpiphdr *ti;
109	struct mbuf *m;
110{
111	register struct tcpiphdr *q;
112	struct socket *so = tp->t_inpcb->inp_socket;
113	int flags;
114
115	/*
116	 * Call with ti==0 after become established to
117	 * force pre-ESTABLISHED data up to user socket.
118	 */
119	if (ti == 0)
120		goto present;
121
122	/*
123	 * Find a segment which begins after this one does.
124	 */
125	for (q = tp->seg_next; q != (struct tcpiphdr *)tp;
126	    q = (struct tcpiphdr *)q->ti_next)
127		if (SEQ_GT(q->ti_seq, ti->ti_seq))
128			break;
129
130	/*
131	 * If there is a preceding segment, it may provide some of
132	 * our data already.  If so, drop the data from the incoming
133	 * segment.  If it provides all of our data, drop us.
134	 */
135	if ((struct tcpiphdr *)q->ti_prev != (struct tcpiphdr *)tp) {
136		register int i;
137		q = (struct tcpiphdr *)q->ti_prev;
138		/* conversion to int (in i) handles seq wraparound */
139		i = q->ti_seq + q->ti_len - ti->ti_seq;
140		if (i > 0) {
141			if (i >= ti->ti_len) {
142				tcpstat.tcps_rcvduppack++;
143				tcpstat.tcps_rcvdupbyte += ti->ti_len;
144				m_freem(m);
145				return (0);
146			}
147			m_adj(m, i);
148			ti->ti_len -= i;
149			ti->ti_seq += i;
150		}
151		q = (struct tcpiphdr *)(q->ti_next);
152	}
153	tcpstat.tcps_rcvoopack++;
154	tcpstat.tcps_rcvoobyte += ti->ti_len;
155	REASS_MBUF(ti) = m;		/* XXX */
156
157	/*
158	 * While we overlap succeeding segments trim them or,
159	 * if they are completely covered, dequeue them.
160	 */
161	while (q != (struct tcpiphdr *)tp) {
162		register int i = (ti->ti_seq + ti->ti_len) - q->ti_seq;
163		if (i <= 0)
164			break;
165		if (i < q->ti_len) {
166			q->ti_seq += i;
167			q->ti_len -= i;
168			m_adj(REASS_MBUF(q), i);
169			break;
170		}
171		q = (struct tcpiphdr *)q->ti_next;
172		m = REASS_MBUF((struct tcpiphdr *)q->ti_prev);
173		remque(q->ti_prev);
174		m_freem(m);
175	}
176
177	/*
178	 * Stick new segment in its place.
179	 */
180	insque(ti, q->ti_prev);
181
182present:
183	/*
184	 * Present data to user, advancing rcv_nxt through
185	 * completed sequence space.
186	 */
187	if (TCPS_HAVERCVDSYN(tp->t_state) == 0)
188		return (0);
189	ti = tp->seg_next;
190	if (ti == (struct tcpiphdr *)tp || ti->ti_seq != tp->rcv_nxt)
191		return (0);
192	if (tp->t_state == TCPS_SYN_RECEIVED && ti->ti_len)
193		return (0);
194	do {
195		tp->rcv_nxt += ti->ti_len;
196		flags = ti->ti_flags & TH_FIN;
197		remque(ti);
198		m = REASS_MBUF(ti);
199		ti = (struct tcpiphdr *)ti->ti_next;
200		if (so->so_state & SS_CANTRCVMORE)
201			m_freem(m);
202		else
203			sbappend(&so->so_rcv, m);
204	} while (ti != (struct tcpiphdr *)tp && ti->ti_seq == tp->rcv_nxt);
205	sorwakeup(so);
206	return (flags);
207}
208
209/*
210 * TCP input routine, follows pages 65-76 of the
211 * protocol specification dated September, 1981 very closely.
212 */
213void
214tcp_input(m, iphlen)
215	register struct mbuf *m;
216	int iphlen;
217{
218	register struct tcpiphdr *ti;
219	register struct inpcb *inp;
220	caddr_t optp = NULL;
221	int optlen = 0;
222	int len, tlen, off;
223	register struct tcpcb *tp = 0;
224	register int tiflags;
225	struct socket *so = 0;
226	int todrop, acked, ourfinisacked, needoutput = 0;
227	short ostate = 0;
228	struct in_addr laddr;
229	int dropsocket = 0;
230	int iss = 0;
231	u_long tiwin, ts_val, ts_ecr;
232	int ts_present = 0;
233
234	tcpstat.tcps_rcvtotal++;
235	/*
236	 * Get IP and TCP header together in first mbuf.
237	 * Note: IP leaves IP header in first mbuf.
238	 */
239	ti = mtod(m, struct tcpiphdr *);
240	if (iphlen > sizeof (struct ip))
241		ip_stripoptions(m, (struct mbuf *)0);
242	if (m->m_len < sizeof (struct tcpiphdr)) {
243		if ((m = m_pullup(m, sizeof (struct tcpiphdr))) == 0) {
244			tcpstat.tcps_rcvshort++;
245			return;
246		}
247		ti = mtod(m, struct tcpiphdr *);
248	}
249
250	/*
251	 * Checksum extended TCP header and data.
252	 */
253	tlen = ((struct ip *)ti)->ip_len;
254	len = sizeof (struct ip) + tlen;
255	ti->ti_next = ti->ti_prev = 0;
256	ti->ti_x1 = 0;
257	ti->ti_len = (u_short)tlen;
258	HTONS(ti->ti_len);
259	if (ti->ti_sum = in_cksum(m, len)) {
260		tcpstat.tcps_rcvbadsum++;
261		goto drop;
262	}
263#endif /* TUBA_INCLUDE */
264
265	/*
266	 * Check that TCP offset makes sense,
267	 * pull out TCP options and adjust length.		XXX
268	 */
269	off = ti->ti_off << 2;
270	if (off < sizeof (struct tcphdr) || off > tlen) {
271		tcpstat.tcps_rcvbadoff++;
272		goto drop;
273	}
274	tlen -= off;
275	ti->ti_len = tlen;
276	if (off > sizeof (struct tcphdr)) {
277		if (m->m_len < sizeof(struct ip) + off) {
278			if ((m = m_pullup(m, sizeof (struct ip) + off)) == 0) {
279				tcpstat.tcps_rcvshort++;
280				return;
281			}
282			ti = mtod(m, struct tcpiphdr *);
283		}
284		optlen = off - sizeof (struct tcphdr);
285		optp = mtod(m, caddr_t) + sizeof (struct tcpiphdr);
286		/*
287		 * Do quick retrieval of timestamp options ("options
288		 * prediction?").  If timestamp is the only option and it's
289		 * formatted as recommended in RFC 1323 appendix A, we
290		 * quickly get the values now and not bother calling
291		 * tcp_dooptions(), etc.
292		 */
293		if ((optlen == TCPOLEN_TSTAMP_APPA ||
294		     (optlen > TCPOLEN_TSTAMP_APPA &&
295			optp[TCPOLEN_TSTAMP_APPA] == TCPOPT_EOL)) &&
296		     *(u_long *)optp == htonl(TCPOPT_TSTAMP_HDR) &&
297		     (ti->ti_flags & TH_SYN) == 0) {
298			ts_present = 1;
299			ts_val = ntohl(*(u_long *)(optp + 4));
300			ts_ecr = ntohl(*(u_long *)(optp + 8));
301			optp = NULL;	/* we've parsed the options */
302		}
303	}
304	tiflags = ti->ti_flags;
305
306	/*
307	 * Convert TCP protocol specific fields to host format.
308	 */
309	NTOHL(ti->ti_seq);
310	NTOHL(ti->ti_ack);
311	NTOHS(ti->ti_win);
312	NTOHS(ti->ti_urp);
313
314	/*
315	 * Locate pcb for segment.
316	 */
317findpcb:
318	inp = tcp_last_inpcb;
319	if (inp->inp_lport != ti->ti_dport ||
320	    inp->inp_fport != ti->ti_sport ||
321	    inp->inp_faddr.s_addr != ti->ti_src.s_addr ||
322	    inp->inp_laddr.s_addr != ti->ti_dst.s_addr) {
323		inp = in_pcblookup(&tcb, ti->ti_src, ti->ti_sport,
324		    ti->ti_dst, ti->ti_dport, INPLOOKUP_WILDCARD);
325		if (inp)
326			tcp_last_inpcb = inp;
327		++tcpstat.tcps_pcbcachemiss;
328	}
329
330	/*
331	 * If the state is CLOSED (i.e., TCB does not exist) then
332	 * all data in the incoming segment is discarded.
333	 * If the TCB exists but is in CLOSED state, it is embryonic,
334	 * but should either do a listen or a connect soon.
335	 */
336	if (inp == 0)
337		goto dropwithreset;
338	tp = intotcpcb(inp);
339	if (tp == 0)
340		goto dropwithreset;
341	if (tp->t_state == TCPS_CLOSED)
342		goto drop;
343
344	/* Unscale the window into a 32-bit value. */
345	if ((tiflags & TH_SYN) == 0)
346		tiwin = ti->ti_win << tp->snd_scale;
347	else
348		tiwin = ti->ti_win;
349
350	so = inp->inp_socket;
351	if (so->so_options & (SO_DEBUG|SO_ACCEPTCONN)) {
352		if (so->so_options & SO_DEBUG) {
353			ostate = tp->t_state;
354			tcp_saveti = *ti;
355		}
356		if (so->so_options & SO_ACCEPTCONN) {
357			so = sonewconn(so, 0);
358			if (so == 0)
359				goto drop;
360			/*
361			 * This is ugly, but ....
362			 *
363			 * Mark socket as temporary until we're
364			 * committed to keeping it.  The code at
365			 * ``drop'' and ``dropwithreset'' check the
366			 * flag dropsocket to see if the temporary
367			 * socket created here should be discarded.
368			 * We mark the socket as discardable until
369			 * we're committed to it below in TCPS_LISTEN.
370			 */
371			dropsocket++;
372			inp = (struct inpcb *)so->so_pcb;
373			inp->inp_laddr = ti->ti_dst;
374			inp->inp_lport = ti->ti_dport;
375#if BSD>=43
376			inp->inp_options = ip_srcroute();
377#endif
378			tp = intotcpcb(inp);
379			tp->t_state = TCPS_LISTEN;
380
381			/* Compute proper scaling value from buffer space
382			 */
383			while (tp->request_r_scale < TCP_MAX_WINSHIFT &&
384			   TCP_MAXWIN << tp->request_r_scale < so->so_rcv.sb_hiwat)
385				tp->request_r_scale++;
386		}
387	}
388
389	/*
390	 * Segment received on connection.
391	 * Reset idle time and keep-alive timer.
392	 */
393	tp->t_idle = 0;
394	tp->t_timer[TCPT_KEEP] = tcp_keepidle;
395
396	/*
397	 * Process options if not in LISTEN state,
398	 * else do it below (after getting remote address).
399	 */
400	if (optp && tp->t_state != TCPS_LISTEN)
401		tcp_dooptions(tp, optp, optlen, ti,
402			&ts_present, &ts_val, &ts_ecr);
403
404	/*
405	 * Header prediction: check for the two common cases
406	 * of a uni-directional data xfer.  If the packet has
407	 * no control flags, is in-sequence, the window didn't
408	 * change and we're not retransmitting, it's a
409	 * candidate.  If the length is zero and the ack moved
410	 * forward, we're the sender side of the xfer.  Just
411	 * free the data acked & wake any higher level process
412	 * that was blocked waiting for space.  If the length
413	 * is non-zero and the ack didn't move, we're the
414	 * receiver side.  If we're getting packets in-order
415	 * (the reassembly queue is empty), add the data to
416	 * the socket buffer and note that we need a delayed ack.
417	 */
418	if (tp->t_state == TCPS_ESTABLISHED &&
419	    (tiflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
420	    (!ts_present || TSTMP_GEQ(ts_val, tp->ts_recent)) &&
421	    ti->ti_seq == tp->rcv_nxt &&
422	    tiwin && tiwin == tp->snd_wnd &&
423	    tp->snd_nxt == tp->snd_max) {
424
425		/*
426		 * If last ACK falls within this segment's sequence numbers,
427		 *  record the timestamp.
428		 */
429		if (ts_present && SEQ_LEQ(ti->ti_seq, tp->last_ack_sent) &&
430		   SEQ_LT(tp->last_ack_sent, ti->ti_seq + ti->ti_len)) {
431			tp->ts_recent_age = tcp_now;
432			tp->ts_recent = ts_val;
433		}
434
435		if (ti->ti_len == 0) {
436			if (SEQ_GT(ti->ti_ack, tp->snd_una) &&
437			    SEQ_LEQ(ti->ti_ack, tp->snd_max) &&
438			    tp->snd_cwnd >= tp->snd_wnd) {
439				/*
440				 * this is a pure ack for outstanding data.
441				 */
442				++tcpstat.tcps_predack;
443				if (ts_present)
444					tcp_xmit_timer(tp, tcp_now-ts_ecr+1);
445				else if (tp->t_rtt &&
446					    SEQ_GT(ti->ti_ack, tp->t_rtseq))
447					tcp_xmit_timer(tp, tp->t_rtt);
448				acked = ti->ti_ack - tp->snd_una;
449				tcpstat.tcps_rcvackpack++;
450				tcpstat.tcps_rcvackbyte += acked;
451				sbdrop(&so->so_snd, acked);
452				tp->snd_una = ti->ti_ack;
453				m_freem(m);
454
455				/*
456				 * If all outstanding data are acked, stop
457				 * retransmit timer, otherwise restart timer
458				 * using current (possibly backed-off) value.
459				 * If process is waiting for space,
460				 * wakeup/selwakeup/signal.  If data
461				 * are ready to send, let tcp_output
462				 * decide between more output or persist.
463				 */
464				if (tp->snd_una == tp->snd_max)
465					tp->t_timer[TCPT_REXMT] = 0;
466				else if (tp->t_timer[TCPT_PERSIST] == 0)
467					tp->t_timer[TCPT_REXMT] = tp->t_rxtcur;
468
469				if (so->so_snd.sb_flags & SB_NOTIFY)
470					sowwakeup(so);
471				if (so->so_snd.sb_cc)
472					(void) tcp_output(tp);
473				return;
474			}
475		} else if (ti->ti_ack == tp->snd_una &&
476		    tp->seg_next == (struct tcpiphdr *)tp &&
477		    ti->ti_len <= sbspace(&so->so_rcv)) {
478			/*
479			 * this is a pure, in-sequence data packet
480			 * with nothing on the reassembly queue and
481			 * we have enough buffer space to take it.
482			 */
483			++tcpstat.tcps_preddat;
484			tp->rcv_nxt += ti->ti_len;
485			tcpstat.tcps_rcvpack++;
486			tcpstat.tcps_rcvbyte += ti->ti_len;
487			/*
488			 * Drop TCP, IP headers and TCP options then add data
489			 * to socket buffer.
490			 */
491			m->m_data += sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr);
492			m->m_len -= sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr);
493			sbappend(&so->so_rcv, m);
494			sorwakeup(so);
495			/*
496			 * If this is a small packet, then ACK now - with Nagel
497			 *	congestion avoidance sender won't send more until
498			 *	he gets an ACK.
499			 */
500			if ((unsigned)ti->ti_len < tp->t_maxseg) {
501				tp->t_flags |= TF_ACKNOW;
502				tcp_output(tp);
503			} else {
504				tp->t_flags |= TF_DELACK;
505			}
506			return;
507		}
508	}
509
510	/*
511	 * Drop TCP, IP headers and TCP options.
512	 */
513	m->m_data += sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr);
514	m->m_len  -= sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr);
515
516	/*
517	 * Calculate amount of space in receive window,
518	 * and then do TCP input processing.
519	 * Receive window is amount of space in rcv queue,
520	 * but not less than advertised window.
521	 */
522	{ int win;
523
524	win = sbspace(&so->so_rcv);
525	if (win < 0)
526		win = 0;
527	tp->rcv_wnd = max(win, (int)(tp->rcv_adv - tp->rcv_nxt));
528	}
529
530	switch (tp->t_state) {
531
532	/*
533	 * If the state is LISTEN then ignore segment if it contains an RST.
534	 * If the segment contains an ACK then it is bad and send a RST.
535	 * If it does not contain a SYN then it is not interesting; drop it.
536	 * Don't bother responding if the destination was a broadcast.
537	 * Otherwise initialize tp->rcv_nxt, and tp->irs, select an initial
538	 * tp->iss, and send a segment:
539	 *     <SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK>
540	 * Also initialize tp->snd_nxt to tp->iss+1 and tp->snd_una to tp->iss.
541	 * Fill in remote peer address fields if not previously specified.
542	 * Enter SYN_RECEIVED state, and process any other fields of this
543	 * segment in this state.
544	 */
545	case TCPS_LISTEN: {
546		struct mbuf *am;
547		register struct sockaddr_in *sin;
548
549		if (tiflags & TH_RST)
550			goto drop;
551		if (tiflags & TH_ACK)
552			goto dropwithreset;
553		if ((tiflags & TH_SYN) == 0)
554			goto drop;
555		/*
556		 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
557		 * in_broadcast() should never return true on a received
558		 * packet with M_BCAST not set.
559		 */
560		if (m->m_flags & (M_BCAST|M_MCAST) ||
561		    IN_MULTICAST(ntohl(ti->ti_dst.s_addr)))
562			goto drop;
563		am = m_get(M_DONTWAIT, MT_SONAME);	/* XXX */
564		if (am == NULL)
565			goto drop;
566		am->m_len = sizeof (struct sockaddr_in);
567		sin = mtod(am, struct sockaddr_in *);
568		sin->sin_family = AF_INET;
569		sin->sin_len = sizeof(*sin);
570		sin->sin_addr = ti->ti_src;
571		sin->sin_port = ti->ti_sport;
572		bzero((caddr_t)sin->sin_zero, sizeof(sin->sin_zero));
573		laddr = inp->inp_laddr;
574		if (inp->inp_laddr.s_addr == INADDR_ANY)
575			inp->inp_laddr = ti->ti_dst;
576		if (in_pcbconnect(inp, am)) {
577			inp->inp_laddr = laddr;
578			(void) m_free(am);
579			goto drop;
580		}
581		(void) m_free(am);
582		tp->t_template = tcp_template(tp);
583		if (tp->t_template == 0) {
584			tp = tcp_drop(tp, ENOBUFS);
585			dropsocket = 0;		/* socket is already gone */
586			goto drop;
587		}
588		if (optp)
589			tcp_dooptions(tp, optp, optlen, ti,
590				&ts_present, &ts_val, &ts_ecr);
591		if (iss)
592			tp->iss = iss;
593		else
594			tp->iss = tcp_iss;
595		tcp_iss += TCP_ISSINCR/2;
596		tp->irs = ti->ti_seq;
597		tcp_sendseqinit(tp);
598		tcp_rcvseqinit(tp);
599		tp->t_flags |= TF_ACKNOW;
600		tp->t_state = TCPS_SYN_RECEIVED;
601		tp->t_timer[TCPT_KEEP] = TCPTV_KEEP_INIT;
602		dropsocket = 0;		/* committed to socket */
603		tcpstat.tcps_accepts++;
604		goto trimthenstep6;
605		}
606
607	/*
608	 * If the state is SYN_SENT:
609	 *	if seg contains an ACK, but not for our SYN, drop the input.
610	 *	if seg contains a RST, then drop the connection.
611	 *	if seg does not contain SYN, then drop it.
612	 * Otherwise this is an acceptable SYN segment
613	 *	initialize tp->rcv_nxt and tp->irs
614	 *	if seg contains ack then advance tp->snd_una
615	 *	if SYN has been acked change to ESTABLISHED else SYN_RCVD state
616	 *	arrange for segment to be acked (eventually)
617	 *	continue processing rest of data/controls, beginning with URG
618	 */
619	case TCPS_SYN_SENT:
620		if ((tiflags & TH_ACK) &&
621		    (SEQ_LEQ(ti->ti_ack, tp->iss) ||
622		     SEQ_GT(ti->ti_ack, tp->snd_max)))
623			goto dropwithreset;
624		if (tiflags & TH_RST) {
625			if (tiflags & TH_ACK)
626				tp = tcp_drop(tp, ECONNREFUSED);
627			goto drop;
628		}
629		if ((tiflags & TH_SYN) == 0)
630			goto drop;
631		if (tiflags & TH_ACK) {
632			tp->snd_una = ti->ti_ack;
633			if (SEQ_LT(tp->snd_nxt, tp->snd_una))
634				tp->snd_nxt = tp->snd_una;
635		}
636		tp->t_timer[TCPT_REXMT] = 0;
637		tp->irs = ti->ti_seq;
638		tcp_rcvseqinit(tp);
639		tp->t_flags |= TF_ACKNOW;
640		if (tiflags & TH_ACK && SEQ_GT(tp->snd_una, tp->iss)) {
641			tcpstat.tcps_connects++;
642			soisconnected(so);
643			tp->t_state = TCPS_ESTABLISHED;
644			/* Do window scaling on this connection? */
645			if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
646				(TF_RCVD_SCALE|TF_REQ_SCALE)) {
647				tp->snd_scale = tp->requested_s_scale;
648				tp->rcv_scale = tp->request_r_scale;
649			}
650			(void) tcp_reass(tp, (struct tcpiphdr *)0,
651				(struct mbuf *)0);
652			/*
653			 * if we didn't have to retransmit the SYN,
654			 * use its rtt as our initial srtt & rtt var.
655			 */
656			if (tp->t_rtt)
657				tcp_xmit_timer(tp, tp->t_rtt);
658		} else
659			tp->t_state = TCPS_SYN_RECEIVED;
660
661trimthenstep6:
662		/*
663		 * Advance ti->ti_seq to correspond to first data byte.
664		 * If data, trim to stay within window,
665		 * dropping FIN if necessary.
666		 */
667		ti->ti_seq++;
668		if (ti->ti_len > tp->rcv_wnd) {
669			todrop = ti->ti_len - tp->rcv_wnd;
670			m_adj(m, -todrop);
671			ti->ti_len = tp->rcv_wnd;
672			tiflags &= ~TH_FIN;
673			tcpstat.tcps_rcvpackafterwin++;
674			tcpstat.tcps_rcvbyteafterwin += todrop;
675		}
676		tp->snd_wl1 = ti->ti_seq - 1;
677		tp->rcv_up = ti->ti_seq;
678		goto step6;
679	}
680
681	/*
682	 * States other than LISTEN or SYN_SENT.
683	 * First check timestamp, if present.
684	 * Then check that at least some bytes of segment are within
685	 * receive window.  If segment begins before rcv_nxt,
686	 * drop leading data (and SYN); if nothing left, just ack.
687	 *
688	 * RFC 1323 PAWS: If we have a timestamp reply on this segment
689	 * and it's less than ts_recent, drop it.
690	 */
691	if (ts_present && (tiflags & TH_RST) == 0 && tp->ts_recent &&
692	    TSTMP_LT(ts_val, tp->ts_recent)) {
693
694		/* Check to see if ts_recent is over 24 days old.  */
695		if ((int)(tcp_now - tp->ts_recent_age) > TCP_PAWS_IDLE) {
696			/*
697			 * Invalidate ts_recent.  If this segment updates
698			 * ts_recent, the age will be reset later and ts_recent
699			 * will get a valid value.  If it does not, setting
700			 * ts_recent to zero will at least satisfy the
701			 * requirement that zero be placed in the timestamp
702			 * echo reply when ts_recent isn't valid.  The
703			 * age isn't reset until we get a valid ts_recent
704			 * because we don't want out-of-order segments to be
705			 * dropped when ts_recent is old.
706			 */
707			tp->ts_recent = 0;
708		} else {
709			tcpstat.tcps_rcvduppack++;
710			tcpstat.tcps_rcvdupbyte += ti->ti_len;
711			tcpstat.tcps_pawsdrop++;
712			goto dropafterack;
713		}
714	}
715
716	todrop = tp->rcv_nxt - ti->ti_seq;
717	if (todrop > 0) {
718		if (tiflags & TH_SYN) {
719			tiflags &= ~TH_SYN;
720			ti->ti_seq++;
721			if (ti->ti_urp > 1)
722				ti->ti_urp--;
723			else
724				tiflags &= ~TH_URG;
725			todrop--;
726		}
727		if (todrop >= ti->ti_len) {
728			tcpstat.tcps_rcvduppack++;
729			tcpstat.tcps_rcvdupbyte += ti->ti_len;
730			/*
731			 * If segment is just one to the left of the window,
732			 * check two special cases:
733			 * 1. Don't toss RST in response to 4.2-style keepalive.
734			 * 2. If the only thing to drop is a FIN, we can drop
735			 *    it, but check the ACK or we will get into FIN
736			 *    wars if our FINs crossed (both CLOSING).
737			 * In either case, send ACK to resynchronize,
738			 * but keep on processing for RST or ACK.
739			 */
740			if ((tiflags & TH_FIN && todrop == ti->ti_len + 1)
741#ifdef TCP_COMPAT_42
742			  || (tiflags & TH_RST && ti->ti_seq == tp->rcv_nxt - 1)
743#endif
744			   ) {
745				todrop = ti->ti_len;
746				tiflags &= ~TH_FIN;
747				tp->t_flags |= TF_ACKNOW;
748			} else {
749				/*
750				 * Handle the case when a bound socket connects
751				 * to itself. Allow packets with a SYN and
752				 * an ACK to continue with the processing.
753				 */
754				if (todrop != 0 || (tiflags & TH_ACK) == 0)
755					goto dropafterack;
756			}
757		} else {
758			tcpstat.tcps_rcvpartduppack++;
759			tcpstat.tcps_rcvpartdupbyte += todrop;
760		}
761		m_adj(m, todrop);
762		ti->ti_seq += todrop;
763		ti->ti_len -= todrop;
764		if (ti->ti_urp > todrop)
765			ti->ti_urp -= todrop;
766		else {
767			tiflags &= ~TH_URG;
768			ti->ti_urp = 0;
769		}
770	}
771
772	/*
773	 * If new data are received on a connection after the
774	 * user processes are gone, then RST the other end.
775	 */
776	if ((so->so_state & SS_NOFDREF) &&
777	    tp->t_state > TCPS_CLOSE_WAIT && ti->ti_len) {
778		tp = tcp_close(tp);
779		tcpstat.tcps_rcvafterclose++;
780		goto dropwithreset;
781	}
782
783	/*
784	 * If segment ends after window, drop trailing data
785	 * (and PUSH and FIN); if nothing left, just ACK.
786	 */
787	todrop = (ti->ti_seq+ti->ti_len) - (tp->rcv_nxt+tp->rcv_wnd);
788	if (todrop > 0) {
789		tcpstat.tcps_rcvpackafterwin++;
790		if (todrop >= ti->ti_len) {
791			tcpstat.tcps_rcvbyteafterwin += ti->ti_len;
792			/*
793			 * If a new connection request is received
794			 * while in TIME_WAIT, drop the old connection
795			 * and start over if the sequence numbers
796			 * are above the previous ones.
797			 */
798			if (tiflags & TH_SYN &&
799			    tp->t_state == TCPS_TIME_WAIT &&
800			    SEQ_GT(ti->ti_seq, tp->rcv_nxt)) {
801				iss = tp->rcv_nxt + TCP_ISSINCR;
802				tp = tcp_close(tp);
803				goto findpcb;
804			}
805			/*
806			 * If window is closed can only take segments at
807			 * window edge, and have to drop data and PUSH from
808			 * incoming segments.  Continue processing, but
809			 * remember to ack.  Otherwise, drop segment
810			 * and ack.
811			 */
812			if (tp->rcv_wnd == 0 && ti->ti_seq == tp->rcv_nxt) {
813				tp->t_flags |= TF_ACKNOW;
814				tcpstat.tcps_rcvwinprobe++;
815			} else
816				goto dropafterack;
817		} else
818			tcpstat.tcps_rcvbyteafterwin += todrop;
819		m_adj(m, -todrop);
820		ti->ti_len -= todrop;
821		tiflags &= ~(TH_PUSH|TH_FIN);
822	}
823
824	/*
825	 * If last ACK falls within this segment's sequence numbers,
826	 * record its timestamp.
827	 */
828	if (ts_present && SEQ_LEQ(ti->ti_seq, tp->last_ack_sent) &&
829	    SEQ_LT(tp->last_ack_sent, ti->ti_seq + ti->ti_len +
830		   ((tiflags & (TH_SYN|TH_FIN)) != 0))) {
831		tp->ts_recent_age = tcp_now;
832		tp->ts_recent = ts_val;
833	}
834
835	/*
836	 * If the RST bit is set examine the state:
837	 *    SYN_RECEIVED STATE:
838	 *	If passive open, return to LISTEN state.
839	 *	If active open, inform user that connection was refused.
840	 *    ESTABLISHED, FIN_WAIT_1, FIN_WAIT2, CLOSE_WAIT STATES:
841	 *	Inform user that connection was reset, and close tcb.
842	 *    CLOSING, LAST_ACK, TIME_WAIT STATES
843	 *	Close the tcb.
844	 */
845	if (tiflags&TH_RST) switch (tp->t_state) {
846
847	case TCPS_SYN_RECEIVED:
848		so->so_error = ECONNREFUSED;
849		goto close;
850
851	case TCPS_ESTABLISHED:
852	case TCPS_FIN_WAIT_1:
853	case TCPS_FIN_WAIT_2:
854	case TCPS_CLOSE_WAIT:
855		so->so_error = ECONNRESET;
856	close:
857		tp->t_state = TCPS_CLOSED;
858		tcpstat.tcps_drops++;
859		tp = tcp_close(tp);
860		goto drop;
861
862	case TCPS_CLOSING:
863	case TCPS_LAST_ACK:
864	case TCPS_TIME_WAIT:
865		tp = tcp_close(tp);
866		goto drop;
867	}
868
869	/*
870	 * If a SYN is in the window, then this is an
871	 * error and we send an RST and drop the connection.
872	 */
873	if (tiflags & TH_SYN) {
874		tp = tcp_drop(tp, ECONNRESET);
875		goto dropwithreset;
876	}
877
878	/*
879	 * If the ACK bit is off we drop the segment and return.
880	 */
881	if ((tiflags & TH_ACK) == 0)
882		goto drop;
883
884	/*
885	 * Ack processing.
886	 */
887	switch (tp->t_state) {
888
889	/*
890	 * In SYN_RECEIVED state if the ack ACKs our SYN then enter
891	 * ESTABLISHED state and continue processing, otherwise
892	 * send an RST.
893	 */
894	case TCPS_SYN_RECEIVED:
895		if (SEQ_GT(tp->snd_una, ti->ti_ack) ||
896		    SEQ_GT(ti->ti_ack, tp->snd_max))
897			goto dropwithreset;
898		tcpstat.tcps_connects++;
899		soisconnected(so);
900		tp->t_state = TCPS_ESTABLISHED;
901		/* Do window scaling? */
902		if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
903			(TF_RCVD_SCALE|TF_REQ_SCALE)) {
904			tp->snd_scale = tp->requested_s_scale;
905			tp->rcv_scale = tp->request_r_scale;
906		}
907		(void) tcp_reass(tp, (struct tcpiphdr *)0, (struct mbuf *)0);
908		tp->snd_wl1 = ti->ti_seq - 1;
909		/* fall into ... */
910
911	/*
912	 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
913	 * ACKs.  If the ack is in the range
914	 *	tp->snd_una < ti->ti_ack <= tp->snd_max
915	 * then advance tp->snd_una to ti->ti_ack and drop
916	 * data from the retransmission queue.  If this ACK reflects
917	 * more up to date window information we update our window information.
918	 */
919	case TCPS_ESTABLISHED:
920	case TCPS_FIN_WAIT_1:
921	case TCPS_FIN_WAIT_2:
922	case TCPS_CLOSE_WAIT:
923	case TCPS_CLOSING:
924	case TCPS_LAST_ACK:
925	case TCPS_TIME_WAIT:
926
927		if (SEQ_LEQ(ti->ti_ack, tp->snd_una)) {
928			if (ti->ti_len == 0 && tiwin == tp->snd_wnd) {
929				tcpstat.tcps_rcvdupack++;
930				/*
931				 * If we have outstanding data (other than
932				 * a window probe), this is a completely
933				 * duplicate ack (ie, window info didn't
934				 * change), the ack is the biggest we've
935				 * seen and we've seen exactly our rexmt
936				 * threshhold of them, assume a packet
937				 * has been dropped and retransmit it.
938				 * Kludge snd_nxt & the congestion
939				 * window so we send only this one
940				 * packet.
941				 *
942				 * We know we're losing at the current
943				 * window size so do congestion avoidance
944				 * (set ssthresh to half the current window
945				 * and pull our congestion window back to
946				 * the new ssthresh).
947				 *
948				 * Dup acks mean that packets have left the
949				 * network (they're now cached at the receiver)
950				 * so bump cwnd by the amount in the receiver
951				 * to keep a constant cwnd packets in the
952				 * network.
953				 */
954				if (tp->t_timer[TCPT_REXMT] == 0 ||
955				    ti->ti_ack != tp->snd_una)
956					tp->t_dupacks = 0;
957				else if (++tp->t_dupacks == tcprexmtthresh) {
958					tcp_seq onxt = tp->snd_nxt;
959					u_int win =
960					    min(tp->snd_wnd, tp->snd_cwnd) / 2 /
961						tp->t_maxseg;
962
963					if (win < 2)
964						win = 2;
965					tp->snd_ssthresh = win * tp->t_maxseg;
966					tp->t_timer[TCPT_REXMT] = 0;
967					tp->t_rtt = 0;
968					tp->snd_nxt = ti->ti_ack;
969					tp->snd_cwnd = tp->t_maxseg;
970					(void) tcp_output(tp);
971					tp->snd_cwnd = tp->snd_ssthresh +
972					       tp->t_maxseg * tp->t_dupacks;
973					if (SEQ_GT(onxt, tp->snd_nxt))
974						tp->snd_nxt = onxt;
975					goto drop;
976				} else if (tp->t_dupacks > tcprexmtthresh) {
977					tp->snd_cwnd += tp->t_maxseg;
978					(void) tcp_output(tp);
979					goto drop;
980				}
981			} else
982				tp->t_dupacks = 0;
983			break;
984		}
985		/*
986		 * If the congestion window was inflated to account
987		 * for the other side's cached packets, retract it.
988		 */
989		if (tp->t_dupacks > tcprexmtthresh &&
990		    tp->snd_cwnd > tp->snd_ssthresh)
991			tp->snd_cwnd = tp->snd_ssthresh;
992		tp->t_dupacks = 0;
993		if (SEQ_GT(ti->ti_ack, tp->snd_max)) {
994			tcpstat.tcps_rcvacktoomuch++;
995			goto dropafterack;
996		}
997		acked = ti->ti_ack - tp->snd_una;
998		tcpstat.tcps_rcvackpack++;
999		tcpstat.tcps_rcvackbyte += acked;
1000
1001		/*
1002		 * If we have a timestamp reply, update smoothed
1003		 * round trip time.  If no timestamp is present but
1004		 * transmit timer is running and timed sequence
1005		 * number was acked, update smoothed round trip time.
1006		 * Since we now have an rtt measurement, cancel the
1007		 * timer backoff (cf., Phil Karn's retransmit alg.).
1008		 * Recompute the initial retransmit timer.
1009		 */
1010		if (ts_present)
1011			tcp_xmit_timer(tp, tcp_now-ts_ecr+1);
1012		else if (tp->t_rtt && SEQ_GT(ti->ti_ack, tp->t_rtseq))
1013			tcp_xmit_timer(tp,tp->t_rtt);
1014
1015		/*
1016		 * If all outstanding data is acked, stop retransmit
1017		 * timer and remember to restart (more output or persist).
1018		 * If there is more data to be acked, restart retransmit
1019		 * timer, using current (possibly backed-off) value.
1020		 */
1021		if (ti->ti_ack == tp->snd_max) {
1022			tp->t_timer[TCPT_REXMT] = 0;
1023			needoutput = 1;
1024		} else if (tp->t_timer[TCPT_PERSIST] == 0)
1025			tp->t_timer[TCPT_REXMT] = tp->t_rxtcur;
1026		/*
1027		 * When new data is acked, open the congestion window.
1028		 * If the window gives us less than ssthresh packets
1029		 * in flight, open exponentially (maxseg per packet).
1030		 * Otherwise open linearly: maxseg per window
1031		 * (maxseg^2 / cwnd per packet), plus a constant
1032		 * fraction of a packet (maxseg/8) to help larger windows
1033		 * open quickly enough.
1034		 */
1035		{
1036		register u_int cw = tp->snd_cwnd;
1037		register u_int incr = tp->t_maxseg;
1038
1039		if (cw > tp->snd_ssthresh)
1040			incr = incr * incr / cw + incr / 8;
1041		tp->snd_cwnd = min(cw + incr, TCP_MAXWIN<<tp->snd_scale);
1042		}
1043		if (acked > so->so_snd.sb_cc) {
1044			tp->snd_wnd -= so->so_snd.sb_cc;
1045			sbdrop(&so->so_snd, (int)so->so_snd.sb_cc);
1046			ourfinisacked = 1;
1047		} else {
1048			sbdrop(&so->so_snd, acked);
1049			tp->snd_wnd -= acked;
1050			ourfinisacked = 0;
1051		}
1052		if (so->so_snd.sb_flags & SB_NOTIFY)
1053			sowwakeup(so);
1054		tp->snd_una = ti->ti_ack;
1055		if (SEQ_LT(tp->snd_nxt, tp->snd_una))
1056			tp->snd_nxt = tp->snd_una;
1057
1058		switch (tp->t_state) {
1059
1060		/*
1061		 * In FIN_WAIT_1 STATE in addition to the processing
1062		 * for the ESTABLISHED state if our FIN is now acknowledged
1063		 * then enter FIN_WAIT_2.
1064		 */
1065		case TCPS_FIN_WAIT_1:
1066			if (ourfinisacked) {
1067				/*
1068				 * If we can't receive any more
1069				 * data, then closing user can proceed.
1070				 * Starting the timer is contrary to the
1071				 * specification, but if we don't get a FIN
1072				 * we'll hang forever.
1073				 */
1074				if (so->so_state & SS_CANTRCVMORE) {
1075					soisdisconnected(so);
1076					tp->t_timer[TCPT_2MSL] = tcp_maxidle;
1077				}
1078				tp->t_state = TCPS_FIN_WAIT_2;
1079			}
1080			break;
1081
1082	 	/*
1083		 * In CLOSING STATE in addition to the processing for
1084		 * the ESTABLISHED state if the ACK acknowledges our FIN
1085		 * then enter the TIME-WAIT state, otherwise ignore
1086		 * the segment.
1087		 */
1088		case TCPS_CLOSING:
1089			if (ourfinisacked) {
1090				tp->t_state = TCPS_TIME_WAIT;
1091				tcp_canceltimers(tp);
1092				tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
1093				soisdisconnected(so);
1094			}
1095			break;
1096
1097		/*
1098		 * In LAST_ACK, we may still be waiting for data to drain
1099		 * and/or to be acked, as well as for the ack of our FIN.
1100		 * If our FIN is now acknowledged, delete the TCB,
1101		 * enter the closed state and return.
1102		 */
1103		case TCPS_LAST_ACK:
1104			if (ourfinisacked) {
1105				tp = tcp_close(tp);
1106				goto drop;
1107			}
1108			break;
1109
1110		/*
1111		 * In TIME_WAIT state the only thing that should arrive
1112		 * is a retransmission of the remote FIN.  Acknowledge
1113		 * it and restart the finack timer.
1114		 */
1115		case TCPS_TIME_WAIT:
1116			tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
1117			goto dropafterack;
1118		}
1119	}
1120
1121step6:
1122	/*
1123	 * Update window information.
1124	 * Don't look at window if no ACK: TAC's send garbage on first SYN.
1125	 */
1126	if ((tiflags & TH_ACK) &&
1127	    (SEQ_LT(tp->snd_wl1, ti->ti_seq) || tp->snd_wl1 == ti->ti_seq &&
1128	    (SEQ_LT(tp->snd_wl2, ti->ti_ack) ||
1129	     tp->snd_wl2 == ti->ti_ack && tiwin > tp->snd_wnd))) {
1130		/* keep track of pure window updates */
1131		if (ti->ti_len == 0 &&
1132		    tp->snd_wl2 == ti->ti_ack && tiwin > tp->snd_wnd)
1133			tcpstat.tcps_rcvwinupd++;
1134		tp->snd_wnd = tiwin;
1135		tp->snd_wl1 = ti->ti_seq;
1136		tp->snd_wl2 = ti->ti_ack;
1137		if (tp->snd_wnd > tp->max_sndwnd)
1138			tp->max_sndwnd = tp->snd_wnd;
1139		needoutput = 1;
1140	}
1141
1142	/*
1143	 * Process segments with URG.
1144	 */
1145	if ((tiflags & TH_URG) && ti->ti_urp &&
1146	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
1147		/*
1148		 * This is a kludge, but if we receive and accept
1149		 * random urgent pointers, we'll crash in
1150		 * soreceive.  It's hard to imagine someone
1151		 * actually wanting to send this much urgent data.
1152		 */
1153		if (ti->ti_urp + so->so_rcv.sb_cc > sb_max) {
1154			ti->ti_urp = 0;			/* XXX */
1155			tiflags &= ~TH_URG;		/* XXX */
1156			goto dodata;			/* XXX */
1157		}
1158		/*
1159		 * If this segment advances the known urgent pointer,
1160		 * then mark the data stream.  This should not happen
1161		 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
1162		 * a FIN has been received from the remote side.
1163		 * In these states we ignore the URG.
1164		 *
1165		 * According to RFC961 (Assigned Protocols),
1166		 * the urgent pointer points to the last octet
1167		 * of urgent data.  We continue, however,
1168		 * to consider it to indicate the first octet
1169		 * of data past the urgent section as the original
1170		 * spec states (in one of two places).
1171		 */
1172		if (SEQ_GT(ti->ti_seq+ti->ti_urp, tp->rcv_up)) {
1173			tp->rcv_up = ti->ti_seq + ti->ti_urp;
1174			so->so_oobmark = so->so_rcv.sb_cc +
1175			    (tp->rcv_up - tp->rcv_nxt) - 1;
1176			if (so->so_oobmark == 0)
1177				so->so_state |= SS_RCVATMARK;
1178			sohasoutofband(so);
1179			tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
1180		}
1181		/*
1182		 * Remove out of band data so doesn't get presented to user.
1183		 * This can happen independent of advancing the URG pointer,
1184		 * but if two URG's are pending at once, some out-of-band
1185		 * data may creep in... ick.
1186		 */
1187		if (ti->ti_urp <= (u_long)ti->ti_len
1188#ifdef SO_OOBINLINE
1189		     && (so->so_options & SO_OOBINLINE) == 0
1190#endif
1191		     )
1192			tcp_pulloutofband(so, ti, m);
1193	} else
1194		/*
1195		 * If no out of band data is expected,
1196		 * pull receive urgent pointer along
1197		 * with the receive window.
1198		 */
1199		if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
1200			tp->rcv_up = tp->rcv_nxt;
1201dodata:							/* XXX */
1202
1203	/*
1204	 * Process the segment text, merging it into the TCP sequencing queue,
1205	 * and arranging for acknowledgment of receipt if necessary.
1206	 * This process logically involves adjusting tp->rcv_wnd as data
1207	 * is presented to the user (this happens in tcp_usrreq.c,
1208	 * case PRU_RCVD).  If a FIN has already been received on this
1209	 * connection then we just ignore the text.
1210	 */
1211	if ((ti->ti_len || (tiflags&TH_FIN)) &&
1212	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
1213		TCP_REASS(tp, ti, m, so, tiflags);
1214		/*
1215		 * Note the amount of data that peer has sent into
1216		 * our window, in order to estimate the sender's
1217		 * buffer size.
1218		 */
1219		len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
1220	} else {
1221		m_freem(m);
1222		tiflags &= ~TH_FIN;
1223	}
1224
1225	/*
1226	 * If FIN is received ACK the FIN and let the user know
1227	 * that the connection is closing.
1228	 */
1229	if (tiflags & TH_FIN) {
1230		if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
1231			socantrcvmore(so);
1232			tp->t_flags |= TF_ACKNOW;
1233			tp->rcv_nxt++;
1234		}
1235		switch (tp->t_state) {
1236
1237	 	/*
1238		 * In SYN_RECEIVED and ESTABLISHED STATES
1239		 * enter the CLOSE_WAIT state.
1240		 */
1241		case TCPS_SYN_RECEIVED:
1242		case TCPS_ESTABLISHED:
1243			tp->t_state = TCPS_CLOSE_WAIT;
1244			break;
1245
1246	 	/*
1247		 * If still in FIN_WAIT_1 STATE FIN has not been acked so
1248		 * enter the CLOSING state.
1249		 */
1250		case TCPS_FIN_WAIT_1:
1251			tp->t_state = TCPS_CLOSING;
1252			break;
1253
1254	 	/*
1255		 * In FIN_WAIT_2 state enter the TIME_WAIT state,
1256		 * starting the time-wait timer, turning off the other
1257		 * standard timers.
1258		 */
1259		case TCPS_FIN_WAIT_2:
1260			tp->t_state = TCPS_TIME_WAIT;
1261			tcp_canceltimers(tp);
1262			tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
1263			soisdisconnected(so);
1264			break;
1265
1266		/*
1267		 * In TIME_WAIT state restart the 2 MSL time_wait timer.
1268		 */
1269		case TCPS_TIME_WAIT:
1270			tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
1271			break;
1272		}
1273	}
1274	if (so->so_options & SO_DEBUG)
1275		tcp_trace(TA_INPUT, ostate, tp, &tcp_saveti, 0);
1276
1277	/*
1278	 * If this is a small packet, then ACK now - with Nagel
1279	 *      congestion avoidance sender won't send more until
1280	 *      he gets an ACK.
1281	 */
1282	if (ti->ti_len && ((unsigned)ti->ti_len < tp->t_maxseg))
1283		tp->t_flags |= TF_ACKNOW;
1284
1285	/*
1286	 * Return any desired output.
1287	 */
1288	if (needoutput || (tp->t_flags & TF_ACKNOW))
1289		(void) tcp_output(tp);
1290	return;
1291
1292dropafterack:
1293	/*
1294	 * Generate an ACK dropping incoming segment if it occupies
1295	 * sequence space, where the ACK reflects our state.
1296	 */
1297	if (tiflags & TH_RST)
1298		goto drop;
1299	m_freem(m);
1300	tp->t_flags |= TF_ACKNOW;
1301	(void) tcp_output(tp);
1302	return;
1303
1304dropwithreset:
1305	/*
1306	 * Generate a RST, dropping incoming segment.
1307	 * Make ACK acceptable to originator of segment.
1308	 * Don't bother to respond if destination was broadcast/multicast.
1309	 */
1310	if ((tiflags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST) ||
1311	    IN_MULTICAST(ntohl(ti->ti_dst.s_addr)))
1312		goto drop;
1313	if (tiflags & TH_ACK)
1314		tcp_respond(tp, ti, m, (tcp_seq)0, ti->ti_ack, TH_RST);
1315	else {
1316		if (tiflags & TH_SYN)
1317			ti->ti_len++;
1318		tcp_respond(tp, ti, m, ti->ti_seq+ti->ti_len, (tcp_seq)0,
1319		    TH_RST|TH_ACK);
1320	}
1321	/* destroy temporarily created socket */
1322	if (dropsocket)
1323		(void) soabort(so);
1324	return;
1325
1326drop:
1327	/*
1328	 * Drop space held by incoming segment and return.
1329	 */
1330	if (tp && (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
1331		tcp_trace(TA_DROP, ostate, tp, &tcp_saveti, 0);
1332	m_freem(m);
1333	/* destroy temporarily created socket */
1334	if (dropsocket)
1335		(void) soabort(so);
1336	return;
1337#ifndef TUBA_INCLUDE
1338}
1339
1340void
1341tcp_dooptions(tp, cp, cnt, ti, ts_present, ts_val, ts_ecr)
1342	struct tcpcb *tp;
1343	u_char *cp;
1344	int cnt;
1345	struct tcpiphdr *ti;
1346	int *ts_present;
1347	u_long *ts_val, *ts_ecr;
1348{
1349	u_short mss;
1350	int opt, optlen;
1351
1352	for (; cnt > 0; cnt -= optlen, cp += optlen) {
1353		opt = cp[0];
1354		if (opt == TCPOPT_EOL)
1355			break;
1356		if (opt == TCPOPT_NOP)
1357			optlen = 1;
1358		else {
1359			optlen = cp[1];
1360			if (optlen <= 0)
1361				break;
1362		}
1363		switch (opt) {
1364
1365		default:
1366			continue;
1367
1368		case TCPOPT_MAXSEG:
1369			if (optlen != TCPOLEN_MAXSEG)
1370				continue;
1371			if (!(ti->ti_flags & TH_SYN))
1372				continue;
1373			bcopy((char *) cp + 2, (char *) &mss, sizeof(mss));
1374			NTOHS(mss);
1375			(void) tcp_mss(tp, mss);	/* sets t_maxseg */
1376			break;
1377
1378		case TCPOPT_WINDOW:
1379			if (optlen != TCPOLEN_WINDOW)
1380				continue;
1381			if (!(ti->ti_flags & TH_SYN))
1382				continue;
1383			tp->t_flags |= TF_RCVD_SCALE;
1384			tp->requested_s_scale = min(cp[2], TCP_MAX_WINSHIFT);
1385			break;
1386
1387		case TCPOPT_TIMESTAMP:
1388			if (optlen != TCPOLEN_TIMESTAMP)
1389				continue;
1390			*ts_present = 1;
1391			bcopy((char *)cp + 2, (char *) ts_val, sizeof(*ts_val));
1392			NTOHL(*ts_val);
1393			bcopy((char *)cp + 6, (char *) ts_ecr, sizeof(*ts_ecr));
1394			NTOHL(*ts_ecr);
1395
1396			/*
1397			 * A timestamp received in a SYN makes
1398			 * it ok to send timestamp requests and replies.
1399			 */
1400			if (ti->ti_flags & TH_SYN) {
1401				tp->t_flags |= TF_RCVD_TSTMP;
1402				tp->ts_recent = *ts_val;
1403				tp->ts_recent_age = tcp_now;
1404			}
1405			break;
1406		}
1407	}
1408}
1409
1410/*
1411 * Pull out of band byte out of a segment so
1412 * it doesn't appear in the user's data queue.
1413 * It is still reflected in the segment length for
1414 * sequencing purposes.
1415 */
1416void
1417tcp_pulloutofband(so, ti, m)
1418	struct socket *so;
1419	struct tcpiphdr *ti;
1420	register struct mbuf *m;
1421{
1422	int cnt = ti->ti_urp - 1;
1423
1424	while (cnt >= 0) {
1425		if (m->m_len > cnt) {
1426			char *cp = mtod(m, caddr_t) + cnt;
1427			struct tcpcb *tp = sototcpcb(so);
1428
1429			tp->t_iobc = *cp;
1430			tp->t_oobflags |= TCPOOB_HAVEDATA;
1431			bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
1432			m->m_len--;
1433			return;
1434		}
1435		cnt -= m->m_len;
1436		m = m->m_next;
1437		if (m == 0)
1438			break;
1439	}
1440	panic("tcp_pulloutofband");
1441}
1442
1443/*
1444 * Collect new round-trip time estimate
1445 * and update averages and current timeout.
1446 */
1447void
1448tcp_xmit_timer(tp, rtt)
1449	register struct tcpcb *tp;
1450	short rtt;
1451{
1452	register short delta;
1453
1454	tcpstat.tcps_rttupdated++;
1455	if (tp->t_srtt != 0) {
1456		/*
1457		 * srtt is stored as fixed point with 3 bits after the
1458		 * binary point (i.e., scaled by 8).  The following magic
1459		 * is equivalent to the smoothing algorithm in rfc793 with
1460		 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
1461		 * point).  Adjust rtt to origin 0.
1462		 */
1463		delta = rtt - 1 - (tp->t_srtt >> TCP_RTT_SHIFT);
1464		if ((tp->t_srtt += delta) <= 0)
1465			tp->t_srtt = 1;
1466		/*
1467		 * We accumulate a smoothed rtt variance (actually, a
1468		 * smoothed mean difference), then set the retransmit
1469		 * timer to smoothed rtt + 4 times the smoothed variance.
1470		 * rttvar is stored as fixed point with 2 bits after the
1471		 * binary point (scaled by 4).  The following is
1472		 * equivalent to rfc793 smoothing with an alpha of .75
1473		 * (rttvar = rttvar*3/4 + |delta| / 4).  This replaces
1474		 * rfc793's wired-in beta.
1475		 */
1476		if (delta < 0)
1477			delta = -delta;
1478		delta -= (tp->t_rttvar >> TCP_RTTVAR_SHIFT);
1479		if ((tp->t_rttvar += delta) <= 0)
1480			tp->t_rttvar = 1;
1481	} else {
1482		/*
1483		 * No rtt measurement yet - use the unsmoothed rtt.
1484		 * Set the variance to half the rtt (so our first
1485		 * retransmit happens at 3*rtt).
1486		 */
1487		tp->t_srtt = rtt << TCP_RTT_SHIFT;
1488		tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
1489	}
1490	tp->t_rtt = 0;
1491	tp->t_rxtshift = 0;
1492
1493	/*
1494	 * the retransmit should happen at rtt + 4 * rttvar.
1495	 * Because of the way we do the smoothing, srtt and rttvar
1496	 * will each average +1/2 tick of bias.  When we compute
1497	 * the retransmit timer, we want 1/2 tick of rounding and
1498	 * 1 extra tick because of +-1/2 tick uncertainty in the
1499	 * firing of the timer.  The bias will give us exactly the
1500	 * 1.5 tick we need.  But, because the bias is
1501	 * statistical, we have to test that we don't drop below
1502	 * the minimum feasible timer (which is 2 ticks).
1503	 */
1504	TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
1505	    tp->t_rttmin, TCPTV_REXMTMAX);
1506
1507	/*
1508	 * We received an ack for a packet that wasn't retransmitted;
1509	 * it is probably safe to discard any error indications we've
1510	 * received recently.  This isn't quite right, but close enough
1511	 * for now (a route might have failed after we sent a segment,
1512	 * and the return path might not be symmetrical).
1513	 */
1514	tp->t_softerror = 0;
1515}
1516
1517/*
1518 * Determine a reasonable value for maxseg size.
1519 * If the route is known, check route for mtu.
1520 * If none, use an mss that can be handled on the outgoing
1521 * interface without forcing IP to fragment; if bigger than
1522 * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
1523 * to utilize large mbufs.  If no route is found, route has no mtu,
1524 * or the destination isn't local, use a default, hopefully conservative
1525 * size (usually 512 or the default IP max size, but no more than the mtu
1526 * of the interface), as we can't discover anything about intervening
1527 * gateways or networks.  We also initialize the congestion/slow start
1528 * window to be a single segment if the destination isn't local.
1529 * While looking at the routing entry, we also initialize other path-dependent
1530 * parameters from pre-set or cached values in the routing entry.
1531 */
1532int
1533tcp_mss(tp, offer)
1534	register struct tcpcb *tp;
1535	u_int offer;
1536{
1537	struct route *ro;
1538	register struct rtentry *rt;
1539	struct ifnet *ifp;
1540	register int rtt, mss;
1541	u_long bufsize;
1542	struct inpcb *inp;
1543	struct socket *so;
1544	extern int tcp_mssdflt;
1545
1546	inp = tp->t_inpcb;
1547	ro = &inp->inp_route;
1548
1549	if ((rt = ro->ro_rt) == (struct rtentry *)0) {
1550		/* No route yet, so try to acquire one */
1551		if (inp->inp_faddr.s_addr != INADDR_ANY) {
1552			ro->ro_dst.sa_family = AF_INET;
1553			ro->ro_dst.sa_len = sizeof(ro->ro_dst);
1554			((struct sockaddr_in *) &ro->ro_dst)->sin_addr =
1555				inp->inp_faddr;
1556			rtalloc(ro);
1557		}
1558		if ((rt = ro->ro_rt) == (struct rtentry *)0)
1559			return (tcp_mssdflt);
1560	}
1561	ifp = rt->rt_ifp;
1562	so = inp->inp_socket;
1563
1564#ifdef RTV_MTU	/* if route characteristics exist ... */
1565	/*
1566	 * While we're here, check if there's an initial rtt
1567	 * or rttvar.  Convert from the route-table units
1568	 * to scaled multiples of the slow timeout timer.
1569	 */
1570	if (tp->t_srtt == 0 && (rtt = rt->rt_rmx.rmx_rtt)) {
1571		/*
1572		 * XXX the lock bit for MTU indicates that the value
1573		 * is also a minimum value; this is subject to time.
1574		 */
1575		if (rt->rt_rmx.rmx_locks & RTV_RTT)
1576			tp->t_rttmin = rtt / (RTM_RTTUNIT / PR_SLOWHZ);
1577		tp->t_srtt = rtt / (RTM_RTTUNIT / (PR_SLOWHZ * TCP_RTT_SCALE));
1578		if (rt->rt_rmx.rmx_rttvar)
1579			tp->t_rttvar = rt->rt_rmx.rmx_rttvar /
1580			    (RTM_RTTUNIT / (PR_SLOWHZ * TCP_RTTVAR_SCALE));
1581		else
1582			/* default variation is +- 1 rtt */
1583			tp->t_rttvar =
1584			    tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
1585		TCPT_RANGESET(tp->t_rxtcur,
1586		    ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
1587		    tp->t_rttmin, TCPTV_REXMTMAX);
1588	}
1589	/*
1590	 * if there's an mtu associated with the route, use it
1591	 */
1592	if (rt->rt_rmx.rmx_mtu)
1593		mss = rt->rt_rmx.rmx_mtu - sizeof(struct tcpiphdr);
1594	else
1595#endif /* RTV_MTU */
1596	{
1597		mss = ifp->if_mtu - sizeof(struct tcpiphdr);
1598#if	(MCLBYTES & (MCLBYTES - 1)) == 0
1599		if (mss > MCLBYTES)
1600			mss &= ~(MCLBYTES-1);
1601#else
1602		if (mss > MCLBYTES)
1603			mss = mss / MCLBYTES * MCLBYTES;
1604#endif
1605		if (!in_localaddr(inp->inp_faddr))
1606			mss = min(mss, tcp_mssdflt);
1607	}
1608	/*
1609	 * The current mss, t_maxseg, is initialized to the default value.
1610	 * If we compute a smaller value, reduce the current mss.
1611	 * If we compute a larger value, return it for use in sending
1612	 * a max seg size option, but don't store it for use
1613	 * unless we received an offer at least that large from peer.
1614	 * However, do not accept offers under 32 bytes.
1615	 */
1616	if (offer)
1617		mss = min(mss, offer);
1618	mss = max(mss, 32);		/* sanity */
1619	if (mss < tp->t_maxseg || offer != 0) {
1620		/*
1621		 * If there's a pipesize, change the socket buffer
1622		 * to that size.  Make the socket buffers an integral
1623		 * number of mss units; if the mss is larger than
1624		 * the socket buffer, decrease the mss.
1625		 */
1626#ifdef RTV_SPIPE
1627		if ((bufsize = rt->rt_rmx.rmx_sendpipe) == 0)
1628#endif
1629			bufsize = so->so_snd.sb_hiwat;
1630		if (bufsize < mss)
1631			mss = bufsize;
1632		else {
1633			bufsize = roundup(bufsize, mss);
1634			if (bufsize > sb_max)
1635				bufsize = sb_max;
1636			(void)sbreserve(&so->so_snd, bufsize);
1637		}
1638		tp->t_maxseg = mss;
1639
1640#ifdef RTV_RPIPE
1641		if ((bufsize = rt->rt_rmx.rmx_recvpipe) == 0)
1642#endif
1643			bufsize = so->so_rcv.sb_hiwat;
1644		if (bufsize > mss) {
1645			bufsize = roundup(bufsize, mss);
1646			if (bufsize > sb_max)
1647				bufsize = sb_max;
1648			(void)sbreserve(&so->so_rcv, bufsize);
1649		}
1650	}
1651	tp->snd_cwnd = mss;
1652
1653#ifdef RTV_SSTHRESH
1654	if (rt->rt_rmx.rmx_ssthresh) {
1655		/*
1656		 * There's some sort of gateway or interface
1657		 * buffer limit on the path.  Use this to set
1658		 * the slow start threshhold, but set the
1659		 * threshold to no less than 2*mss.
1660		 */
1661		tp->snd_ssthresh = max(2 * mss, rt->rt_rmx.rmx_ssthresh);
1662	}
1663#endif /* RTV_MTU */
1664	return (mss);
1665}
1666#endif /* TUBA_INCLUDE */
1667