11 #define HEXDUMP_INCOMING 0
12 #define HEXDUMP_OUTGOING 0
14 #define TCP_MIN_DYNPORT 0xC000
15 #define TCP_MAX_HALFOPEN 1024 // Should be enough
17 #define TCP_MAX_PACKET_SIZE 1024
18 #define TCP_WINDOW_SIZE 0x2000
19 #define TCP_RECIEVE_BUFFER_SIZE 0x8000
20 #define TCP_DACK_THRESHOLD 4096
21 #define TCP_DACK_TIMEOUT 500
23 #define TCP_DEBUG 0 // Set to non-0 to enable TCP packet logging
26 void TCP_Initialise(void);
27 void TCP_StartConnection(tTCPConnection *Conn);
28 void TCP_SendPacket(tTCPConnection *Conn, tTCPHeader *Header, size_t DataLen, const void *Data);
29 void TCP_int_SendPacket(tInterface *Interface, const void *Dest, tTCPHeader *Header, size_t Length, const void *Data);
30 void TCP_GetPacket(tInterface *Interface, void *Address, int Length, void *Buffer);
31 void TCP_INT_HandleConnectionPacket(tTCPConnection *Connection, tTCPHeader *Header, int Length);
32 int TCP_INT_AppendRecieved(tTCPConnection *Connection, const void *Data, size_t Length);
33 void TCP_INT_UpdateRecievedFromFuture(tTCPConnection *Connection);
34 void TCP_int_SendDelayedACK(void *ConnPtr);
35 void TCP_INT_SendACK(tTCPConnection *Connection, const char *Reason);
36 Uint16 TCP_GetUnusedPort();
37 int TCP_AllocatePort(Uint16 Port);
38 int TCP_DeallocatePort(Uint16 Port);
39 tTCPConnection *TCP_int_CreateConnection(tInterface *Interface, enum eTCPConnectionState State);
40 void TCP_int_FreeTCB(tTCPConnection *Connection);
42 tVFS_Node *TCP_Server_Init(tInterface *Interface);
43 int TCP_Server_ReadDir(tVFS_Node *Node, int Pos, char Name[FILENAME_MAX]);
44 tVFS_Node *TCP_Server_FindDir(tVFS_Node *Node, const char *Name, Uint Flags);
45 int TCP_Server_IOCtl(tVFS_Node *Node, int ID, void *Data);
46 void TCP_Server_Close(tVFS_Node *Node);
48 tVFS_Node *TCP_Client_Init(tInterface *Interface);
49 size_t TCP_Client_Read(tVFS_Node *Node, off_t Offset, size_t Length, void *Buffer, Uint Flags);
50 size_t TCP_Client_Write(tVFS_Node *Node, off_t Offset, size_t Length, const void *Buffer, Uint Flags);
51 int TCP_Client_IOCtl(tVFS_Node *Node, int ID, void *Data);
52 void TCP_Client_Close(tVFS_Node *Node);
54 int WrapBetween(Uint32 Lower, Uint32 Value, Uint32 Higher, Uint32 MaxValue);
57 tSocketFile gTCP_ServerFile = {NULL, "tcps", TCP_Server_Init};
58 tSocketFile gTCP_ClientFile = {NULL, "tcpc", TCP_Client_Init};
59 tVFS_NodeType gTCP_ServerNodeType = {
60 .TypeName = "TCP Server",
61 .ReadDir = TCP_Server_ReadDir,
62 .FindDir = TCP_Server_FindDir,
63 .IOCtl = TCP_Server_IOCtl,
64 .Close = TCP_Server_Close
66 tVFS_NodeType gTCP_ClientNodeType = {
67 .TypeName = "TCP Client/Connection",
68 .Read = TCP_Client_Read,
69 .Write = TCP_Client_Write,
70 .IOCtl = TCP_Client_IOCtl,
71 .Close = TCP_Client_Close
75 int giTCP_NumHalfopen = 0;
76 tShortSpinlock glTCP_Listeners;
77 tTCPListener *gTCP_Listeners;
78 tShortSpinlock glTCP_OutbountCons;
79 tTCPConnection *gTCP_OutbountCons;
80 Uint32 gaTCP_PortBitmap[0x800];
81 int giTCP_NextOutPort = TCP_MIN_DYNPORT;
85 * \brief Initialise the TCP Layer
87 * Registers the client and server files and the GetPacket callback
89 void TCP_Initialise(void)
91 giTCP_NextOutPort += rand()%128;
92 IPStack_AddFile(&gTCP_ServerFile);
93 IPStack_AddFile(&gTCP_ClientFile);
94 IPv4_RegisterCallback(IP4PROT_TCP, TCP_GetPacket);
95 IPv6_RegisterCallback(IP4PROT_TCP, TCP_GetPacket);
99 * \brief Sends a packet from the specified connection, calculating the checksums
100 * \param Conn Connection
101 * \param Length Length of data
102 * \param Data Packet data (cast as a TCP Header)
104 void TCP_SendPacket( tTCPConnection *Conn, tTCPHeader *Header, size_t Length, const void *Data )
106 TCP_int_SendPacket(Conn->Interface, &Conn->RemoteIP, Header, Length, Data);
109 void TCP_int_SendPacket(tInterface *Interface, const void *Dest, tTCPHeader *Header, size_t Length, const void *Data )
111 tIPStackBuffer *buffer;
113 int packlen = sizeof(*Header) + Length;
115 buffer = IPStack_Buffer_CreateBuffer(2 + IPV4_BUFFERS);
117 IPStack_Buffer_AppendSubBuffer(buffer, Length, 0, Data, NULL, NULL);
118 IPStack_Buffer_AppendSubBuffer(buffer, sizeof(*Header), 0, Header, NULL, NULL);
120 LOG("Sending %i+%i to %s:%i", sizeof(*Header), Length,
121 IPStack_PrintAddress(Interface->Type, Dest),
122 ntohs(Header->RemotePort)
125 Header->Checksum = 0;
126 checksum[1] = htons( ~IPv4_Checksum(Header, sizeof(tTCPHeader)) );
127 checksum[2] = htons( ~IPv4_Checksum(Data, Length) );
129 // TODO: Fragment packet
131 switch( Interface->Type )
134 // Get IPv4 pseudo-header checksum
137 buf[0] = ((tIPv4*)Interface->Address)->L;
138 buf[1] = ((tIPv4*)Dest)->L;
139 buf[2] = htonl( (packlen) | (IP4PROT_TCP<<16) | (0<<24) );
140 checksum[0] = htons( ~IPv4_Checksum(buf, sizeof(buf)) ); // Partial checksum
142 // - Combine checksums
143 Header->Checksum = htons( IPv4_Checksum(checksum, sizeof(checksum)) );
144 IPv4_SendPacket(Interface, *(tIPv4*)Dest, IP4PROT_TCP, 0, buffer);
148 // Append IPv6 Pseudo Header
151 memcpy(buf, Interface->Address, 16);
152 memcpy(&buf[4], Dest, 16);
153 buf[8] = htonl(packlen);
154 buf[9] = htonl(IP4PROT_TCP);
155 checksum[0] = htons( ~IPv4_Checksum(buf, sizeof(buf)) ); // Partial checksum
157 Header->Checksum = htons( IPv4_Checksum(checksum, sizeof(checksum)) ); // Combine the two
158 IPv6_SendPacket(Interface, *(tIPv6*)Dest, IP4PROT_TCP, buffer);
163 void TCP_int_SendRSTTo(tInterface *Interface, void *Address, size_t Length, const tTCPHeader *Header)
165 tTCPHeader out_hdr = {0};
167 out_hdr.DataOffset = (sizeof(out_hdr)/4) << 4;
168 out_hdr.DestPort = Header->SourcePort;
169 out_hdr.SourcePort = Header->DestPort;
171 size_t data_len = Length - (Header->DataOffset>>4)*4;
172 out_hdr.AcknowlegementNumber = htonl( ntohl(Header->SequenceNumber) + data_len );
173 if( Header->Flags & TCP_FLAG_ACK ) {
174 out_hdr.Flags = TCP_FLAG_RST;
175 out_hdr.SequenceNumber = Header->AcknowlegementNumber;
178 out_hdr.Flags = TCP_FLAG_RST|TCP_FLAG_ACK;
179 out_hdr.SequenceNumber = 0;
181 TCP_int_SendPacket(Interface, Address, &out_hdr, 0, NULL);
185 * \brief Handles a packet from the IP Layer
186 * \param Interface Interface the packet arrived from
187 * \param Address Pointer to the addres structure
188 * \param Length Size of packet in bytes
189 * \param Buffer Packet data
191 void TCP_GetPacket(tInterface *Interface, void *Address, int Length, void *Buffer)
193 tTCPHeader *hdr = Buffer;
196 Log_Log("TCP", "TCP_GetPacket: <Local>:%i from [%s]:%i, Flags = %s%s%s%s%s%s%s%s",
197 ntohs(hdr->DestPort),
198 IPStack_PrintAddress(Interface->Type, Address),
199 ntohs(hdr->SourcePort),
200 (hdr->Flags & TCP_FLAG_CWR) ? "CWR " : "",
201 (hdr->Flags & TCP_FLAG_ECE) ? "ECE " : "",
202 (hdr->Flags & TCP_FLAG_URG) ? "URG " : "",
203 (hdr->Flags & TCP_FLAG_ACK) ? "ACK " : "",
204 (hdr->Flags & TCP_FLAG_PSH) ? "PSH " : "",
205 (hdr->Flags & TCP_FLAG_RST) ? "RST " : "",
206 (hdr->Flags & TCP_FLAG_SYN) ? "SYN " : "",
207 (hdr->Flags & TCP_FLAG_FIN) ? "FIN " : ""
211 if( Length > (hdr->DataOffset >> 4)*4 )
213 LOG("SequenceNumber = 0x%x", ntohl(hdr->SequenceNumber));
216 "TCP_GetPacket: Packet Data = ",
217 (Uint8*)hdr + (hdr->DataOffset >> 4)*4,
218 Length - (hdr->DataOffset >> 4)*4
224 for( tTCPListener *srv = gTCP_Listeners; srv; srv = srv->Next )
226 // Check if the server is active
227 if(srv->Port == 0) continue;
228 // Check the interface
229 if(srv->Interface && srv->Interface != Interface) continue;
230 // Check the destination port
231 if(srv->Port != htons(hdr->DestPort)) continue;
233 Log_Log("TCP", "TCP_GetPacket: Matches server %p", srv);
234 // Is this in an established connection?
235 for( tTCPConnection *conn = srv->Connections; conn; conn = conn->Next )
237 // Check that it is coming in on the same interface
238 if(conn->Interface != Interface) continue;
241 Log_Log("TCP", "TCP_GetPacket: conn->RemotePort(%i) == hdr->SourcePort(%i)",
242 conn->RemotePort, ntohs(hdr->SourcePort));
243 if(conn->RemotePort != ntohs(hdr->SourcePort)) continue;
246 Log_Debug("TCP", "TCP_GetPacket: conn->RemoteIP(%s)",
247 IPStack_PrintAddress(conn->Interface->Type, &conn->RemoteIP));
248 Log_Debug("TCP", " == Address(%s)",
249 IPStack_PrintAddress(conn->Interface->Type, Address));
250 if( IPStack_CompareAddress(conn->Interface->Type, &conn->RemoteIP, Address, -1) == 0 )
253 Log_Log("TCP", "TCP_GetPacket: Matches connection %p", conn);
254 // We have a response!
255 TCP_INT_HandleConnectionPacket(conn, hdr, Length);
261 if( hdr->Flags & TCP_FLAG_RST ) {
265 else if( hdr->Flags & TCP_FLAG_ACK ) {
266 LOG("ACK, send RST");
267 TCP_int_SendRSTTo(Interface, Address, Length, hdr);
270 else if( !(hdr->Flags & TCP_FLAG_SYN) ) {
271 LOG("Other, ignore");
274 Log_Log("TCP", "TCP_GetPacket: Opening Connection");
276 // TODO: Check for halfopen max
278 tTCPConnection *conn = TCP_int_CreateConnection(Interface, TCP_ST_SYN_RCVD);
279 conn->LocalPort = srv->Port;
280 conn->RemotePort = ntohs(hdr->SourcePort);
282 switch(Interface->Type)
284 case 4: conn->RemoteIP.v4 = *(tIPv4*)Address; break;
285 case 6: conn->RemoteIP.v6 = *(tIPv6*)Address; break;
286 default: ASSERTC(Interface->Type,==,4); return;
289 conn->NextSequenceRcv = ntohl( hdr->SequenceNumber ) + 1;
290 conn->HighestSequenceRcvd = conn->NextSequenceRcv;
291 conn->NextSequenceSend = rand();
293 conn->Node.ImplInt = srv->NextID ++;
295 // Hmm... Theoretically, this lock will never have to wait,
296 // as the interface is locked to the watching thread, and this
297 // runs in the watching thread. But, it's a good idea to have
299 // Oh, wait, there is a case where a wildcard can be used
300 // (srv->Interface == NULL) so having the lock is a good idea
301 SHORTLOCK(&srv->lConnections);
303 conn->Prev = srv->ConnectionsTail;
304 if(srv->Connections) {
305 ASSERT(srv->ConnectionsTail);
306 srv->ConnectionsTail->Next = conn;
309 ASSERT(!srv->ConnectionsTail);
310 srv->Connections = conn;
312 srv->ConnectionsTail = conn;
313 if(!srv->NewConnections)
314 srv->NewConnections = conn;
315 VFS_MarkAvaliable( &srv->Node, 1 );
316 SHORTREL(&srv->lConnections);
317 Semaphore_Signal(&srv->WaitingConnections, 1);
320 hdr->Flags |= TCP_FLAG_ACK;
321 hdr->AcknowlegementNumber = htonl(conn->NextSequenceRcv);
322 hdr->SequenceNumber = htonl(conn->NextSequenceSend);
323 hdr->DestPort = hdr->SourcePort;
324 hdr->SourcePort = htons(srv->Port);
325 hdr->DataOffset = (sizeof(tTCPHeader)/4) << 4;
326 TCP_SendPacket( conn, hdr, 0, NULL );
327 conn->NextSequenceSend ++;
331 // Check Open Connections
333 for( tTCPConnection *conn = gTCP_OutbountCons; conn; conn = conn->Next )
335 // Check that it is coming in on the same interface
336 if(conn->Interface != Interface) continue;
339 if(conn->RemotePort != ntohs(hdr->SourcePort)) continue;
342 if(conn->Interface->Type == 6 && !IP6_EQU(conn->RemoteIP.v6, *(tIPv6*)Address))
344 if(conn->Interface->Type == 4 && !IP4_EQU(conn->RemoteIP.v4, *(tIPv4*)Address))
347 TCP_INT_HandleConnectionPacket(conn, hdr, Length);
352 Log_Log("TCP", "TCP_GetPacket: No Match");
353 // If not a RST, send a RST
354 if( !(hdr->Flags & TCP_FLAG_RST) )
356 TCP_int_SendRSTTo(Interface, Address, Length, hdr);
361 * \brief Handles a packet sent to a specific connection
362 * \param Connection TCP Connection pointer
363 * \param Header TCP Packet pointer
364 * \param Length Length of the packet
366 void TCP_INT_HandleConnectionPacket(tTCPConnection *Connection, tTCPHeader *Header, int Length)
371 // Silently drop once finished
372 // TODO: Check if this needs to be here
373 if( Connection->State == TCP_ST_FINISHED ) {
374 Log_Log("TCP", "Packet ignored - connection finnished");
378 // Syncronise sequence values
379 if(Header->Flags & TCP_FLAG_SYN) {
380 // TODO: What if the packet also has data?
381 if( Connection->LastACKSequence != Connection->NextSequenceRcv )
382 TCP_INT_SendACK(Connection, "SYN");
383 Connection->NextSequenceRcv = ntohl(Header->SequenceNumber);
384 // TODO: Process HighestSequenceRcvd
386 if( Connection->HighestSequenceRcvd == 0 )
387 Connection->HighestSequenceRcvd = Connection->NextSequenceRcv;
388 Connection->LastACKSequence = Connection->NextSequenceRcv;
391 // Ackowledge a sent packet
392 if(Header->Flags & TCP_FLAG_ACK) {
393 // TODO: Process an ACKed Packet
394 LOG("Conn %p, Sent packet 0x%x ACKed", Connection, Header->AcknowlegementNumber);
397 // Get length of data
398 dataLen = Length - (Header->DataOffset>>4)*4;
399 LOG("dataLen = %i", dataLen);
401 Log_Debug("TCP", "State %i, dataLen = %x", Connection->State, dataLen);
407 switch( Connection->State )
409 // Pre-init connection?
411 Log_Log("TCP", "Packets to a closed connection?!");
414 // --- Init States ---
415 // SYN sent, expecting SYN-ACK Connection Opening
416 case TCP_ST_SYN_SENT:
417 if( Header->Flags & TCP_FLAG_SYN )
419 if( Connection->HighestSequenceRcvd == Connection->NextSequenceRcv )
420 Connection->HighestSequenceRcvd ++;
421 Connection->NextSequenceRcv ++;
423 if( Header->Flags & TCP_FLAG_ACK )
425 Log_Log("TCP", "ACKing SYN-ACK");
426 Connection->State = TCP_ST_OPEN;
427 VFS_MarkFull(&Connection->Node, 0);
428 TCP_INT_SendACK(Connection, "SYN-ACK");
432 Log_Log("TCP", "ACKing SYN");
433 Connection->State = TCP_ST_SYN_RCVD;
434 TCP_INT_SendACK(Connection, "SYN");
439 // SYN-ACK sent, expecting ACK
440 case TCP_ST_SYN_RCVD:
441 if( Header->Flags & TCP_FLAG_ACK )
443 // TODO: Handle max half-open limit
444 Log_Log("TCP", "Connection fully opened");
445 Connection->State = TCP_ST_OPEN;
446 VFS_MarkFull(&Connection->Node, 0);
450 // --- Established State ---
452 // - Handle State changes
454 if( Header->Flags & TCP_FLAG_FIN ) {
455 Log_Log("TCP", "Conn %p closed, recieved FIN", Connection);
456 VFS_MarkError(&Connection->Node, 1);
457 Connection->NextSequenceRcv ++;
458 TCP_INT_SendACK(Connection, "FIN Received");
459 Connection->State = TCP_ST_CLOSE_WAIT;
460 // CLOSE WAIT requires the client to close
464 // Check for an empty packet
466 if( Header->Flags == TCP_FLAG_ACK )
468 Log_Log("TCP", "ACK only packet");
471 // TODO: Is this right? (empty packet counts as one byte)
472 if( Connection->HighestSequenceRcvd == Connection->NextSequenceRcv )
473 Connection->HighestSequenceRcvd ++;
474 Connection->NextSequenceRcv ++;
475 Log_Log("TCP", "Empty Packet, inc and ACK the current sequence number");
476 TCP_INT_SendACK(Connection, "Empty");
485 sequence_num = ntohl(Header->SequenceNumber);
487 LOG("0x%08x <= 0x%08x < 0x%08x",
488 Connection->NextSequenceRcv,
489 ntohl(Header->SequenceNumber),
490 Connection->NextSequenceRcv + TCP_WINDOW_SIZE
493 // Is this packet the next expected packet?
494 if( sequence_num == Connection->NextSequenceRcv )
497 // Ooh, Goodie! Add it to the recieved list
498 rv = TCP_INT_AppendRecieved(Connection,
499 (Uint8*)Header + (Header->DataOffset>>4)*4,
503 Log_Notice("TCP", "TCP_INT_AppendRecieved rv %i", rv);
506 LOG("0x%08x += %i", Connection->NextSequenceRcv, dataLen);
507 if( Connection->HighestSequenceRcvd == Connection->NextSequenceRcv )
508 Connection->HighestSequenceRcvd += dataLen;
509 Connection->NextSequenceRcv += dataLen;
511 // TODO: This should be moved out of the watcher thread,
512 // so that a single lost packet on one connection doesn't cause
513 // all connections on the interface to lag.
514 // - Meh, no real issue, as the cache shouldn't be that large
515 TCP_INT_UpdateRecievedFromFuture(Connection);
518 // - Only send an ACK if we've had a burst
519 if( Connection->NextSequenceRcv > (Uint32)(TCP_DACK_THRESHOLD + Connection->LastACKSequence) )
521 TCP_INT_SendACK(Connection, "DACK Burst");
522 // - Extend TCP deferred ACK timer
523 Time_RemoveTimer(Connection->DeferredACKTimer);
525 // - Schedule the deferred ACK timer (if already scheduled, this is a NOP)
526 Time_ScheduleTimer(Connection->DeferredACKTimer, TCP_DACK_TIMEOUT);
528 TCP_INT_SendACK(Connection, "RX");
531 // Check if the packet is in window
532 else if( WrapBetween(Connection->NextSequenceRcv, sequence_num,
533 Connection->NextSequenceRcv+TCP_WINDOW_SIZE, 0xFFFFFFFF) )
535 Uint8 *dataptr = (Uint8*)Header + (Header->DataOffset>>4)*4;
536 #if CACHE_FUTURE_PACKETS_IN_BYTES
539 index = sequence_num % TCP_WINDOW_SIZE;
540 for( int i = 0; i < dataLen; i ++ )
542 Connection->FuturePacketValidBytes[index/8] |= 1 << (index%8);
543 Connection->FuturePacketData[index] = dataptr[i];
544 // Do a wrap increment
546 if(index == TCP_WINDOW_SIZE) index = 0;
549 tTCPStoredPacket *pkt, *tmp, *prev = NULL;
551 // Allocate and fill cached packet
552 pkt = malloc( sizeof(tTCPStoredPacket) + dataLen );
554 pkt->Sequence = ntohl(Header->SequenceNumber);
555 pkt->Length = dataLen;
556 memcpy(pkt->Data, dataptr, dataLen);
558 Log_Log("TCP", "We missed a packet, caching",
559 pkt->Sequence, Connection->NextSequenceRcv);
561 // No? Well, let's cache it and look at it later
562 SHORTLOCK( &Connection->lFuturePackets );
563 for(tmp = Connection->FuturePackets;
565 prev = tmp, tmp = tmp->Next)
567 if(tmp->Sequence >= pkt->Sequence) break;
570 // Add if before first, or sequences don't match
571 if( !tmp || tmp->Sequence != pkt->Sequence )
576 Connection->FuturePackets = pkt;
580 else if(pkt->Length > tmp->Length)
584 pkt->Next = tmp->Next;
589 free(pkt); // TODO: Find some way to remove this
591 SHORTREL( &Connection->lFuturePackets );
594 // Badly out of sequence packet
597 Log_Log("TCP", "Fully out of sequence packet (0x%08x not between 0x%08x and 0x%08x), dropped",
598 sequence_num, Connection->NextSequenceRcv, Connection->NextSequenceRcv+TCP_WINDOW_SIZE);
599 // Spec says we should send an empty ACK with the current state
600 TCP_INT_SendACK(Connection, "Bad Seq");
604 // --- Remote close states
605 case TCP_ST_CLOSE_WAIT:
607 // Ignore everything, CLOSE_WAIT is terminated by the client
608 Log_Debug("TCP", "CLOSE WAIT - Ignoring packets");
612 // LAST-ACK - Waiting for the ACK of FIN (from CLOSE WAIT)
613 case TCP_ST_LAST_ACK:
614 if( Header->Flags & TCP_FLAG_ACK )
616 Connection->State = TCP_ST_FINISHED; // Connection completed
617 Log_Log("TCP", "LAST-ACK to CLOSED - Connection remote closed");
618 TCP_int_FreeTCB(Connection);
622 // --- Local close States
623 case TCP_ST_FIN_WAIT1:
624 if( Header->Flags & TCP_FLAG_FIN )
626 Connection->State = TCP_ST_CLOSING;
627 Log_Debug("TCP", "Conn %p closed, sent FIN and recieved FIN", Connection);
628 VFS_MarkError(&Connection->Node, 1);
630 TCP_INT_SendACK(Connection, "FINWAIT-1 FIN");
634 // TODO: Make sure that the packet is actually ACKing the FIN
635 if( Header->Flags & TCP_FLAG_ACK )
637 Connection->State = TCP_ST_FIN_WAIT2;
638 Log_Debug("TCP", "Conn %p closed, sent FIN ACKed", Connection);
639 VFS_MarkError(&Connection->Node, 1);
644 case TCP_ST_FIN_WAIT2:
645 if( Header->Flags & TCP_FLAG_FIN )
647 Connection->State = TCP_ST_TIME_WAIT;
648 Log_Debug("TCP", "Conn %p FINWAIT-2 -> TIME WAIT", Connection);
649 TCP_INT_SendACK(Connection, "FINWAIT-2 FIN");
654 // TODO: Make sure that the packet is actually ACKing the FIN
655 if( Header->Flags & TCP_FLAG_ACK )
657 Connection->State = TCP_ST_TIME_WAIT;
658 Log_Debug("TCP", "Conn %p CLOSING -> TIME WAIT", Connection);
659 VFS_MarkError(&Connection->Node, 1);
664 // --- Closed (or near closed) states) ---
665 case TCP_ST_TIME_WAIT:
666 Log_Log("TCP", "Packets on Time-Wait, ignored");
669 case TCP_ST_FINISHED:
670 Log_Log("TCP", "Packets when CLOSED, ignoring");
674 // Log_Warning("TCP", "Unhandled TCP state %i", Connection->State);
681 * \brief Appends a packet to the recieved list
682 * \param Connection Connection structure
683 * \param Data Packet contents
684 * \param Length Length of \a Data
686 int TCP_INT_AppendRecieved(tTCPConnection *Connection, const void *Data, size_t Length)
688 Mutex_Acquire( &Connection->lRecievedPackets );
690 if(Connection->RecievedBuffer->Length + Length > Connection->RecievedBuffer->Space )
692 VFS_MarkAvaliable(&Connection->Node, 1);
693 Log_Error("TCP", "Buffer filled, packet dropped (:%i) - %i + %i > %i",
694 Connection->LocalPort, Connection->RecievedBuffer->Length, Length,
695 Connection->RecievedBuffer->Space
697 Mutex_Release( &Connection->lRecievedPackets );
701 RingBuffer_Write( Connection->RecievedBuffer, Data, Length );
703 VFS_MarkAvaliable(&Connection->Node, 1);
705 Mutex_Release( &Connection->lRecievedPackets );
710 * \brief Updates the connections recieved list from the future list
711 * \param Connection Connection structure
713 * Updates the recieved packets list with packets from the future (out
714 * of order) packets list that are now able to be added in direct
717 void TCP_INT_UpdateRecievedFromFuture(tTCPConnection *Connection)
719 #if CACHE_FUTURE_PACKETS_IN_BYTES
720 // Calculate length of contiguous bytes
721 int length = Connection->HighestSequenceRcvd - Connection->NextSequenceRcv;
722 Uint32 index = Connection->NextSequenceRcv % TCP_WINDOW_SIZE;
723 LOG("length=%i, index=%i", length, index);
724 for( int i = 0; i < length; i ++ )
727 Uint8 bitfield_byte = Connection->FuturePacketValidBytes[index / 8];
728 if( (bitfield_byte & (1 << bit)) == 0 ) {
733 if( bitfield_byte == 0xFF ) {
741 if(index > TCP_WINDOW_SIZE)
742 index -= TCP_WINDOW_SIZE;
745 index = Connection->NextSequenceRcv % TCP_WINDOW_SIZE;
747 // Write data to to the ring buffer
748 if( TCP_WINDOW_SIZE - index > length )
751 RingBuffer_Write( Connection->RecievedBuffer, Connection->FuturePacketData + index, length );
755 int endLen = TCP_WINDOW_SIZE - index;
757 RingBuffer_Write( Connection->RecievedBuffer, Connection->FuturePacketData + index, endLen );
758 RingBuffer_Write( Connection->RecievedBuffer, Connection->FuturePacketData, endLen - length );
761 // Mark (now saved) bytes as invalid
763 while(index % 8 && length > 0)
765 Connection->FuturePacketData[index] = 0;
766 Connection->FuturePacketValidBytes[index/8] &= ~(1 << (index%8));
768 if(index > TCP_WINDOW_SIZE)
769 index -= TCP_WINDOW_SIZE;
774 Connection->FuturePacketData[index] = 0;
775 Connection->FuturePacketValidBytes[index/8] = 0;
778 if(index > TCP_WINDOW_SIZE)
779 index -= TCP_WINDOW_SIZE;
783 Connection->FuturePacketData[index] = 0;
784 Connection->FuturePacketData[index/8] &= ~(1 << (index%8));
786 if(index > TCP_WINDOW_SIZE)
787 index -= TCP_WINDOW_SIZE;
792 tTCPStoredPacket *pkt;
795 SHORTLOCK( &Connection->lFuturePackets );
797 // Clear out duplicates from cache
798 // - If a packet has just been recieved, and it is expected, then
799 // (since NextSequenceRcv = rcvd->Sequence + rcvd->Length) all
800 // packets in cache that are smaller than the next expected
802 pkt = Connection->FuturePackets;
803 while(pkt && pkt->Sequence < Connection->NextSequenceRcv)
805 tTCPStoredPacket *next = pkt->Next;
810 // If there's no packets left in cache, stop looking
811 if(!pkt || pkt->Sequence > Connection->NextSequenceRcv) {
812 SHORTREL( &Connection->lFuturePackets );
816 // Delete packet from future list
817 Connection->FuturePackets = pkt->Next;
820 SHORTREL( &Connection->lFuturePackets );
822 // Looks like we found one
823 TCP_INT_AppendRecieved(Connection, pkt->Data, pkt->Length);
824 if( Connection->HighestSequenceRcvd == Connection->NextSequenceRcv )
825 Connection->HighestSequenceRcvd += pkt->Length;
826 Connection->NextSequenceRcv += pkt->Length;
832 void TCP_int_SendDelayedACK(void *ConnPtr)
834 TCP_INT_SendACK(ConnPtr, "DACK Timeout");
837 void TCP_INT_SendACK(tTCPConnection *Connection, const char *Reason)
841 hdr.DataOffset = (sizeof(tTCPHeader)/4) << 4;
842 hdr.DestPort = htons(Connection->RemotePort);
843 hdr.SourcePort = htons(Connection->LocalPort);
844 hdr.AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
845 hdr.SequenceNumber = htonl(Connection->NextSequenceSend);
846 hdr.WindowSize = htons(TCP_WINDOW_SIZE);
847 hdr.Flags = TCP_FLAG_ACK; // TODO: Determine if SYN is wanted too
848 hdr.Checksum = 0; // TODO: Checksum
849 hdr.UrgentPointer = 0;
850 Log_Debug("TCP", "Sending ACK for 0x%08x (%s)", Connection->NextSequenceRcv, Reason);
851 TCP_SendPacket( Connection, &hdr, 0, NULL );
852 //Connection->NextSequenceSend ++;
853 Connection->LastACKSequence = Connection->NextSequenceRcv;
857 * \fn Uint16 TCP_GetUnusedPort()
858 * \brief Gets an unused port and allocates it
860 Uint16 TCP_GetUnusedPort()
864 // Get Next outbound port
865 ret = giTCP_NextOutPort++;
866 while( gaTCP_PortBitmap[ret/32] & (1UL << (ret%32)) )
870 if(giTCP_NextOutPort == 0x10000) {
871 ret = giTCP_NextOutPort = TCP_MIN_DYNPORT;
875 // Mark the new port as used
876 gaTCP_PortBitmap[ret/32] |= 1 << (ret%32);
882 * \fn int TCP_AllocatePort(Uint16 Port)
883 * \brief Marks a port as used
885 int TCP_AllocatePort(Uint16 Port)
887 // Check if the port has already been allocated
888 if( gaTCP_PortBitmap[Port/32] & (1 << (Port%32)) )
892 gaTCP_PortBitmap[Port/32] |= 1 << (Port%32);
898 * \fn int TCP_DeallocatePort(Uint16 Port)
899 * \brief Marks a port as unused
901 int TCP_DeallocatePort(Uint16 Port)
903 // Check if the port has already been allocated
904 if( !(gaTCP_PortBitmap[Port/32] & (1 << (Port%32))) )
908 gaTCP_PortBitmap[Port/32] &= ~(1 << (Port%32));
913 tTCPConnection *TCP_int_CreateConnection(tInterface *Interface, enum eTCPConnectionState State)
915 tTCPConnection *conn = calloc( sizeof(tTCPConnection) + TCP_WINDOW_SIZE + TCP_WINDOW_SIZE/8, 1 );
918 conn->Interface = Interface;
919 conn->LocalPort = -1;
920 conn->RemotePort = -1;
922 conn->Node.ReferenceCount = 1;
923 conn->Node.ImplPtr = conn;
924 conn->Node.NumACLs = 1;
925 conn->Node.ACLs = &gVFS_ACL_EveryoneRW;
926 conn->Node.Type = &gTCP_ClientNodeType;
927 conn->Node.BufferFull = 1; // Cleared when connection opens
929 conn->RecievedBuffer = RingBuffer_Create( TCP_RECIEVE_BUFFER_SIZE );
931 conn->SentBuffer = RingBuffer_Create( TCP_SEND_BUFFER_SIZE );
932 Semaphore_Init(conn->SentBufferSpace, 0, TCP_SEND_BUFFER_SIZE, "TCP SentBuffer", conn->Name);
935 #if CACHE_FUTURE_PACKETS_IN_BYTES
936 // Future recieved data (ahead of the expected sequence number)
937 conn->FuturePacketData = (Uint8*)conn + sizeof(tTCPConnection);
938 conn->FuturePacketValidBytes = conn->FuturePacketData + TCP_WINDOW_SIZE;
941 conn->DeferredACKTimer = Time_AllocateTimer( TCP_int_SendDelayedACK, conn);
945 void TCP_int_FreeTCB(tTCPConnection *Connection)
947 ASSERTC(Connection->State, ==, TCP_ST_FINISHED);
948 ASSERTC(Connection->Node.ReferenceCount, ==, 0);
950 if( Connection->Server )
952 tTCPListener *srv = Connection->Server;
953 SHORTLOCK(&srv->lConnections);
955 Connection->Prev->Next = Connection->Next;
957 srv->Connections = Connection->Next;
959 Connection->Next->Prev = Connection->Prev;
961 ASSERT(srv->ConnectionsTail == Connection);
962 srv->ConnectionsTail = Connection->Prev;
964 SHORTREL(&srv->lConnections);
968 SHORTLOCK(&glTCP_OutbountCons);
970 Connection->Prev->Next = Connection->Next;
972 gTCP_OutbountCons = Connection->Next;
974 Connection->Next->Prev = Connection->Prev;
977 SHORTREL(&glTCP_OutbountCons);
980 RingBuffer_Free(Connection->RecievedBuffer);
981 Time_FreeTimer(Connection->DeferredACKTimer);
982 // TODO: Force VFS to close handles? (they should all be closed);
987 tVFS_Node *TCP_Server_Init(tInterface *Interface)
991 srv = calloc( 1, sizeof(tTCPListener) );
994 Log_Warning("TCP", "malloc failed for listener (%i) bytes", sizeof(tTCPListener));
998 srv->Interface = Interface;
1001 srv->Connections = NULL;
1002 srv->ConnectionsTail = NULL;
1003 srv->NewConnections = NULL;
1005 srv->Node.Flags = VFS_FFLAG_DIRECTORY;
1006 srv->Node.Size = -1;
1007 srv->Node.ImplPtr = srv;
1008 srv->Node.NumACLs = 1;
1009 srv->Node.ACLs = &gVFS_ACL_EveryoneRW;
1010 srv->Node.Type = &gTCP_ServerNodeType;
1012 SHORTLOCK(&glTCP_Listeners);
1013 srv->Next = gTCP_Listeners;
1014 gTCP_Listeners = srv;
1015 SHORTREL(&glTCP_Listeners);
1021 * \brief Wait for a new connection and return the connection ID
1022 * \note Blocks until a new connection is made
1023 * \param Node Server node
1024 * \param Pos Position (ignored)
1026 int TCP_Server_ReadDir(tVFS_Node *Node, int Pos, char Dest[FILENAME_MAX])
1028 tTCPListener *srv = Node->ImplPtr;
1029 tTCPConnection *conn;
1031 ENTER("pNode iPos", Node, Pos);
1033 Log_Log("TCP", "Thread %i waiting for a connection", Threads_GetTID());
1034 Semaphore_Wait( &srv->WaitingConnections, 1 );
1036 SHORTLOCK(&srv->lConnections);
1037 // Increment the new list (the current connection is still on the
1039 conn = srv->NewConnections;
1040 srv->NewConnections = conn->Next;
1042 if( srv->NewConnections == NULL )
1043 VFS_MarkAvaliable( Node, 0 );
1045 SHORTREL( &srv->lConnections );
1047 LOG("conn = %p", conn);
1048 LOG("srv->Connections = %p", srv->Connections);
1049 LOG("srv->NewConnections = %p", srv->NewConnections);
1050 LOG("srv->ConnectionsTail = %p", srv->ConnectionsTail);
1052 itoa(Dest, conn->Node.ImplInt, 16, 8, '0');
1053 Log_Log("TCP", "Thread %i got connection '%s'", Threads_GetTID(), Dest);
1059 * \brief Gets a client connection node
1060 * \param Node Server node
1061 * \param Name Hexadecimal ID of the node
1063 tVFS_Node *TCP_Server_FindDir(tVFS_Node *Node, const char *Name, Uint Flags)
1065 tTCPConnection *conn;
1066 tTCPListener *srv = Node->ImplPtr;
1068 int id = atoi(Name);
1070 ENTER("pNode sName", Node, Name);
1072 // Check for a non-empty name
1076 itoa(tmp, id, 16, 8, '0');
1077 if(strcmp(tmp, Name) != 0) {
1078 LOG("'%s' != '%s' (%08x)", Name, tmp, id);
1083 Log_Debug("TCP", "srv->Connections = %p", srv->Connections);
1084 Log_Debug("TCP", "srv->NewConnections = %p", srv->NewConnections);
1085 Log_Debug("TCP", "srv->ConnectionsTail = %p", srv->ConnectionsTail);
1088 SHORTLOCK( &srv->lConnections );
1089 for(conn = srv->Connections;
1093 LOG("conn->Node.ImplInt = %i", conn->Node.ImplInt);
1094 if(conn->Node.ImplInt == id) break;
1096 SHORTREL( &srv->lConnections );
1098 // If not found, ret NULL
1100 LOG("Connection %i not found", id);
1105 // Empty Name - Check for a new connection and if it's there, open it
1108 SHORTLOCK( &srv->lConnections );
1109 conn = srv->NewConnections;
1111 srv->NewConnections = conn->Next;
1112 VFS_MarkAvaliable( Node, srv->NewConnections != NULL );
1113 SHORTREL( &srv->lConnections );
1115 LOG("No new connections");
1122 LEAVE('p', &conn->Node);
1127 * \brief Handle IOCtl calls
1129 int TCP_Server_IOCtl(tVFS_Node *Node, int ID, void *Data)
1131 tTCPListener *srv = Node->ImplPtr;
1135 case 4: // Get/Set Port
1136 if(!Data) // Get Port
1139 if(srv->Port) // Wait, you can't CHANGE the port
1142 if(!CheckMem(Data, sizeof(Uint16))) // Sanity check
1145 // Permissions check
1146 if(Threads_GetUID() != 0
1147 && *(Uint16*)Data != 0
1148 && *(Uint16*)Data < 1024)
1151 // TODO: Check if a port is in use
1154 srv->Port = *(Uint16*)Data;
1155 if(srv->Port == 0) // Allocate a random port
1156 srv->Port = TCP_GetUnusedPort();
1157 else // Else, mark this as used
1158 TCP_AllocatePort(srv->Port);
1160 Log_Log("TCP", "Server %p listening on port %i", srv, srv->Port);
1167 void TCP_Server_Close(tVFS_Node *Node)
1169 free(Node->ImplPtr);
1174 * \brief Create a client node
1176 tVFS_Node *TCP_Client_Init(tInterface *Interface)
1178 tTCPConnection *conn = TCP_int_CreateConnection(Interface, TCP_ST_CLOSED);
1180 SHORTLOCK(&glTCP_OutbountCons);
1181 conn->Server = NULL;
1183 conn->Next = gTCP_OutbountCons;
1184 gTCP_OutbountCons->Prev = conn;
1185 gTCP_OutbountCons = conn;
1186 SHORTREL(&glTCP_OutbountCons);
1192 * \brief Wait for a packet and return it
1193 * \note If \a Length is smaller than the size of the packet, the rest
1194 * of the packet's data will be discarded.
1196 size_t TCP_Client_Read(tVFS_Node *Node, off_t Offset, size_t Length, void *Buffer, Uint Flags)
1198 tTCPConnection *conn = Node->ImplPtr;
1201 ENTER("pNode XOffset XLength pBuffer", Node, Offset, Length, Buffer);
1202 LOG("conn = %p {State:%i}", conn, conn->State);
1204 // If the connection has been closed (state > ST_OPEN) then clear
1205 // any stale data in the buffer (until it is empty (until it is empty))
1206 if( conn->State > TCP_ST_OPEN )
1208 Mutex_Acquire( &conn->lRecievedPackets );
1209 len = RingBuffer_Read( Buffer, conn->RecievedBuffer, Length );
1210 Mutex_Release( &conn->lRecievedPackets );
1213 VFS_MarkAvaliable(Node, 0);
1225 tTime *timeout = NULL;
1226 tTime timeout_zero = 0;
1227 if( Flags & VFS_IOFLAG_NOBLOCK )
1228 timeout = &timeout_zero;
1229 if( !VFS_SelectNode(Node, VFS_SELECT_READ|VFS_SELECT_ERROR, timeout, "TCP_Client_Read") ) {
1230 errno = EWOULDBLOCK;
1236 // Lock list and read as much as possible (up to `Length`)
1237 Mutex_Acquire( &conn->lRecievedPackets );
1238 len = RingBuffer_Read( Buffer, conn->RecievedBuffer, Length );
1240 if( len == 0 || conn->RecievedBuffer->Length == 0 ) {
1241 LOG("Marking as none avaliable (len = %i)", len);
1242 VFS_MarkAvaliable(Node, 0);
1245 // Release the lock (we don't need it any more)
1246 Mutex_Release( &conn->lRecievedPackets );
1253 * \brief Send a data packet on a connection
1255 void TCP_INT_SendDataPacket(tTCPConnection *Connection, size_t Length, const void *Data)
1257 char buf[sizeof(tTCPHeader)+Length];
1258 tTCPHeader *packet = (void*)buf;
1260 // - Stop Delayed ACK timer (as this data packet ACKs)
1261 Time_RemoveTimer(Connection->DeferredACKTimer);
1263 packet->SourcePort = htons(Connection->LocalPort);
1264 packet->DestPort = htons(Connection->RemotePort);
1265 packet->DataOffset = (sizeof(tTCPHeader)/4)*16;
1266 packet->WindowSize = htons(TCP_WINDOW_SIZE);
1268 packet->AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
1269 packet->SequenceNumber = htonl(Connection->NextSequenceSend);
1270 packet->Flags = TCP_FLAG_PSH|TCP_FLAG_ACK; // Hey, ACK if you can!
1271 packet->UrgentPointer = 0;
1273 memcpy(packet->Options, Data, Length);
1275 Log_Debug("TCP", "Send sequence 0x%08x", Connection->NextSequenceSend);
1276 #if HEXDUMP_OUTGOING
1277 Debug_HexDump("TCP_INT_SendDataPacket: Data = ", Data, Length);
1280 TCP_SendPacket( Connection, packet, Length, Data );
1282 Connection->NextSequenceSend += Length;
1286 * \brief Send some bytes on a connection
1288 size_t TCP_Client_Write(tVFS_Node *Node, off_t Offset, size_t Length, const void *Buffer, Uint Flags)
1290 tTCPConnection *conn = Node->ImplPtr;
1291 size_t rem = Length;
1293 ENTER("pNode XOffset XLength pBuffer", Node, Offset, Length, Buffer);
1296 // Debug_HexDump("TCP_Client_Write: Buffer = ",
1300 // Don't allow a write to a closed connection
1301 if( conn->State > TCP_ST_OPEN ) {
1302 VFS_MarkError(Node, 1);
1310 tTime *timeout = NULL;
1311 tTime timeout_zero = 0;
1312 if( Flags & VFS_IOFLAG_NOBLOCK )
1313 timeout = &timeout_zero;
1314 if( !VFS_SelectNode(Node, VFS_SELECT_WRITE|VFS_SELECT_ERROR, timeout, "TCP_Client_Write") ) {
1315 errno = EWOULDBLOCK;
1323 int len = (rem < TCP_MAX_PACKET_SIZE) ? rem : TCP_MAX_PACKET_SIZE;
1326 // Wait for space in the buffer
1327 Semaphore_Signal( &Connection->SentBufferSpace, len );
1329 // Save data to buffer (and update the length read by the ammount written)
1330 len = RingBuffer_Write( &Connection->SentBuffer, Buffer, len);
1334 TCP_INT_SendDataPacket(conn, len, Buffer);
1345 * \brief Open a connection to another host using TCP
1346 * \param Conn Connection structure
1348 void TCP_StartConnection(tTCPConnection *Conn)
1350 tTCPHeader hdr = {0};
1352 Conn->State = TCP_ST_SYN_SENT;
1354 hdr.SourcePort = htons(Conn->LocalPort);
1355 hdr.DestPort = htons(Conn->RemotePort);
1356 Conn->NextSequenceSend = rand();
1357 hdr.SequenceNumber = htonl(Conn->NextSequenceSend);
1358 hdr.DataOffset = (sizeof(tTCPHeader)/4) << 4;
1359 hdr.Flags = TCP_FLAG_SYN;
1360 hdr.WindowSize = htons(TCP_WINDOW_SIZE); // Max
1361 hdr.Checksum = 0; // TODO
1363 TCP_SendPacket( Conn, &hdr, 0, NULL );
1365 Conn->NextSequenceSend ++;
1366 Conn->State = TCP_ST_SYN_SENT;
1372 * \brief Control a client socket
1374 int TCP_Client_IOCtl(tVFS_Node *Node, int ID, void *Data)
1376 tTCPConnection *conn = Node->ImplPtr;
1378 ENTER("pNode iID pData", Node, ID, Data);
1382 case 4: // Get/Set local port
1384 LEAVE_RET('i', conn->LocalPort);
1385 if(conn->State != TCP_ST_CLOSED)
1387 if(!CheckMem(Data, sizeof(Uint16)))
1390 if(Threads_GetUID() != 0 && *(Uint16*)Data < 1024)
1393 conn->LocalPort = *(Uint16*)Data;
1394 LEAVE_RET('i', conn->LocalPort);
1396 case 5: // Get/Set remote port
1397 if(!Data) LEAVE_RET('i', conn->RemotePort);
1398 if(conn->State != TCP_ST_CLOSED) LEAVE_RET('i', -1);
1399 if(!CheckMem(Data, sizeof(Uint16))) LEAVE_RET('i', -1);
1400 conn->RemotePort = *(Uint16*)Data;
1401 LEAVE_RET('i', conn->RemotePort);
1403 case 6: // Set Remote IP
1404 if( conn->State != TCP_ST_CLOSED )
1406 if( conn->Interface->Type == 4 )
1408 if(!CheckMem(Data, sizeof(tIPv4))) LEAVE_RET('i', -1);
1409 conn->RemoteIP.v4 = *(tIPv4*)Data;
1411 else if( conn->Interface->Type == 6 )
1413 if(!CheckMem(Data, sizeof(tIPv6))) LEAVE_RET('i', -1);
1414 conn->RemoteIP.v6 = *(tIPv6*)Data;
1419 if(conn->LocalPort == 0xFFFF)
1420 conn->LocalPort = TCP_GetUnusedPort();
1421 if(conn->RemotePort == -1)
1425 tTime timeout = conn->Interface->TimeoutDelay;
1427 TCP_StartConnection(conn);
1428 VFS_SelectNode(&conn->Node, VFS_SELECT_WRITE, &timeout, "TCP Connection");
1429 if( conn->State == TCP_ST_SYN_SENT )
1435 // Get recieve buffer length
1437 LEAVE_RET('i', conn->RecievedBuffer->Length);
1443 void TCP_Client_Close(tVFS_Node *Node)
1445 tTCPConnection *conn = Node->ImplPtr;
1448 ENTER("pNode", Node);
1450 ASSERT(Node->ReferenceCount != 0);
1452 if( Node->ReferenceCount > 1 ) {
1453 Node->ReferenceCount --;
1454 LOG("Dereference only");
1458 Node->ReferenceCount --;
1460 if( conn->State == TCP_ST_CLOSE_WAIT || conn->State == TCP_ST_OPEN )
1462 packet.SourcePort = htons(conn->LocalPort);
1463 packet.DestPort = htons(conn->RemotePort);
1464 packet.DataOffset = (sizeof(tTCPHeader)/4)*16;
1465 packet.WindowSize = TCP_WINDOW_SIZE;
1467 packet.AcknowlegementNumber = 0;
1468 packet.SequenceNumber = htonl(conn->NextSequenceSend);
1469 packet.Flags = TCP_FLAG_FIN;
1471 TCP_SendPacket( conn, &packet, 0, NULL );
1474 Time_RemoveTimer(conn->DeferredACKTimer);
1476 switch( conn->State )
1479 Log_Warning("TCP", "Closing connection that was never opened");
1480 TCP_int_FreeTCB(conn);
1482 case TCP_ST_CLOSE_WAIT:
1483 conn->State = TCP_ST_LAST_ACK;
1486 conn->State = TCP_ST_FIN_WAIT1;
1487 while( conn->State == TCP_ST_FIN_WAIT1 )
1489 // No free, freed after TIME_WAIT
1492 Log_Warning("TCP", "Unhandled connection state %i in TCP_Client_Close",
1501 * \brief Checks if a value is between two others (after taking into account wrapping)
1503 int WrapBetween(Uint32 Lower, Uint32 Value, Uint32 Higher, Uint32 MaxValue)
1505 if( MaxValue < 0xFFFFFFFF )
1507 Lower %= MaxValue + 1;
1508 Value %= MaxValue + 1;
1509 Higher %= MaxValue + 1;
1512 // Simple Case, no wrap ?
1513 // Lower Value Higher
1514 // | ... + ... + ... + ... |
1516 if( Lower < Higher ) {
1517 return Lower < Value && Value < Higher;
1519 // Higher has wrapped below lower
1522 // Higher Lower Value
1523 // | ... + ... + ... + ... |
1524 if( Value > Lower ) {
1529 // Value Higher Lower
1530 // | ... + ... + ... + ... |
1531 if( Value < Higher ) {