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