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
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.
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
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
34 * Changes and additions relating to SLiRP
35 * Copyright (c) 1995 Danny Gasparovski.
37 * Please read the file COPYRIGHT for the
38 * terms and conditions of the copyright.
41 #include "qemu/osdep.h"
45 #define TCPREXMTTHRESH 3
47 #define TCP_PAWS_IDLE (24 * 24 * 60 * 60 * PR_SLOWHZ)
49 /* for modulo comparisons of timestamps */
50 #define TSTMP_LT(a,b) ((int)((a)-(b)) < 0)
51 #define TSTMP_GEQ(a,b) ((int)((a)-(b)) >= 0)
54 * Insert segment ti into reassembly queue of tcp with
55 * control block tp. Return TH_FIN if reassembly now includes
56 * a segment with FIN. The macro form does the common case inline
57 * (segment is the next to be received on an established connection,
58 * and the queue is empty), avoiding linkage into and removal
59 * from the queue and repetition of various conversions.
60 * Set DELACK for segments received in order, but ack immediately
61 * when segments are out of order (so fast retransmit can work).
64 #define TCP_REASS(tp, ti, m, so, flags) {\
65 if ((ti)->ti_seq == (tp)->rcv_nxt && \
66 tcpfrag_list_empty(tp) && \
67 (tp)->t_state == TCPS_ESTABLISHED) {\
68 if (ti->ti_flags & TH_PUSH) \
69 tp->t_flags |= TF_ACKNOW; \
71 tp->t_flags |= TF_DELACK; \
72 (tp)->rcv_nxt += (ti)->ti_len; \
73 flags = (ti)->ti_flags & TH_FIN; \
75 if (tcp_emu((so),(m))) sbappend((so), (m)); \
77 sbappend((so), (m)); \
79 (flags) = tcp_reass((tp), (ti), (m)); \
80 tp->t_flags |= TF_ACKNOW; \
84 #define TCP_REASS(tp, ti, m, so, flags) { \
85 if ((ti)->ti_seq == (tp)->rcv_nxt && \
86 tcpfrag_list_empty(tp) && \
87 (tp)->t_state == TCPS_ESTABLISHED) { \
88 tp->t_flags |= TF_DELACK; \
89 (tp)->rcv_nxt += (ti)->ti_len; \
90 flags = (ti)->ti_flags & TH_FIN; \
92 if (tcp_emu((so),(m))) sbappend(so, (m)); \
94 sbappend((so), (m)); \
96 (flags) = tcp_reass((tp), (ti), (m)); \
97 tp->t_flags |= TF_ACKNOW; \
101 static void tcp_dooptions(struct tcpcb
*tp
, u_char
*cp
, int cnt
,
102 struct tcpiphdr
*ti
);
103 static void tcp_xmit_timer(register struct tcpcb
*tp
, int rtt
);
106 tcp_reass(register struct tcpcb
*tp
, register struct tcpiphdr
*ti
,
109 register struct tcpiphdr
*q
;
110 struct socket
*so
= tp
->t_socket
;
114 * Call with ti==NULL after become established to
115 * force pre-ESTABLISHED data up to user socket.
121 * Find a segment which begins after this one does.
123 for (q
= tcpfrag_list_first(tp
); !tcpfrag_list_end(q
, tp
);
124 q
= tcpiphdr_next(q
))
125 if (SEQ_GT(q
->ti_seq
, ti
->ti_seq
))
129 * If there is a preceding segment, it may provide some of
130 * our data already. If so, drop the data from the incoming
131 * segment. If it provides all of our data, drop us.
133 if (!tcpfrag_list_end(tcpiphdr_prev(q
), tp
)) {
135 q
= tcpiphdr_prev(q
);
136 /* conversion to int (in i) handles seq wraparound */
137 i
= q
->ti_seq
+ q
->ti_len
- ti
->ti_seq
;
139 if (i
>= ti
->ti_len
) {
142 * Try to present any queued data
143 * at the left window edge to the user.
144 * This is needed after the 3-WHS
147 goto present
; /* ??? */
153 q
= tcpiphdr_next(q
);
158 * While we overlap succeeding segments trim them or,
159 * if they are completely covered, dequeue them.
161 while (!tcpfrag_list_end(q
, tp
)) {
162 register int i
= (ti
->ti_seq
+ ti
->ti_len
) - q
->ti_seq
;
168 m_adj(q
->ti_mbuf
, i
);
171 q
= tcpiphdr_next(q
);
172 m
= tcpiphdr_prev(q
)->ti_mbuf
;
173 remque(tcpiphdr2qlink(tcpiphdr_prev(q
)));
178 * Stick new segment in its place.
180 insque(tcpiphdr2qlink(ti
), tcpiphdr2qlink(tcpiphdr_prev(q
)));
184 * Present data to user, advancing rcv_nxt through
185 * completed sequence space.
187 if (!TCPS_HAVEESTABLISHED(tp
->t_state
))
189 ti
= tcpfrag_list_first(tp
);
190 if (tcpfrag_list_end(ti
, tp
) || ti
->ti_seq
!= tp
->rcv_nxt
)
192 if (tp
->t_state
== TCPS_SYN_RECEIVED
&& ti
->ti_len
)
195 tp
->rcv_nxt
+= ti
->ti_len
;
196 flags
= ti
->ti_flags
& TH_FIN
;
197 remque(tcpiphdr2qlink(ti
));
199 ti
= tcpiphdr_next(ti
);
200 if (so
->so_state
& SS_FCANTSENDMORE
)
204 if (tcp_emu(so
,m
)) sbappend(so
, m
);
208 } while (ti
!= (struct tcpiphdr
*)tp
&& ti
->ti_seq
== tp
->rcv_nxt
);
213 * TCP input routine, follows pages 65-76 of the
214 * protocol specification dated September, 1981 very closely.
217 tcp_input(struct mbuf
*m
, int iphlen
, struct socket
*inso
)
219 struct ip save_ip
, *ip
;
220 register struct tcpiphdr
*ti
;
224 register struct tcpcb
*tp
= NULL
;
225 register int tiflags
;
226 struct socket
*so
= NULL
;
227 int todrop
, acked
, ourfinisacked
, needoutput
= 0;
231 struct sockaddr_storage lhost
, fhost
;
232 struct sockaddr_in
*lhost4
, *fhost4
;
233 struct ex_list
*ex_ptr
;
236 DEBUG_CALL("tcp_input");
237 DEBUG_ARGS((dfd
, " m = %p iphlen = %2d inso = %p\n",
241 * If called with m == 0, then we're continuing the connect
247 /* Re-set a few variables */
253 tiflags
= ti
->ti_flags
;
259 if (iphlen
> sizeof(struct ip
)) {
260 ip_stripoptions(m
, (struct mbuf
*)0);
261 iphlen
=sizeof(struct ip
);
263 /* XXX Check if too short */
267 * Save a copy of the IP header in case we want restore it
268 * for sending an ICMP error message in response.
270 ip
=mtod(m
, struct ip
*);
272 save_ip
.ip_len
+= iphlen
;
275 * Get IP and TCP header together in first mbuf.
276 * Note: IP leaves IP header in first mbuf.
278 m
->m_data
-= sizeof(struct tcpiphdr
) - sizeof(struct ip
)
279 - sizeof(struct tcphdr
);
280 m
->m_len
+= sizeof(struct tcpiphdr
) - sizeof(struct ip
)
281 - sizeof(struct tcphdr
);
282 ti
= mtod(m
, struct tcpiphdr
*);
285 * Checksum extended TCP header and data.
288 tcpiphdr2qlink(ti
)->next
= tcpiphdr2qlink(ti
)->prev
= NULL
;
289 memset(&ti
->ih_mbuf
, 0 , sizeof(struct mbuf_ptr
));
290 memset(&ti
->ti
, 0, sizeof(ti
->ti
));
292 ti
->ti_src
= save_ip
.ip_src
;
293 ti
->ti_dst
= save_ip
.ip_dst
;
294 ti
->ti_pr
= save_ip
.ip_p
;
295 ti
->ti_len
= htons((uint16_t)tlen
);
296 len
= ((sizeof(struct tcpiphdr
) - sizeof(struct tcphdr
)) + tlen
);
302 * Check that TCP offset makes sense,
303 * pull out TCP options and adjust length. XXX
305 off
= ti
->ti_off
<< 2;
306 if (off
< sizeof (struct tcphdr
) || off
> tlen
) {
311 if (off
> sizeof (struct tcphdr
)) {
312 optlen
= off
- sizeof (struct tcphdr
);
313 optp
= mtod(m
, caddr_t
) + sizeof (struct tcpiphdr
);
315 tiflags
= ti
->ti_flags
;
318 * Convert TCP protocol specific fields to host format.
326 * Drop TCP, IP headers and TCP options.
328 m
->m_data
+= sizeof(struct tcpiphdr
)+off
-sizeof(struct tcphdr
);
329 m
->m_len
-= sizeof(struct tcpiphdr
)+off
-sizeof(struct tcphdr
);
332 * Locate pcb for segment.
335 lhost
.ss_family
= AF_INET
;
336 lhost4
= (struct sockaddr_in
*) &lhost
;
337 lhost4
->sin_addr
= ti
->ti_src
;
338 lhost4
->sin_port
= ti
->ti_sport
;
339 fhost
.ss_family
= AF_INET
;
340 fhost4
= (struct sockaddr_in
*) &fhost
;
341 fhost4
->sin_addr
= ti
->ti_dst
;
342 fhost4
->sin_port
= ti
->ti_dport
;
344 so
= solookup(&slirp
->tcp_last_so
, &slirp
->tcb
, &lhost
, &fhost
);
347 * If the state is CLOSED (i.e., TCB does not exist) then
348 * all data in the incoming segment is discarded.
349 * If the TCB exists but is in CLOSED state, it is embryonic,
350 * but should either do a listen or a connect soon.
352 * state == CLOSED means we've done socreate() but haven't
353 * attached it to a protocol yet...
355 * XXX If a TCB does not exist, and the TH_SYN flag is
356 * the only flag set, then create a session, mark it
357 * as if it was LISTENING, and continue...
360 if (slirp
->restricted
) {
361 /* Any hostfwds will have an existing socket, so we only get here
362 * for non-hostfwd connections. These should be dropped, unless it
363 * happens to be a guestfwd.
365 for (ex_ptr
= slirp
->exec_list
; ex_ptr
; ex_ptr
= ex_ptr
->ex_next
) {
366 if (ex_ptr
->ex_fport
== ti
->ti_dport
&&
367 ti
->ti_dst
.s_addr
== ex_ptr
->ex_addr
.s_addr
) {
376 if ((tiflags
& (TH_SYN
|TH_FIN
|TH_RST
|TH_URG
|TH_ACK
)) != TH_SYN
)
379 if ((so
= socreate(slirp
)) == NULL
)
381 if (tcp_attach(so
) < 0) {
382 free(so
); /* Not sofree (if it failed, it's not insqued) */
386 sbreserve(&so
->so_snd
, TCP_SNDSPACE
);
387 sbreserve(&so
->so_rcv
, TCP_RCVSPACE
);
389 so
->lhost
.ss
= lhost
;
390 so
->fhost
.ss
= fhost
;
392 if ((so
->so_iptos
= tcp_tos(so
)) == 0)
393 so
->so_iptos
= ((struct ip
*)ti
)->ip_tos
;
396 tp
->t_state
= TCPS_LISTEN
;
400 * If this is a still-connecting socket, this probably
401 * a retransmit of the SYN. Whether it's a retransmit SYN
402 * or something else, we nuke it.
404 if (so
->so_state
& SS_ISFCONNECTING
)
409 /* XXX Should never fail */
412 if (tp
->t_state
== TCPS_CLOSED
)
418 * Segment received on connection.
419 * Reset idle time and keep-alive timer.
423 tp
->t_timer
[TCPT_KEEP
] = TCPTV_KEEPINTVL
;
425 tp
->t_timer
[TCPT_KEEP
] = TCPTV_KEEP_IDLE
;
428 * Process options if not in LISTEN state,
429 * else do it below (after getting remote address).
431 if (optp
&& tp
->t_state
!= TCPS_LISTEN
)
432 tcp_dooptions(tp
, (u_char
*)optp
, optlen
, ti
);
435 * Header prediction: check for the two common cases
436 * of a uni-directional data xfer. If the packet has
437 * no control flags, is in-sequence, the window didn't
438 * change and we're not retransmitting, it's a
439 * candidate. If the length is zero and the ack moved
440 * forward, we're the sender side of the xfer. Just
441 * free the data acked & wake any higher level process
442 * that was blocked waiting for space. If the length
443 * is non-zero and the ack didn't move, we're the
444 * receiver side. If we're getting packets in-order
445 * (the reassembly queue is empty), add the data to
446 * the socket buffer and note that we need a delayed ack.
448 * XXX Some of these tests are not needed
449 * eg: the tiwin == tp->snd_wnd prevents many more
450 * predictions.. with no *real* advantage..
452 if (tp
->t_state
== TCPS_ESTABLISHED
&&
453 (tiflags
& (TH_SYN
|TH_FIN
|TH_RST
|TH_URG
|TH_ACK
)) == TH_ACK
&&
454 ti
->ti_seq
== tp
->rcv_nxt
&&
455 tiwin
&& tiwin
== tp
->snd_wnd
&&
456 tp
->snd_nxt
== tp
->snd_max
) {
457 if (ti
->ti_len
== 0) {
458 if (SEQ_GT(ti
->ti_ack
, tp
->snd_una
) &&
459 SEQ_LEQ(ti
->ti_ack
, tp
->snd_max
) &&
460 tp
->snd_cwnd
>= tp
->snd_wnd
) {
462 * this is a pure ack for outstanding data.
465 SEQ_GT(ti
->ti_ack
, tp
->t_rtseq
))
466 tcp_xmit_timer(tp
, tp
->t_rtt
);
467 acked
= ti
->ti_ack
- tp
->snd_una
;
468 sbdrop(&so
->so_snd
, acked
);
469 tp
->snd_una
= ti
->ti_ack
;
473 * If all outstanding data are acked, stop
474 * retransmit timer, otherwise restart timer
475 * using current (possibly backed-off) value.
476 * If process is waiting for space,
477 * wakeup/selwakeup/signal. If data
478 * are ready to send, let tcp_output
479 * decide between more output or persist.
481 if (tp
->snd_una
== tp
->snd_max
)
482 tp
->t_timer
[TCPT_REXMT
] = 0;
483 else if (tp
->t_timer
[TCPT_PERSIST
] == 0)
484 tp
->t_timer
[TCPT_REXMT
] = tp
->t_rxtcur
;
487 * This is called because sowwakeup might have
488 * put data into so_snd. Since we don't so sowwakeup,
489 * we don't need this.. XXX???
491 if (so
->so_snd
.sb_cc
)
492 (void) tcp_output(tp
);
496 } else if (ti
->ti_ack
== tp
->snd_una
&&
497 tcpfrag_list_empty(tp
) &&
498 ti
->ti_len
<= sbspace(&so
->so_rcv
)) {
500 * this is a pure, in-sequence data packet
501 * with nothing on the reassembly queue and
502 * we have enough buffer space to take it.
504 tp
->rcv_nxt
+= ti
->ti_len
;
506 * Add data to socket buffer.
509 if (tcp_emu(so
,m
)) sbappend(so
, m
);
514 * If this is a short packet, then ACK now - with Nagel
515 * congestion avoidance sender won't send more until
518 * It is better to not delay acks at all to maximize
519 * TCP throughput. See RFC 2581.
521 tp
->t_flags
|= TF_ACKNOW
;
525 } /* header prediction */
527 * Calculate amount of space in receive window,
528 * and then do TCP input processing.
529 * Receive window is amount of space in rcv queue,
530 * but not less than advertised window.
533 win
= sbspace(&so
->so_rcv
);
536 tp
->rcv_wnd
= max(win
, (int)(tp
->rcv_adv
- tp
->rcv_nxt
));
539 switch (tp
->t_state
) {
542 * If the state is LISTEN then ignore segment if it contains an RST.
543 * If the segment contains an ACK then it is bad and send a RST.
544 * If it does not contain a SYN then it is not interesting; drop it.
545 * Don't bother responding if the destination was a broadcast.
546 * Otherwise initialize tp->rcv_nxt, and tp->irs, select an initial
547 * tp->iss, and send a segment:
548 * <SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK>
549 * Also initialize tp->snd_nxt to tp->iss+1 and tp->snd_una to tp->iss.
550 * Fill in remote peer address fields if not previously specified.
551 * Enter SYN_RECEIVED state, and process any other fields of this
552 * segment in this state.
556 if (tiflags
& TH_RST
)
558 if (tiflags
& TH_ACK
)
560 if ((tiflags
& TH_SYN
) == 0)
564 * This has way too many gotos...
565 * But a bit of spaghetti code never hurt anybody :)
569 * If this is destined for the control address, then flag to
570 * tcp_ctl once connected, otherwise connect
572 if ((so
->so_faddr
.s_addr
& slirp
->vnetwork_mask
.s_addr
) ==
573 slirp
->vnetwork_addr
.s_addr
) {
574 if (so
->so_faddr
.s_addr
!= slirp
->vhost_addr
.s_addr
&&
575 so
->so_faddr
.s_addr
!= slirp
->vnameserver_addr
.s_addr
) {
576 /* May be an add exec */
577 for (ex_ptr
= slirp
->exec_list
; ex_ptr
;
578 ex_ptr
= ex_ptr
->ex_next
) {
579 if(ex_ptr
->ex_fport
== so
->so_fport
&&
580 so
->so_faddr
.s_addr
== ex_ptr
->ex_addr
.s_addr
) {
581 so
->so_state
|= SS_CTL
;
585 if (so
->so_state
& SS_CTL
) {
589 /* CTL_ALIAS: Do nothing, tcp_fconnect will be called on it */
592 if (so
->so_emu
& EMU_NOCONNECT
) {
593 so
->so_emu
&= ~EMU_NOCONNECT
;
597 if ((tcp_fconnect(so
, so
->so_ffamily
) == -1) &&
598 (errno
!= EINPROGRESS
) && (errno
!= EWOULDBLOCK
)
600 u_char code
=ICMP_UNREACH_NET
;
601 DEBUG_MISC((dfd
, " tcp fconnect errno = %d-%s\n",
602 errno
,strerror(errno
)));
603 if(errno
== ECONNREFUSED
) {
604 /* ACK the SYN, send RST to refuse the connection */
605 tcp_respond(tp
, ti
, m
, ti
->ti_seq
+1, (tcp_seq
)0,
608 if(errno
== EHOSTUNREACH
) code
=ICMP_UNREACH_HOST
;
609 HTONL(ti
->ti_seq
); /* restore tcp header */
613 m
->m_data
-= sizeof(struct tcpiphdr
)+off
-sizeof(struct tcphdr
);
614 m
->m_len
+= sizeof(struct tcpiphdr
)+off
-sizeof(struct tcphdr
);
615 m
->m_data
+= sizeof(struct tcpiphdr
) - sizeof(struct ip
)
616 - sizeof(struct tcphdr
);
617 m
->m_len
-= sizeof(struct tcpiphdr
) - sizeof(struct ip
)
618 - sizeof(struct tcphdr
);
620 icmp_send_error(m
, ICMP_UNREACH
, code
, 0, strerror(errno
));
626 * Haven't connected yet, save the current mbuf
628 * XXX Some OS's don't tell us whether the connect()
629 * succeeded or not. So we must time it out.
633 tp
->t_timer
[TCPT_KEEP
] = TCPTV_KEEP_INIT
;
634 tp
->t_state
= TCPS_SYN_RECEIVED
;
641 * Check if the connect succeeded
643 if (so
->so_state
& SS_NOFDREF
) {
651 tcp_dooptions(tp
, (u_char
*)optp
, optlen
, ti
);
656 tp
->iss
= slirp
->tcp_iss
;
657 slirp
->tcp_iss
+= TCP_ISSINCR
/2;
658 tp
->irs
= ti
->ti_seq
;
661 tp
->t_flags
|= TF_ACKNOW
;
662 tp
->t_state
= TCPS_SYN_RECEIVED
;
663 tp
->t_timer
[TCPT_KEEP
] = TCPTV_KEEP_INIT
;
665 } /* case TCPS_LISTEN */
668 * If the state is SYN_SENT:
669 * if seg contains an ACK, but not for our SYN, drop the input.
670 * if seg contains a RST, then drop the connection.
671 * if seg does not contain SYN, then drop it.
672 * Otherwise this is an acceptable SYN segment
673 * initialize tp->rcv_nxt and tp->irs
674 * if seg contains ack then advance tp->snd_una
675 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state
676 * arrange for segment to be acked (eventually)
677 * continue processing rest of data/controls, beginning with URG
680 if ((tiflags
& TH_ACK
) &&
681 (SEQ_LEQ(ti
->ti_ack
, tp
->iss
) ||
682 SEQ_GT(ti
->ti_ack
, tp
->snd_max
)))
685 if (tiflags
& TH_RST
) {
686 if (tiflags
& TH_ACK
) {
687 tcp_drop(tp
, 0); /* XXX Check t_softerror! */
692 if ((tiflags
& TH_SYN
) == 0)
694 if (tiflags
& TH_ACK
) {
695 tp
->snd_una
= ti
->ti_ack
;
696 if (SEQ_LT(tp
->snd_nxt
, tp
->snd_una
))
697 tp
->snd_nxt
= tp
->snd_una
;
700 tp
->t_timer
[TCPT_REXMT
] = 0;
701 tp
->irs
= ti
->ti_seq
;
703 tp
->t_flags
|= TF_ACKNOW
;
704 if (tiflags
& TH_ACK
&& SEQ_GT(tp
->snd_una
, tp
->iss
)) {
706 tp
->t_state
= TCPS_ESTABLISHED
;
708 (void) tcp_reass(tp
, (struct tcpiphdr
*)0,
711 * if we didn't have to retransmit the SYN,
712 * use its rtt as our initial srtt & rtt var.
715 tcp_xmit_timer(tp
, tp
->t_rtt
);
717 tp
->t_state
= TCPS_SYN_RECEIVED
;
721 * Advance ti->ti_seq to correspond to first data byte.
722 * If data, trim to stay within window,
723 * dropping FIN if necessary.
726 if (ti
->ti_len
> tp
->rcv_wnd
) {
727 todrop
= ti
->ti_len
- tp
->rcv_wnd
;
729 ti
->ti_len
= tp
->rcv_wnd
;
732 tp
->snd_wl1
= ti
->ti_seq
- 1;
733 tp
->rcv_up
= ti
->ti_seq
;
735 } /* switch tp->t_state */
737 * States other than LISTEN or SYN_SENT.
738 * Check that at least some bytes of segment are within
739 * receive window. If segment begins before rcv_nxt,
740 * drop leading data (and SYN); if nothing left, just ack.
742 todrop
= tp
->rcv_nxt
- ti
->ti_seq
;
744 if (tiflags
& TH_SYN
) {
754 * Following if statement from Stevens, vol. 2, p. 960.
756 if (todrop
> ti
->ti_len
757 || (todrop
== ti
->ti_len
&& (tiflags
& TH_FIN
) == 0)) {
759 * Any valid FIN must be to the left of the window.
760 * At this point the FIN must be a duplicate or out
761 * of sequence; drop it.
766 * Send an ACK to resynchronize and drop any data.
767 * But keep on processing for RST or ACK.
769 tp
->t_flags
|= TF_ACKNOW
;
773 ti
->ti_seq
+= todrop
;
774 ti
->ti_len
-= todrop
;
775 if (ti
->ti_urp
> todrop
)
776 ti
->ti_urp
-= todrop
;
783 * If new data are received on a connection after the
784 * user processes are gone, then RST the other end.
786 if ((so
->so_state
& SS_NOFDREF
) &&
787 tp
->t_state
> TCPS_CLOSE_WAIT
&& ti
->ti_len
) {
793 * If segment ends after window, drop trailing data
794 * (and PUSH and FIN); if nothing left, just ACK.
796 todrop
= (ti
->ti_seq
+ti
->ti_len
) - (tp
->rcv_nxt
+tp
->rcv_wnd
);
798 if (todrop
>= ti
->ti_len
) {
800 * If a new connection request is received
801 * while in TIME_WAIT, drop the old connection
802 * and start over if the sequence numbers
803 * are above the previous ones.
805 if (tiflags
& TH_SYN
&&
806 tp
->t_state
== TCPS_TIME_WAIT
&&
807 SEQ_GT(ti
->ti_seq
, tp
->rcv_nxt
)) {
808 iss
= tp
->rcv_nxt
+ TCP_ISSINCR
;
813 * If window is closed can only take segments at
814 * window edge, and have to drop data and PUSH from
815 * incoming segments. Continue processing, but
816 * remember to ack. Otherwise, drop segment
819 if (tp
->rcv_wnd
== 0 && ti
->ti_seq
== tp
->rcv_nxt
) {
820 tp
->t_flags
|= TF_ACKNOW
;
826 ti
->ti_len
-= todrop
;
827 tiflags
&= ~(TH_PUSH
|TH_FIN
);
831 * If the RST bit is set examine the state:
832 * SYN_RECEIVED STATE:
833 * If passive open, return to LISTEN state.
834 * If active open, inform user that connection was refused.
835 * ESTABLISHED, FIN_WAIT_1, FIN_WAIT2, CLOSE_WAIT STATES:
836 * Inform user that connection was reset, and close tcb.
837 * CLOSING, LAST_ACK, TIME_WAIT STATES
840 if (tiflags
&TH_RST
) switch (tp
->t_state
) {
842 case TCPS_SYN_RECEIVED
:
843 case TCPS_ESTABLISHED
:
844 case TCPS_FIN_WAIT_1
:
845 case TCPS_FIN_WAIT_2
:
846 case TCPS_CLOSE_WAIT
:
847 tp
->t_state
= TCPS_CLOSED
;
859 * If a SYN is in the window, then this is an
860 * error and we send an RST and drop the connection.
862 if (tiflags
& TH_SYN
) {
868 * If the ACK bit is off we drop the segment and return.
870 if ((tiflags
& TH_ACK
) == 0) goto drop
;
875 switch (tp
->t_state
) {
877 * In SYN_RECEIVED state if the ack ACKs our SYN then enter
878 * ESTABLISHED state and continue processing, otherwise
879 * send an RST. una<=ack<=max
881 case TCPS_SYN_RECEIVED
:
883 if (SEQ_GT(tp
->snd_una
, ti
->ti_ack
) ||
884 SEQ_GT(ti
->ti_ack
, tp
->snd_max
))
886 tp
->t_state
= TCPS_ESTABLISHED
;
888 * The sent SYN is ack'ed with our sequence number +1
889 * The first data byte already in the buffer will get
890 * lost if no correction is made. This is only needed for
891 * SS_CTL since the buffer is empty otherwise.
894 tp
->snd_una
=ti
->ti_ack
;
895 if (so
->so_state
& SS_CTL
) {
896 /* So tcp_ctl reports the right state */
900 so
->so_state
&= ~SS_CTL
; /* success XXX */
901 } else if (ret
== 2) {
902 so
->so_state
&= SS_PERSISTENT_MASK
;
903 so
->so_state
|= SS_NOFDREF
; /* CTL_CMD */
906 tp
->t_state
= TCPS_FIN_WAIT_1
;
912 (void) tcp_reass(tp
, (struct tcpiphdr
*)0, (struct mbuf
*)0);
913 tp
->snd_wl1
= ti
->ti_seq
- 1;
914 /* Avoid ack processing; snd_una==ti_ack => dup ack */
919 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
920 * ACKs. If the ack is in the range
921 * tp->snd_una < ti->ti_ack <= tp->snd_max
922 * then advance tp->snd_una to ti->ti_ack and drop
923 * data from the retransmission queue. If this ACK reflects
924 * more up to date window information we update our window information.
926 case TCPS_ESTABLISHED
:
927 case TCPS_FIN_WAIT_1
:
928 case TCPS_FIN_WAIT_2
:
929 case TCPS_CLOSE_WAIT
:
934 if (SEQ_LEQ(ti
->ti_ack
, tp
->snd_una
)) {
935 if (ti
->ti_len
== 0 && tiwin
== tp
->snd_wnd
) {
936 DEBUG_MISC((dfd
, " dup ack m = %p so = %p\n",
939 * If we have outstanding data (other than
940 * a window probe), this is a completely
941 * duplicate ack (ie, window info didn't
942 * change), the ack is the biggest we've
943 * seen and we've seen exactly our rexmt
944 * threshold of them, assume a packet
945 * has been dropped and retransmit it.
946 * Kludge snd_nxt & the congestion
947 * window so we send only this one
950 * We know we're losing at the current
951 * window size so do congestion avoidance
952 * (set ssthresh to half the current window
953 * and pull our congestion window back to
956 * Dup acks mean that packets have left the
957 * network (they're now cached at the receiver)
958 * so bump cwnd by the amount in the receiver
959 * to keep a constant cwnd packets in the
962 if (tp
->t_timer
[TCPT_REXMT
] == 0 ||
963 ti
->ti_ack
!= tp
->snd_una
)
965 else if (++tp
->t_dupacks
== TCPREXMTTHRESH
) {
966 tcp_seq onxt
= tp
->snd_nxt
;
968 min(tp
->snd_wnd
, tp
->snd_cwnd
) / 2 /
973 tp
->snd_ssthresh
= win
* tp
->t_maxseg
;
974 tp
->t_timer
[TCPT_REXMT
] = 0;
976 tp
->snd_nxt
= ti
->ti_ack
;
977 tp
->snd_cwnd
= tp
->t_maxseg
;
978 (void) tcp_output(tp
);
979 tp
->snd_cwnd
= tp
->snd_ssthresh
+
980 tp
->t_maxseg
* tp
->t_dupacks
;
981 if (SEQ_GT(onxt
, tp
->snd_nxt
))
984 } else if (tp
->t_dupacks
> TCPREXMTTHRESH
) {
985 tp
->snd_cwnd
+= tp
->t_maxseg
;
986 (void) tcp_output(tp
);
995 * If the congestion window was inflated to account
996 * for the other side's cached packets, retract it.
998 if (tp
->t_dupacks
> TCPREXMTTHRESH
&&
999 tp
->snd_cwnd
> tp
->snd_ssthresh
)
1000 tp
->snd_cwnd
= tp
->snd_ssthresh
;
1002 if (SEQ_GT(ti
->ti_ack
, tp
->snd_max
)) {
1005 acked
= ti
->ti_ack
- tp
->snd_una
;
1008 * If transmit timer is running and timed sequence
1009 * number was acked, update smoothed round trip time.
1010 * Since we now have an rtt measurement, cancel the
1011 * timer backoff (cf., Phil Karn's retransmit alg.).
1012 * Recompute the initial retransmit timer.
1014 if (tp
->t_rtt
&& SEQ_GT(ti
->ti_ack
, tp
->t_rtseq
))
1015 tcp_xmit_timer(tp
,tp
->t_rtt
);
1018 * If all outstanding data is acked, stop retransmit
1019 * timer and remember to restart (more output or persist).
1020 * If there is more data to be acked, restart retransmit
1021 * timer, using current (possibly backed-off) value.
1023 if (ti
->ti_ack
== tp
->snd_max
) {
1024 tp
->t_timer
[TCPT_REXMT
] = 0;
1026 } else if (tp
->t_timer
[TCPT_PERSIST
] == 0)
1027 tp
->t_timer
[TCPT_REXMT
] = tp
->t_rxtcur
;
1029 * When new data is acked, open the congestion window.
1030 * If the window gives us less than ssthresh packets
1031 * in flight, open exponentially (maxseg per packet).
1032 * Otherwise open linearly: maxseg per window
1033 * (maxseg^2 / cwnd per packet).
1036 register u_int cw
= tp
->snd_cwnd
;
1037 register u_int incr
= tp
->t_maxseg
;
1039 if (cw
> tp
->snd_ssthresh
)
1040 incr
= incr
* incr
/ cw
;
1041 tp
->snd_cwnd
= min(cw
+ incr
, TCP_MAXWIN
<<tp
->snd_scale
);
1043 if (acked
> so
->so_snd
.sb_cc
) {
1044 tp
->snd_wnd
-= so
->so_snd
.sb_cc
;
1045 sbdrop(&so
->so_snd
, (int )so
->so_snd
.sb_cc
);
1048 sbdrop(&so
->so_snd
, acked
);
1049 tp
->snd_wnd
-= acked
;
1052 tp
->snd_una
= ti
->ti_ack
;
1053 if (SEQ_LT(tp
->snd_nxt
, tp
->snd_una
))
1054 tp
->snd_nxt
= tp
->snd_una
;
1056 switch (tp
->t_state
) {
1059 * In FIN_WAIT_1 STATE in addition to the processing
1060 * for the ESTABLISHED state if our FIN is now acknowledged
1061 * then enter FIN_WAIT_2.
1063 case TCPS_FIN_WAIT_1
:
1064 if (ourfinisacked
) {
1066 * If we can't receive any more
1067 * data, then closing user can proceed.
1068 * Starting the timer is contrary to the
1069 * specification, but if we don't get a FIN
1070 * we'll hang forever.
1072 if (so
->so_state
& SS_FCANTRCVMORE
) {
1073 tp
->t_timer
[TCPT_2MSL
] = TCP_MAXIDLE
;
1075 tp
->t_state
= TCPS_FIN_WAIT_2
;
1080 * In CLOSING STATE in addition to the processing for
1081 * the ESTABLISHED state if the ACK acknowledges our FIN
1082 * then enter the TIME-WAIT state, otherwise ignore
1086 if (ourfinisacked
) {
1087 tp
->t_state
= TCPS_TIME_WAIT
;
1088 tcp_canceltimers(tp
);
1089 tp
->t_timer
[TCPT_2MSL
] = 2 * TCPTV_MSL
;
1094 * In LAST_ACK, we may still be waiting for data to drain
1095 * and/or to be acked, as well as for the ack of our FIN.
1096 * If our FIN is now acknowledged, delete the TCB,
1097 * enter the closed state and return.
1100 if (ourfinisacked
) {
1107 * In TIME_WAIT state the only thing that should arrive
1108 * is a retransmission of the remote FIN. Acknowledge
1109 * it and restart the finack timer.
1111 case TCPS_TIME_WAIT
:
1112 tp
->t_timer
[TCPT_2MSL
] = 2 * TCPTV_MSL
;
1115 } /* switch(tp->t_state) */
1119 * Update window information.
1120 * Don't look at window if no ACK: TAC's send garbage on first SYN.
1122 if ((tiflags
& TH_ACK
) &&
1123 (SEQ_LT(tp
->snd_wl1
, ti
->ti_seq
) ||
1124 (tp
->snd_wl1
== ti
->ti_seq
&& (SEQ_LT(tp
->snd_wl2
, ti
->ti_ack
) ||
1125 (tp
->snd_wl2
== ti
->ti_ack
&& tiwin
> tp
->snd_wnd
))))) {
1126 tp
->snd_wnd
= tiwin
;
1127 tp
->snd_wl1
= ti
->ti_seq
;
1128 tp
->snd_wl2
= ti
->ti_ack
;
1129 if (tp
->snd_wnd
> tp
->max_sndwnd
)
1130 tp
->max_sndwnd
= tp
->snd_wnd
;
1135 * Process segments with URG.
1137 if ((tiflags
& TH_URG
) && ti
->ti_urp
&&
1138 TCPS_HAVERCVDFIN(tp
->t_state
) == 0) {
1140 * This is a kludge, but if we receive and accept
1141 * random urgent pointers, we'll crash in
1142 * soreceive. It's hard to imagine someone
1143 * actually wanting to send this much urgent data.
1145 if (ti
->ti_urp
+ so
->so_rcv
.sb_cc
> so
->so_rcv
.sb_datalen
) {
1151 * If this segment advances the known urgent pointer,
1152 * then mark the data stream. This should not happen
1153 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
1154 * a FIN has been received from the remote side.
1155 * In these states we ignore the URG.
1157 * According to RFC961 (Assigned Protocols),
1158 * the urgent pointer points to the last octet
1159 * of urgent data. We continue, however,
1160 * to consider it to indicate the first octet
1161 * of data past the urgent section as the original
1162 * spec states (in one of two places).
1164 if (SEQ_GT(ti
->ti_seq
+ti
->ti_urp
, tp
->rcv_up
)) {
1165 tp
->rcv_up
= ti
->ti_seq
+ ti
->ti_urp
;
1166 so
->so_urgc
= so
->so_rcv
.sb_cc
+
1167 (tp
->rcv_up
- tp
->rcv_nxt
); /* -1; */
1168 tp
->rcv_up
= ti
->ti_seq
+ ti
->ti_urp
;
1173 * If no out of band data is expected,
1174 * pull receive urgent pointer along
1175 * with the receive window.
1177 if (SEQ_GT(tp
->rcv_nxt
, tp
->rcv_up
))
1178 tp
->rcv_up
= tp
->rcv_nxt
;
1182 * If this is a small packet, then ACK now - with Nagel
1183 * congestion avoidance sender won't send more until
1186 if (ti
->ti_len
&& (unsigned)ti
->ti_len
<= 5 &&
1187 ((struct tcpiphdr_2
*)ti
)->first_char
== (char)27) {
1188 tp
->t_flags
|= TF_ACKNOW
;
1192 * Process the segment text, merging it into the TCP sequencing queue,
1193 * and arranging for acknowledgment of receipt if necessary.
1194 * This process logically involves adjusting tp->rcv_wnd as data
1195 * is presented to the user (this happens in tcp_usrreq.c,
1196 * case PRU_RCVD). If a FIN has already been received on this
1197 * connection then we just ignore the text.
1199 if ((ti
->ti_len
|| (tiflags
&TH_FIN
)) &&
1200 TCPS_HAVERCVDFIN(tp
->t_state
) == 0) {
1201 TCP_REASS(tp
, ti
, m
, so
, tiflags
);
1208 * If FIN is received ACK the FIN and let the user know
1209 * that the connection is closing.
1211 if (tiflags
& TH_FIN
) {
1212 if (TCPS_HAVERCVDFIN(tp
->t_state
) == 0) {
1214 * If we receive a FIN we can't send more data,
1216 * Shutdown the socket if there is no rx data in the
1218 * soread() is called on completion of shutdown() and
1219 * will got to TCPS_LAST_ACK, and use tcp_output()
1224 tp
->t_flags
|= TF_ACKNOW
;
1227 switch (tp
->t_state
) {
1230 * In SYN_RECEIVED and ESTABLISHED STATES
1231 * enter the CLOSE_WAIT state.
1233 case TCPS_SYN_RECEIVED
:
1234 case TCPS_ESTABLISHED
:
1235 if(so
->so_emu
== EMU_CTL
) /* no shutdown on socket */
1236 tp
->t_state
= TCPS_LAST_ACK
;
1238 tp
->t_state
= TCPS_CLOSE_WAIT
;
1242 * If still in FIN_WAIT_1 STATE FIN has not been acked so
1243 * enter the CLOSING state.
1245 case TCPS_FIN_WAIT_1
:
1246 tp
->t_state
= TCPS_CLOSING
;
1250 * In FIN_WAIT_2 state enter the TIME_WAIT state,
1251 * starting the time-wait timer, turning off the other
1254 case TCPS_FIN_WAIT_2
:
1255 tp
->t_state
= TCPS_TIME_WAIT
;
1256 tcp_canceltimers(tp
);
1257 tp
->t_timer
[TCPT_2MSL
] = 2 * TCPTV_MSL
;
1261 * In TIME_WAIT state restart the 2 MSL time_wait timer.
1263 case TCPS_TIME_WAIT
:
1264 tp
->t_timer
[TCPT_2MSL
] = 2 * TCPTV_MSL
;
1270 * Return any desired output.
1272 if (needoutput
|| (tp
->t_flags
& TF_ACKNOW
)) {
1273 (void) tcp_output(tp
);
1279 * Generate an ACK dropping incoming segment if it occupies
1280 * sequence space, where the ACK reflects our state.
1282 if (tiflags
& TH_RST
)
1285 tp
->t_flags
|= TF_ACKNOW
;
1286 (void) tcp_output(tp
);
1290 /* reuses m if m!=NULL, m_free() unnecessary */
1291 if (tiflags
& TH_ACK
)
1292 tcp_respond(tp
, ti
, m
, (tcp_seq
)0, ti
->ti_ack
, TH_RST
);
1294 if (tiflags
& TH_SYN
) ti
->ti_len
++;
1295 tcp_respond(tp
, ti
, m
, ti
->ti_seq
+ti
->ti_len
, (tcp_seq
)0,
1303 * Drop space held by incoming segment and return.
1309 tcp_dooptions(struct tcpcb
*tp
, u_char
*cp
, int cnt
, struct tcpiphdr
*ti
)
1314 DEBUG_CALL("tcp_dooptions");
1315 DEBUG_ARGS((dfd
, " tp = %p cnt=%i\n", tp
, cnt
));
1317 for (; cnt
> 0; cnt
-= optlen
, cp
+= optlen
) {
1319 if (opt
== TCPOPT_EOL
)
1321 if (opt
== TCPOPT_NOP
)
1334 if (optlen
!= TCPOLEN_MAXSEG
)
1336 if (!(ti
->ti_flags
& TH_SYN
))
1338 memcpy((char *) &mss
, (char *) cp
+ 2, sizeof(mss
));
1340 (void) tcp_mss(tp
, mss
); /* sets t_maxseg */
1348 * Pull out of band byte out of a segment so
1349 * it doesn't appear in the user's data queue.
1350 * It is still reflected in the segment length for
1351 * sequencing purposes.
1357 tcp_pulloutofband(so
, ti
, m
)
1359 struct tcpiphdr
*ti
;
1360 register struct mbuf
*m
;
1362 int cnt
= ti
->ti_urp
- 1;
1365 if (m
->m_len
> cnt
) {
1366 char *cp
= mtod(m
, caddr_t
) + cnt
;
1367 struct tcpcb
*tp
= sototcpcb(so
);
1370 tp
->t_oobflags
|= TCPOOB_HAVEDATA
;
1371 memcpy(sp
, cp
+1, (unsigned)(m
->m_len
- cnt
- 1));
1376 m
= m
->m_next
; /* XXX WRONG! Fix it! */
1380 panic("tcp_pulloutofband");
1386 * Collect new round-trip time estimate
1387 * and update averages and current timeout.
1391 tcp_xmit_timer(register struct tcpcb
*tp
, int rtt
)
1393 register short delta
;
1395 DEBUG_CALL("tcp_xmit_timer");
1396 DEBUG_ARG("tp = %p", tp
);
1397 DEBUG_ARG("rtt = %d", rtt
);
1399 if (tp
->t_srtt
!= 0) {
1401 * srtt is stored as fixed point with 3 bits after the
1402 * binary point (i.e., scaled by 8). The following magic
1403 * is equivalent to the smoothing algorithm in rfc793 with
1404 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
1405 * point). Adjust rtt to origin 0.
1407 delta
= rtt
- 1 - (tp
->t_srtt
>> TCP_RTT_SHIFT
);
1408 if ((tp
->t_srtt
+= delta
) <= 0)
1411 * We accumulate a smoothed rtt variance (actually, a
1412 * smoothed mean difference), then set the retransmit
1413 * timer to smoothed rtt + 4 times the smoothed variance.
1414 * rttvar is stored as fixed point with 2 bits after the
1415 * binary point (scaled by 4). The following is
1416 * equivalent to rfc793 smoothing with an alpha of .75
1417 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces
1418 * rfc793's wired-in beta.
1422 delta
-= (tp
->t_rttvar
>> TCP_RTTVAR_SHIFT
);
1423 if ((tp
->t_rttvar
+= delta
) <= 0)
1427 * No rtt measurement yet - use the unsmoothed rtt.
1428 * Set the variance to half the rtt (so our first
1429 * retransmit happens at 3*rtt).
1431 tp
->t_srtt
= rtt
<< TCP_RTT_SHIFT
;
1432 tp
->t_rttvar
= rtt
<< (TCP_RTTVAR_SHIFT
- 1);
1438 * the retransmit should happen at rtt + 4 * rttvar.
1439 * Because of the way we do the smoothing, srtt and rttvar
1440 * will each average +1/2 tick of bias. When we compute
1441 * the retransmit timer, we want 1/2 tick of rounding and
1442 * 1 extra tick because of +-1/2 tick uncertainty in the
1443 * firing of the timer. The bias will give us exactly the
1444 * 1.5 tick we need. But, because the bias is
1445 * statistical, we have to test that we don't drop below
1446 * the minimum feasible timer (which is 2 ticks).
1448 TCPT_RANGESET(tp
->t_rxtcur
, TCP_REXMTVAL(tp
),
1449 (short)tp
->t_rttmin
, TCPTV_REXMTMAX
); /* XXX */
1452 * We received an ack for a packet that wasn't retransmitted;
1453 * it is probably safe to discard any error indications we've
1454 * received recently. This isn't quite right, but close enough
1455 * for now (a route might have failed after we sent a segment,
1456 * and the return path might not be symmetrical).
1458 tp
->t_softerror
= 0;
1462 * Determine a reasonable value for maxseg size.
1463 * If the route is known, check route for mtu.
1464 * If none, use an mss that can be handled on the outgoing
1465 * interface without forcing IP to fragment; if bigger than
1466 * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
1467 * to utilize large mbufs. If no route is found, route has no mtu,
1468 * or the destination isn't local, use a default, hopefully conservative
1469 * size (usually 512 or the default IP max size, but no more than the mtu
1470 * of the interface), as we can't discover anything about intervening
1471 * gateways or networks. We also initialize the congestion/slow start
1472 * window to be a single segment if the destination isn't local.
1473 * While looking at the routing entry, we also initialize other path-dependent
1474 * parameters from pre-set or cached values in the routing entry.
1478 tcp_mss(struct tcpcb
*tp
, u_int offer
)
1480 struct socket
*so
= tp
->t_socket
;
1483 DEBUG_CALL("tcp_mss");
1484 DEBUG_ARG("tp = %p", tp
);
1485 DEBUG_ARG("offer = %d", offer
);
1487 mss
= min(IF_MTU
, IF_MRU
) - sizeof(struct tcphdr
) + sizeof(struct ip
);
1489 mss
= min(mss
, offer
);
1491 if (mss
< tp
->t_maxseg
|| offer
!= 0)
1496 sbreserve(&so
->so_snd
, TCP_SNDSPACE
+ ((TCP_SNDSPACE
% mss
) ?
1497 (mss
- (TCP_SNDSPACE
% mss
)) :
1499 sbreserve(&so
->so_rcv
, TCP_RCVSPACE
+ ((TCP_RCVSPACE
% mss
) ?
1500 (mss
- (TCP_RCVSPACE
% mss
)) :
1503 DEBUG_MISC((dfd
, " returning mss = %d\n", mss
));