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 1 // 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 .Read = TCP_Client_Read,
71 .Write = TCP_Client_Write,
72 .IOCtl = TCP_Client_IOCtl,
73 .Close = TCP_Client_Close
77 int giTCP_NumHalfopen = 0;
78 tShortSpinlock glTCP_Listeners;
79 tTCPListener *gTCP_Listeners;
80 tShortSpinlock glTCP_OutbountCons;
81 tTCPConnection *gTCP_OutbountCons;
82 Uint32 gaTCP_PortBitmap[0x800];
83 int giTCP_NextOutPort = TCP_MIN_DYNPORT;
87 * \brief Initialise the TCP Layer
89 * Registers the client and server files and the GetPacket callback
91 void TCP_Initialise(void)
93 giTCP_NextOutPort += rand()%128;
94 IPStack_AddFile(&gTCP_ServerFile);
95 IPStack_AddFile(&gTCP_ClientFile);
96 IPv4_RegisterCallback(IP4PROT_TCP, TCP_GetPacket);
97 IPv6_RegisterCallback(IP4PROT_TCP, TCP_GetPacket);
101 * \brief Sends a packet from the specified connection, calculating the checksums
102 * \param Conn Connection
103 * \param Length Length of data
104 * \param Data Packet data (cast as a TCP Header)
106 void TCP_SendPacket( tTCPConnection *Conn, tTCPHeader *Header, size_t Length, const void *Data )
108 TCP_int_SendPacket(Conn->Interface, &Conn->RemoteIP, Header, Length, Data);
111 Uint16 TCP_int_CalculateChecksum(int AddrType, const void *LAddr, const void *RAddr,
112 size_t HeaderLength, const tTCPHeader *Header, size_t DataLength, const void *Data)
114 size_t packlen = HeaderLength + DataLength;
121 buf[0] = ((tIPv4*)LAddr)->L;
122 buf[1] = ((tIPv4*)RAddr)->L;
123 buf[2] = htonl( (packlen) | (IP4PROT_TCP<<16) | (0<<24) );
124 checksum[0] = htons( ~IPv4_Checksum(buf, sizeof(buf)) ); // Partial checksum
128 memcpy(&buf[0], LAddr, 16);
129 memcpy(&buf[4], RAddr, 16);
130 buf[8] = htonl(packlen);
131 buf[9] = htonl(IP4PROT_TCP);
132 checksum[0] = htons( ~IPv4_Checksum(buf, sizeof(buf)) ); // Partial checksum
137 checksum[1] = htons( ~IPv4_Checksum(Header, HeaderLength) );
138 checksum[2] = htons( ~IPv4_Checksum(Data, DataLength) );
140 return htons( IPv4_Checksum(checksum, sizeof(checksum)) );
143 void TCP_int_SendPacket(tInterface *Interface, const void *Dest, tTCPHeader *Header, size_t Length, const void *Data )
145 tIPStackBuffer *buffer = IPStack_Buffer_CreateBuffer(2 + IPV4_BUFFERS);
147 IPStack_Buffer_AppendSubBuffer(buffer, Length, 0, Data, NULL, NULL);
148 IPStack_Buffer_AppendSubBuffer(buffer, sizeof(*Header), 0, Header, NULL, NULL);
151 Log_Log("TCP", "TCP_int_SendPacket: <Local>:%i to [%s]:%i (%i data), Flags = %s%s%s%s%s%s%s%s",
152 ntohs(Header->SourcePort),
153 IPStack_PrintAddress(Interface->Type, Dest),
154 ntohs(Header->DestPort),
156 (Header->Flags & TCP_FLAG_CWR) ? "CWR " : "",
157 (Header->Flags & TCP_FLAG_ECE) ? "ECE " : "",
158 (Header->Flags & TCP_FLAG_URG) ? "URG " : "",
159 (Header->Flags & TCP_FLAG_ACK) ? "ACK " : "",
160 (Header->Flags & TCP_FLAG_PSH) ? "PSH " : "",
161 (Header->Flags & TCP_FLAG_RST) ? "RST " : "",
162 (Header->Flags & TCP_FLAG_SYN) ? "SYN " : "",
163 (Header->Flags & TCP_FLAG_FIN) ? "FIN " : ""
167 Header->Checksum = 0;
168 Header->Checksum = TCP_int_CalculateChecksum(Interface->Type, Interface->Address, Dest,
169 sizeof(tTCPHeader), Header, Length, Data);
171 // TODO: Fragment packet
173 switch( Interface->Type )
176 IPv4_SendPacket(Interface, *(tIPv4*)Dest, IP4PROT_TCP, 0, buffer);
179 IPv6_SendPacket(Interface, *(tIPv6*)Dest, IP4PROT_TCP, buffer);
184 void TCP_int_SendRSTTo(tInterface *Interface, const void *Address, size_t Length, const tTCPHeader *Header)
186 tTCPHeader out_hdr = {0};
188 out_hdr.DataOffset = (sizeof(out_hdr)/4) << 4;
189 out_hdr.DestPort = Header->SourcePort;
190 out_hdr.SourcePort = Header->DestPort;
192 size_t data_len = Length - (Header->DataOffset>>4)*4;
193 out_hdr.AcknowlegementNumber = htonl( ntohl(Header->SequenceNumber) + data_len );
194 if( Header->Flags & TCP_FLAG_ACK ) {
195 out_hdr.Flags = TCP_FLAG_RST;
196 out_hdr.SequenceNumber = Header->AcknowlegementNumber;
199 out_hdr.Flags = TCP_FLAG_RST|TCP_FLAG_ACK;
200 out_hdr.SequenceNumber = 0;
202 TCP_int_SendPacket(Interface, Address, &out_hdr, 0, NULL);
206 * \brief Handles a packet from the IP Layer
207 * \param Interface Interface the packet arrived from
208 * \param Address Pointer to the addres structure
209 * \param Length Size of packet in bytes
210 * \param Buffer Packet data
212 void TCP_GetPacket(tInterface *Interface, void *Address, int Length, void *Buffer)
214 tTCPHeader *hdr = Buffer;
217 Log_Log("TCP", "TCP_GetPacket: <Local>:%i from [%s]:%i, Flags = %s%s%s%s%s%s%s%s",
218 ntohs(hdr->DestPort),
219 IPStack_PrintAddress(Interface->Type, Address),
220 ntohs(hdr->SourcePort),
221 (hdr->Flags & TCP_FLAG_CWR) ? "CWR " : "",
222 (hdr->Flags & TCP_FLAG_ECE) ? "ECE " : "",
223 (hdr->Flags & TCP_FLAG_URG) ? "URG " : "",
224 (hdr->Flags & TCP_FLAG_ACK) ? "ACK " : "",
225 (hdr->Flags & TCP_FLAG_PSH) ? "PSH " : "",
226 (hdr->Flags & TCP_FLAG_RST) ? "RST " : "",
227 (hdr->Flags & TCP_FLAG_SYN) ? "SYN " : "",
228 (hdr->Flags & TCP_FLAG_FIN) ? "FIN " : ""
232 if( Length > (hdr->DataOffset >> 4)*4 )
234 LOG("SequenceNumber = 0x%x", ntohl(hdr->SequenceNumber));
237 "TCP_GetPacket: Packet Data = ",
238 (Uint8*)hdr + (hdr->DataOffset >> 4)*4,
239 Length - (hdr->DataOffset >> 4)*4
245 for( tTCPListener *srv = gTCP_Listeners; srv; srv = srv->Next )
247 // Check if the server is active
248 if(srv->Port == 0) continue;
249 // Check the interface
250 if(srv->Interface && srv->Interface != Interface) continue;
251 // Check the destination port
252 if(srv->Port != htons(hdr->DestPort)) continue;
254 Log_Log("TCP", "TCP_GetPacket: Matches server %p", srv);
255 // Is this in an established connection?
256 for( tTCPConnection *conn = srv->Connections; conn; conn = conn->Next )
258 // Check that it is coming in on the same interface
259 if(conn->Interface != Interface) continue;
261 if(conn->RemotePort != ntohs(hdr->SourcePort)) continue;
263 if( IPStack_CompareAddress(conn->Interface->Type, &conn->RemoteIP, Address, -1) == 0 )
266 Log_Log("TCP", "TCP_GetPacket: Matches connection %p", conn);
267 // We have a response!
268 if( TCP_INT_HandleConnectionPacket(conn, hdr, Length) == 0 )
273 TCP_INT_HandleServerPacket(Interface, srv, Address, hdr, Length);
277 // Check Open Connections
279 for( tTCPConnection *conn = gTCP_OutbountCons; conn; conn = conn->Next )
281 // Check that it is coming in on the same interface
282 if(conn->Interface != Interface) continue;
285 if(conn->RemotePort != ntohs(hdr->SourcePort)) continue;
288 if( IPStack_CompareAddress(conn->Interface->Type, &conn->RemoteIP, Address, -1) == 0 )
291 // Handle or fall through
292 if( TCP_INT_HandleConnectionPacket(conn, hdr, Length) == 0 )
298 Log_Log("TCP", "TCP_GetPacket: No Match");
299 // If not a RST, send a RST
300 if( !(hdr->Flags & TCP_FLAG_RST) )
302 TCP_int_SendRSTTo(Interface, Address, Length, hdr);
307 * Handle packets in LISTEN state
309 int TCP_INT_HandleServerPacket(tInterface *Interface, tTCPListener *Server, const void *Address, tTCPHeader *Header, size_t Length)
311 if( Header->Flags & TCP_FLAG_RST ) {
315 else if( Header->Flags & TCP_FLAG_ACK ) {
316 LOG("ACK, send RST");
317 TCP_int_SendRSTTo(Interface, Address, Length, Header);
320 else if( !(Header->Flags & TCP_FLAG_SYN) ) {
321 LOG("Other, ignore");
325 Log_Log("TCP", "TCP_GetPacket: Opening Connection");
327 // TODO: Check security (a TCP Option)
328 // TODO: Check SEG.PRC
329 // TODO: Check for halfopen max
331 tTCPConnection *conn = TCP_int_CreateConnection(Interface, TCP_ST_SYN_RCVD);
332 conn->LocalPort = Server->Port;
333 conn->RemotePort = ntohs(Header->SourcePort);
335 switch(Interface->Type)
337 case 4: conn->RemoteIP.v4 = *(tIPv4*)Address; break;
338 case 6: conn->RemoteIP.v6 = *(tIPv6*)Address; break;
339 default: ASSERTC(Interface->Type,==,4); return 0;
342 conn->NextSequenceRcv = ntohl( Header->SequenceNumber ) + 1;
343 conn->HighestSequenceRcvd = conn->NextSequenceRcv;
344 conn->NextSequenceSend = rand();
345 conn->LastACKSequence = ntohl( Header->SequenceNumber );
347 conn->Node.ImplInt = Server->NextID ++;
349 // Hmm... Theoretically, this lock will never have to wait,
350 // as the interface is locked to the watching thread, and this
351 // runs in the watching thread. But, it's a good idea to have
353 // Oh, wait, there is a case where a wildcard can be used
354 // (Server->Interface == NULL) so having the lock is a good idea
355 SHORTLOCK(&Server->lConnections);
356 conn->Server = Server;
357 conn->Prev = Server->ConnectionsTail;
358 if(Server->Connections) {
359 ASSERT(Server->ConnectionsTail);
360 Server->ConnectionsTail->Next = conn;
363 ASSERT(!Server->ConnectionsTail);
364 Server->Connections = conn;
366 Server->ConnectionsTail = conn;
367 if(!Server->NewConnections)
368 Server->NewConnections = conn;
369 VFS_MarkAvaliable( &Server->Node, 1 );
370 SHORTREL(&Server->lConnections);
371 Semaphore_Signal(&Server->WaitingConnections, 1);
374 Header->Flags = TCP_FLAG_ACK|TCP_FLAG_SYN;
375 Header->AcknowlegementNumber = htonl(conn->NextSequenceRcv);
376 Header->SequenceNumber = htonl(conn->NextSequenceSend);
377 Header->DestPort = Header->SourcePort;
378 Header->SourcePort = htons(Server->Port);
379 Header->DataOffset = (sizeof(tTCPHeader)/4) << 4;
380 TCP_SendPacket( conn, Header, 0, NULL );
381 conn->NextSequenceSend ++;
386 * \brief Handles a packet sent to a specific connection
387 * \param Connection TCP Connection pointer
388 * \param Header TCP Packet pointer
389 * \param Length Length of the packet
391 int TCP_INT_HandleConnectionPacket(tTCPConnection *Connection, tTCPHeader *Header, int Length)
396 // Silently drop once finished
397 // TODO: Check if this needs to be here
398 if( Connection->State == TCP_ST_FINISHED ) {
399 Log_Log("TCP", "Packet ignored - connection finnished");
402 if( Connection->State == TCP_ST_FORCE_CLOSE ) {
403 Log_Log("TCP", "Packet ignored - connection reset");
407 // Syncronise sequence values
408 if(Header->Flags & TCP_FLAG_SYN) {
409 // TODO: What if the packet also has data?
410 if( Connection->LastACKSequence != Connection->NextSequenceRcv )
411 TCP_INT_SendACK(Connection, "SYN");
412 Connection->NextSequenceRcv = ntohl(Header->SequenceNumber);
413 // TODO: Process HighestSequenceRcvd
415 if( Connection->HighestSequenceRcvd == 0 )
416 Connection->HighestSequenceRcvd = Connection->NextSequenceRcv;
417 Connection->LastACKSequence = Connection->NextSequenceRcv;
420 // Ackowledge a sent packet
421 if(Header->Flags & TCP_FLAG_ACK) {
422 // TODO: Process an ACKed Packet
423 LOG("Conn %p, Sent packet 0x%x ACKed", Connection, Header->AcknowlegementNumber);
426 // Get length of data
427 dataLen = Length - (Header->DataOffset>>4)*4;
428 LOG("dataLen = %i", dataLen);
430 Log_Debug("TCP", "State %i, dataLen = %x", Connection->State, dataLen);
436 switch( Connection->State )
438 // Pre-init connection?
440 Log_Log("TCP", "Packets to a closed connection?!");
443 // --- Init States ---
444 // SYN sent, expecting SYN-ACK Connection Opening
445 case TCP_ST_SYN_SENT:
446 if( Header->Flags & TCP_FLAG_SYN )
448 if( Connection->HighestSequenceRcvd == Connection->NextSequenceRcv )
449 Connection->HighestSequenceRcvd ++;
450 Connection->NextSequenceRcv ++;
452 if( Header->Flags & TCP_FLAG_ACK )
454 Log_Log("TCP", "ACKing SYN-ACK");
455 Connection->State = TCP_ST_ESTABLISHED;
456 VFS_MarkFull(&Connection->Node, 0);
457 TCP_INT_SendACK(Connection, "SYN-ACK");
461 Log_Log("TCP", "ACKing SYN");
462 Connection->State = TCP_ST_SYN_RCVD;
463 TCP_INT_SendACK(Connection, "SYN");
468 // SYN-ACK sent, expecting ACK
469 case TCP_ST_SYN_RCVD:
470 if( Header->Flags & TCP_FLAG_RST )
472 Log_Log("TCP", "RST Received, closing");
473 Connection->State = TCP_ST_FORCE_CLOSE;
474 VFS_MarkError(&Connection->Node, 1);
477 if( Header->Flags & TCP_FLAG_ACK )
479 // TODO: Handle max half-open limit
480 Log_Log("TCP", "Connection fully opened");
481 Connection->State = TCP_ST_ESTABLISHED;
482 VFS_MarkFull(&Connection->Node, 0);
486 // --- Established State ---
487 case TCP_ST_ESTABLISHED:
488 // - Handle State changes
490 if( Header->Flags & TCP_FLAG_RST )
492 Log_Log("TCP", "Conn %p closed, received RST");
493 // Error outstanding transactions
494 Connection->State = TCP_ST_FORCE_CLOSE;
495 VFS_MarkError(&Connection->Node, 1);
498 if( Header->Flags & TCP_FLAG_FIN ) {
499 Log_Log("TCP", "Conn %p closed, recieved FIN", Connection);
500 VFS_MarkError(&Connection->Node, 1);
501 Connection->NextSequenceRcv ++;
502 TCP_INT_SendACK(Connection, "FIN Received");
503 Connection->State = TCP_ST_CLOSE_WAIT;
504 // CLOSE WAIT requires the client to close
508 // Check for an empty packet
510 if( Header->Flags == TCP_FLAG_ACK )
512 Log_Log("TCP", "ACK only packet");
515 // TODO: Is this right? (empty packet counts as one byte)
516 if( Connection->HighestSequenceRcvd == Connection->NextSequenceRcv )
517 Connection->HighestSequenceRcvd ++;
518 Connection->NextSequenceRcv ++;
519 Log_Log("TCP", "Empty Packet, inc and ACK the current sequence number");
520 TCP_INT_SendACK(Connection, "Empty");
529 sequence_num = ntohl(Header->SequenceNumber);
531 LOG("0x%08x <= 0x%08x < 0x%08x",
532 Connection->NextSequenceRcv,
533 ntohl(Header->SequenceNumber),
534 Connection->NextSequenceRcv + TCP_WINDOW_SIZE
537 // Is this packet the next expected packet?
538 if( sequence_num == Connection->NextSequenceRcv )
541 // Ooh, Goodie! Add it to the recieved list
542 rv = TCP_INT_AppendRecieved(Connection,
543 (Uint8*)Header + (Header->DataOffset>>4)*4,
547 Log_Notice("TCP", "TCP_INT_AppendRecieved rv %i", rv);
550 LOG("0x%08x += %i", Connection->NextSequenceRcv, dataLen);
551 if( Connection->HighestSequenceRcvd == Connection->NextSequenceRcv )
552 Connection->HighestSequenceRcvd += dataLen;
553 Connection->NextSequenceRcv += dataLen;
555 // TODO: This should be moved out of the watcher thread,
556 // so that a single lost packet on one connection doesn't cause
557 // all connections on the interface to lag.
558 // - Meh, no real issue, as the cache shouldn't be that large
559 TCP_INT_UpdateRecievedFromFuture(Connection);
562 // - Only send an ACK if we've had a burst
563 Uint32 bytes_since_last_ack = Connection->NextSequenceRcv - Connection->LastACKSequence;
564 LOG("bytes_since_last_ack = 0x%x", bytes_since_last_ack);
565 if( bytes_since_last_ack > TCP_DACK_THRESHOLD )
567 TCP_INT_SendACK(Connection, "DACK Burst");
568 // - Extend TCP deferred ACK timer
569 Time_RemoveTimer(Connection->DeferredACKTimer);
571 // - Schedule the deferred ACK timer (if already scheduled, this is a NOP)
572 Time_ScheduleTimer(Connection->DeferredACKTimer, TCP_DACK_TIMEOUT);
574 TCP_INT_SendACK(Connection, "RX");
577 // Check if the packet is in window
578 else if( sequence_num - Connection->NextSequenceRcv < TCP_WINDOW_SIZE )
580 Uint8 *dataptr = (Uint8*)Header + (Header->DataOffset>>4)*4;
581 Uint32 index = sequence_num % TCP_WINDOW_SIZE;
582 Uint32 max = Connection->NextSequenceRcv % TCP_WINDOW_SIZE;
583 if( !(Connection->FuturePacketValidBytes[index/8] & (1 << (index%8))) )
584 TCP_INT_SendACK(Connection, "Lost packet");
585 for( int i = 0; i < dataLen; i ++ )
587 Connection->FuturePacketValidBytes[index/8] |= 1 << (index%8);
588 Connection->FuturePacketData[index] = dataptr[i];
589 // Do a wrap increment
591 if(index == TCP_WINDOW_SIZE) index = 0;
592 if(index == max) break;
594 Uint32 rel_highest = Connection->HighestSequenceRcvd - Connection->NextSequenceRcv;
595 Uint32 rel_this = index - Connection->NextSequenceRcv;
596 LOG("Updating highest this(0x%x) > highest(%x)", rel_this, rel_highest);
597 if( rel_this > rel_highest )
599 Connection->HighestSequenceRcvd = index;
602 // Badly out of sequence packet
605 Log_Log("TCP", "Fully out of sequence packet (0x%08x not between 0x%08x and 0x%08x), dropped",
606 sequence_num, Connection->NextSequenceRcv, Connection->NextSequenceRcv+TCP_WINDOW_SIZE);
607 // Spec says we should send an empty ACK with the current state
608 TCP_INT_SendACK(Connection, "Bad Seq");
612 // --- Remote close states
613 case TCP_ST_CLOSE_WAIT:
615 // Ignore everything, CLOSE_WAIT is terminated by the client
616 Log_Debug("TCP", "CLOSE WAIT - Ignoring packets");
620 // LAST-ACK - Waiting for the ACK of FIN (from CLOSE WAIT)
621 case TCP_ST_LAST_ACK:
622 if( Header->Flags & TCP_FLAG_ACK )
624 Connection->State = TCP_ST_FINISHED; // Connection completed
625 Log_Log("TCP", "LAST-ACK to CLOSED - Connection remote closed");
626 TCP_int_FreeTCB(Connection);
630 // --- Local close States
631 case TCP_ST_FIN_WAIT1:
632 if( Header->Flags & TCP_FLAG_FIN )
634 Connection->State = TCP_ST_CLOSING;
635 Log_Debug("TCP", "Conn %p closed, sent FIN and recieved FIN", Connection);
636 VFS_MarkError(&Connection->Node, 1);
638 TCP_INT_SendACK(Connection, "FINWAIT-1 FIN");
642 // TODO: Make sure that the packet is actually ACKing the FIN
643 if( Header->Flags & TCP_FLAG_ACK )
645 Connection->State = TCP_ST_FIN_WAIT2;
646 Log_Debug("TCP", "Conn %p closed, sent FIN ACKed", Connection);
647 VFS_MarkError(&Connection->Node, 1);
652 case TCP_ST_FIN_WAIT2:
653 if( Header->Flags & TCP_FLAG_FIN )
655 Connection->State = TCP_ST_TIME_WAIT;
656 Log_Debug("TCP", "Conn %p FINWAIT-2 -> TIME WAIT", Connection);
657 TCP_INT_SendACK(Connection, "FINWAIT-2 FIN");
662 // TODO: Make sure that the packet is actually ACKing the FIN
663 if( Header->Flags & TCP_FLAG_ACK )
665 Connection->State = TCP_ST_TIME_WAIT;
666 Log_Debug("TCP", "Conn %p CLOSING -> TIME WAIT", Connection);
667 VFS_MarkError(&Connection->Node, 1);
672 // --- Closed (or near closed) states) ---
673 case TCP_ST_TIME_WAIT:
674 Log_Log("TCP", "Packets on Time-Wait, ignored");
677 case TCP_ST_FINISHED:
678 Log_Log("TCP", "Packets when CLOSED, ignoring");
680 case TCP_ST_FORCE_CLOSE:
681 Log_Log("TCP", "Packets when force CLOSED, ignoring");
685 // Log_Warning("TCP", "Unhandled TCP state %i", Connection->State);
694 * \brief Appends a packet to the recieved list
695 * \param Connection Connection structure
696 * \param Data Packet contents
697 * \param Length Length of \a Data
699 int TCP_INT_AppendRecieved(tTCPConnection *Connection, const void *Data, size_t Length)
701 Mutex_Acquire( &Connection->lRecievedPackets );
703 if(Connection->RecievedBuffer->Length + Length > Connection->RecievedBuffer->Space )
705 VFS_MarkAvaliable(&Connection->Node, 1);
706 Log_Error("TCP", "Buffer filled, packet dropped (:%i) - %i + %i > %i",
707 Connection->LocalPort, Connection->RecievedBuffer->Length, Length,
708 Connection->RecievedBuffer->Space
710 Mutex_Release( &Connection->lRecievedPackets );
714 RingBuffer_Write( Connection->RecievedBuffer, Data, Length );
716 VFS_MarkAvaliable(&Connection->Node, 1);
718 Mutex_Release( &Connection->lRecievedPackets );
723 * \brief Updates the connections recieved list from the future list
724 * \param Connection Connection structure
726 * Updates the recieved packets list with packets from the future (out
727 * of order) packets list that are now able to be added in direct
730 void TCP_INT_UpdateRecievedFromFuture(tTCPConnection *Connection)
732 // Calculate length of contiguous bytes
733 const size_t length = Connection->HighestSequenceRcvd - Connection->NextSequenceRcv;
734 Uint32 index = Connection->NextSequenceRcv % TCP_WINDOW_SIZE;
735 size_t runlength = length;
736 LOG("HSR=0x%x,NSR=0x%x", Connection->HighestSequenceRcvd, Connection->NextSequenceRcv);
737 if( Connection->HighestSequenceRcvd == Connection->NextSequenceRcv )
741 LOG("length=%u, index=0x%x", length, index);
742 for( int i = 0; i < length; i ++ )
745 Uint8 bitfield_byte = Connection->FuturePacketValidBytes[index / 8];
746 if( (bitfield_byte & (1 << bit)) == 0 ) {
748 LOG("Hit missing, break");
752 if( bitfield_byte == 0xFF ) {
760 if(index > TCP_WINDOW_SIZE)
761 index -= TCP_WINDOW_SIZE;
764 index = Connection->NextSequenceRcv % TCP_WINDOW_SIZE;
765 Connection->NextSequenceRcv += runlength;
767 // Write data to to the ring buffer
768 if( TCP_WINDOW_SIZE - index > runlength )
771 RingBuffer_Write( Connection->RecievedBuffer, Connection->FuturePacketData + index, runlength );
775 int endLen = TCP_WINDOW_SIZE - index;
777 RingBuffer_Write( Connection->RecievedBuffer, Connection->FuturePacketData + index, endLen );
778 RingBuffer_Write( Connection->RecievedBuffer, Connection->FuturePacketData, endLen - runlength );
781 // Mark (now saved) bytes as invalid
783 while(index % 8 && runlength > 0)
785 Connection->FuturePacketData[index] = 0;
786 Connection->FuturePacketValidBytes[index/8] &= ~(1 << (index%8));
788 if(index > TCP_WINDOW_SIZE)
789 index -= TCP_WINDOW_SIZE;
792 while( runlength > 7 )
794 Connection->FuturePacketData[index] = 0;
795 Connection->FuturePacketValidBytes[index/8] = 0;
798 if(index > TCP_WINDOW_SIZE)
799 index -= TCP_WINDOW_SIZE;
801 while( runlength > 0)
803 Connection->FuturePacketData[index] = 0;
804 Connection->FuturePacketData[index/8] &= ~(1 << (index%8));
806 if(index > TCP_WINDOW_SIZE)
807 index -= TCP_WINDOW_SIZE;
812 void TCP_int_SendDelayedACK(void *ConnPtr)
814 TCP_INT_SendACK(ConnPtr, "DACK Timeout");
817 void TCP_INT_SendACK(tTCPConnection *Connection, const char *Reason)
821 hdr.DataOffset = (sizeof(tTCPHeader)/4) << 4;
822 hdr.DestPort = htons(Connection->RemotePort);
823 hdr.SourcePort = htons(Connection->LocalPort);
824 hdr.AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
825 hdr.SequenceNumber = htonl(Connection->NextSequenceSend);
826 hdr.WindowSize = htons(TCP_WINDOW_SIZE);
827 hdr.Flags = TCP_FLAG_ACK; // TODO: Determine if SYN is wanted too
828 hdr.Checksum = 0; // TODO: Checksum
829 hdr.UrgentPointer = 0;
830 Log_Debug("TCP", "Sending ACK for 0x%08x (%s)", Connection->NextSequenceRcv, Reason);
831 TCP_SendPacket( Connection, &hdr, 0, NULL );
832 //Connection->NextSequenceSend ++;
833 Connection->LastACKSequence = Connection->NextSequenceRcv;
837 * \fn Uint16 TCP_GetUnusedPort()
838 * \brief Gets an unused port and allocates it
840 Uint16 TCP_GetUnusedPort()
844 // Get Next outbound port
845 ret = giTCP_NextOutPort++;
846 while( gaTCP_PortBitmap[ret/32] & (1UL << (ret%32)) )
850 if(giTCP_NextOutPort == 0x10000) {
851 ret = giTCP_NextOutPort = TCP_MIN_DYNPORT;
855 // Mark the new port as used
856 gaTCP_PortBitmap[ret/32] |= 1 << (ret%32);
862 * \fn int TCP_AllocatePort(Uint16 Port)
863 * \brief Marks a port as used
865 int TCP_AllocatePort(Uint16 Port)
867 // Check if the port has already been allocated
868 if( gaTCP_PortBitmap[Port/32] & (1 << (Port%32)) )
872 gaTCP_PortBitmap[Port/32] |= 1 << (Port%32);
878 * \fn int TCP_DeallocatePort(Uint16 Port)
879 * \brief Marks a port as unused
881 int TCP_DeallocatePort(Uint16 Port)
883 // Check if the port has already been allocated
884 if( !(gaTCP_PortBitmap[Port/32] & (1 << (Port%32))) )
888 gaTCP_PortBitmap[Port/32] &= ~(1 << (Port%32));
893 tTCPConnection *TCP_int_CreateConnection(tInterface *Interface, enum eTCPConnectionState State)
895 tTCPConnection *conn = calloc( sizeof(tTCPConnection) + TCP_WINDOW_SIZE + TCP_WINDOW_SIZE/8, 1 );
898 conn->Interface = Interface;
899 conn->LocalPort = -1;
900 conn->RemotePort = -1;
902 conn->Node.ReferenceCount = 1;
903 conn->Node.ImplPtr = conn;
904 conn->Node.NumACLs = 1;
905 conn->Node.ACLs = &gVFS_ACL_EveryoneRW;
906 conn->Node.Type = &gTCP_ClientNodeType;
907 conn->Node.BufferFull = 1; // Cleared when connection opens
909 conn->RecievedBuffer = RingBuffer_Create( TCP_RECIEVE_BUFFER_SIZE );
911 conn->SentBuffer = RingBuffer_Create( TCP_SEND_BUFFER_SIZE );
912 Semaphore_Init(conn->SentBufferSpace, 0, TCP_SEND_BUFFER_SIZE, "TCP SentBuffer", conn->Name);
915 conn->HighestSequenceRcvd = 0;
916 #if CACHE_FUTURE_PACKETS_IN_BYTES
917 // Future recieved data (ahead of the expected sequence number)
918 conn->FuturePacketData = (Uint8*)conn + sizeof(tTCPConnection);
919 conn->FuturePacketValidBytes = conn->FuturePacketData + TCP_WINDOW_SIZE;
922 conn->DeferredACKTimer = Time_AllocateTimer( TCP_int_SendDelayedACK, conn);
926 void TCP_int_FreeTCB(tTCPConnection *Connection)
928 ASSERTC(Connection->State, ==, TCP_ST_FINISHED);
929 ASSERTC(Connection->Node.ReferenceCount, ==, 0);
931 if( Connection->Server )
933 tTCPListener *srv = Connection->Server;
934 SHORTLOCK(&srv->lConnections);
936 Connection->Prev->Next = Connection->Next;
938 srv->Connections = Connection->Next;
940 Connection->Next->Prev = Connection->Prev;
942 ASSERT(srv->ConnectionsTail == Connection);
943 srv->ConnectionsTail = Connection->Prev;
945 SHORTREL(&srv->lConnections);
949 SHORTLOCK(&glTCP_OutbountCons);
951 Connection->Prev->Next = Connection->Next;
953 gTCP_OutbountCons = Connection->Next;
955 Connection->Next->Prev = Connection->Prev;
958 SHORTREL(&glTCP_OutbountCons);
961 RingBuffer_Free(Connection->RecievedBuffer);
962 Time_FreeTimer(Connection->DeferredACKTimer);
963 // TODO: Force VFS to close handles? (they should all be closed);
968 tVFS_Node *TCP_Server_Init(tInterface *Interface)
972 srv = calloc( 1, sizeof(tTCPListener) );
975 Log_Warning("TCP", "malloc failed for listener (%i) bytes", sizeof(tTCPListener));
979 srv->Interface = Interface;
982 srv->Connections = NULL;
983 srv->ConnectionsTail = NULL;
984 srv->NewConnections = NULL;
986 srv->Node.Flags = VFS_FFLAG_DIRECTORY;
988 srv->Node.ImplPtr = srv;
989 srv->Node.NumACLs = 1;
990 srv->Node.ACLs = &gVFS_ACL_EveryoneRW;
991 srv->Node.Type = &gTCP_ServerNodeType;
993 SHORTLOCK(&glTCP_Listeners);
994 srv->Next = gTCP_Listeners;
995 gTCP_Listeners = srv;
996 SHORTREL(&glTCP_Listeners);
1002 * \brief Wait for a new connection and return the connection ID
1003 * \note Blocks until a new connection is made
1004 * \param Node Server node
1005 * \param Pos Position (ignored)
1007 int TCP_Server_ReadDir(tVFS_Node *Node, int Pos, char Dest[FILENAME_MAX])
1009 tTCPListener *srv = Node->ImplPtr;
1010 tTCPConnection *conn;
1012 ENTER("pNode iPos", Node, Pos);
1014 Log_Log("TCP", "Thread %i waiting for a connection", Threads_GetTID());
1015 Semaphore_Wait( &srv->WaitingConnections, 1 );
1017 SHORTLOCK(&srv->lConnections);
1018 // Increment the new list (the current connection is still on the
1020 conn = srv->NewConnections;
1021 srv->NewConnections = conn->Next;
1023 if( srv->NewConnections == NULL )
1024 VFS_MarkAvaliable( Node, 0 );
1026 SHORTREL( &srv->lConnections );
1028 LOG("conn = %p", conn);
1029 LOG("srv->Connections = %p", srv->Connections);
1030 LOG("srv->NewConnections = %p", srv->NewConnections);
1031 LOG("srv->ConnectionsTail = %p", srv->ConnectionsTail);
1033 itoa(Dest, conn->Node.ImplInt, 16, 8, '0');
1034 Log_Log("TCP", "Thread %i got connection '%s'", Threads_GetTID(), Dest);
1040 * \brief Gets a client connection node
1041 * \param Node Server node
1042 * \param Name Hexadecimal ID of the node
1044 tVFS_Node *TCP_Server_FindDir(tVFS_Node *Node, const char *Name, Uint Flags)
1046 tTCPConnection *conn;
1047 tTCPListener *srv = Node->ImplPtr;
1049 int id = atoi(Name);
1051 ENTER("pNode sName", Node, Name);
1053 // Check for a non-empty name
1057 itoa(tmp, id, 16, 8, '0');
1058 if(strcmp(tmp, Name) != 0) {
1059 LOG("'%s' != '%s' (%08x)", Name, tmp, id);
1064 Log_Debug("TCP", "srv->Connections = %p", srv->Connections);
1065 Log_Debug("TCP", "srv->NewConnections = %p", srv->NewConnections);
1066 Log_Debug("TCP", "srv->ConnectionsTail = %p", srv->ConnectionsTail);
1069 SHORTLOCK( &srv->lConnections );
1070 for(conn = srv->Connections;
1074 LOG("conn->Node.ImplInt = %i", conn->Node.ImplInt);
1075 if(conn->Node.ImplInt == id) break;
1077 SHORTREL( &srv->lConnections );
1079 // If not found, ret NULL
1081 LOG("Connection %i not found", id);
1086 // Empty Name - Check for a new connection and if it's there, open it
1089 SHORTLOCK( &srv->lConnections );
1090 conn = srv->NewConnections;
1092 srv->NewConnections = conn->Next;
1093 VFS_MarkAvaliable( Node, srv->NewConnections != NULL );
1094 SHORTREL( &srv->lConnections );
1096 LOG("No new connections");
1103 LEAVE('p', &conn->Node);
1108 * \brief Handle IOCtl calls
1110 int TCP_Server_IOCtl(tVFS_Node *Node, int ID, void *Data)
1112 tTCPListener *srv = Node->ImplPtr;
1116 case 4: // Get/Set Port
1117 if(!Data) // Get Port
1120 if(srv->Port) // Wait, you can't CHANGE the port
1123 if(!CheckMem(Data, sizeof(Uint16))) // Sanity check
1126 // Permissions check
1127 if(Threads_GetUID() != 0
1128 && *(Uint16*)Data != 0
1129 && *(Uint16*)Data < 1024)
1132 // TODO: Check if a port is in use
1135 srv->Port = *(Uint16*)Data;
1136 if(srv->Port == 0) // Allocate a random port
1137 srv->Port = TCP_GetUnusedPort();
1138 else // Else, mark this as used
1139 TCP_AllocatePort(srv->Port);
1141 Log_Log("TCP", "Server %p listening on port %i", srv, srv->Port);
1148 void TCP_Server_Close(tVFS_Node *Node)
1150 free(Node->ImplPtr);
1155 * \brief Create a client node
1157 tVFS_Node *TCP_Client_Init(tInterface *Interface)
1159 tTCPConnection *conn = TCP_int_CreateConnection(Interface, TCP_ST_CLOSED);
1161 SHORTLOCK(&glTCP_OutbountCons);
1162 conn->Server = NULL;
1164 conn->Next = gTCP_OutbountCons;
1165 if(gTCP_OutbountCons)
1166 gTCP_OutbountCons->Prev = conn;
1167 gTCP_OutbountCons = conn;
1168 SHORTREL(&glTCP_OutbountCons);
1174 * \brief Wait for a packet and return it
1175 * \note If \a Length is smaller than the size of the packet, the rest
1176 * of the packet's data will be discarded.
1178 size_t TCP_Client_Read(tVFS_Node *Node, off_t Offset, size_t Length, void *Buffer, Uint Flags)
1180 tTCPConnection *conn = Node->ImplPtr;
1183 ENTER("pNode XOffset xLength pBuffer", Node, Offset, Length, Buffer);
1184 LOG("conn = %p {State:%i}", conn, conn->State);
1186 // If the connection has been closed (state > ST_OPEN) then clear
1187 // any stale data in the buffer (until it is empty (until it is empty))
1188 if( conn->State > TCP_ST_ESTABLISHED )
1190 LOG("Connection closed");
1191 Mutex_Acquire( &conn->lRecievedPackets );
1192 len = RingBuffer_Read( Buffer, conn->RecievedBuffer, Length );
1193 Mutex_Release( &conn->lRecievedPackets );
1196 VFS_MarkAvaliable(Node, 0);
1208 tTime *timeout = NULL;
1209 tTime timeout_zero = 0;
1210 if( Flags & VFS_IOFLAG_NOBLOCK )
1211 timeout = &timeout_zero;
1212 if( !VFS_SelectNode(Node, VFS_SELECT_READ|VFS_SELECT_ERROR, timeout, "TCP_Client_Read") ) {
1213 errno = EWOULDBLOCK;
1219 // Lock list and read as much as possible (up to `Length`)
1220 Mutex_Acquire( &conn->lRecievedPackets );
1221 len = RingBuffer_Read( Buffer, conn->RecievedBuffer, Length );
1223 if( len == 0 || conn->RecievedBuffer->Length == 0 ) {
1224 LOG("Marking as none avaliable (len = %i)", len);
1225 VFS_MarkAvaliable(Node, 0);
1228 // Release the lock (we don't need it any more)
1229 Mutex_Release( &conn->lRecievedPackets );
1236 * \brief Send a data packet on a connection
1238 void TCP_INT_SendDataPacket(tTCPConnection *Connection, size_t Length, const void *Data)
1240 char buf[sizeof(tTCPHeader)+Length];
1241 tTCPHeader *packet = (void*)buf;
1243 // - Stop Delayed ACK timer (as this data packet ACKs)
1244 Time_RemoveTimer(Connection->DeferredACKTimer);
1246 // TODO: Don't exceed window size
1248 packet->SourcePort = htons(Connection->LocalPort);
1249 packet->DestPort = htons(Connection->RemotePort);
1250 packet->DataOffset = (sizeof(tTCPHeader)/4)*16;
1251 packet->WindowSize = htons(TCP_WINDOW_SIZE);
1253 packet->AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
1254 packet->SequenceNumber = htonl(Connection->NextSequenceSend);
1255 packet->Flags = TCP_FLAG_PSH|TCP_FLAG_ACK; // Hey, ACK if you can!
1256 packet->UrgentPointer = 0;
1258 memcpy(packet->Options, Data, Length);
1260 Log_Debug("TCP", "Send sequence 0x%08x", Connection->NextSequenceSend);
1261 #if HEXDUMP_OUTGOING
1262 Debug_HexDump("TCP_INT_SendDataPacket: Data = ", Data, Length);
1265 TCP_SendPacket( Connection, packet, Length, Data );
1267 Connection->NextSequenceSend += Length;
1271 * \brief Send some bytes on a connection
1273 size_t TCP_Client_Write(tVFS_Node *Node, off_t Offset, size_t Length, const void *Buffer, Uint Flags)
1275 tTCPConnection *conn = Node->ImplPtr;
1276 size_t rem = Length;
1278 ENTER("pNode XOffset XLength pBuffer", Node, Offset, Length, Buffer);
1281 // Debug_HexDump("TCP_Client_Write: Buffer = ",
1285 // Don't allow a write to a closed connection
1286 if( conn->State > TCP_ST_ESTABLISHED ) {
1287 VFS_MarkError(Node, 1);
1295 tTime *timeout = NULL;
1296 tTime timeout_zero = 0;
1297 if( Flags & VFS_IOFLAG_NOBLOCK )
1298 timeout = &timeout_zero;
1299 if( !VFS_SelectNode(Node, VFS_SELECT_WRITE|VFS_SELECT_ERROR, timeout, "TCP_Client_Write") ) {
1300 errno = EWOULDBLOCK;
1308 int len = (rem < TCP_MAX_PACKET_SIZE) ? rem : TCP_MAX_PACKET_SIZE;
1311 // Wait for space in the buffer
1312 Semaphore_Signal( &Connection->SentBufferSpace, len );
1314 // Save data to buffer (and update the length read by the ammount written)
1315 len = RingBuffer_Write( &Connection->SentBuffer, Buffer, len);
1319 TCP_INT_SendDataPacket(conn, len, Buffer);
1330 * \brief Open a connection to another host using TCP
1331 * \param Conn Connection structure
1333 void TCP_StartConnection(tTCPConnection *Conn)
1335 tTCPHeader hdr = {0};
1337 Conn->State = TCP_ST_SYN_SENT;
1339 hdr.SourcePort = htons(Conn->LocalPort);
1340 hdr.DestPort = htons(Conn->RemotePort);
1341 Conn->NextSequenceSend = rand();
1342 hdr.SequenceNumber = htonl(Conn->NextSequenceSend);
1343 hdr.DataOffset = (sizeof(tTCPHeader)/4) << 4;
1344 hdr.Flags = TCP_FLAG_SYN;
1345 hdr.WindowSize = htons(TCP_WINDOW_SIZE); // Max
1346 hdr.Checksum = 0; // TODO
1348 TCP_SendPacket( Conn, &hdr, 0, NULL );
1350 Conn->NextSequenceSend ++;
1351 Conn->State = TCP_ST_SYN_SENT;
1357 * \brief Control a client socket
1359 int TCP_Client_IOCtl(tVFS_Node *Node, int ID, void *Data)
1361 tTCPConnection *conn = Node->ImplPtr;
1363 ENTER("pNode iID pData", Node, ID, Data);
1367 case 4: // Get/Set local port
1369 LEAVE_RET('i', conn->LocalPort);
1370 if(conn->State != TCP_ST_CLOSED)
1372 if(!CheckMem(Data, sizeof(Uint16)))
1375 if(Threads_GetUID() != 0 && *(Uint16*)Data < 1024)
1378 conn->LocalPort = *(Uint16*)Data;
1379 LEAVE_RET('i', conn->LocalPort);
1381 case 5: // Get/Set remote port
1382 if(!Data) LEAVE_RET('i', conn->RemotePort);
1383 if(conn->State != TCP_ST_CLOSED) LEAVE_RET('i', -1);
1384 if(!CheckMem(Data, sizeof(Uint16))) LEAVE_RET('i', -1);
1385 conn->RemotePort = *(Uint16*)Data;
1386 LEAVE_RET('i', conn->RemotePort);
1388 case 6: // Set Remote IP
1389 if( conn->State != TCP_ST_CLOSED )
1391 if( conn->Interface->Type == 4 )
1393 if(!CheckMem(Data, sizeof(tIPv4))) LEAVE_RET('i', -1);
1394 conn->RemoteIP.v4 = *(tIPv4*)Data;
1396 else if( conn->Interface->Type == 6 )
1398 if(!CheckMem(Data, sizeof(tIPv6))) LEAVE_RET('i', -1);
1399 conn->RemoteIP.v6 = *(tIPv6*)Data;
1404 if(conn->LocalPort == 0xFFFF)
1405 conn->LocalPort = TCP_GetUnusedPort();
1406 if(conn->RemotePort == -1)
1410 tTime timeout = conn->Interface->TimeoutDelay;
1412 TCP_StartConnection(conn);
1413 VFS_SelectNode(&conn->Node, VFS_SELECT_WRITE, &timeout, "TCP Connection");
1414 if( conn->State == TCP_ST_SYN_SENT )
1420 // Get recieve buffer length
1422 LEAVE_RET('i', conn->RecievedBuffer->Length);
1428 void TCP_Client_Close(tVFS_Node *Node)
1430 tTCPConnection *conn = Node->ImplPtr;
1433 ENTER("pNode", Node);
1435 ASSERT(Node->ReferenceCount != 0);
1437 if( Node->ReferenceCount > 1 ) {
1438 Node->ReferenceCount --;
1439 LOG("Dereference only");
1443 Node->ReferenceCount --;
1445 if( conn->State == TCP_ST_CLOSE_WAIT || conn->State == TCP_ST_ESTABLISHED )
1447 packet.SourcePort = htons(conn->LocalPort);
1448 packet.DestPort = htons(conn->RemotePort);
1449 packet.DataOffset = (sizeof(tTCPHeader)/4)*16;
1450 packet.WindowSize = TCP_WINDOW_SIZE;
1452 packet.AcknowlegementNumber = 0;
1453 packet.SequenceNumber = htonl(conn->NextSequenceSend);
1454 packet.Flags = TCP_FLAG_FIN;
1456 TCP_SendPacket( conn, &packet, 0, NULL );
1459 Time_RemoveTimer(conn->DeferredACKTimer);
1461 switch( conn->State )
1464 Log_Warning("TCP", "Closing connection that was never opened");
1465 TCP_int_FreeTCB(conn);
1467 case TCP_ST_FORCE_CLOSE:
1468 conn->State = TCP_ST_FINISHED;
1469 TCP_int_FreeTCB(conn);
1471 case TCP_ST_CLOSE_WAIT:
1472 conn->State = TCP_ST_LAST_ACK;
1474 case TCP_ST_ESTABLISHED:
1475 conn->State = TCP_ST_FIN_WAIT1;
1476 while( conn->State == TCP_ST_FIN_WAIT1 )
1478 // No free, freed after TIME_WAIT
1481 Log_Warning("TCP", "Unhandled connection state %i in TCP_Client_Close",
1490 * \brief Checks if a value is between two others (after taking into account wrapping)
1492 int WrapBetween(Uint32 Lower, Uint32 Value, Uint32 Higher, Uint32 MaxValue)
1494 if( MaxValue < 0xFFFFFFFF )
1496 Lower %= MaxValue + 1;
1497 Value %= MaxValue + 1;
1498 Higher %= MaxValue + 1;
1501 // Simple Case, no wrap ?
1502 // Lower Value Higher
1503 // | ... + ... + ... + ... |
1505 if( Lower < Higher ) {
1506 return Lower < Value && Value < Higher;
1508 // Higher has wrapped below lower
1511 // Higher Lower Value
1512 // | ... + ... + ... + ... |
1513 if( Value > Lower ) {
1518 // Value Higher Lower
1519 // | ... + ... + ... + ... |
1520 if( Value < Higher ) {
1526 Uint32 GetRelative(Uint32 Base, Uint32 Value)
1529 return Value - Base + 0xFFFFFFFF;
1531 return Value - Base;