AF_IPN is no longer protocol #34 (assigned to AF_ISDN).
[vde.git] / vde-2 / src / slirpvde / tcp_input.c
blob87c3f678a503547ffc53016f400258d037c6c18c
1 /*
2 * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994
3 * The Regents of the University of California. All rights reserved.
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.
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.
33 * @(#)tcp_input.c 8.5 (Berkeley) 4/10/94
34 * tcp_input.c,v 1.10 1994/10/13 18:36:32 wollman Exp
38 * Changes and additions relating to SLiRP
39 * Copyright (c) 1995 Danny Gasparovski.
41 * Please read the file COPYRIGHT for the
42 * terms and conditions of the copyright.
45 #include "slirp.h"
46 #include "ip_icmp.h"
47 #include <stdlib.h>
48 #include <sys/time.h>
49 #include <time.h>
50 #include <unistd.h>
52 #include <config.h>
53 #include <vde.h>
54 #include <vdecommon.h>
56 struct socket tcb;
58 #define min(x,y) ((x) < (y) ? (x) : (y))
59 #define max(x,y) ((x) > (y) ? (x) : (y))
61 int tcprexmtthresh = 3;
62 struct socket *tcp_last_so = &tcb;
64 tcp_seq tcp_iss; /* tcp initial send seq # */
66 #define TCP_PAWS_IDLE (24 * 24 * 60 * 60 * PR_SLOWHZ)
68 /* for modulo comparisons of timestamps */
69 #define TSTMP_LT(a,b) ((int)((a)-(b)) < 0)
70 #define TSTMP_GEQ(a,b) ((int)((a)-(b)) >= 0)
73 * Insert segment ti into reassembly queue of tcp with
74 * control block tp. Return TH_FIN if reassembly now includes
75 * a segment with FIN. The macro form does the common case inline
76 * (segment is the next to be received on an established connection,
77 * and the queue is empty), avoiding linkage into and removal
78 * from the queue and repetition of various conversions.
79 * Set DELACK for segments received in order, but ack immediately
80 * when segments are out of order (so fast retransmit can work).
82 #ifdef TCP_ACK_HACK
83 #define TCP_REASS(tp, ti, m, so, flags) {\
84 if ((ti)->ti_seq == (tp)->rcv_nxt && \
85 (tp)->seg_next == (tcpiphdrp_32)(tp) && \
86 (tp)->t_state == TCPS_ESTABLISHED) {\
87 if (ti->ti_flags & TH_PUSH) \
88 tp->t_flags |= TF_ACKNOW; \
89 else \
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 if (so->so_emu) { \
96 if (tcp_emu((so),(m))) sbappend((so), (m)); \
97 } else \
98 sbappend((so), (m)); \
99 /* sorwakeup(so); */ \
100 } else {\
101 (flags) = tcp_reass((tp), (ti), (m)); \
102 tp->t_flags |= TF_ACKNOW; \
105 #else
106 #define TCP_REASS(tp, ti, m, so, flags) { \
107 if ((ti)->ti_seq == (tp)->rcv_nxt && \
108 (tp)->seg_next == (tcpiphdrp_32)(tp) && \
109 (tp)->t_state == TCPS_ESTABLISHED) { \
110 tp->t_flags |= TF_DELACK; \
111 (tp)->rcv_nxt += (ti)->ti_len; \
112 flags = (ti)->ti_flags & TH_FIN; \
113 tcpstat.tcps_rcvpack++;\
114 tcpstat.tcps_rcvbyte += (ti)->ti_len;\
115 if (so->so_emu) { \
116 if (tcp_emu((so),(m))) sbappend(so, (m)); \
117 } else \
118 sbappend((so), (m)); \
119 /* sorwakeup(so); */ \
120 } else { \
121 (flags) = tcp_reass((tp), (ti), (m)); \
122 tp->t_flags |= TF_ACKNOW; \
125 #endif
128 tcp_reass(tp, ti, m)
129 register struct tcpcb *tp;
130 register struct tcpiphdr *ti;
131 struct mbuf *m;
133 register struct tcpiphdr *q;
134 struct socket *so = tp->t_socket;
135 int flags;
138 * Call with ti==0 after become established to
139 * force pre-ESTABLISHED data up to user socket.
141 if (ti == 0)
142 goto present;
145 * Find a segment which begins after this one does.
147 for (q = (struct tcpiphdr *)tp->seg_next; q != (struct tcpiphdr *)tp;
148 q = (struct tcpiphdr *)q->ti_next)
149 if (SEQ_GT(q->ti_seq, ti->ti_seq))
150 break;
153 * If there is a preceding segment, it may provide some of
154 * our data already. If so, drop the data from the incoming
155 * segment. If it provides all of our data, drop us.
157 if ((struct tcpiphdr *)q->ti_prev != (struct tcpiphdr *)tp) {
158 register int i;
159 q = (struct tcpiphdr *)q->ti_prev;
160 /* conversion to int (in i) handles seq wraparound */
161 i = q->ti_seq + q->ti_len - ti->ti_seq;
162 if (i > 0) {
163 if (i >= ti->ti_len) {
164 tcpstat.tcps_rcvduppack++;
165 tcpstat.tcps_rcvdupbyte += ti->ti_len;
166 m_freem(m);
168 * Try to present any queued data
169 * at the left window edge to the user.
170 * This is needed after the 3-WHS
171 * completes.
173 goto present; /* ??? */
175 m_adj(m, i);
176 ti->ti_len -= i;
177 ti->ti_seq += i;
179 q = (struct tcpiphdr *)(q->ti_next);
181 tcpstat.tcps_rcvoopack++;
182 tcpstat.tcps_rcvoobyte += ti->ti_len;
183 REASS_MBUF(ti) = (mbufp_32) m; /* XXX */
186 * While we overlap succeeding segments trim them or,
187 * if they are completely covered, dequeue them.
189 while (q != (struct tcpiphdr *)tp) {
190 register int i = (ti->ti_seq + ti->ti_len) - q->ti_seq;
191 if (i <= 0)
192 break;
193 if (i < q->ti_len) {
194 q->ti_seq += i;
195 q->ti_len -= i;
196 m_adj((struct mbuf *) REASS_MBUF(q), i);
197 break;
199 q = (struct tcpiphdr *)q->ti_next;
200 m = (struct mbuf *) REASS_MBUF((struct tcpiphdr *)q->ti_prev);
201 remque_32((void *)(q->ti_prev));
202 m_freem(m);
206 * Stick new segment in its place.
208 insque_32(ti, (void *)(q->ti_prev));
210 present:
212 * Present data to user, advancing rcv_nxt through
213 * completed sequence space.
215 if (!TCPS_HAVEESTABLISHED(tp->t_state))
216 return (0);
217 ti = (struct tcpiphdr *) tp->seg_next;
218 if (ti == (struct tcpiphdr *)tp || ti->ti_seq != tp->rcv_nxt)
219 return (0);
220 if (tp->t_state == TCPS_SYN_RECEIVED && ti->ti_len)
221 return (0);
222 do {
223 tp->rcv_nxt += ti->ti_len;
224 flags = ti->ti_flags & TH_FIN;
225 remque_32(ti);
226 m = (struct mbuf *) REASS_MBUF(ti); /* XXX */
227 ti = (struct tcpiphdr *)ti->ti_next;
228 /* if (so->so_state & SS_FCANTRCVMORE) */
229 if (so->so_state & SS_FCANTSENDMORE)
230 m_freem(m);
231 else {
232 if (so->so_emu) {
233 if (tcp_emu(so,m)) sbappend(so, m);
234 } else
235 sbappend(so, m);
237 } while (ti != (struct tcpiphdr *)tp && ti->ti_seq == tp->rcv_nxt);
238 /* sorwakeup(so); */
239 return (flags);
243 * TCP input routine, follows pages 65-76 of the
244 * protocol specification dated September, 1981 very closely.
246 void
247 tcp_input(m, iphlen, inso)
248 register struct mbuf *m;
249 int iphlen;
250 struct socket *inso;
252 struct ip save_ip, *ip;
253 register struct tcpiphdr *ti;
254 caddr_t optp = NULL;
255 int optlen = 0;
256 int len, tlen, off;
257 register struct tcpcb *tp = 0;
258 register int tiflags;
259 struct socket *so = 0;
260 int todrop, acked, ourfinisacked, needoutput = 0;
261 /* int dropsocket = 0; */
262 int iss = 0;
263 u_long tiwin;
264 int ret;
265 /* int ts_present = 0; */
267 DEBUG_CALL("tcp_input");
268 DEBUG_ARGS((dfd," m = %8lx iphlen = %2d inso = %lx\n",
269 (long )m, iphlen, (long )inso ));
272 * If called with m == 0, then we're continuing the connect
274 if (m == NULL) {
275 so = inso;
277 /* Re-set a few variables */
278 tp = sototcpcb(so);
279 m = so->so_m;
280 so->so_m = 0;
281 ti = so->so_ti;
282 tiwin = ti->ti_win;
283 tiflags = ti->ti_flags;
285 goto cont_conn;
289 tcpstat.tcps_rcvtotal++;
291 * Get IP and TCP header together in first mbuf.
292 * Note: IP leaves IP header in first mbuf.
294 ti = mtod(m, struct tcpiphdr *);
295 if (iphlen > sizeof(struct ip )) {
296 ip_stripoptions(m, (struct mbuf *)0);
297 iphlen=sizeof(struct ip );
299 /* XXX Check if too short */
303 * Save a copy of the IP header in case we want restore it
304 * for sending an ICMP error message in response.
306 ip=mtod(m, struct ip *);
307 save_ip = *ip;
310 * Checksum extended TCP header and data.
312 //tlen = ((struct ip *)ti)->ip_len;
313 // use save_ip instead of ti to be avoid gcc aliasing optimization problems
314 tlen=save_ip.ip_len;
315 ti->ti_next = ti->ti_prev = 0;
316 ti->ti_x1 = 0;
317 ti->ti_len = htons((u_int16_t)tlen);
318 len = sizeof(struct ip ) + tlen;
319 /* keep checksum for ICMP reply
320 * ti->ti_sum = cksum(m, len);
321 * if (ti->ti_sum) { */
322 if(cksum(m, len)) {
323 tcpstat.tcps_rcvbadsum++;
324 goto drop;
327 save_ip.ip_len+= iphlen;
330 * Check that TCP offset makes sense,
331 * pull out TCP options and adjust length. XXX
333 off = ti->ti_off << 2;
334 if (off < sizeof (struct tcphdr) || off > tlen) {
335 tcpstat.tcps_rcvbadoff++;
336 goto drop;
338 tlen -= off;
339 ti->ti_len = tlen;
340 if (off > sizeof (struct tcphdr)) {
341 optlen = off - sizeof (struct tcphdr);
342 optp = mtod(m, caddr_t) + sizeof (struct tcpiphdr);
345 * Do quick retrieval of timestamp options ("options
346 * prediction?"). If timestamp is the only option and it's
347 * formatted as recommended in RFC 1323 appendix A, we
348 * quickly get the values now and not bother calling
349 * tcp_dooptions(), etc.
351 /* if ((optlen == TCPOLEN_TSTAMP_APPA ||
352 * (optlen > TCPOLEN_TSTAMP_APPA &&
353 * optp[TCPOLEN_TSTAMP_APPA] == TCPOPT_EOL)) &&
354 * *(u_int32_t *)optp == htonl(TCPOPT_TSTAMP_HDR) &&
355 * (ti->ti_flags & TH_SYN) == 0) {
356 * ts_present = 1;
357 * ts_val = ntohl(*(u_int32_t *)(optp + 4));
358 * ts_ecr = ntohl(*(u_int32_t *)(optp + 8));
359 * optp = NULL; / * we've parsed the options * /
363 tiflags = ti->ti_flags;
366 * Convert TCP protocol specific fields to host format.
368 NTOHL(ti->ti_seq);
369 NTOHL(ti->ti_ack);
370 NTOHS(ti->ti_win);
371 NTOHS(ti->ti_urp);
374 * Drop TCP, IP headers and TCP options.
376 m->m_data += sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr);
377 m->m_len -= sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr);
380 * Locate pcb for segment.
382 findso:
383 so = tcp_last_so;
384 if (so->so_fport != ti->ti_dport ||
385 so->so_lport != ti->ti_sport ||
386 so->so_laddr.s_addr != ti->ti_src.s_addr ||
387 so->so_faddr.s_addr != ti->ti_dst.s_addr) {
388 so = solookup(&tcb, ti->ti_src, ti->ti_sport,
389 ti->ti_dst, ti->ti_dport);
390 if (so)
391 tcp_last_so = so;
392 ++tcpstat.tcps_socachemiss;
396 * If the state is CLOSED (i.e., TCB does not exist) then
397 * all data in the incoming segment is discarded.
398 * If the TCB exists but is in CLOSED state, it is embryonic,
399 * but should either do a listen or a connect soon.
401 * state == CLOSED means we've done socreate() but haven't
402 * attached it to a protocol yet...
404 * XXX If a TCB does not exist, and the TH_SYN flag is
405 * the only flag set, then create a session, mark it
406 * as if it was LISTENING, and continue...
408 if (so == 0) {
409 if ((tiflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) != TH_SYN)
410 goto dropwithreset;
412 if ((so = socreate()) == NULL)
413 goto dropwithreset;
414 if (tcp_attach(so) < 0) {
415 free(so); /* Not sofree (if it failed, it's not insqued) */
416 goto dropwithreset;
419 sbreserve(&so->so_snd, tcp_sndspace);
420 sbreserve(&so->so_rcv, tcp_rcvspace);
422 /* tcp_last_so = so; */ /* XXX ? */
423 /* tp = sototcpcb(so); */
425 so->so_laddr = ti->ti_src;
426 so->so_lport = ti->ti_sport;
427 so->so_faddr = ti->ti_dst;
428 so->so_fport = ti->ti_dport;
430 if ((so->so_iptos = tcp_tos(so)) == 0)
431 so->so_iptos = ((struct ip *)ti)->ip_tos;
433 tp = sototcpcb(so);
434 tp->t_state = TCPS_LISTEN;
438 * If this is a still-connecting socket, this probably
439 * a retransmit of the SYN. Whether it's a retransmit SYN
440 * or something else, we nuke it.
442 if (so->so_state & SS_ISFCONNECTING)
443 goto drop;
444 tp = sototcpcb(so);
446 /* XXX Should never fail */
447 if (tp == 0)
448 goto dropwithreset;
449 if (tp->t_state == TCPS_CLOSED)
450 goto drop;
452 /* Unscale the window into a 32-bit value. */
453 /* if ((tiflags & TH_SYN) == 0)
454 * tiwin = ti->ti_win << tp->snd_scale;
455 * else
457 tiwin = ti->ti_win;
460 * Segment received on connection.
461 * Reset idle time and keep-alive timer.
463 tp->t_idle = 0;
464 if (so_options)
465 tp->t_timer[TCPT_KEEP] = tcp_keepintvl;
466 else
467 tp->t_timer[TCPT_KEEP] = tcp_keepidle;
470 * Process options if not in LISTEN state,
471 * else do it below (after getting remote address).
473 if (optp && tp->t_state != TCPS_LISTEN)
474 tcp_dooptions(tp, (u_char *)optp, optlen, ti);
475 /* , */
476 /* &ts_present, &ts_val, &ts_ecr); */
479 * Header prediction: check for the two common cases
480 * of a uni-directional data xfer. If the packet has
481 * no control flags, is in-sequence, the window didn't
482 * change and we're not retransmitting, it's a
483 * candidate. If the length is zero and the ack moved
484 * forward, we're the sender side of the xfer. Just
485 * free the data acked & wake any higher level process
486 * that was blocked waiting for space. If the length
487 * is non-zero and the ack didn't move, we're the
488 * receiver side. If we're getting packets in-order
489 * (the reassembly queue is empty), add the data to
490 * the socket buffer and note that we need a delayed ack.
492 * XXX Some of these tests are not needed
493 * eg: the tiwin == tp->snd_wnd prevents many more
494 * predictions.. with no *real* advantage..
496 if (tp->t_state == TCPS_ESTABLISHED &&
497 (tiflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
498 /* (!ts_present || TSTMP_GEQ(ts_val, tp->ts_recent)) && */
499 ti->ti_seq == tp->rcv_nxt &&
500 tiwin && tiwin == tp->snd_wnd &&
501 tp->snd_nxt == tp->snd_max) {
503 * If last ACK falls within this segment's sequence numbers,
504 * record the timestamp.
506 /* if (ts_present && SEQ_LEQ(ti->ti_seq, tp->last_ack_sent) &&
507 * SEQ_LT(tp->last_ack_sent, ti->ti_seq + ti->ti_len)) {
508 * tp->ts_recent_age = tcp_now;
509 * tp->ts_recent = ts_val;
512 if (ti->ti_len == 0) {
513 if (SEQ_GT(ti->ti_ack, tp->snd_una) &&
514 SEQ_LEQ(ti->ti_ack, tp->snd_max) &&
515 tp->snd_cwnd >= tp->snd_wnd) {
517 * this is a pure ack for outstanding data.
519 ++tcpstat.tcps_predack;
520 /* if (ts_present)
521 * tcp_xmit_timer(tp, tcp_now-ts_ecr+1);
522 * else
523 */ if (tp->t_rtt &&
524 SEQ_GT(ti->ti_ack, tp->t_rtseq))
525 tcp_xmit_timer(tp, tp->t_rtt);
526 acked = ti->ti_ack - tp->snd_una;
527 tcpstat.tcps_rcvackpack++;
528 tcpstat.tcps_rcvackbyte += acked;
529 sbdrop(&so->so_snd, acked);
530 tp->snd_una = ti->ti_ack;
531 m_freem(m);
534 * If all outstanding data are acked, stop
535 * retransmit timer, otherwise restart timer
536 * using current (possibly backed-off) value.
537 * If process is waiting for space,
538 * wakeup/selwakeup/signal. If data
539 * are ready to send, let tcp_output
540 * decide between more output or persist.
542 if (tp->snd_una == tp->snd_max)
543 tp->t_timer[TCPT_REXMT] = 0;
544 else if (tp->t_timer[TCPT_PERSIST] == 0)
545 tp->t_timer[TCPT_REXMT] = tp->t_rxtcur;
548 * There's room in so_snd, sowwakup will read()
549 * from the socket if we can
551 /* if (so->so_snd.sb_flags & SB_NOTIFY)
552 * sowwakeup(so);
555 * This is called because sowwakeup might have
556 * put data into so_snd. Since we don't so sowwakeup,
557 * we don't need this.. XXX???
559 if (so->so_snd.sb_cc)
560 (void) tcp_output(tp);
562 return;
564 } else if (ti->ti_ack == tp->snd_una &&
565 tp->seg_next == (tcpiphdrp_32)tp &&
566 ti->ti_len <= sbspace(&so->so_rcv)) {
568 * this is a pure, in-sequence data packet
569 * with nothing on the reassembly queue and
570 * we have enough buffer space to take it.
572 ++tcpstat.tcps_preddat;
573 tp->rcv_nxt += ti->ti_len;
574 tcpstat.tcps_rcvpack++;
575 tcpstat.tcps_rcvbyte += ti->ti_len;
577 * Add data to socket buffer.
579 if (so->so_emu) {
580 if (tcp_emu(so,m)) sbappend(so, m);
581 } else
582 sbappend(so, m);
585 * XXX This is called when data arrives. Later, check
586 * if we can actually write() to the socket
587 * XXX Need to check? It's be NON_BLOCKING
589 /* sorwakeup(so); */
592 * If this is a short packet, then ACK now - with Nagel
593 * congestion avoidance sender won't send more until
594 * he gets an ACK.
596 * Here are 3 interpretations of what should happen.
597 * The best (for me) is to delay-ack everything except
598 * if it's a one-byte packet containing an ESC
599 * (this means it's an arrow key (or similar) sent using
600 * Nagel, hence there will be no echo)
601 * The first of these is the original, the second is the
602 * middle ground between the other 2
604 /* if (((unsigned)ti->ti_len < tp->t_maxseg)) {
606 /* if (((unsigned)ti->ti_len < tp->t_maxseg &&
607 * (so->so_iptos & IPTOS_LOWDELAY) == 0) ||
608 * ((so->so_iptos & IPTOS_LOWDELAY) &&
609 * ((struct tcpiphdr_2 *)ti)->first_char == (char)27)) {
611 if ((unsigned)ti->ti_len == 1 &&
612 ((struct tcpiphdr_2 *)ti)->first_char == (char)27) {
613 tp->t_flags |= TF_ACKNOW;
614 tcp_output(tp);
615 } else {
616 tp->t_flags |= TF_DELACK;
618 return;
620 } /* header prediction */
622 * Calculate amount of space in receive window,
623 * and then do TCP input processing.
624 * Receive window is amount of space in rcv queue,
625 * but not less than advertised window.
627 { int win;
628 win = sbspace(&so->so_rcv);
629 if (win < 0)
630 win = 0;
631 tp->rcv_wnd = max(win, (int)(tp->rcv_adv - tp->rcv_nxt));
634 switch (tp->t_state) {
637 * If the state is LISTEN then ignore segment if it contains an RST.
638 * If the segment contains an ACK then it is bad and send a RST.
639 * If it does not contain a SYN then it is not interesting; drop it.
640 * Don't bother responding if the destination was a broadcast.
641 * Otherwise initialize tp->rcv_nxt, and tp->irs, select an initial
642 * tp->iss, and send a segment:
643 * <SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK>
644 * Also initialize tp->snd_nxt to tp->iss+1 and tp->snd_una to tp->iss.
645 * Fill in remote peer address fields if not previously specified.
646 * Enter SYN_RECEIVED state, and process any other fields of this
647 * segment in this state.
649 case TCPS_LISTEN: {
651 if (tiflags & TH_RST)
652 goto drop;
653 if (tiflags & TH_ACK)
654 goto dropwithreset;
655 if ((tiflags & TH_SYN) == 0)
656 goto drop;
659 * This has way too many gotos...
660 * But a bit of spaghetti code never hurt anybody :)
664 * If this is destined for the control address, then flag to
665 * tcp_ctl once connected, otherwise connect
667 if ((so->so_faddr.s_addr&htonl(0xffffff00)) == special_addr.s_addr) {
668 int lastbyte=ntohl(so->so_faddr.s_addr) & 0xff;
669 if (lastbyte!=CTL_ALIAS && lastbyte!=CTL_DNS) {
670 #if 0
671 if(lastbyte==CTL_CMD || lastbyte==CTL_EXEC) {
672 /* Command or exec adress */
673 so->so_state |= SS_CTL;
674 } else {
675 /* May be an add exec */
676 struct ex_list *ex_ptr;
678 for(ex_ptr = exec_list; ex_ptr; ex_ptr = ex_ptr->ex_next) {
679 if(ex_ptr->ex_fport == so->so_fport &&
680 lastbyte == ex_ptr->ex_addr) {
681 so->so_state |= SS_CTL;
682 break;
686 if(so->so_state & SS_CTL) goto cont_input;
687 #endif
689 /* CTL_ALIAS: Do nothing, tcp_fconnect will be called on it */
692 if (so->so_emu & EMU_NOCONNECT) {
693 so->so_emu &= ~EMU_NOCONNECT;
694 goto cont_input;
697 if(tcp_fconnect(so) == -1 && errno != EINPROGRESS) {
698 u_char code=ICMP_UNREACH_NET;
699 DEBUG_MISC((dfd," tcp fconnect errno = %d-%s\n",
700 errno,strerror(errno)));
701 if(errno == ECONNREFUSED) {
702 /* ACK the SYN, send RST to refuse the connection */
703 tcp_respond(tp, ti, m, ti->ti_seq+1, (tcp_seq)0,
704 TH_RST|TH_ACK);
705 } else {
706 if(errno == EHOSTUNREACH) code=ICMP_UNREACH_HOST;
707 HTONL(ti->ti_seq); /* restore tcp header */
708 HTONL(ti->ti_ack);
709 HTONS(ti->ti_win);
710 HTONS(ti->ti_urp);
711 m->m_data -= sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr);
712 m->m_len += sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr);
713 *ip=save_ip;
714 icmp_error(m, ICMP_UNREACH,code, 0,strerror(errno));
716 tp = tcp_close(tp);
717 m_free(m);
718 } else {
720 * Haven't connected yet, save the current mbuf
721 * and ti, and return
722 * XXX Some OS's don't tell us whether the connect()
723 * succeeded or not. So we must time it out.
725 so->so_m = m;
726 so->so_ti = ti;
727 tp->t_timer[TCPT_KEEP] = TCPTV_KEEP_INIT;
728 tp->t_state = TCPS_SYN_RECEIVED;
730 return;
732 cont_conn:
733 /* m==NULL
734 * Check if the connect succeeded
736 if (so->so_state & SS_NOFDREF) {
737 tp = tcp_close(tp);
738 goto dropwithreset;
740 cont_input:
741 tcp_template(tp);
743 if (optp)
744 tcp_dooptions(tp, (u_char *)optp, optlen, ti);
745 /* , */
746 /* &ts_present, &ts_val, &ts_ecr); */
748 if (iss)
749 tp->iss = iss;
750 else
751 tp->iss = tcp_iss;
752 tcp_iss += TCP_ISSINCR/2;
753 tp->irs = ti->ti_seq;
754 tcp_sendseqinit(tp);
755 tcp_rcvseqinit(tp);
756 tp->t_flags |= TF_ACKNOW;
757 tp->t_state = TCPS_SYN_RECEIVED;
758 tp->t_timer[TCPT_KEEP] = TCPTV_KEEP_INIT;
759 tcpstat.tcps_accepts++;
760 goto trimthenstep6;
761 } /* case TCPS_LISTEN */
764 * If the state is SYN_SENT:
765 * if seg contains an ACK, but not for our SYN, drop the input.
766 * if seg contains a RST, then drop the connection.
767 * if seg does not contain SYN, then drop it.
768 * Otherwise this is an acceptable SYN segment
769 * initialize tp->rcv_nxt and tp->irs
770 * if seg contains ack then advance tp->snd_una
771 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state
772 * arrange for segment to be acked (eventually)
773 * continue processing rest of data/controls, beginning with URG
775 case TCPS_SYN_SENT:
776 if ((tiflags & TH_ACK) &&
777 (SEQ_LEQ(ti->ti_ack, tp->iss) ||
778 SEQ_GT(ti->ti_ack, tp->snd_max)))
779 goto dropwithreset;
781 if (tiflags & TH_RST) {
782 if (tiflags & TH_ACK)
783 tp = tcp_drop(tp,0); /* XXX Check t_softerror! */
784 goto drop;
787 if ((tiflags & TH_SYN) == 0)
788 goto drop;
789 if (tiflags & TH_ACK) {
790 tp->snd_una = ti->ti_ack;
791 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
792 tp->snd_nxt = tp->snd_una;
795 tp->t_timer[TCPT_REXMT] = 0;
796 tp->irs = ti->ti_seq;
797 tcp_rcvseqinit(tp);
798 tp->t_flags |= TF_ACKNOW;
799 if (tiflags & TH_ACK && SEQ_GT(tp->snd_una, tp->iss)) {
800 tcpstat.tcps_connects++;
801 soisfconnected(so);
802 tp->t_state = TCPS_ESTABLISHED;
804 /* Do window scaling on this connection? */
805 /* if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
806 * (TF_RCVD_SCALE|TF_REQ_SCALE)) {
807 * tp->snd_scale = tp->requested_s_scale;
808 * tp->rcv_scale = tp->request_r_scale;
811 (void) tcp_reass(tp, (struct tcpiphdr *)0,
812 (struct mbuf *)0);
814 * if we didn't have to retransmit the SYN,
815 * use its rtt as our initial srtt & rtt var.
817 if (tp->t_rtt)
818 tcp_xmit_timer(tp, tp->t_rtt);
819 } else
820 tp->t_state = TCPS_SYN_RECEIVED;
822 trimthenstep6:
824 * Advance ti->ti_seq to correspond to first data byte.
825 * If data, trim to stay within window,
826 * dropping FIN if necessary.
828 ti->ti_seq++;
829 if (ti->ti_len > tp->rcv_wnd) {
830 todrop = ti->ti_len - tp->rcv_wnd;
831 m_adj(m, -todrop);
832 ti->ti_len = tp->rcv_wnd;
833 tiflags &= ~TH_FIN;
834 tcpstat.tcps_rcvpackafterwin++;
835 tcpstat.tcps_rcvbyteafterwin += todrop;
837 tp->snd_wl1 = ti->ti_seq - 1;
838 tp->rcv_up = ti->ti_seq;
839 goto step6;
840 } /* switch tp->t_state */
842 * States other than LISTEN or SYN_SENT.
843 * First check timestamp, if present.
844 * Then check that at least some bytes of segment are within
845 * receive window. If segment begins before rcv_nxt,
846 * drop leading data (and SYN); if nothing left, just ack.
848 * RFC 1323 PAWS: If we have a timestamp reply on this segment
849 * and it's less than ts_recent, drop it.
851 /* if (ts_present && (tiflags & TH_RST) == 0 && tp->ts_recent &&
852 * TSTMP_LT(ts_val, tp->ts_recent)) {
854 */ /* Check to see if ts_recent is over 24 days old. */
855 /* if ((int)(tcp_now - tp->ts_recent_age) > TCP_PAWS_IDLE) {
856 */ /*
857 * * Invalidate ts_recent. If this segment updates
858 * * ts_recent, the age will be reset later and ts_recent
859 * * will get a valid value. If it does not, setting
860 * * ts_recent to zero will at least satisfy the
861 * * requirement that zero be placed in the timestamp
862 * * echo reply when ts_recent isn't valid. The
863 * * age isn't reset until we get a valid ts_recent
864 * * because we don't want out-of-order segments to be
865 * * dropped when ts_recent is old.
866 * */
867 /* tp->ts_recent = 0;
868 * } else {
869 * tcpstat.tcps_rcvduppack++;
870 * tcpstat.tcps_rcvdupbyte += ti->ti_len;
871 * tcpstat.tcps_pawsdrop++;
872 * goto dropafterack;
877 todrop = tp->rcv_nxt - ti->ti_seq;
878 if (todrop > 0) {
879 if (tiflags & TH_SYN) {
880 tiflags &= ~TH_SYN;
881 ti->ti_seq++;
882 if (ti->ti_urp > 1)
883 ti->ti_urp--;
884 else
885 tiflags &= ~TH_URG;
886 todrop--;
889 * Following if statement from Stevens, vol. 2, p. 960.
891 if (todrop > ti->ti_len
892 || (todrop == ti->ti_len && (tiflags & TH_FIN) == 0)) {
894 * Any valid FIN must be to the left of the window.
895 * At this point the FIN must be a duplicate or out
896 * of sequence; drop it.
898 tiflags &= ~TH_FIN;
901 * Send an ACK to resynchronize and drop any data.
902 * But keep on processing for RST or ACK.
904 tp->t_flags |= TF_ACKNOW;
905 todrop = ti->ti_len;
906 tcpstat.tcps_rcvduppack++;
907 tcpstat.tcps_rcvdupbyte += todrop;
908 } else {
909 tcpstat.tcps_rcvpartduppack++;
910 tcpstat.tcps_rcvpartdupbyte += todrop;
912 m_adj(m, todrop);
913 ti->ti_seq += todrop;
914 ti->ti_len -= todrop;
915 if (ti->ti_urp > todrop)
916 ti->ti_urp -= todrop;
917 else {
918 tiflags &= ~TH_URG;
919 ti->ti_urp = 0;
923 * If new data are received on a connection after the
924 * user processes are gone, then RST the other end.
926 if ((so->so_state & SS_NOFDREF) &&
927 tp->t_state > TCPS_CLOSE_WAIT && ti->ti_len) {
928 tp = tcp_close(tp);
929 tcpstat.tcps_rcvafterclose++;
930 goto dropwithreset;
934 * If segment ends after window, drop trailing data
935 * (and PUSH and FIN); if nothing left, just ACK.
937 todrop = (ti->ti_seq+ti->ti_len) - (tp->rcv_nxt+tp->rcv_wnd);
938 if (todrop > 0) {
939 tcpstat.tcps_rcvpackafterwin++;
940 if (todrop >= ti->ti_len) {
941 tcpstat.tcps_rcvbyteafterwin += ti->ti_len;
943 * If a new connection request is received
944 * while in TIME_WAIT, drop the old connection
945 * and start over if the sequence numbers
946 * are above the previous ones.
948 if (tiflags & TH_SYN &&
949 tp->t_state == TCPS_TIME_WAIT &&
950 SEQ_GT(ti->ti_seq, tp->rcv_nxt)) {
951 iss = tp->rcv_nxt + TCP_ISSINCR;
952 tp = tcp_close(tp);
953 goto findso;
956 * If window is closed can only take segments at
957 * window edge, and have to drop data and PUSH from
958 * incoming segments. Continue processing, but
959 * remember to ack. Otherwise, drop segment
960 * and ack.
962 if (tp->rcv_wnd == 0 && ti->ti_seq == tp->rcv_nxt) {
963 tp->t_flags |= TF_ACKNOW;
964 tcpstat.tcps_rcvwinprobe++;
965 } else
966 goto dropafterack;
967 } else
968 tcpstat.tcps_rcvbyteafterwin += todrop;
969 m_adj(m, -todrop);
970 ti->ti_len -= todrop;
971 tiflags &= ~(TH_PUSH|TH_FIN);
975 * If last ACK falls within this segment's sequence numbers,
976 * record its timestamp.
978 /* if (ts_present && SEQ_LEQ(ti->ti_seq, tp->last_ack_sent) &&
979 * SEQ_LT(tp->last_ack_sent, ti->ti_seq + ti->ti_len +
980 * ((tiflags & (TH_SYN|TH_FIN)) != 0))) {
981 * tp->ts_recent_age = tcp_now;
982 * tp->ts_recent = ts_val;
987 * If the RST bit is set examine the state:
988 * SYN_RECEIVED STATE:
989 * If passive open, return to LISTEN state.
990 * If active open, inform user that connection was refused.
991 * ESTABLISHED, FIN_WAIT_1, FIN_WAIT2, CLOSE_WAIT STATES:
992 * Inform user that connection was reset, and close tcb.
993 * CLOSING, LAST_ACK, TIME_WAIT STATES
994 * Close the tcb.
996 if (tiflags&TH_RST) switch (tp->t_state) {
998 case TCPS_SYN_RECEIVED:
999 /* so->so_error = ECONNREFUSED; */
1000 goto close;
1002 case TCPS_ESTABLISHED:
1003 case TCPS_FIN_WAIT_1:
1004 case TCPS_FIN_WAIT_2:
1005 case TCPS_CLOSE_WAIT:
1006 /* so->so_error = ECONNRESET; */
1007 close:
1008 tp->t_state = TCPS_CLOSED;
1009 tcpstat.tcps_drops++;
1010 tp = tcp_close(tp);
1011 goto drop;
1013 case TCPS_CLOSING:
1014 case TCPS_LAST_ACK:
1015 case TCPS_TIME_WAIT:
1016 tp = tcp_close(tp);
1017 goto drop;
1021 * If a SYN is in the window, then this is an
1022 * error and we send an RST and drop the connection.
1024 if (tiflags & TH_SYN) {
1025 tp = tcp_drop(tp,0);
1026 goto dropwithreset;
1030 * If the ACK bit is off we drop the segment and return.
1032 if ((tiflags & TH_ACK) == 0) goto drop;
1035 * Ack processing.
1037 switch (tp->t_state) {
1039 * In SYN_RECEIVED state if the ack ACKs our SYN then enter
1040 * ESTABLISHED state and continue processing, otherwise
1041 * send an RST. una<=ack<=max
1043 case TCPS_SYN_RECEIVED:
1045 if (SEQ_GT(tp->snd_una, ti->ti_ack) ||
1046 SEQ_GT(ti->ti_ack, tp->snd_max))
1047 goto dropwithreset;
1048 tcpstat.tcps_connects++;
1049 tp->t_state = TCPS_ESTABLISHED;
1051 * The sent SYN is ack'ed with our sequence number +1
1052 * The first data byte already in the buffer will get
1053 * lost if no correction is made. This is only needed for
1054 * SS_CTL since the buffer is empty otherwise.
1055 * tp->snd_una++; or:
1057 tp->snd_una=ti->ti_ack;
1058 if (so->so_state & SS_CTL) {
1059 /* So tcp_ctl reports the right state */
1060 ret = tcp_ctl(so);
1061 if (ret == 1) {
1062 soisfconnected(so);
1063 so->so_state &= ~SS_CTL; /* success XXX */
1064 } else if (ret == 2) {
1065 so->so_state = SS_NOFDREF; /* CTL_CMD */
1066 } else {
1067 needoutput = 1;
1068 tp->t_state = TCPS_FIN_WAIT_1;
1070 } else {
1071 soisfconnected(so);
1074 /* Do window scaling? */
1075 /* if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1076 * (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1077 * tp->snd_scale = tp->requested_s_scale;
1078 * tp->rcv_scale = tp->request_r_scale;
1081 (void) tcp_reass(tp, (struct tcpiphdr *)0, (struct mbuf *)0);
1082 tp->snd_wl1 = ti->ti_seq - 1;
1083 /* Avoid ack processing; snd_una==ti_ack => dup ack */
1084 goto synrx_to_est;
1085 /* fall into ... */
1088 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
1089 * ACKs. If the ack is in the range
1090 * tp->snd_una < ti->ti_ack <= tp->snd_max
1091 * then advance tp->snd_una to ti->ti_ack and drop
1092 * data from the retransmission queue. If this ACK reflects
1093 * more up to date window information we update our window information.
1095 case TCPS_ESTABLISHED:
1096 case TCPS_FIN_WAIT_1:
1097 case TCPS_FIN_WAIT_2:
1098 case TCPS_CLOSE_WAIT:
1099 case TCPS_CLOSING:
1100 case TCPS_LAST_ACK:
1101 case TCPS_TIME_WAIT:
1103 if (SEQ_LEQ(ti->ti_ack, tp->snd_una)) {
1104 if (ti->ti_len == 0 && tiwin == tp->snd_wnd) {
1105 tcpstat.tcps_rcvdupack++;
1106 DEBUG_MISC((dfd," dup ack m = %lx so = %lx \n",
1107 (long )m, (long )so));
1109 * If we have outstanding data (other than
1110 * a window probe), this is a completely
1111 * duplicate ack (ie, window info didn't
1112 * change), the ack is the biggest we've
1113 * seen and we've seen exactly our rexmt
1114 * threshold of them, assume a packet
1115 * has been dropped and retransmit it.
1116 * Kludge snd_nxt & the congestion
1117 * window so we send only this one
1118 * packet.
1120 * We know we're losing at the current
1121 * window size so do congestion avoidance
1122 * (set ssthresh to half the current window
1123 * and pull our congestion window back to
1124 * the new ssthresh).
1126 * Dup acks mean that packets have left the
1127 * network (they're now cached at the receiver)
1128 * so bump cwnd by the amount in the receiver
1129 * to keep a constant cwnd packets in the
1130 * network.
1132 if (tp->t_timer[TCPT_REXMT] == 0 ||
1133 ti->ti_ack != tp->snd_una)
1134 tp->t_dupacks = 0;
1135 else if (++tp->t_dupacks == tcprexmtthresh) {
1136 tcp_seq onxt = tp->snd_nxt;
1137 u_int win =
1138 min(tp->snd_wnd, tp->snd_cwnd) / 2 /
1139 tp->t_maxseg;
1141 if (win < 2)
1142 win = 2;
1143 tp->snd_ssthresh = win * tp->t_maxseg;
1144 tp->t_timer[TCPT_REXMT] = 0;
1145 tp->t_rtt = 0;
1146 tp->snd_nxt = ti->ti_ack;
1147 tp->snd_cwnd = tp->t_maxseg;
1148 (void) tcp_output(tp);
1149 tp->snd_cwnd = tp->snd_ssthresh +
1150 tp->t_maxseg * tp->t_dupacks;
1151 if (SEQ_GT(onxt, tp->snd_nxt))
1152 tp->snd_nxt = onxt;
1153 goto drop;
1154 } else if (tp->t_dupacks > tcprexmtthresh) {
1155 tp->snd_cwnd += tp->t_maxseg;
1156 (void) tcp_output(tp);
1157 goto drop;
1159 } else
1160 tp->t_dupacks = 0;
1161 break;
1163 synrx_to_est:
1165 * If the congestion window was inflated to account
1166 * for the other side's cached packets, retract it.
1168 if (tp->t_dupacks > tcprexmtthresh &&
1169 tp->snd_cwnd > tp->snd_ssthresh)
1170 tp->snd_cwnd = tp->snd_ssthresh;
1171 tp->t_dupacks = 0;
1172 if (SEQ_GT(ti->ti_ack, tp->snd_max)) {
1173 tcpstat.tcps_rcvacktoomuch++;
1174 goto dropafterack;
1176 acked = ti->ti_ack - tp->snd_una;
1177 tcpstat.tcps_rcvackpack++;
1178 tcpstat.tcps_rcvackbyte += acked;
1181 * If we have a timestamp reply, update smoothed
1182 * round trip time. If no timestamp is present but
1183 * transmit timer is running and timed sequence
1184 * number was acked, update smoothed round trip time.
1185 * Since we now have an rtt measurement, cancel the
1186 * timer backoff (cf., Phil Karn's retransmit alg.).
1187 * Recompute the initial retransmit timer.
1189 /* if (ts_present)
1190 * tcp_xmit_timer(tp, tcp_now-ts_ecr+1);
1191 * else
1193 if (tp->t_rtt && SEQ_GT(ti->ti_ack, tp->t_rtseq))
1194 tcp_xmit_timer(tp,tp->t_rtt);
1197 * If all outstanding data is acked, stop retransmit
1198 * timer and remember to restart (more output or persist).
1199 * If there is more data to be acked, restart retransmit
1200 * timer, using current (possibly backed-off) value.
1202 if (ti->ti_ack == tp->snd_max) {
1203 tp->t_timer[TCPT_REXMT] = 0;
1204 needoutput = 1;
1205 } else if (tp->t_timer[TCPT_PERSIST] == 0)
1206 tp->t_timer[TCPT_REXMT] = tp->t_rxtcur;
1208 * When new data is acked, open the congestion window.
1209 * If the window gives us less than ssthresh packets
1210 * in flight, open exponentially (maxseg per packet).
1211 * Otherwise open linearly: maxseg per window
1212 * (maxseg^2 / cwnd per packet).
1215 register u_int cw = tp->snd_cwnd;
1216 register u_int incr = tp->t_maxseg;
1218 if (cw > tp->snd_ssthresh)
1219 incr = incr * incr / cw;
1220 tp->snd_cwnd = min(cw + incr, TCP_MAXWIN<<tp->snd_scale);
1222 if (acked > so->so_snd.sb_cc) {
1223 tp->snd_wnd -= so->so_snd.sb_cc;
1224 sbdrop(&so->so_snd, (int )so->so_snd.sb_cc);
1225 ourfinisacked = 1;
1226 } else {
1227 sbdrop(&so->so_snd, acked);
1228 tp->snd_wnd -= acked;
1229 ourfinisacked = 0;
1232 * XXX sowwakup is called when data is acked and there's room for
1233 * for more data... it should read() the socket
1235 /* if (so->so_snd.sb_flags & SB_NOTIFY)
1236 * sowwakeup(so);
1238 tp->snd_una = ti->ti_ack;
1239 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
1240 tp->snd_nxt = tp->snd_una;
1242 switch (tp->t_state) {
1245 * In FIN_WAIT_1 STATE in addition to the processing
1246 * for the ESTABLISHED state if our FIN is now acknowledged
1247 * then enter FIN_WAIT_2.
1249 case TCPS_FIN_WAIT_1:
1250 if (ourfinisacked) {
1252 * If we can't receive any more
1253 * data, then closing user can proceed.
1254 * Starting the timer is contrary to the
1255 * specification, but if we don't get a FIN
1256 * we'll hang forever.
1258 if (so->so_state & SS_FCANTRCVMORE) {
1259 soisfdisconnected(so);
1260 tp->t_timer[TCPT_2MSL] = tcp_maxidle;
1262 tp->t_state = TCPS_FIN_WAIT_2;
1264 break;
1267 * In CLOSING STATE in addition to the processing for
1268 * the ESTABLISHED state if the ACK acknowledges our FIN
1269 * then enter the TIME-WAIT state, otherwise ignore
1270 * the segment.
1272 case TCPS_CLOSING:
1273 if (ourfinisacked) {
1274 tp->t_state = TCPS_TIME_WAIT;
1275 tcp_canceltimers(tp);
1276 tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
1277 soisfdisconnected(so);
1279 break;
1282 * In LAST_ACK, we may still be waiting for data to drain
1283 * and/or to be acked, as well as for the ack of our FIN.
1284 * If our FIN is now acknowledged, delete the TCB,
1285 * enter the closed state and return.
1287 case TCPS_LAST_ACK:
1288 if (ourfinisacked) {
1289 tp = tcp_close(tp);
1290 goto drop;
1292 break;
1295 * In TIME_WAIT state the only thing that should arrive
1296 * is a retransmission of the remote FIN. Acknowledge
1297 * it and restart the finack timer.
1299 case TCPS_TIME_WAIT:
1300 tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
1301 goto dropafterack;
1303 } /* switch(tp->t_state) */
1305 step6:
1307 * Update window information.
1308 * Don't look at window if no ACK: TAC's send garbage on first SYN.
1310 if ((tiflags & TH_ACK) &&
1311 (SEQ_LT(tp->snd_wl1, ti->ti_seq) ||
1312 (tp->snd_wl1 == ti->ti_seq && (SEQ_LT(tp->snd_wl2, ti->ti_ack) ||
1313 (tp->snd_wl2 == ti->ti_ack && tiwin > tp->snd_wnd))))) {
1314 /* keep track of pure window updates */
1315 if (ti->ti_len == 0 &&
1316 tp->snd_wl2 == ti->ti_ack && tiwin > tp->snd_wnd)
1317 tcpstat.tcps_rcvwinupd++;
1318 tp->snd_wnd = tiwin;
1319 tp->snd_wl1 = ti->ti_seq;
1320 tp->snd_wl2 = ti->ti_ack;
1321 if (tp->snd_wnd > tp->max_sndwnd)
1322 tp->max_sndwnd = tp->snd_wnd;
1323 needoutput = 1;
1327 * Process segments with URG.
1329 if ((tiflags & TH_URG) && ti->ti_urp &&
1330 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
1332 * This is a kludge, but if we receive and accept
1333 * random urgent pointers, we'll crash in
1334 * soreceive. It's hard to imagine someone
1335 * actually wanting to send this much urgent data.
1337 if (ti->ti_urp + so->so_rcv.sb_cc > so->so_rcv.sb_datalen) {
1338 ti->ti_urp = 0;
1339 tiflags &= ~TH_URG;
1340 goto dodata;
1343 * If this segment advances the known urgent pointer,
1344 * then mark the data stream. This should not happen
1345 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
1346 * a FIN has been received from the remote side.
1347 * In these states we ignore the URG.
1349 * According to RFC961 (Assigned Protocols),
1350 * the urgent pointer points to the last octet
1351 * of urgent data. We continue, however,
1352 * to consider it to indicate the first octet
1353 * of data past the urgent section as the original
1354 * spec states (in one of two places).
1356 if (SEQ_GT(ti->ti_seq+ti->ti_urp, tp->rcv_up)) {
1357 tp->rcv_up = ti->ti_seq + ti->ti_urp;
1358 so->so_urgc = so->so_rcv.sb_cc +
1359 (tp->rcv_up - tp->rcv_nxt); /* -1; */
1360 tp->rcv_up = ti->ti_seq + ti->ti_urp;
1363 } else
1365 * If no out of band data is expected,
1366 * pull receive urgent pointer along
1367 * with the receive window.
1369 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
1370 tp->rcv_up = tp->rcv_nxt;
1371 dodata:
1374 * Process the segment text, merging it into the TCP sequencing queue,
1375 * and arranging for acknowledgment of receipt if necessary.
1376 * This process logically involves adjusting tp->rcv_wnd as data
1377 * is presented to the user (this happens in tcp_usrreq.c,
1378 * case PRU_RCVD). If a FIN has already been received on this
1379 * connection then we just ignore the text.
1381 if ((ti->ti_len || (tiflags&TH_FIN)) &&
1382 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
1383 TCP_REASS(tp, ti, m, so, tiflags);
1385 * Note the amount of data that peer has sent into
1386 * our window, in order to estimate the sender's
1387 * buffer size.
1389 len = so->so_rcv.sb_datalen - (tp->rcv_adv - tp->rcv_nxt);
1390 } else {
1391 m_free(m);
1392 tiflags &= ~TH_FIN;
1396 * If FIN is received ACK the FIN and let the user know
1397 * that the connection is closing.
1399 if (tiflags & TH_FIN) {
1400 if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
1402 * If we receive a FIN we can't send more data,
1403 * set it SS_FDRAIN
1404 * Shutdown the socket if there is no rx data in the
1405 * buffer.
1406 * soread() is called on completion of shutdown() and
1407 * will got to TCPS_LAST_ACK, and use tcp_output()
1408 * to send the FIN.
1410 /* sofcantrcvmore(so); */
1411 sofwdrain(so);
1413 tp->t_flags |= TF_ACKNOW;
1414 tp->rcv_nxt++;
1416 switch (tp->t_state) {
1419 * In SYN_RECEIVED and ESTABLISHED STATES
1420 * enter the CLOSE_WAIT state.
1422 case TCPS_SYN_RECEIVED:
1423 case TCPS_ESTABLISHED:
1424 if(so->so_emu == EMU_CTL) /* no shutdown on socket */
1425 tp->t_state = TCPS_LAST_ACK;
1426 else
1427 tp->t_state = TCPS_CLOSE_WAIT;
1428 break;
1431 * If still in FIN_WAIT_1 STATE FIN has not been acked so
1432 * enter the CLOSING state.
1434 case TCPS_FIN_WAIT_1:
1435 tp->t_state = TCPS_CLOSING;
1436 break;
1439 * In FIN_WAIT_2 state enter the TIME_WAIT state,
1440 * starting the time-wait timer, turning off the other
1441 * standard timers.
1443 case TCPS_FIN_WAIT_2:
1444 tp->t_state = TCPS_TIME_WAIT;
1445 tcp_canceltimers(tp);
1446 tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
1447 soisfdisconnected(so);
1448 break;
1451 * In TIME_WAIT state restart the 2 MSL time_wait timer.
1453 case TCPS_TIME_WAIT:
1454 tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
1455 break;
1460 * If this is a small packet, then ACK now - with Nagel
1461 * congestion avoidance sender won't send more until
1462 * he gets an ACK.
1464 * See above.
1466 /* if (ti->ti_len && (unsigned)ti->ti_len < tp->t_maxseg) {
1468 /* if ((ti->ti_len && (unsigned)ti->ti_len < tp->t_maxseg &&
1469 * (so->so_iptos & IPTOS_LOWDELAY) == 0) ||
1470 * ((so->so_iptos & IPTOS_LOWDELAY) &&
1471 * ((struct tcpiphdr_2 *)ti)->first_char == (char)27)) {
1473 if (ti->ti_len && (unsigned)ti->ti_len <= 5 &&
1474 ((struct tcpiphdr_2 *)ti)->first_char == (char)27) {
1475 tp->t_flags |= TF_ACKNOW;
1479 * Return any desired output.
1481 if (needoutput || (tp->t_flags & TF_ACKNOW)) {
1482 (void) tcp_output(tp);
1484 return;
1486 dropafterack:
1488 * Generate an ACK dropping incoming segment if it occupies
1489 * sequence space, where the ACK reflects our state.
1491 if (tiflags & TH_RST)
1492 goto drop;
1493 m_freem(m);
1494 tp->t_flags |= TF_ACKNOW;
1495 (void) tcp_output(tp);
1496 return;
1498 dropwithreset:
1499 /* reuses m if m!=NULL, m_free() unnecessary */
1500 if (tiflags & TH_ACK)
1501 tcp_respond(tp, ti, m, (tcp_seq)0, ti->ti_ack, TH_RST);
1502 else {
1503 if (tiflags & TH_SYN) ti->ti_len++;
1504 tcp_respond(tp, ti, m, ti->ti_seq+ti->ti_len, (tcp_seq)0,
1505 TH_RST|TH_ACK);
1508 return;
1510 drop:
1512 * Drop space held by incoming segment and return.
1514 m_free(m);
1516 return;
1519 /* , ts_present, ts_val, ts_ecr) */
1520 /* int *ts_present;
1521 * u_int32_t *ts_val, *ts_ecr;
1523 void
1524 tcp_dooptions(tp, cp, cnt, ti)
1525 struct tcpcb *tp;
1526 u_char *cp;
1527 int cnt;
1528 struct tcpiphdr *ti;
1530 u_int16_t mss;
1531 int opt, optlen;
1533 DEBUG_CALL("tcp_dooptions");
1534 DEBUG_ARGS((dfd," tp = %lx cnt=%i \n", (long )tp, cnt));
1536 for (; cnt > 0; cnt -= optlen, cp += optlen) {
1537 opt = cp[0];
1538 if (opt == TCPOPT_EOL)
1539 break;
1540 if (opt == TCPOPT_NOP)
1541 optlen = 1;
1542 else {
1543 optlen = cp[1];
1544 if (optlen <= 0)
1545 break;
1547 switch (opt) {
1549 default:
1550 continue;
1552 case TCPOPT_MAXSEG:
1553 if (optlen != TCPOLEN_MAXSEG)
1554 continue;
1555 if (!(ti->ti_flags & TH_SYN))
1556 continue;
1557 memcpy((char *) &mss, (char *) cp + 2, sizeof(mss));
1558 NTOHS(mss);
1559 (void) tcp_mss(tp, mss); /* sets t_maxseg */
1560 break;
1562 /* case TCPOPT_WINDOW:
1563 * if (optlen != TCPOLEN_WINDOW)
1564 * continue;
1565 * if (!(ti->ti_flags & TH_SYN))
1566 * continue;
1567 * tp->t_flags |= TF_RCVD_SCALE;
1568 * tp->requested_s_scale = min(cp[2], TCP_MAX_WINSHIFT);
1569 * break;
1571 /* case TCPOPT_TIMESTAMP:
1572 * if (optlen != TCPOLEN_TIMESTAMP)
1573 * continue;
1574 * *ts_present = 1;
1575 * memcpy((char *) ts_val, (char *)cp + 2, sizeof(*ts_val));
1576 * NTOHL(*ts_val);
1577 * memcpy((char *) ts_ecr, (char *)cp + 6, sizeof(*ts_ecr));
1578 * NTOHL(*ts_ecr);
1580 */ /*
1581 * * A timestamp received in a SYN makes
1582 * * it ok to send timestamp requests and replies.
1583 * */
1584 /* if (ti->ti_flags & TH_SYN) {
1585 * tp->t_flags |= TF_RCVD_TSTMP;
1586 * tp->ts_recent = *ts_val;
1587 * tp->ts_recent_age = tcp_now;
1589 */ break;
1596 * Pull out of band byte out of a segment so
1597 * it doesn't appear in the user's data queue.
1598 * It is still reflected in the segment length for
1599 * sequencing purposes.
1602 #ifdef notdef
1604 void
1605 tcp_pulloutofband(so, ti, m)
1606 struct socket *so;
1607 struct tcpiphdr *ti;
1608 register struct mbuf *m;
1610 int cnt = ti->ti_urp - 1;
1612 while (cnt >= 0) {
1613 if (m->m_len > cnt) {
1614 char *cp = mtod(m, caddr_t) + cnt;
1615 struct tcpcb *tp = sototcpcb(so);
1617 tp->t_iobc = *cp;
1618 tp->t_oobflags |= TCPOOB_HAVEDATA;
1619 memcpy(sp, cp+1, (unsigned)(m->m_len - cnt - 1));
1620 m->m_len--;
1621 return;
1623 cnt -= m->m_len;
1624 m = m->m_next; /* XXX WRONG! Fix it! */
1625 if (m == 0)
1626 break;
1628 panic("tcp_pulloutofband");
1631 #endif /* notdef */
1634 * Collect new round-trip time estimate
1635 * and update averages and current timeout.
1638 void
1639 tcp_xmit_timer(tp, rtt)
1640 register struct tcpcb *tp;
1641 int rtt;
1643 register short delta;
1645 DEBUG_CALL("tcp_xmit_timer");
1646 DEBUG_ARG("tp = %lx", (long)tp);
1647 DEBUG_ARG("rtt = %d", rtt);
1649 tcpstat.tcps_rttupdated++;
1650 if (tp->t_srtt != 0) {
1652 * srtt is stored as fixed point with 3 bits after the
1653 * binary point (i.e., scaled by 8). The following magic
1654 * is equivalent to the smoothing algorithm in rfc793 with
1655 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
1656 * point). Adjust rtt to origin 0.
1658 delta = rtt - 1 - (tp->t_srtt >> TCP_RTT_SHIFT);
1659 if ((tp->t_srtt += delta) <= 0)
1660 tp->t_srtt = 1;
1662 * We accumulate a smoothed rtt variance (actually, a
1663 * smoothed mean difference), then set the retransmit
1664 * timer to smoothed rtt + 4 times the smoothed variance.
1665 * rttvar is stored as fixed point with 2 bits after the
1666 * binary point (scaled by 4). The following is
1667 * equivalent to rfc793 smoothing with an alpha of .75
1668 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces
1669 * rfc793's wired-in beta.
1671 if (delta < 0)
1672 delta = -delta;
1673 delta -= (tp->t_rttvar >> TCP_RTTVAR_SHIFT);
1674 if ((tp->t_rttvar += delta) <= 0)
1675 tp->t_rttvar = 1;
1676 } else {
1678 * No rtt measurement yet - use the unsmoothed rtt.
1679 * Set the variance to half the rtt (so our first
1680 * retransmit happens at 3*rtt).
1682 tp->t_srtt = rtt << TCP_RTT_SHIFT;
1683 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
1685 tp->t_rtt = 0;
1686 tp->t_rxtshift = 0;
1689 * the retransmit should happen at rtt + 4 * rttvar.
1690 * Because of the way we do the smoothing, srtt and rttvar
1691 * will each average +1/2 tick of bias. When we compute
1692 * the retransmit timer, we want 1/2 tick of rounding and
1693 * 1 extra tick because of +-1/2 tick uncertainty in the
1694 * firing of the timer. The bias will give us exactly the
1695 * 1.5 tick we need. But, because the bias is
1696 * statistical, we have to test that we don't drop below
1697 * the minimum feasible timer (which is 2 ticks).
1699 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
1700 (short)tp->t_rttmin, TCPTV_REXMTMAX); /* XXX */
1703 * We received an ack for a packet that wasn't retransmitted;
1704 * it is probably safe to discard any error indications we've
1705 * received recently. This isn't quite right, but close enough
1706 * for now (a route might have failed after we sent a segment,
1707 * and the return path might not be symmetrical).
1709 tp->t_softerror = 0;
1713 * Determine a reasonable value for maxseg size.
1714 * If the route is known, check route for mtu.
1715 * If none, use an mss that can be handled on the outgoing
1716 * interface without forcing IP to fragment; if bigger than
1717 * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
1718 * to utilize large mbufs. If no route is found, route has no mtu,
1719 * or the destination isn't local, use a default, hopefully conservative
1720 * size (usually 512 or the default IP max size, but no more than the mtu
1721 * of the interface), as we can't discover anything about intervening
1722 * gateways or networks. We also initialize the congestion/slow start
1723 * window to be a single segment if the destination isn't local.
1724 * While looking at the routing entry, we also initialize other path-dependent
1725 * parameters from pre-set or cached values in the routing entry.
1729 tcp_mss(tp, offer)
1730 register struct tcpcb *tp;
1731 u_int offer;
1733 struct socket *so = tp->t_socket;
1734 int mss;
1736 DEBUG_CALL("tcp_mss");
1737 DEBUG_ARG("tp = %lx", (long)tp);
1738 DEBUG_ARG("offer = %d", offer);
1740 mss = min(if_mtu, if_mru) - sizeof(struct tcpiphdr);
1741 if (offer)
1742 mss = min(mss, offer);
1743 mss = max(mss, 32);
1744 if (mss < tp->t_maxseg || offer != 0)
1745 tp->t_maxseg = mss;
1747 tp->snd_cwnd = mss;
1749 sbreserve(&so->so_snd, tcp_sndspace+((tcp_sndspace%mss)?(mss-(tcp_sndspace%mss)):0));
1750 sbreserve(&so->so_rcv, tcp_rcvspace+((tcp_rcvspace%mss)?(mss-(tcp_rcvspace%mss)):0));
1752 DEBUG_MISC((dfd, " returning mss = %d\n", mss));
1754 return mss;