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 100
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 int TCP_INT_HandleServerPacket(tInterface *Interface, tTCPListener *Server, const void *Address, tTCPHeader *Header, size_t Length);
32 int TCP_INT_HandleConnectionPacket(tTCPConnection *Connection, tTCPHeader *Header, int Length);
33 int TCP_INT_AppendRecieved(tTCPConnection *Connection, const void *Data, size_t Length);
34 void TCP_INT_UpdateRecievedFromFuture(tTCPConnection *Connection);
35 void TCP_int_SendDelayedACK(void *ConnPtr);
36 void TCP_INT_SendACK(tTCPConnection *Connection, const char *Reason);
37 Uint16 TCP_GetUnusedPort();
38 int TCP_AllocatePort(Uint16 Port);
39 int TCP_DeallocatePort(Uint16 Port);
40 tTCPConnection *TCP_int_CreateConnection(tInterface *Interface, enum eTCPConnectionState State);
41 void TCP_int_FreeTCB(tTCPConnection *Connection);
43 tVFS_Node *TCP_Server_Init(tInterface *Interface);
44 int TCP_Server_ReadDir(tVFS_Node *Node, int Pos, char Name[FILENAME_MAX]);
45 tVFS_Node *TCP_Server_FindDir(tVFS_Node *Node, const char *Name, Uint Flags);
46 int TCP_Server_IOCtl(tVFS_Node *Node, int ID, void *Data);
47 void TCP_Server_Close(tVFS_Node *Node);
49 tVFS_Node *TCP_Client_Init(tInterface *Interface);
50 size_t TCP_Client_Read(tVFS_Node *Node, off_t Offset, size_t Length, void *Buffer, Uint Flags);
51 size_t TCP_Client_Write(tVFS_Node *Node, off_t Offset, size_t Length, const void *Buffer, Uint Flags);
52 int TCP_Client_IOCtl(tVFS_Node *Node, int ID, void *Data);
53 void TCP_Client_Close(tVFS_Node *Node);
55 int WrapBetween(Uint32 Lower, Uint32 Value, Uint32 Higher, Uint32 MaxValue);
56 Uint32 GetRelative(Uint32 Base, Uint32 Value);
59 tSocketFile gTCP_ServerFile = {NULL, "tcps", TCP_Server_Init};
60 tSocketFile gTCP_ClientFile = {NULL, "tcpc", TCP_Client_Init};
61 tVFS_NodeType gTCP_ServerNodeType = {
62 .TypeName = "TCP Server",
63 .ReadDir = TCP_Server_ReadDir,
64 .FindDir = TCP_Server_FindDir,
65 .IOCtl = TCP_Server_IOCtl,
66 .Close = TCP_Server_Close
68 tVFS_NodeType gTCP_ClientNodeType = {
69 .TypeName = "TCP Client/Connection",
70 .Flags = VFS_NODETYPEFLAG_STREAM,
71 .Read = TCP_Client_Read,
72 .Write = TCP_Client_Write,
73 .IOCtl = TCP_Client_IOCtl,
74 .Close = TCP_Client_Close
78 int giTCP_NumHalfopen = 0;
79 tShortSpinlock glTCP_Listeners;
80 tTCPListener *gTCP_Listeners;
81 tShortSpinlock glTCP_OutbountCons;
82 tTCPConnection *gTCP_OutbountCons;
83 Uint32 gaTCP_PortBitmap[0x800];
84 int giTCP_NextOutPort = TCP_MIN_DYNPORT;
88 * \brief Initialise the TCP Layer
90 * Registers the client and server files and the GetPacket callback
92 void TCP_Initialise(void)
94 giTCP_NextOutPort += rand()%128;
95 IPStack_AddFile(&gTCP_ServerFile);
96 IPStack_AddFile(&gTCP_ClientFile);
97 IPv4_RegisterCallback(IP4PROT_TCP, TCP_GetPacket);
98 IPv6_RegisterCallback(IP4PROT_TCP, TCP_GetPacket);
102 * \brief Sends a packet from the specified connection, calculating the checksums
103 * \param Conn Connection
104 * \param Length Length of data
105 * \param Data Packet data (cast as a TCP Header)
107 void TCP_SendPacket( tTCPConnection *Conn, tTCPHeader *Header, size_t Length, const void *Data )
109 TCP_int_SendPacket(Conn->Interface, &Conn->RemoteIP, Header, Length, Data);
112 Uint16 TCP_int_CalculateChecksum(int AddrType, const void *LAddr, const void *RAddr,
113 size_t HeaderLength, const tTCPHeader *Header, size_t DataLength, const void *Data)
115 size_t packlen = HeaderLength + DataLength;
122 buf[0] = ((tIPv4*)LAddr)->L;
123 buf[1] = ((tIPv4*)RAddr)->L;
124 buf[2] = htonl( (packlen) | (IP4PROT_TCP<<16) | (0<<24) );
125 checksum[0] = htons( ~IPv4_Checksum(buf, sizeof(buf)) ); // Partial checksum
129 memcpy(&buf[0], LAddr, 16);
130 memcpy(&buf[4], RAddr, 16);
131 buf[8] = htonl(packlen);
132 buf[9] = htonl(IP4PROT_TCP);
133 checksum[0] = htons( ~IPv4_Checksum(buf, sizeof(buf)) ); // Partial checksum
138 checksum[1] = htons( ~IPv4_Checksum(Header, HeaderLength) );
139 checksum[2] = htons( ~IPv4_Checksum(Data, DataLength) );
141 return htons( IPv4_Checksum(checksum, sizeof(checksum)) );
144 void TCP_int_SendPacket(tInterface *Interface, const void *Dest, tTCPHeader *Header, size_t Length, const void *Data )
146 tIPStackBuffer *buffer = IPStack_Buffer_CreateBuffer(2 + IPV4_BUFFERS);
148 IPStack_Buffer_AppendSubBuffer(buffer, Length, 0, Data, NULL, NULL);
149 IPStack_Buffer_AppendSubBuffer(buffer, sizeof(*Header), 0, Header, NULL, NULL);
152 Log_Log("TCP", "TCP_int_SendPacket: <Local>:%i to [%s]:%i (%i data), Flags = %s%s%s%s%s%s%s%s",
153 ntohs(Header->SourcePort),
154 IPStack_PrintAddress(Interface->Type, Dest),
155 ntohs(Header->DestPort),
157 (Header->Flags & TCP_FLAG_CWR) ? "CWR " : "",
158 (Header->Flags & TCP_FLAG_ECE) ? "ECE " : "",
159 (Header->Flags & TCP_FLAG_URG) ? "URG " : "",
160 (Header->Flags & TCP_FLAG_ACK) ? "ACK " : "",
161 (Header->Flags & TCP_FLAG_PSH) ? "PSH " : "",
162 (Header->Flags & TCP_FLAG_RST) ? "RST " : "",
163 (Header->Flags & TCP_FLAG_SYN) ? "SYN " : "",
164 (Header->Flags & TCP_FLAG_FIN) ? "FIN " : ""
168 Header->Checksum = 0;
169 Header->Checksum = TCP_int_CalculateChecksum(Interface->Type, Interface->Address, Dest,
170 sizeof(tTCPHeader), Header, Length, Data);
172 // TODO: Fragment packet
174 switch( Interface->Type )
177 IPv4_SendPacket(Interface, *(tIPv4*)Dest, IP4PROT_TCP, 0, buffer);
180 IPv6_SendPacket(Interface, *(tIPv6*)Dest, IP4PROT_TCP, buffer);
185 void TCP_int_SendRSTTo(tInterface *Interface, const void *Address, size_t Length, const tTCPHeader *Header)
187 tTCPHeader out_hdr = {0};
189 out_hdr.DataOffset = (sizeof(out_hdr)/4) << 4;
190 out_hdr.DestPort = Header->SourcePort;
191 out_hdr.SourcePort = Header->DestPort;
193 size_t data_len = Length - (Header->DataOffset>>4)*4;
194 out_hdr.AcknowlegementNumber = htonl( ntohl(Header->SequenceNumber) + data_len );
195 if( Header->Flags & TCP_FLAG_ACK ) {
196 out_hdr.Flags = TCP_FLAG_RST;
197 out_hdr.SequenceNumber = Header->AcknowlegementNumber;
200 out_hdr.Flags = TCP_FLAG_RST|TCP_FLAG_ACK;
201 out_hdr.SequenceNumber = 0;
203 TCP_int_SendPacket(Interface, Address, &out_hdr, 0, NULL);
207 * \brief Handles a packet from the IP Layer
208 * \param Interface Interface the packet arrived from
209 * \param Address Pointer to the addres structure
210 * \param Length Size of packet in bytes
211 * \param Buffer Packet data
213 void TCP_GetPacket(tInterface *Interface, void *Address, int Length, void *Buffer)
215 tTCPHeader *hdr = Buffer;
218 Log_Log("TCP", "TCP_GetPacket: <Local>:%i from [%s]:%i, Flags = %s%s%s%s%s%s%s%s",
219 ntohs(hdr->DestPort),
220 IPStack_PrintAddress(Interface->Type, Address),
221 ntohs(hdr->SourcePort),
222 (hdr->Flags & TCP_FLAG_CWR) ? "CWR " : "",
223 (hdr->Flags & TCP_FLAG_ECE) ? "ECE " : "",
224 (hdr->Flags & TCP_FLAG_URG) ? "URG " : "",
225 (hdr->Flags & TCP_FLAG_ACK) ? "ACK " : "",
226 (hdr->Flags & TCP_FLAG_PSH) ? "PSH " : "",
227 (hdr->Flags & TCP_FLAG_RST) ? "RST " : "",
228 (hdr->Flags & TCP_FLAG_SYN) ? "SYN " : "",
229 (hdr->Flags & TCP_FLAG_FIN) ? "FIN " : ""
233 if( Length > (hdr->DataOffset >> 4)*4 )
235 LOG("SequenceNumber = 0x%x", ntohl(hdr->SequenceNumber));
238 "TCP_GetPacket: Packet Data = ",
239 (Uint8*)hdr + (hdr->DataOffset >> 4)*4,
240 Length - (hdr->DataOffset >> 4)*4
246 for( tTCPListener *srv = gTCP_Listeners; srv; srv = srv->Next )
248 // Check if the server is active
249 if(srv->Port == 0) continue;
250 // Check the interface
251 if(srv->Interface && srv->Interface != Interface) continue;
252 // Check the destination port
253 if(srv->Port != htons(hdr->DestPort)) continue;
255 Log_Log("TCP", "TCP_GetPacket: Matches server %p", srv);
256 // Is this in an established connection?
257 for( tTCPConnection *conn = srv->Connections; conn; conn = conn->Next )
259 // Check that it is coming in on the same interface
260 if(conn->Interface != Interface) continue;
262 if(conn->RemotePort != ntohs(hdr->SourcePort)) continue;
264 if( IPStack_CompareAddress(conn->Interface->Type, &conn->RemoteIP, Address, -1) == 0 )
267 Log_Log("TCP", "TCP_GetPacket: Matches connection %p", conn);
268 // We have a response!
269 if( TCP_INT_HandleConnectionPacket(conn, hdr, Length) == 0 )
274 TCP_INT_HandleServerPacket(Interface, srv, Address, hdr, Length);
278 // Check Open Connections
280 for( tTCPConnection *conn = gTCP_OutbountCons; conn; conn = conn->Next )
282 // Check that it is coming in on the same interface
283 if(conn->Interface != Interface) continue;
286 if(conn->RemotePort != ntohs(hdr->SourcePort)) continue;
289 if( IPStack_CompareAddress(conn->Interface->Type, &conn->RemoteIP, Address, -1) == 0 )
292 // Handle or fall through
293 if( TCP_INT_HandleConnectionPacket(conn, hdr, Length) == 0 )
299 Log_Log("TCP", "TCP_GetPacket: No Match");
300 // If not a RST, send a RST
301 if( !(hdr->Flags & TCP_FLAG_RST) )
303 TCP_int_SendRSTTo(Interface, Address, Length, hdr);
308 * Handle packets in LISTEN state
310 int TCP_INT_HandleServerPacket(tInterface *Interface, tTCPListener *Server, const void *Address, tTCPHeader *Header, size_t Length)
312 if( Header->Flags & TCP_FLAG_RST ) {
316 else if( Header->Flags & TCP_FLAG_ACK ) {
317 LOG("ACK, send RST");
318 TCP_int_SendRSTTo(Interface, Address, Length, Header);
321 else if( !(Header->Flags & TCP_FLAG_SYN) ) {
322 LOG("Other, ignore");
326 Log_Log("TCP", "TCP_GetPacket: Opening Connection");
328 // TODO: Check security (a TCP Option)
329 // TODO: Check SEG.PRC
330 // TODO: Check for halfopen max
332 tTCPConnection *conn = TCP_int_CreateConnection(Interface, TCP_ST_SYN_RCVD);
333 conn->LocalPort = Server->Port;
334 conn->RemotePort = ntohs(Header->SourcePort);
336 switch(Interface->Type)
338 case 4: conn->RemoteIP.v4 = *(tIPv4*)Address; break;
339 case 6: conn->RemoteIP.v6 = *(tIPv6*)Address; break;
340 default: ASSERTC(Interface->Type,==,4); return 0;
343 conn->NextSequenceRcv = ntohl( Header->SequenceNumber ) + 1;
344 conn->HighestSequenceRcvd = conn->NextSequenceRcv;
345 conn->NextSequenceSend = rand();
346 conn->LastACKSequence = ntohl( Header->SequenceNumber );
348 conn->Node.ImplInt = Server->NextID ++;
349 conn->Node.Size = -1;
351 // Hmm... Theoretically, this lock will never have to wait,
352 // as the interface is locked to the watching thread, and this
353 // runs in the watching thread. But, it's a good idea to have
355 // Oh, wait, there is a case where a wildcard can be used
356 // (Server->Interface == NULL) so having the lock is a good idea
357 SHORTLOCK(&Server->lConnections);
358 conn->Server = Server;
359 conn->Prev = Server->ConnectionsTail;
360 if(Server->Connections) {
361 ASSERT(Server->ConnectionsTail);
362 Server->ConnectionsTail->Next = conn;
365 ASSERT(!Server->ConnectionsTail);
366 Server->Connections = conn;
368 Server->ConnectionsTail = conn;
369 if(!Server->NewConnections)
370 Server->NewConnections = conn;
371 VFS_MarkAvaliable( &Server->Node, 1 );
372 SHORTREL(&Server->lConnections);
373 Semaphore_Signal(&Server->WaitingConnections, 1);
376 Header->Flags = TCP_FLAG_ACK|TCP_FLAG_SYN;
377 Header->AcknowlegementNumber = htonl(conn->NextSequenceRcv);
378 Header->SequenceNumber = htonl(conn->NextSequenceSend);
379 Header->DestPort = Header->SourcePort;
380 Header->SourcePort = htons(Server->Port);
381 Header->DataOffset = (sizeof(tTCPHeader)/4) << 4;
382 TCP_SendPacket( conn, Header, 0, NULL );
383 conn->NextSequenceSend ++;
388 * \brief Handles a packet sent to a specific connection
389 * \param Connection TCP Connection pointer
390 * \param Header TCP Packet pointer
391 * \param Length Length of the packet
393 int TCP_INT_HandleConnectionPacket(tTCPConnection *Connection, tTCPHeader *Header, int Length)
398 // Silently drop once finished
399 // TODO: Check if this needs to be here
400 if( Connection->State == TCP_ST_FINISHED ) {
401 Log_Log("TCP", "Packet ignored - connection finnished");
404 if( Connection->State == TCP_ST_FORCE_CLOSE ) {
405 Log_Log("TCP", "Packet ignored - connection reset");
409 // Syncronise sequence values
410 if(Header->Flags & TCP_FLAG_SYN) {
411 // TODO: What if the packet also has data?
412 if( Connection->LastACKSequence != Connection->NextSequenceRcv )
413 TCP_INT_SendACK(Connection, "SYN");
414 Connection->NextSequenceRcv = ntohl(Header->SequenceNumber);
415 // TODO: Process HighestSequenceRcvd
417 if( Connection->HighestSequenceRcvd == 0 )
418 Connection->HighestSequenceRcvd = Connection->NextSequenceRcv;
419 Connection->LastACKSequence = Connection->NextSequenceRcv;
422 // Ackowledge a sent packet
423 if(Header->Flags & TCP_FLAG_ACK) {
424 // TODO: Process an ACKed Packet
425 LOG("Conn %p, Sent packet 0x%x ACKed", Connection, Header->AcknowlegementNumber);
428 // Get length of data
429 dataLen = Length - (Header->DataOffset>>4)*4;
430 LOG("dataLen = %i", dataLen);
432 Log_Debug("TCP", "State %i, dataLen = %x", Connection->State, dataLen);
438 switch( Connection->State )
440 // Pre-init connection?
442 Log_Log("TCP", "Packets to a closed connection?!");
445 // --- Init States ---
446 // SYN sent, expecting SYN-ACK Connection Opening
447 case TCP_ST_SYN_SENT:
448 if( Header->Flags & TCP_FLAG_SYN )
450 if( Connection->HighestSequenceRcvd == Connection->NextSequenceRcv )
451 Connection->HighestSequenceRcvd ++;
452 Connection->NextSequenceRcv ++;
454 if( Header->Flags & TCP_FLAG_ACK )
456 Log_Log("TCP", "ACKing SYN-ACK");
457 Connection->State = TCP_ST_ESTABLISHED;
458 VFS_MarkFull(&Connection->Node, 0);
459 TCP_INT_SendACK(Connection, "SYN-ACK");
463 Log_Log("TCP", "ACKing SYN");
464 Connection->State = TCP_ST_SYN_RCVD;
465 TCP_INT_SendACK(Connection, "SYN");
470 // SYN-ACK sent, expecting ACK
471 case TCP_ST_SYN_RCVD:
472 if( Header->Flags & TCP_FLAG_RST )
474 Log_Log("TCP", "RST Received, closing");
475 Connection->State = TCP_ST_FORCE_CLOSE;
476 VFS_MarkError(&Connection->Node, 1);
479 if( Header->Flags & TCP_FLAG_ACK )
481 // TODO: Handle max half-open limit
482 Log_Log("TCP", "Connection fully opened");
483 Connection->State = TCP_ST_ESTABLISHED;
484 VFS_MarkFull(&Connection->Node, 0);
488 // --- Established State ---
489 case TCP_ST_ESTABLISHED:
490 // - Handle State changes
492 if( Header->Flags & TCP_FLAG_RST )
494 Log_Log("TCP", "Conn %p closed, received RST");
495 // Error outstanding transactions
496 Connection->State = TCP_ST_FORCE_CLOSE;
497 VFS_MarkError(&Connection->Node, 1);
500 if( Header->Flags & TCP_FLAG_FIN ) {
501 Log_Log("TCP", "Conn %p closed, recieved FIN", Connection);
502 VFS_MarkError(&Connection->Node, 1);
503 Connection->NextSequenceRcv ++;
504 TCP_INT_SendACK(Connection, "FIN Received");
505 Connection->State = TCP_ST_CLOSE_WAIT;
506 // CLOSE WAIT requires the client to close
510 // Check for an empty packet
512 if( Header->Flags == TCP_FLAG_ACK )
514 Log_Log("TCP", "ACK only packet");
517 // TODO: Is this right? (empty packet counts as one byte)
518 if( Connection->HighestSequenceRcvd == Connection->NextSequenceRcv )
519 Connection->HighestSequenceRcvd ++;
520 Connection->NextSequenceRcv ++;
521 Log_Log("TCP", "Empty Packet, inc and ACK the current sequence number");
522 TCP_INT_SendACK(Connection, "Empty");
531 sequence_num = ntohl(Header->SequenceNumber);
533 LOG("0x%08x <= 0x%08x < 0x%08x",
534 Connection->NextSequenceRcv,
535 ntohl(Header->SequenceNumber),
536 Connection->NextSequenceRcv + TCP_WINDOW_SIZE
539 // Is this packet the next expected packet?
540 if( sequence_num == Connection->NextSequenceRcv )
543 // Ooh, Goodie! Add it to the recieved list
544 rv = TCP_INT_AppendRecieved(Connection,
545 (Uint8*)Header + (Header->DataOffset>>4)*4,
549 Log_Notice("TCP", "TCP_INT_AppendRecieved rv %i", rv);
552 LOG("0x%08x += %i", Connection->NextSequenceRcv, dataLen);
553 if( Connection->HighestSequenceRcvd == Connection->NextSequenceRcv )
554 Connection->HighestSequenceRcvd += dataLen;
555 Connection->NextSequenceRcv += dataLen;
557 // TODO: This should be moved out of the watcher thread,
558 // so that a single lost packet on one connection doesn't cause
559 // all connections on the interface to lag.
560 // - Meh, no real issue, as the cache shouldn't be that large
561 TCP_INT_UpdateRecievedFromFuture(Connection);
564 // - Only send an ACK if we've had a burst
565 Uint32 bytes_since_last_ack = Connection->NextSequenceRcv - Connection->LastACKSequence;
566 LOG("bytes_since_last_ack = 0x%x", bytes_since_last_ack);
567 if( bytes_since_last_ack > TCP_DACK_THRESHOLD )
569 TCP_INT_SendACK(Connection, "DACK Burst");
570 // - Extend TCP deferred ACK timer
571 Time_RemoveTimer(Connection->DeferredACKTimer);
573 // - Schedule the deferred ACK timer (if already scheduled, this is a NOP)
574 Time_ScheduleTimer(Connection->DeferredACKTimer, TCP_DACK_TIMEOUT);
576 TCP_INT_SendACK(Connection, "RX");
579 // Check if the packet is in window
580 else if( sequence_num - Connection->NextSequenceRcv < TCP_WINDOW_SIZE )
582 Uint8 *dataptr = (Uint8*)Header + (Header->DataOffset>>4)*4;
583 Uint32 index = sequence_num % TCP_WINDOW_SIZE;
584 Uint32 max = Connection->NextSequenceRcv % TCP_WINDOW_SIZE;
585 if( !(Connection->FuturePacketValidBytes[index/8] & (1 << (index%8))) )
586 TCP_INT_SendACK(Connection, "Lost packet");
587 for( int i = 0; i < dataLen; i ++ )
589 Connection->FuturePacketValidBytes[index/8] |= 1 << (index%8);
590 Connection->FuturePacketData[index] = dataptr[i];
591 // Do a wrap increment
593 if(index == TCP_WINDOW_SIZE) index = 0;
594 if(index == max) break;
596 Uint32 rel_highest = Connection->HighestSequenceRcvd - Connection->NextSequenceRcv;
597 Uint32 rel_this = index - Connection->NextSequenceRcv;
598 LOG("Updating highest this(0x%x) > highest(%x)", rel_this, rel_highest);
599 if( rel_this > rel_highest )
601 Connection->HighestSequenceRcvd = index;
604 // Badly out of sequence packet
607 Log_Log("TCP", "Fully out of sequence packet (0x%08x not between 0x%08x and 0x%08x), dropped",
608 sequence_num, Connection->NextSequenceRcv, Connection->NextSequenceRcv+TCP_WINDOW_SIZE);
609 // Spec says we should send an empty ACK with the current state
610 TCP_INT_SendACK(Connection, "Bad Seq");
614 // --- Remote close states
615 case TCP_ST_CLOSE_WAIT:
617 // Ignore everything, CLOSE_WAIT is terminated by the client
618 Log_Debug("TCP", "CLOSE WAIT - Ignoring packets");
622 // LAST-ACK - Waiting for the ACK of FIN (from CLOSE WAIT)
623 case TCP_ST_LAST_ACK:
624 if( Header->Flags & TCP_FLAG_ACK )
626 Connection->State = TCP_ST_FINISHED; // Connection completed
627 Log_Log("TCP", "LAST-ACK to CLOSED - Connection remote closed");
628 TCP_int_FreeTCB(Connection);
632 // --- Local close States
633 case TCP_ST_FIN_WAIT1:
634 if( Header->Flags & TCP_FLAG_FIN )
636 Connection->State = TCP_ST_CLOSING;
637 Log_Debug("TCP", "Conn %p closed, sent FIN and recieved FIN", Connection);
638 VFS_MarkError(&Connection->Node, 1);
640 TCP_INT_SendACK(Connection, "FINWAIT-1 FIN");
644 // TODO: Make sure that the packet is actually ACKing the FIN
645 if( Header->Flags & TCP_FLAG_ACK )
647 Connection->State = TCP_ST_FIN_WAIT2;
648 Log_Debug("TCP", "Conn %p closed, sent FIN ACKed", Connection);
649 VFS_MarkError(&Connection->Node, 1);
654 case TCP_ST_FIN_WAIT2:
655 if( Header->Flags & TCP_FLAG_FIN )
657 Connection->State = TCP_ST_TIME_WAIT;
658 Log_Debug("TCP", "Conn %p FINWAIT-2 -> TIME WAIT", Connection);
659 TCP_INT_SendACK(Connection, "FINWAIT-2 FIN");
664 // TODO: Make sure that the packet is actually ACKing the FIN
665 if( Header->Flags & TCP_FLAG_ACK )
667 Connection->State = TCP_ST_TIME_WAIT;
668 Log_Debug("TCP", "Conn %p CLOSING -> TIME WAIT", Connection);
669 VFS_MarkError(&Connection->Node, 1);
674 // --- Closed (or near closed) states) ---
675 case TCP_ST_TIME_WAIT:
676 Log_Log("TCP", "Packets on Time-Wait, ignored");
679 case TCP_ST_FINISHED:
680 Log_Log("TCP", "Packets when CLOSED, ignoring");
682 case TCP_ST_FORCE_CLOSE:
683 Log_Log("TCP", "Packets when force CLOSED, ignoring");
687 // Log_Warning("TCP", "Unhandled TCP state %i", Connection->State);
696 * \brief Appends a packet to the recieved list
697 * \param Connection Connection structure
698 * \param Data Packet contents
699 * \param Length Length of \a Data
701 int TCP_INT_AppendRecieved(tTCPConnection *Connection, const void *Data, size_t Length)
703 Mutex_Acquire( &Connection->lRecievedPackets );
705 if(Connection->RecievedBuffer->Length + Length > Connection->RecievedBuffer->Space )
707 VFS_MarkAvaliable(&Connection->Node, 1);
708 Log_Error("TCP", "Buffer filled, packet dropped (:%i) - %i + %i > %i",
709 Connection->LocalPort, Connection->RecievedBuffer->Length, Length,
710 Connection->RecievedBuffer->Space
712 Mutex_Release( &Connection->lRecievedPackets );
716 RingBuffer_Write( Connection->RecievedBuffer, Data, Length );
718 VFS_MarkAvaliable(&Connection->Node, 1);
720 Mutex_Release( &Connection->lRecievedPackets );
725 * \brief Updates the connections recieved list from the future list
726 * \param Connection Connection structure
728 * Updates the recieved packets list with packets from the future (out
729 * of order) packets list that are now able to be added in direct
732 void TCP_INT_UpdateRecievedFromFuture(tTCPConnection *Connection)
734 // Calculate length of contiguous bytes
735 const size_t length = Connection->HighestSequenceRcvd - Connection->NextSequenceRcv;
736 Uint32 index = Connection->NextSequenceRcv % TCP_WINDOW_SIZE;
737 size_t runlength = length;
738 LOG("HSR=0x%x,NSR=0x%x", Connection->HighestSequenceRcvd, Connection->NextSequenceRcv);
739 if( Connection->HighestSequenceRcvd == Connection->NextSequenceRcv )
743 LOG("length=%u, index=0x%x", length, index);
744 for( int i = 0; i < length; i ++ )
747 Uint8 bitfield_byte = Connection->FuturePacketValidBytes[index / 8];
748 if( (bitfield_byte & (1 << bit)) == 0 ) {
750 LOG("Hit missing, break");
754 if( bitfield_byte == 0xFF ) {
762 if(index > TCP_WINDOW_SIZE)
763 index -= TCP_WINDOW_SIZE;
766 index = Connection->NextSequenceRcv % TCP_WINDOW_SIZE;
767 Connection->NextSequenceRcv += runlength;
769 // Write data to to the ring buffer
770 if( TCP_WINDOW_SIZE - index > runlength )
773 RingBuffer_Write( Connection->RecievedBuffer, Connection->FuturePacketData + index, runlength );
777 int endLen = TCP_WINDOW_SIZE - index;
779 RingBuffer_Write( Connection->RecievedBuffer, Connection->FuturePacketData + index, endLen );
780 RingBuffer_Write( Connection->RecievedBuffer, Connection->FuturePacketData, endLen - runlength );
783 // Mark (now saved) bytes as invalid
785 while(index % 8 && runlength > 0)
787 Connection->FuturePacketData[index] = 0;
788 Connection->FuturePacketValidBytes[index/8] &= ~(1 << (index%8));
790 if(index > TCP_WINDOW_SIZE)
791 index -= TCP_WINDOW_SIZE;
794 while( runlength > 7 )
796 Connection->FuturePacketData[index] = 0;
797 Connection->FuturePacketValidBytes[index/8] = 0;
800 if(index > TCP_WINDOW_SIZE)
801 index -= TCP_WINDOW_SIZE;
803 while( runlength > 0)
805 Connection->FuturePacketData[index] = 0;
806 Connection->FuturePacketData[index/8] &= ~(1 << (index%8));
808 if(index > TCP_WINDOW_SIZE)
809 index -= TCP_WINDOW_SIZE;
814 void TCP_int_SendDelayedACK(void *ConnPtr)
816 TCP_INT_SendACK(ConnPtr, "DACK Timeout");
819 void TCP_INT_SendACK(tTCPConnection *Connection, const char *Reason)
823 hdr.DataOffset = (sizeof(tTCPHeader)/4) << 4;
824 hdr.DestPort = htons(Connection->RemotePort);
825 hdr.SourcePort = htons(Connection->LocalPort);
826 hdr.AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
827 hdr.SequenceNumber = htonl(Connection->NextSequenceSend);
828 hdr.WindowSize = htons(TCP_WINDOW_SIZE);
829 hdr.Flags = TCP_FLAG_ACK; // TODO: Determine if SYN is wanted too
830 hdr.Checksum = 0; // TODO: Checksum
831 hdr.UrgentPointer = 0;
832 Log_Debug("TCP", "Sending ACK for 0x%08x (%s)", Connection->NextSequenceRcv, Reason);
833 TCP_SendPacket( Connection, &hdr, 0, NULL );
834 //Connection->NextSequenceSend ++;
835 Connection->LastACKSequence = Connection->NextSequenceRcv;
839 * \fn Uint16 TCP_GetUnusedPort()
840 * \brief Gets an unused port and allocates it
842 Uint16 TCP_GetUnusedPort()
846 // Get Next outbound port
847 ret = giTCP_NextOutPort++;
848 while( gaTCP_PortBitmap[ret/32] & (1UL << (ret%32)) )
852 if(giTCP_NextOutPort == 0x10000) {
853 ret = giTCP_NextOutPort = TCP_MIN_DYNPORT;
857 // Mark the new port as used
858 gaTCP_PortBitmap[ret/32] |= 1 << (ret%32);
864 * \fn int TCP_AllocatePort(Uint16 Port)
865 * \brief Marks a port as used
867 int TCP_AllocatePort(Uint16 Port)
869 // Check if the port has already been allocated
870 if( gaTCP_PortBitmap[Port/32] & (1 << (Port%32)) )
874 gaTCP_PortBitmap[Port/32] |= 1 << (Port%32);
880 * \fn int TCP_DeallocatePort(Uint16 Port)
881 * \brief Marks a port as unused
883 int TCP_DeallocatePort(Uint16 Port)
885 // Check if the port has already been allocated
886 if( !(gaTCP_PortBitmap[Port/32] & (1 << (Port%32))) )
890 gaTCP_PortBitmap[Port/32] &= ~(1 << (Port%32));
895 tTCPConnection *TCP_int_CreateConnection(tInterface *Interface, enum eTCPConnectionState State)
897 tTCPConnection *conn = calloc( sizeof(tTCPConnection) + TCP_WINDOW_SIZE + TCP_WINDOW_SIZE/8, 1 );
900 conn->Interface = Interface;
901 conn->LocalPort = -1;
902 conn->RemotePort = -1;
904 conn->Node.Size = -1;
905 conn->Node.ReferenceCount = 1;
906 conn->Node.ImplPtr = conn;
907 conn->Node.NumACLs = 1;
908 conn->Node.ACLs = &gVFS_ACL_EveryoneRW;
909 conn->Node.Type = &gTCP_ClientNodeType;
910 conn->Node.BufferFull = 1; // Cleared when connection opens
912 conn->RecievedBuffer = RingBuffer_Create( TCP_RECIEVE_BUFFER_SIZE );
914 conn->SentBuffer = RingBuffer_Create( TCP_SEND_BUFFER_SIZE );
915 Semaphore_Init(conn->SentBufferSpace, 0, TCP_SEND_BUFFER_SIZE, "TCP SentBuffer", conn->Name);
918 conn->HighestSequenceRcvd = 0;
919 #if CACHE_FUTURE_PACKETS_IN_BYTES
920 // Future recieved data (ahead of the expected sequence number)
921 conn->FuturePacketData = (Uint8*)conn + sizeof(tTCPConnection);
922 conn->FuturePacketValidBytes = conn->FuturePacketData + TCP_WINDOW_SIZE;
925 conn->DeferredACKTimer = Time_AllocateTimer( TCP_int_SendDelayedACK, conn);
929 void TCP_int_FreeTCB(tTCPConnection *Connection)
931 ASSERTC(Connection->State, ==, TCP_ST_FINISHED);
932 ASSERTC(Connection->Node.ReferenceCount, ==, 0);
934 if( Connection->Server )
936 tTCPListener *srv = Connection->Server;
937 SHORTLOCK(&srv->lConnections);
939 Connection->Prev->Next = Connection->Next;
941 srv->Connections = Connection->Next;
943 Connection->Next->Prev = Connection->Prev;
945 ASSERT(srv->ConnectionsTail == Connection);
946 srv->ConnectionsTail = Connection->Prev;
948 SHORTREL(&srv->lConnections);
952 SHORTLOCK(&glTCP_OutbountCons);
954 Connection->Prev->Next = Connection->Next;
956 gTCP_OutbountCons = Connection->Next;
958 Connection->Next->Prev = Connection->Prev;
961 SHORTREL(&glTCP_OutbountCons);
964 RingBuffer_Free(Connection->RecievedBuffer);
965 Time_FreeTimer(Connection->DeferredACKTimer);
966 // TODO: Force VFS to close handles? (they should all be closed);
971 tVFS_Node *TCP_Server_Init(tInterface *Interface)
975 srv = calloc( 1, sizeof(tTCPListener) );
978 Log_Warning("TCP", "malloc failed for listener (%i) bytes", sizeof(tTCPListener));
982 srv->Interface = Interface;
985 srv->Connections = NULL;
986 srv->ConnectionsTail = NULL;
987 srv->NewConnections = NULL;
989 srv->Node.Flags = VFS_FFLAG_DIRECTORY;
991 srv->Node.ImplPtr = srv;
992 srv->Node.NumACLs = 1;
993 srv->Node.ACLs = &gVFS_ACL_EveryoneRW;
994 srv->Node.Type = &gTCP_ServerNodeType;
996 SHORTLOCK(&glTCP_Listeners);
997 srv->Next = gTCP_Listeners;
998 gTCP_Listeners = srv;
999 SHORTREL(&glTCP_Listeners);
1005 * \brief Wait for a new connection and return the connection ID
1006 * \note Blocks until a new connection is made
1007 * \param Node Server node
1008 * \param Pos Position (ignored)
1010 int TCP_Server_ReadDir(tVFS_Node *Node, int Pos, char Dest[FILENAME_MAX])
1012 tTCPListener *srv = Node->ImplPtr;
1013 tTCPConnection *conn;
1015 ENTER("pNode iPos", Node, Pos);
1017 Log_Log("TCP", "Thread %i waiting for a connection", Threads_GetTID());
1018 Semaphore_Wait( &srv->WaitingConnections, 1 );
1020 SHORTLOCK(&srv->lConnections);
1021 // Increment the new list (the current connection is still on the
1023 conn = srv->NewConnections;
1024 srv->NewConnections = conn->Next;
1026 if( srv->NewConnections == NULL )
1027 VFS_MarkAvaliable( Node, 0 );
1029 SHORTREL( &srv->lConnections );
1031 LOG("conn = %p", conn);
1032 LOG("srv->Connections = %p", srv->Connections);
1033 LOG("srv->NewConnections = %p", srv->NewConnections);
1034 LOG("srv->ConnectionsTail = %p", srv->ConnectionsTail);
1036 itoa(Dest, conn->Node.ImplInt, 16, 8, '0');
1037 Log_Log("TCP", "Thread %i got connection '%s'", Threads_GetTID(), Dest);
1043 * \brief Gets a client connection node
1044 * \param Node Server node
1045 * \param Name Hexadecimal ID of the node
1047 tVFS_Node *TCP_Server_FindDir(tVFS_Node *Node, const char *Name, Uint Flags)
1049 tTCPConnection *conn;
1050 tTCPListener *srv = Node->ImplPtr;
1052 int id = atoi(Name);
1054 ENTER("pNode sName", Node, Name);
1056 // Check for a non-empty name
1060 itoa(tmp, id, 16, 8, '0');
1061 if(strcmp(tmp, Name) != 0) {
1062 LOG("'%s' != '%s' (%08x)", Name, tmp, id);
1067 Log_Debug("TCP", "srv->Connections = %p", srv->Connections);
1068 Log_Debug("TCP", "srv->NewConnections = %p", srv->NewConnections);
1069 Log_Debug("TCP", "srv->ConnectionsTail = %p", srv->ConnectionsTail);
1072 SHORTLOCK( &srv->lConnections );
1073 for(conn = srv->Connections;
1077 LOG("conn->Node.ImplInt = %i", conn->Node.ImplInt);
1078 if(conn->Node.ImplInt == id) break;
1080 SHORTREL( &srv->lConnections );
1082 // If not found, ret NULL
1084 LOG("Connection %i not found", id);
1089 // Empty Name - Check for a new connection and if it's there, open it
1092 SHORTLOCK( &srv->lConnections );
1093 conn = srv->NewConnections;
1095 srv->NewConnections = conn->Next;
1096 VFS_MarkAvaliable( Node, srv->NewConnections != NULL );
1097 SHORTREL( &srv->lConnections );
1099 LOG("No new connections");
1106 LEAVE('p', &conn->Node);
1111 * \brief Handle IOCtl calls
1113 int TCP_Server_IOCtl(tVFS_Node *Node, int ID, void *Data)
1115 tTCPListener *srv = Node->ImplPtr;
1119 case 4: // Get/Set Port
1120 if(!Data) // Get Port
1123 if(srv->Port) // Wait, you can't CHANGE the port
1126 if(!CheckMem(Data, sizeof(Uint16))) // Sanity check
1129 // Permissions check
1130 if(Threads_GetUID() != 0
1131 && *(Uint16*)Data != 0
1132 && *(Uint16*)Data < 1024)
1135 // TODO: Check if a port is in use
1138 srv->Port = *(Uint16*)Data;
1139 if(srv->Port == 0) // Allocate a random port
1140 srv->Port = TCP_GetUnusedPort();
1141 else // Else, mark this as used
1142 TCP_AllocatePort(srv->Port);
1144 Log_Log("TCP", "Server %p listening on port %i", srv, srv->Port);
1151 void TCP_Server_Close(tVFS_Node *Node)
1153 free(Node->ImplPtr);
1158 * \brief Create a client node
1160 tVFS_Node *TCP_Client_Init(tInterface *Interface)
1162 tTCPConnection *conn = TCP_int_CreateConnection(Interface, TCP_ST_CLOSED);
1164 SHORTLOCK(&glTCP_OutbountCons);
1165 conn->Server = NULL;
1167 conn->Next = gTCP_OutbountCons;
1168 if(gTCP_OutbountCons)
1169 gTCP_OutbountCons->Prev = conn;
1170 gTCP_OutbountCons = conn;
1171 SHORTREL(&glTCP_OutbountCons);
1177 * \brief Wait for a packet and return it
1178 * \note If \a Length is smaller than the size of the packet, the rest
1179 * of the packet's data will be discarded.
1181 size_t TCP_Client_Read(tVFS_Node *Node, off_t Offset, size_t Length, void *Buffer, Uint Flags)
1183 tTCPConnection *conn = Node->ImplPtr;
1186 ENTER("pNode XOffset xLength pBuffer", Node, Offset, Length, Buffer);
1187 LOG("conn = %p {State:%i}", conn, conn->State);
1189 // If the connection has been closed (state > ST_OPEN) then clear
1190 // any stale data in the buffer (until it is empty (until it is empty))
1191 if( conn->State > TCP_ST_ESTABLISHED )
1193 LOG("Connection closed");
1194 Mutex_Acquire( &conn->lRecievedPackets );
1195 len = RingBuffer_Read( Buffer, conn->RecievedBuffer, Length );
1196 Mutex_Release( &conn->lRecievedPackets );
1199 VFS_MarkAvaliable(Node, 0);
1211 tTime *timeout = NULL;
1212 tTime timeout_zero = 0;
1213 if( Flags & VFS_IOFLAG_NOBLOCK )
1214 timeout = &timeout_zero;
1215 if( !VFS_SelectNode(Node, VFS_SELECT_READ|VFS_SELECT_ERROR, timeout, "TCP_Client_Read") ) {
1216 errno = EWOULDBLOCK;
1222 // Lock list and read as much as possible (up to `Length`)
1223 Mutex_Acquire( &conn->lRecievedPackets );
1224 len = RingBuffer_Read( Buffer, conn->RecievedBuffer, Length );
1226 if( len == 0 || conn->RecievedBuffer->Length == 0 ) {
1227 LOG("Marking as none avaliable (len = %i)", len);
1228 VFS_MarkAvaliable(Node, 0);
1231 // Release the lock (we don't need it any more)
1232 Mutex_Release( &conn->lRecievedPackets );
1239 * \brief Send a data packet on a connection
1241 void TCP_INT_SendDataPacket(tTCPConnection *Connection, size_t Length, const void *Data)
1243 char buf[sizeof(tTCPHeader)+Length];
1244 tTCPHeader *packet = (void*)buf;
1246 // - Stop Delayed ACK timer (as this data packet ACKs)
1247 Time_RemoveTimer(Connection->DeferredACKTimer);
1249 // TODO: Don't exceed window size
1251 packet->SourcePort = htons(Connection->LocalPort);
1252 packet->DestPort = htons(Connection->RemotePort);
1253 packet->DataOffset = (sizeof(tTCPHeader)/4)*16;
1254 packet->WindowSize = htons(TCP_WINDOW_SIZE);
1256 packet->AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
1257 packet->SequenceNumber = htonl(Connection->NextSequenceSend);
1258 packet->Flags = TCP_FLAG_PSH|TCP_FLAG_ACK; // Hey, ACK if you can!
1259 packet->UrgentPointer = 0;
1261 memcpy(packet->Options, Data, Length);
1263 Log_Debug("TCP", "Send sequence 0x%08x", Connection->NextSequenceSend);
1264 #if HEXDUMP_OUTGOING
1265 Debug_HexDump("TCP_INT_SendDataPacket: Data = ", Data, Length);
1268 TCP_SendPacket( Connection, packet, Length, Data );
1270 // TODO: Start a retransmit time (if data is not ACKed in x seconds, send again)
1272 Connection->NextSequenceSend += Length;
1276 * \brief Send some bytes on a connection
1278 size_t TCP_Client_Write(tVFS_Node *Node, off_t Offset, size_t Length, const void *Buffer, Uint Flags)
1280 tTCPConnection *conn = Node->ImplPtr;
1281 size_t rem = Length;
1283 ENTER("pNode XOffset XLength pBuffer", Node, Offset, Length, Buffer);
1286 // Debug_HexDump("TCP_Client_Write: Buffer = ",
1290 // Don't allow a write to a closed connection
1291 if( conn->State > TCP_ST_ESTABLISHED ) {
1292 VFS_MarkError(Node, 1);
1300 tTime *timeout = NULL;
1301 tTime timeout_zero = 0;
1302 if( Flags & VFS_IOFLAG_NOBLOCK )
1303 timeout = &timeout_zero;
1304 if( !VFS_SelectNode(Node, VFS_SELECT_WRITE|VFS_SELECT_ERROR, timeout, "TCP_Client_Write") ) {
1305 errno = EWOULDBLOCK;
1313 int len = (rem < TCP_MAX_PACKET_SIZE) ? rem : TCP_MAX_PACKET_SIZE;
1316 // Wait for space in the buffer
1317 Semaphore_Signal( &Connection->SentBufferSpace, len );
1319 // Save data to buffer (and update the length read by the ammount written)
1320 len = RingBuffer_Write( &Connection->SentBuffer, Buffer, len);
1324 TCP_INT_SendDataPacket(conn, len, Buffer);
1335 * \brief Open a connection to another host using TCP
1336 * \param Conn Connection structure
1338 void TCP_StartConnection(tTCPConnection *Conn)
1340 tTCPHeader hdr = {0};
1342 Conn->State = TCP_ST_SYN_SENT;
1344 hdr.SourcePort = htons(Conn->LocalPort);
1345 hdr.DestPort = htons(Conn->RemotePort);
1346 Conn->NextSequenceSend = rand();
1347 hdr.SequenceNumber = htonl(Conn->NextSequenceSend);
1348 hdr.DataOffset = (sizeof(tTCPHeader)/4) << 4;
1349 hdr.Flags = TCP_FLAG_SYN;
1350 hdr.WindowSize = htons(TCP_WINDOW_SIZE); // Max
1351 hdr.Checksum = 0; // TODO
1353 TCP_SendPacket( Conn, &hdr, 0, NULL );
1355 Conn->NextSequenceSend ++;
1356 Conn->State = TCP_ST_SYN_SENT;
1362 * \brief Control a client socket
1364 int TCP_Client_IOCtl(tVFS_Node *Node, int ID, void *Data)
1366 tTCPConnection *conn = Node->ImplPtr;
1368 ENTER("pNode iID pData", Node, ID, Data);
1372 case 4: // Get/Set local port
1374 LEAVE_RET('i', conn->LocalPort);
1375 if(conn->State != TCP_ST_CLOSED)
1377 if(!CheckMem(Data, sizeof(Uint16)))
1380 if(Threads_GetUID() != 0 && *(Uint16*)Data < 1024)
1383 conn->LocalPort = *(Uint16*)Data;
1384 LEAVE_RET('i', conn->LocalPort);
1386 case 5: // Get/Set remote port
1387 if(!Data) LEAVE_RET('i', conn->RemotePort);
1388 if(conn->State != TCP_ST_CLOSED) LEAVE_RET('i', -1);
1389 if(!CheckMem(Data, sizeof(Uint16))) LEAVE_RET('i', -1);
1390 conn->RemotePort = *(Uint16*)Data;
1391 LEAVE_RET('i', conn->RemotePort);
1393 case 6: // Set Remote IP
1394 if( conn->State != TCP_ST_CLOSED )
1396 if( conn->Interface->Type == 4 )
1398 if(!CheckMem(Data, sizeof(tIPv4))) LEAVE_RET('i', -1);
1399 conn->RemoteIP.v4 = *(tIPv4*)Data;
1401 else if( conn->Interface->Type == 6 )
1403 if(!CheckMem(Data, sizeof(tIPv6))) LEAVE_RET('i', -1);
1404 conn->RemoteIP.v6 = *(tIPv6*)Data;
1409 if(conn->LocalPort == 0xFFFF)
1410 conn->LocalPort = TCP_GetUnusedPort();
1411 if(conn->RemotePort == -1)
1415 tTime timeout = conn->Interface->TimeoutDelay;
1417 TCP_StartConnection(conn);
1418 VFS_SelectNode(&conn->Node, VFS_SELECT_WRITE, &timeout, "TCP Connection");
1419 if( conn->State == TCP_ST_SYN_SENT )
1425 // Get recieve buffer length
1427 LEAVE_RET('i', conn->RecievedBuffer->Length);
1433 void TCP_Client_Close(tVFS_Node *Node)
1435 tTCPConnection *conn = Node->ImplPtr;
1438 ENTER("pNode", Node);
1440 ASSERT(Node->ReferenceCount != 0);
1442 if( Node->ReferenceCount > 1 ) {
1443 Node->ReferenceCount --;
1444 LOG("Dereference only");
1448 Node->ReferenceCount --;
1450 if( conn->State == TCP_ST_CLOSE_WAIT || conn->State == TCP_ST_ESTABLISHED )
1452 packet.SourcePort = htons(conn->LocalPort);
1453 packet.DestPort = htons(conn->RemotePort);
1454 packet.DataOffset = (sizeof(tTCPHeader)/4)*16;
1455 packet.WindowSize = TCP_WINDOW_SIZE;
1457 packet.AcknowlegementNumber = 0;
1458 packet.SequenceNumber = htonl(conn->NextSequenceSend);
1459 packet.Flags = TCP_FLAG_FIN;
1461 TCP_SendPacket( conn, &packet, 0, NULL );
1464 Time_RemoveTimer(conn->DeferredACKTimer);
1466 switch( conn->State )
1469 Log_Warning("TCP", "Closing connection that was never opened");
1470 TCP_int_FreeTCB(conn);
1472 case TCP_ST_FORCE_CLOSE:
1473 conn->State = TCP_ST_FINISHED;
1474 TCP_int_FreeTCB(conn);
1476 case TCP_ST_CLOSE_WAIT:
1477 conn->State = TCP_ST_LAST_ACK;
1479 case TCP_ST_ESTABLISHED:
1480 conn->State = TCP_ST_FIN_WAIT1;
1481 while( conn->State == TCP_ST_FIN_WAIT1 )
1483 // No free, freed after TIME_WAIT
1486 Log_Warning("TCP", "Unhandled connection state %i in TCP_Client_Close",
1495 * \brief Checks if a value is between two others (after taking into account wrapping)
1497 int WrapBetween(Uint32 Lower, Uint32 Value, Uint32 Higher, Uint32 MaxValue)
1499 if( MaxValue < 0xFFFFFFFF )
1501 Lower %= MaxValue + 1;
1502 Value %= MaxValue + 1;
1503 Higher %= MaxValue + 1;
1506 // Simple Case, no wrap ?
1507 // Lower Value Higher
1508 // | ... + ... + ... + ... |
1510 if( Lower < Higher ) {
1511 return Lower < Value && Value < Higher;
1513 // Higher has wrapped below lower
1516 // Higher Lower Value
1517 // | ... + ... + ... + ... |
1518 if( Value > Lower ) {
1523 // Value Higher Lower
1524 // | ... + ... + ... + ... |
1525 if( Value < Higher ) {
1531 Uint32 GetRelative(Uint32 Base, Uint32 Value)
1534 return Value - Base + 0xFFFFFFFF;
1536 return Value - Base;