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