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 ++;
350 // Hmm... Theoretically, this lock will never have to wait,
351 // as the interface is locked to the watching thread, and this
352 // runs in the watching thread. But, it's a good idea to have
354 // Oh, wait, there is a case where a wildcard can be used
355 // (Server->Interface == NULL) so having the lock is a good idea
356 SHORTLOCK(&Server->lConnections);
357 conn->Server = Server;
358 conn->Prev = Server->ConnectionsTail;
359 if(Server->Connections) {
360 ASSERT(Server->ConnectionsTail);
361 Server->ConnectionsTail->Next = conn;
364 ASSERT(!Server->ConnectionsTail);
365 Server->Connections = conn;
367 Server->ConnectionsTail = conn;
368 if(!Server->NewConnections)
369 Server->NewConnections = conn;
370 VFS_MarkAvaliable( &Server->Node, 1 );
371 SHORTREL(&Server->lConnections);
372 Semaphore_Signal(&Server->WaitingConnections, 1);
375 Header->Flags = TCP_FLAG_ACK|TCP_FLAG_SYN;
376 Header->AcknowlegementNumber = htonl(conn->NextSequenceRcv);
377 Header->SequenceNumber = htonl(conn->NextSequenceSend);
378 Header->DestPort = Header->SourcePort;
379 Header->SourcePort = htons(Server->Port);
380 Header->DataOffset = (sizeof(tTCPHeader)/4) << 4;
381 TCP_SendPacket( conn, Header, 0, NULL );
382 conn->NextSequenceSend ++;
387 * \brief Handles a packet sent to a specific connection
388 * \param Connection TCP Connection pointer
389 * \param Header TCP Packet pointer
390 * \param Length Length of the packet
392 int TCP_INT_HandleConnectionPacket(tTCPConnection *Connection, tTCPHeader *Header, int Length)
397 // Silently drop once finished
398 // TODO: Check if this needs to be here
399 if( Connection->State == TCP_ST_FINISHED ) {
400 Log_Log("TCP", "Packet ignored - connection finnished");
403 if( Connection->State == TCP_ST_FORCE_CLOSE ) {
404 Log_Log("TCP", "Packet ignored - connection reset");
408 // Syncronise sequence values
409 if(Header->Flags & TCP_FLAG_SYN) {
410 // TODO: What if the packet also has data?
411 if( Connection->LastACKSequence != Connection->NextSequenceRcv )
412 TCP_INT_SendACK(Connection, "SYN");
413 Connection->NextSequenceRcv = ntohl(Header->SequenceNumber);
414 // TODO: Process HighestSequenceRcvd
416 if( Connection->HighestSequenceRcvd == 0 )
417 Connection->HighestSequenceRcvd = Connection->NextSequenceRcv;
418 Connection->LastACKSequence = Connection->NextSequenceRcv;
421 // Ackowledge a sent packet
422 if(Header->Flags & TCP_FLAG_ACK) {
423 // TODO: Process an ACKed Packet
424 LOG("Conn %p, Sent packet 0x%x ACKed", Connection, Header->AcknowlegementNumber);
427 // Get length of data
428 dataLen = Length - (Header->DataOffset>>4)*4;
429 LOG("dataLen = %i", dataLen);
431 Log_Debug("TCP", "State %i, dataLen = %x", Connection->State, dataLen);
437 switch( Connection->State )
439 // Pre-init connection?
441 Log_Log("TCP", "Packets to a closed connection?!");
444 // --- Init States ---
445 // SYN sent, expecting SYN-ACK Connection Opening
446 case TCP_ST_SYN_SENT:
447 if( Header->Flags & TCP_FLAG_SYN )
449 if( Connection->HighestSequenceRcvd == Connection->NextSequenceRcv )
450 Connection->HighestSequenceRcvd ++;
451 Connection->NextSequenceRcv ++;
453 if( Header->Flags & TCP_FLAG_ACK )
455 Log_Log("TCP", "ACKing SYN-ACK");
456 Connection->State = TCP_ST_ESTABLISHED;
457 VFS_MarkFull(&Connection->Node, 0);
458 TCP_INT_SendACK(Connection, "SYN-ACK");
462 Log_Log("TCP", "ACKing SYN");
463 Connection->State = TCP_ST_SYN_RCVD;
464 TCP_INT_SendACK(Connection, "SYN");
469 // SYN-ACK sent, expecting ACK
470 case TCP_ST_SYN_RCVD:
471 if( Header->Flags & TCP_FLAG_RST )
473 Log_Log("TCP", "RST Received, closing");
474 Connection->State = TCP_ST_FORCE_CLOSE;
475 VFS_MarkError(&Connection->Node, 1);
478 if( Header->Flags & TCP_FLAG_ACK )
480 // TODO: Handle max half-open limit
481 Log_Log("TCP", "Connection fully opened");
482 Connection->State = TCP_ST_ESTABLISHED;
483 VFS_MarkFull(&Connection->Node, 0);
487 // --- Established State ---
488 case TCP_ST_ESTABLISHED:
489 // - Handle State changes
491 if( Header->Flags & TCP_FLAG_RST )
493 Log_Log("TCP", "Conn %p closed, received RST");
494 // Error outstanding transactions
495 Connection->State = TCP_ST_FORCE_CLOSE;
496 VFS_MarkError(&Connection->Node, 1);
499 if( Header->Flags & TCP_FLAG_FIN ) {
500 Log_Log("TCP", "Conn %p closed, recieved FIN", Connection);
501 VFS_MarkError(&Connection->Node, 1);
502 Connection->NextSequenceRcv ++;
503 TCP_INT_SendACK(Connection, "FIN Received");
504 Connection->State = TCP_ST_CLOSE_WAIT;
505 // CLOSE WAIT requires the client to close
509 // Check for an empty packet
511 if( Header->Flags == TCP_FLAG_ACK )
513 Log_Log("TCP", "ACK only packet");
516 // TODO: Is this right? (empty packet counts as one byte)
517 if( Connection->HighestSequenceRcvd == Connection->NextSequenceRcv )
518 Connection->HighestSequenceRcvd ++;
519 Connection->NextSequenceRcv ++;
520 Log_Log("TCP", "Empty Packet, inc and ACK the current sequence number");
521 TCP_INT_SendACK(Connection, "Empty");
530 sequence_num = ntohl(Header->SequenceNumber);
532 LOG("0x%08x <= 0x%08x < 0x%08x",
533 Connection->NextSequenceRcv,
534 ntohl(Header->SequenceNumber),
535 Connection->NextSequenceRcv + TCP_WINDOW_SIZE
538 // Is this packet the next expected packet?
539 if( sequence_num == Connection->NextSequenceRcv )
542 // Ooh, Goodie! Add it to the recieved list
543 rv = TCP_INT_AppendRecieved(Connection,
544 (Uint8*)Header + (Header->DataOffset>>4)*4,
548 Log_Notice("TCP", "TCP_INT_AppendRecieved rv %i", rv);
551 LOG("0x%08x += %i", Connection->NextSequenceRcv, dataLen);
552 if( Connection->HighestSequenceRcvd == Connection->NextSequenceRcv )
553 Connection->HighestSequenceRcvd += dataLen;
554 Connection->NextSequenceRcv += dataLen;
556 // TODO: This should be moved out of the watcher thread,
557 // so that a single lost packet on one connection doesn't cause
558 // all connections on the interface to lag.
559 // - Meh, no real issue, as the cache shouldn't be that large
560 TCP_INT_UpdateRecievedFromFuture(Connection);
563 // - Only send an ACK if we've had a burst
564 Uint32 bytes_since_last_ack = Connection->NextSequenceRcv - Connection->LastACKSequence;
565 LOG("bytes_since_last_ack = 0x%x", bytes_since_last_ack);
566 if( bytes_since_last_ack > TCP_DACK_THRESHOLD )
568 TCP_INT_SendACK(Connection, "DACK Burst");
569 // - Extend TCP deferred ACK timer
570 Time_RemoveTimer(Connection->DeferredACKTimer);
572 // - Schedule the deferred ACK timer (if already scheduled, this is a NOP)
573 Time_ScheduleTimer(Connection->DeferredACKTimer, TCP_DACK_TIMEOUT);
575 TCP_INT_SendACK(Connection, "RX");
578 // Check if the packet is in window
579 else if( sequence_num - Connection->NextSequenceRcv < TCP_WINDOW_SIZE )
581 Uint8 *dataptr = (Uint8*)Header + (Header->DataOffset>>4)*4;
582 Uint32 index = sequence_num % TCP_WINDOW_SIZE;
583 Uint32 max = Connection->NextSequenceRcv % TCP_WINDOW_SIZE;
584 if( !(Connection->FuturePacketValidBytes[index/8] & (1 << (index%8))) )
585 TCP_INT_SendACK(Connection, "Lost packet");
586 for( int i = 0; i < dataLen; i ++ )
588 Connection->FuturePacketValidBytes[index/8] |= 1 << (index%8);
589 Connection->FuturePacketData[index] = dataptr[i];
590 // Do a wrap increment
592 if(index == TCP_WINDOW_SIZE) index = 0;
593 if(index == max) break;
595 Uint32 rel_highest = Connection->HighestSequenceRcvd - Connection->NextSequenceRcv;
596 Uint32 rel_this = index - Connection->NextSequenceRcv;
597 LOG("Updating highest this(0x%x) > highest(%x)", rel_this, rel_highest);
598 if( rel_this > rel_highest )
600 Connection->HighestSequenceRcvd = index;
603 // Badly out of sequence packet
606 Log_Log("TCP", "Fully out of sequence packet (0x%08x not between 0x%08x and 0x%08x), dropped",
607 sequence_num, Connection->NextSequenceRcv, Connection->NextSequenceRcv+TCP_WINDOW_SIZE);
608 // Spec says we should send an empty ACK with the current state
609 TCP_INT_SendACK(Connection, "Bad Seq");
613 // --- Remote close states
614 case TCP_ST_CLOSE_WAIT:
616 // Ignore everything, CLOSE_WAIT is terminated by the client
617 Log_Debug("TCP", "CLOSE WAIT - Ignoring packets");
621 // LAST-ACK - Waiting for the ACK of FIN (from CLOSE WAIT)
622 case TCP_ST_LAST_ACK:
623 if( Header->Flags & TCP_FLAG_ACK )
625 Connection->State = TCP_ST_FINISHED; // Connection completed
626 Log_Log("TCP", "LAST-ACK to CLOSED - Connection remote closed");
627 TCP_int_FreeTCB(Connection);
631 // --- Local close States
632 case TCP_ST_FIN_WAIT1:
633 if( Header->Flags & TCP_FLAG_FIN )
635 Connection->State = TCP_ST_CLOSING;
636 Log_Debug("TCP", "Conn %p closed, sent FIN and recieved FIN", Connection);
637 VFS_MarkError(&Connection->Node, 1);
639 TCP_INT_SendACK(Connection, "FINWAIT-1 FIN");
643 // TODO: Make sure that the packet is actually ACKing the FIN
644 if( Header->Flags & TCP_FLAG_ACK )
646 Connection->State = TCP_ST_FIN_WAIT2;
647 Log_Debug("TCP", "Conn %p closed, sent FIN ACKed", Connection);
648 VFS_MarkError(&Connection->Node, 1);
653 case TCP_ST_FIN_WAIT2:
654 if( Header->Flags & TCP_FLAG_FIN )
656 Connection->State = TCP_ST_TIME_WAIT;
657 Log_Debug("TCP", "Conn %p FINWAIT-2 -> TIME WAIT", Connection);
658 TCP_INT_SendACK(Connection, "FINWAIT-2 FIN");
663 // TODO: Make sure that the packet is actually ACKing the FIN
664 if( Header->Flags & TCP_FLAG_ACK )
666 Connection->State = TCP_ST_TIME_WAIT;
667 Log_Debug("TCP", "Conn %p CLOSING -> TIME WAIT", Connection);
668 VFS_MarkError(&Connection->Node, 1);
673 // --- Closed (or near closed) states) ---
674 case TCP_ST_TIME_WAIT:
675 Log_Log("TCP", "Packets on Time-Wait, ignored");
678 case TCP_ST_FINISHED:
679 Log_Log("TCP", "Packets when CLOSED, ignoring");
681 case TCP_ST_FORCE_CLOSE:
682 Log_Log("TCP", "Packets when force CLOSED, ignoring");
686 // Log_Warning("TCP", "Unhandled TCP state %i", Connection->State);
695 * \brief Appends a packet to the recieved list
696 * \param Connection Connection structure
697 * \param Data Packet contents
698 * \param Length Length of \a Data
700 int TCP_INT_AppendRecieved(tTCPConnection *Connection, const void *Data, size_t Length)
702 Mutex_Acquire( &Connection->lRecievedPackets );
704 if(Connection->RecievedBuffer->Length + Length > Connection->RecievedBuffer->Space )
706 VFS_MarkAvaliable(&Connection->Node, 1);
707 Log_Error("TCP", "Buffer filled, packet dropped (:%i) - %i + %i > %i",
708 Connection->LocalPort, Connection->RecievedBuffer->Length, Length,
709 Connection->RecievedBuffer->Space
711 Mutex_Release( &Connection->lRecievedPackets );
715 RingBuffer_Write( Connection->RecievedBuffer, Data, Length );
717 VFS_MarkAvaliable(&Connection->Node, 1);
719 Mutex_Release( &Connection->lRecievedPackets );
724 * \brief Updates the connections recieved list from the future list
725 * \param Connection Connection structure
727 * Updates the recieved packets list with packets from the future (out
728 * of order) packets list that are now able to be added in direct
731 void TCP_INT_UpdateRecievedFromFuture(tTCPConnection *Connection)
733 // Calculate length of contiguous bytes
734 const size_t length = Connection->HighestSequenceRcvd - Connection->NextSequenceRcv;
735 Uint32 index = Connection->NextSequenceRcv % TCP_WINDOW_SIZE;
736 size_t runlength = length;
737 LOG("HSR=0x%x,NSR=0x%x", Connection->HighestSequenceRcvd, Connection->NextSequenceRcv);
738 if( Connection->HighestSequenceRcvd == Connection->NextSequenceRcv )
742 LOG("length=%u, index=0x%x", length, index);
743 for( int i = 0; i < length; i ++ )
746 Uint8 bitfield_byte = Connection->FuturePacketValidBytes[index / 8];
747 if( (bitfield_byte & (1 << bit)) == 0 ) {
749 LOG("Hit missing, break");
753 if( bitfield_byte == 0xFF ) {
761 if(index > TCP_WINDOW_SIZE)
762 index -= TCP_WINDOW_SIZE;
765 index = Connection->NextSequenceRcv % TCP_WINDOW_SIZE;
766 Connection->NextSequenceRcv += runlength;
768 // Write data to to the ring buffer
769 if( TCP_WINDOW_SIZE - index > runlength )
772 RingBuffer_Write( Connection->RecievedBuffer, Connection->FuturePacketData + index, runlength );
776 int endLen = TCP_WINDOW_SIZE - index;
778 RingBuffer_Write( Connection->RecievedBuffer, Connection->FuturePacketData + index, endLen );
779 RingBuffer_Write( Connection->RecievedBuffer, Connection->FuturePacketData, endLen - runlength );
782 // Mark (now saved) bytes as invalid
784 while(index % 8 && runlength > 0)
786 Connection->FuturePacketData[index] = 0;
787 Connection->FuturePacketValidBytes[index/8] &= ~(1 << (index%8));
789 if(index > TCP_WINDOW_SIZE)
790 index -= TCP_WINDOW_SIZE;
793 while( runlength > 7 )
795 Connection->FuturePacketData[index] = 0;
796 Connection->FuturePacketValidBytes[index/8] = 0;
799 if(index > TCP_WINDOW_SIZE)
800 index -= TCP_WINDOW_SIZE;
802 while( runlength > 0)
804 Connection->FuturePacketData[index] = 0;
805 Connection->FuturePacketData[index/8] &= ~(1 << (index%8));
807 if(index > TCP_WINDOW_SIZE)
808 index -= TCP_WINDOW_SIZE;
813 void TCP_int_SendDelayedACK(void *ConnPtr)
815 TCP_INT_SendACK(ConnPtr, "DACK Timeout");
818 void TCP_INT_SendACK(tTCPConnection *Connection, const char *Reason)
822 hdr.DataOffset = (sizeof(tTCPHeader)/4) << 4;
823 hdr.DestPort = htons(Connection->RemotePort);
824 hdr.SourcePort = htons(Connection->LocalPort);
825 hdr.AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
826 hdr.SequenceNumber = htonl(Connection->NextSequenceSend);
827 hdr.WindowSize = htons(TCP_WINDOW_SIZE);
828 hdr.Flags = TCP_FLAG_ACK; // TODO: Determine if SYN is wanted too
829 hdr.Checksum = 0; // TODO: Checksum
830 hdr.UrgentPointer = 0;
831 Log_Debug("TCP", "Sending ACK for 0x%08x (%s)", Connection->NextSequenceRcv, Reason);
832 TCP_SendPacket( Connection, &hdr, 0, NULL );
833 //Connection->NextSequenceSend ++;
834 Connection->LastACKSequence = Connection->NextSequenceRcv;
838 * \fn Uint16 TCP_GetUnusedPort()
839 * \brief Gets an unused port and allocates it
841 Uint16 TCP_GetUnusedPort()
845 // Get Next outbound port
846 ret = giTCP_NextOutPort++;
847 while( gaTCP_PortBitmap[ret/32] & (1UL << (ret%32)) )
851 if(giTCP_NextOutPort == 0x10000) {
852 ret = giTCP_NextOutPort = TCP_MIN_DYNPORT;
856 // Mark the new port as used
857 gaTCP_PortBitmap[ret/32] |= 1 << (ret%32);
863 * \fn int TCP_AllocatePort(Uint16 Port)
864 * \brief Marks a port as used
866 int TCP_AllocatePort(Uint16 Port)
868 // Check if the port has already been allocated
869 if( gaTCP_PortBitmap[Port/32] & (1 << (Port%32)) )
873 gaTCP_PortBitmap[Port/32] |= 1 << (Port%32);
879 * \fn int TCP_DeallocatePort(Uint16 Port)
880 * \brief Marks a port as unused
882 int TCP_DeallocatePort(Uint16 Port)
884 // Check if the port has already been allocated
885 if( !(gaTCP_PortBitmap[Port/32] & (1 << (Port%32))) )
889 gaTCP_PortBitmap[Port/32] &= ~(1 << (Port%32));
894 tTCPConnection *TCP_int_CreateConnection(tInterface *Interface, enum eTCPConnectionState State)
896 tTCPConnection *conn = calloc( sizeof(tTCPConnection) + TCP_WINDOW_SIZE + TCP_WINDOW_SIZE/8, 1 );
899 conn->Interface = Interface;
900 conn->LocalPort = -1;
901 conn->RemotePort = -1;
903 conn->Node.ReferenceCount = 1;
904 conn->Node.ImplPtr = conn;
905 conn->Node.NumACLs = 1;
906 conn->Node.ACLs = &gVFS_ACL_EveryoneRW;
907 conn->Node.Type = &gTCP_ClientNodeType;
908 conn->Node.BufferFull = 1; // Cleared when connection opens
910 conn->RecievedBuffer = RingBuffer_Create( TCP_RECIEVE_BUFFER_SIZE );
912 conn->SentBuffer = RingBuffer_Create( TCP_SEND_BUFFER_SIZE );
913 Semaphore_Init(conn->SentBufferSpace, 0, TCP_SEND_BUFFER_SIZE, "TCP SentBuffer", conn->Name);
916 conn->HighestSequenceRcvd = 0;
917 #if CACHE_FUTURE_PACKETS_IN_BYTES
918 // Future recieved data (ahead of the expected sequence number)
919 conn->FuturePacketData = (Uint8*)conn + sizeof(tTCPConnection);
920 conn->FuturePacketValidBytes = conn->FuturePacketData + TCP_WINDOW_SIZE;
923 conn->DeferredACKTimer = Time_AllocateTimer( TCP_int_SendDelayedACK, conn);
927 void TCP_int_FreeTCB(tTCPConnection *Connection)
929 ASSERTC(Connection->State, ==, TCP_ST_FINISHED);
930 ASSERTC(Connection->Node.ReferenceCount, ==, 0);
932 if( Connection->Server )
934 tTCPListener *srv = Connection->Server;
935 SHORTLOCK(&srv->lConnections);
937 Connection->Prev->Next = Connection->Next;
939 srv->Connections = Connection->Next;
941 Connection->Next->Prev = Connection->Prev;
943 ASSERT(srv->ConnectionsTail == Connection);
944 srv->ConnectionsTail = Connection->Prev;
946 SHORTREL(&srv->lConnections);
950 SHORTLOCK(&glTCP_OutbountCons);
952 Connection->Prev->Next = Connection->Next;
954 gTCP_OutbountCons = Connection->Next;
956 Connection->Next->Prev = Connection->Prev;
959 SHORTREL(&glTCP_OutbountCons);
962 RingBuffer_Free(Connection->RecievedBuffer);
963 Time_FreeTimer(Connection->DeferredACKTimer);
964 // TODO: Force VFS to close handles? (they should all be closed);
969 tVFS_Node *TCP_Server_Init(tInterface *Interface)
973 srv = calloc( 1, sizeof(tTCPListener) );
976 Log_Warning("TCP", "malloc failed for listener (%i) bytes", sizeof(tTCPListener));
980 srv->Interface = Interface;
983 srv->Connections = NULL;
984 srv->ConnectionsTail = NULL;
985 srv->NewConnections = NULL;
987 srv->Node.Flags = VFS_FFLAG_DIRECTORY;
989 srv->Node.ImplPtr = srv;
990 srv->Node.NumACLs = 1;
991 srv->Node.ACLs = &gVFS_ACL_EveryoneRW;
992 srv->Node.Type = &gTCP_ServerNodeType;
994 SHORTLOCK(&glTCP_Listeners);
995 srv->Next = gTCP_Listeners;
996 gTCP_Listeners = srv;
997 SHORTREL(&glTCP_Listeners);
1003 * \brief Wait for a new connection and return the connection ID
1004 * \note Blocks until a new connection is made
1005 * \param Node Server node
1006 * \param Pos Position (ignored)
1008 int TCP_Server_ReadDir(tVFS_Node *Node, int Pos, char Dest[FILENAME_MAX])
1010 tTCPListener *srv = Node->ImplPtr;
1011 tTCPConnection *conn;
1013 ENTER("pNode iPos", Node, Pos);
1015 Log_Log("TCP", "Thread %i waiting for a connection", Threads_GetTID());
1016 Semaphore_Wait( &srv->WaitingConnections, 1 );
1018 SHORTLOCK(&srv->lConnections);
1019 // Increment the new list (the current connection is still on the
1021 conn = srv->NewConnections;
1022 srv->NewConnections = conn->Next;
1024 if( srv->NewConnections == NULL )
1025 VFS_MarkAvaliable( Node, 0 );
1027 SHORTREL( &srv->lConnections );
1029 LOG("conn = %p", conn);
1030 LOG("srv->Connections = %p", srv->Connections);
1031 LOG("srv->NewConnections = %p", srv->NewConnections);
1032 LOG("srv->ConnectionsTail = %p", srv->ConnectionsTail);
1034 itoa(Dest, conn->Node.ImplInt, 16, 8, '0');
1035 Log_Log("TCP", "Thread %i got connection '%s'", Threads_GetTID(), Dest);
1041 * \brief Gets a client connection node
1042 * \param Node Server node
1043 * \param Name Hexadecimal ID of the node
1045 tVFS_Node *TCP_Server_FindDir(tVFS_Node *Node, const char *Name, Uint Flags)
1047 tTCPConnection *conn;
1048 tTCPListener *srv = Node->ImplPtr;
1050 int id = atoi(Name);
1052 ENTER("pNode sName", Node, Name);
1054 // Check for a non-empty name
1058 itoa(tmp, id, 16, 8, '0');
1059 if(strcmp(tmp, Name) != 0) {
1060 LOG("'%s' != '%s' (%08x)", Name, tmp, id);
1065 Log_Debug("TCP", "srv->Connections = %p", srv->Connections);
1066 Log_Debug("TCP", "srv->NewConnections = %p", srv->NewConnections);
1067 Log_Debug("TCP", "srv->ConnectionsTail = %p", srv->ConnectionsTail);
1070 SHORTLOCK( &srv->lConnections );
1071 for(conn = srv->Connections;
1075 LOG("conn->Node.ImplInt = %i", conn->Node.ImplInt);
1076 if(conn->Node.ImplInt == id) break;
1078 SHORTREL( &srv->lConnections );
1080 // If not found, ret NULL
1082 LOG("Connection %i not found", id);
1087 // Empty Name - Check for a new connection and if it's there, open it
1090 SHORTLOCK( &srv->lConnections );
1091 conn = srv->NewConnections;
1093 srv->NewConnections = conn->Next;
1094 VFS_MarkAvaliable( Node, srv->NewConnections != NULL );
1095 SHORTREL( &srv->lConnections );
1097 LOG("No new connections");
1104 LEAVE('p', &conn->Node);
1109 * \brief Handle IOCtl calls
1111 int TCP_Server_IOCtl(tVFS_Node *Node, int ID, void *Data)
1113 tTCPListener *srv = Node->ImplPtr;
1117 case 4: // Get/Set Port
1118 if(!Data) // Get Port
1121 if(srv->Port) // Wait, you can't CHANGE the port
1124 if(!CheckMem(Data, sizeof(Uint16))) // Sanity check
1127 // Permissions check
1128 if(Threads_GetUID() != 0
1129 && *(Uint16*)Data != 0
1130 && *(Uint16*)Data < 1024)
1133 // TODO: Check if a port is in use
1136 srv->Port = *(Uint16*)Data;
1137 if(srv->Port == 0) // Allocate a random port
1138 srv->Port = TCP_GetUnusedPort();
1139 else // Else, mark this as used
1140 TCP_AllocatePort(srv->Port);
1142 Log_Log("TCP", "Server %p listening on port %i", srv, srv->Port);
1149 void TCP_Server_Close(tVFS_Node *Node)
1151 free(Node->ImplPtr);
1156 * \brief Create a client node
1158 tVFS_Node *TCP_Client_Init(tInterface *Interface)
1160 tTCPConnection *conn = TCP_int_CreateConnection(Interface, TCP_ST_CLOSED);
1162 SHORTLOCK(&glTCP_OutbountCons);
1163 conn->Server = NULL;
1165 conn->Next = gTCP_OutbountCons;
1166 if(gTCP_OutbountCons)
1167 gTCP_OutbountCons->Prev = conn;
1168 gTCP_OutbountCons = conn;
1169 SHORTREL(&glTCP_OutbountCons);
1175 * \brief Wait for a packet and return it
1176 * \note If \a Length is smaller than the size of the packet, the rest
1177 * of the packet's data will be discarded.
1179 size_t TCP_Client_Read(tVFS_Node *Node, off_t Offset, size_t Length, void *Buffer, Uint Flags)
1181 tTCPConnection *conn = Node->ImplPtr;
1184 ENTER("pNode XOffset xLength pBuffer", Node, Offset, Length, Buffer);
1185 LOG("conn = %p {State:%i}", conn, conn->State);
1187 // If the connection has been closed (state > ST_OPEN) then clear
1188 // any stale data in the buffer (until it is empty (until it is empty))
1189 if( conn->State > TCP_ST_ESTABLISHED )
1191 LOG("Connection closed");
1192 Mutex_Acquire( &conn->lRecievedPackets );
1193 len = RingBuffer_Read( Buffer, conn->RecievedBuffer, Length );
1194 Mutex_Release( &conn->lRecievedPackets );
1197 VFS_MarkAvaliable(Node, 0);
1209 tTime *timeout = NULL;
1210 tTime timeout_zero = 0;
1211 if( Flags & VFS_IOFLAG_NOBLOCK )
1212 timeout = &timeout_zero;
1213 if( !VFS_SelectNode(Node, VFS_SELECT_READ|VFS_SELECT_ERROR, timeout, "TCP_Client_Read") ) {
1214 errno = EWOULDBLOCK;
1220 // Lock list and read as much as possible (up to `Length`)
1221 Mutex_Acquire( &conn->lRecievedPackets );
1222 len = RingBuffer_Read( Buffer, conn->RecievedBuffer, Length );
1224 if( len == 0 || conn->RecievedBuffer->Length == 0 ) {
1225 LOG("Marking as none avaliable (len = %i)", len);
1226 VFS_MarkAvaliable(Node, 0);
1229 // Release the lock (we don't need it any more)
1230 Mutex_Release( &conn->lRecievedPackets );
1237 * \brief Send a data packet on a connection
1239 void TCP_INT_SendDataPacket(tTCPConnection *Connection, size_t Length, const void *Data)
1241 char buf[sizeof(tTCPHeader)+Length];
1242 tTCPHeader *packet = (void*)buf;
1244 // - Stop Delayed ACK timer (as this data packet ACKs)
1245 Time_RemoveTimer(Connection->DeferredACKTimer);
1247 // TODO: Don't exceed window size
1249 packet->SourcePort = htons(Connection->LocalPort);
1250 packet->DestPort = htons(Connection->RemotePort);
1251 packet->DataOffset = (sizeof(tTCPHeader)/4)*16;
1252 packet->WindowSize = htons(TCP_WINDOW_SIZE);
1254 packet->AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
1255 packet->SequenceNumber = htonl(Connection->NextSequenceSend);
1256 packet->Flags = TCP_FLAG_PSH|TCP_FLAG_ACK; // Hey, ACK if you can!
1257 packet->UrgentPointer = 0;
1259 memcpy(packet->Options, Data, Length);
1261 Log_Debug("TCP", "Send sequence 0x%08x", Connection->NextSequenceSend);
1262 #if HEXDUMP_OUTGOING
1263 Debug_HexDump("TCP_INT_SendDataPacket: Data = ", Data, Length);
1266 TCP_SendPacket( Connection, packet, Length, Data );
1268 Connection->NextSequenceSend += Length;
1272 * \brief Send some bytes on a connection
1274 size_t TCP_Client_Write(tVFS_Node *Node, off_t Offset, size_t Length, const void *Buffer, Uint Flags)
1276 tTCPConnection *conn = Node->ImplPtr;
1277 size_t rem = Length;
1279 ENTER("pNode XOffset XLength pBuffer", Node, Offset, Length, Buffer);
1282 // Debug_HexDump("TCP_Client_Write: Buffer = ",
1286 // Don't allow a write to a closed connection
1287 if( conn->State > TCP_ST_ESTABLISHED ) {
1288 VFS_MarkError(Node, 1);
1296 tTime *timeout = NULL;
1297 tTime timeout_zero = 0;
1298 if( Flags & VFS_IOFLAG_NOBLOCK )
1299 timeout = &timeout_zero;
1300 if( !VFS_SelectNode(Node, VFS_SELECT_WRITE|VFS_SELECT_ERROR, timeout, "TCP_Client_Write") ) {
1301 errno = EWOULDBLOCK;
1309 int len = (rem < TCP_MAX_PACKET_SIZE) ? rem : TCP_MAX_PACKET_SIZE;
1312 // Wait for space in the buffer
1313 Semaphore_Signal( &Connection->SentBufferSpace, len );
1315 // Save data to buffer (and update the length read by the ammount written)
1316 len = RingBuffer_Write( &Connection->SentBuffer, Buffer, len);
1320 TCP_INT_SendDataPacket(conn, len, Buffer);
1331 * \brief Open a connection to another host using TCP
1332 * \param Conn Connection structure
1334 void TCP_StartConnection(tTCPConnection *Conn)
1336 tTCPHeader hdr = {0};
1338 Conn->State = TCP_ST_SYN_SENT;
1340 hdr.SourcePort = htons(Conn->LocalPort);
1341 hdr.DestPort = htons(Conn->RemotePort);
1342 Conn->NextSequenceSend = rand();
1343 hdr.SequenceNumber = htonl(Conn->NextSequenceSend);
1344 hdr.DataOffset = (sizeof(tTCPHeader)/4) << 4;
1345 hdr.Flags = TCP_FLAG_SYN;
1346 hdr.WindowSize = htons(TCP_WINDOW_SIZE); // Max
1347 hdr.Checksum = 0; // TODO
1349 TCP_SendPacket( Conn, &hdr, 0, NULL );
1351 Conn->NextSequenceSend ++;
1352 Conn->State = TCP_ST_SYN_SENT;
1358 * \brief Control a client socket
1360 int TCP_Client_IOCtl(tVFS_Node *Node, int ID, void *Data)
1362 tTCPConnection *conn = Node->ImplPtr;
1364 ENTER("pNode iID pData", Node, ID, Data);
1368 case 4: // Get/Set local port
1370 LEAVE_RET('i', conn->LocalPort);
1371 if(conn->State != TCP_ST_CLOSED)
1373 if(!CheckMem(Data, sizeof(Uint16)))
1376 if(Threads_GetUID() != 0 && *(Uint16*)Data < 1024)
1379 conn->LocalPort = *(Uint16*)Data;
1380 LEAVE_RET('i', conn->LocalPort);
1382 case 5: // Get/Set remote port
1383 if(!Data) LEAVE_RET('i', conn->RemotePort);
1384 if(conn->State != TCP_ST_CLOSED) LEAVE_RET('i', -1);
1385 if(!CheckMem(Data, sizeof(Uint16))) LEAVE_RET('i', -1);
1386 conn->RemotePort = *(Uint16*)Data;
1387 LEAVE_RET('i', conn->RemotePort);
1389 case 6: // Set Remote IP
1390 if( conn->State != TCP_ST_CLOSED )
1392 if( conn->Interface->Type == 4 )
1394 if(!CheckMem(Data, sizeof(tIPv4))) LEAVE_RET('i', -1);
1395 conn->RemoteIP.v4 = *(tIPv4*)Data;
1397 else if( conn->Interface->Type == 6 )
1399 if(!CheckMem(Data, sizeof(tIPv6))) LEAVE_RET('i', -1);
1400 conn->RemoteIP.v6 = *(tIPv6*)Data;
1405 if(conn->LocalPort == 0xFFFF)
1406 conn->LocalPort = TCP_GetUnusedPort();
1407 if(conn->RemotePort == -1)
1411 tTime timeout = conn->Interface->TimeoutDelay;
1413 TCP_StartConnection(conn);
1414 VFS_SelectNode(&conn->Node, VFS_SELECT_WRITE, &timeout, "TCP Connection");
1415 if( conn->State == TCP_ST_SYN_SENT )
1421 // Get recieve buffer length
1423 LEAVE_RET('i', conn->RecievedBuffer->Length);
1429 void TCP_Client_Close(tVFS_Node *Node)
1431 tTCPConnection *conn = Node->ImplPtr;
1434 ENTER("pNode", Node);
1436 ASSERT(Node->ReferenceCount != 0);
1438 if( Node->ReferenceCount > 1 ) {
1439 Node->ReferenceCount --;
1440 LOG("Dereference only");
1444 Node->ReferenceCount --;
1446 if( conn->State == TCP_ST_CLOSE_WAIT || conn->State == TCP_ST_ESTABLISHED )
1448 packet.SourcePort = htons(conn->LocalPort);
1449 packet.DestPort = htons(conn->RemotePort);
1450 packet.DataOffset = (sizeof(tTCPHeader)/4)*16;
1451 packet.WindowSize = TCP_WINDOW_SIZE;
1453 packet.AcknowlegementNumber = 0;
1454 packet.SequenceNumber = htonl(conn->NextSequenceSend);
1455 packet.Flags = TCP_FLAG_FIN;
1457 TCP_SendPacket( conn, &packet, 0, NULL );
1460 Time_RemoveTimer(conn->DeferredACKTimer);
1462 switch( conn->State )
1465 Log_Warning("TCP", "Closing connection that was never opened");
1466 TCP_int_FreeTCB(conn);
1468 case TCP_ST_FORCE_CLOSE:
1469 conn->State = TCP_ST_FINISHED;
1470 TCP_int_FreeTCB(conn);
1472 case TCP_ST_CLOSE_WAIT:
1473 conn->State = TCP_ST_LAST_ACK;
1475 case TCP_ST_ESTABLISHED:
1476 conn->State = TCP_ST_FIN_WAIT1;
1477 while( conn->State == TCP_ST_FIN_WAIT1 )
1479 // No free, freed after TIME_WAIT
1482 Log_Warning("TCP", "Unhandled connection state %i in TCP_Client_Close",
1491 * \brief Checks if a value is between two others (after taking into account wrapping)
1493 int WrapBetween(Uint32 Lower, Uint32 Value, Uint32 Higher, Uint32 MaxValue)
1495 if( MaxValue < 0xFFFFFFFF )
1497 Lower %= MaxValue + 1;
1498 Value %= MaxValue + 1;
1499 Higher %= MaxValue + 1;
1502 // Simple Case, no wrap ?
1503 // Lower Value Higher
1504 // | ... + ... + ... + ... |
1506 if( Lower < Higher ) {
1507 return Lower < Value && Value < Higher;
1509 // Higher has wrapped below lower
1512 // Higher Lower Value
1513 // | ... + ... + ... + ... |
1514 if( Value > Lower ) {
1519 // Value Higher Lower
1520 // | ... + ... + ... + ... |
1521 if( Value < Higher ) {
1527 Uint32 GetRelative(Uint32 Base, Uint32 Value)
1530 return Value - Base + 0xFFFFFFFF;
1532 return Value - Base;