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 void TCP_IPError(tInterface *Interface, tIPErrorMode Mode, const void *Address, int Length, const void *Buffer);
32 int TCP_INT_HandleServerPacket(tInterface *Interface, tTCPListener *Server, const void *Address, tTCPHeader *Header, size_t Length);
33 int TCP_INT_HandleConnectionPacket(tTCPConnection *Connection, tTCPHeader *Header, int Length);
34 int TCP_INT_AppendRecieved(tTCPConnection *Connection, const void *Data, size_t Length);
35 void TCP_INT_UpdateRecievedFromFuture(tTCPConnection *Connection);
36 void TCP_int_SendDelayedACK(void *ConnPtr);
37 void TCP_INT_SendACK(tTCPConnection *Connection, const char *Reason);
38 Uint16 TCP_GetUnusedPort();
39 int TCP_AllocatePort(Uint16 Port);
40 int TCP_DeallocatePort(Uint16 Port);
41 tTCPConnection *TCP_int_CreateConnection(tInterface *Interface, enum eTCPConnectionState State);
42 void TCP_int_FreeTCB(tTCPConnection *Connection);
44 tVFS_Node *TCP_Server_Init(tInterface *Interface);
45 int TCP_Server_ReadDir(tVFS_Node *Node, int Pos, char Name[FILENAME_MAX]);
46 tVFS_Node *TCP_Server_FindDir(tVFS_Node *Node, const char *Name, Uint Flags);
47 int TCP_Server_IOCtl(tVFS_Node *Node, int ID, void *Data);
48 void TCP_Server_Close(tVFS_Node *Node);
50 tVFS_Node *TCP_Client_Init(tInterface *Interface);
51 size_t TCP_Client_Read(tVFS_Node *Node, off_t Offset, size_t Length, void *Buffer, Uint Flags);
52 size_t TCP_Client_Write(tVFS_Node *Node, off_t Offset, size_t Length, const void *Buffer, Uint Flags);
53 int TCP_Client_IOCtl(tVFS_Node *Node, int ID, void *Data);
54 void TCP_Client_Close(tVFS_Node *Node);
56 int WrapBetween(Uint32 Lower, Uint32 Value, Uint32 Higher, Uint32 MaxValue);
57 Uint32 GetRelative(Uint32 Base, Uint32 Value);
60 tSocketFile gTCP_ServerFile = {NULL, "tcps", TCP_Server_Init};
61 tSocketFile gTCP_ClientFile = {NULL, "tcpc", TCP_Client_Init};
62 tVFS_NodeType gTCP_ServerNodeType = {
63 .TypeName = "TCP Server",
64 .ReadDir = TCP_Server_ReadDir,
65 .FindDir = TCP_Server_FindDir,
66 .IOCtl = TCP_Server_IOCtl,
67 .Close = TCP_Server_Close
69 tVFS_NodeType gTCP_ClientNodeType = {
70 .TypeName = "TCP Client/Connection",
71 .Flags = VFS_NODETYPEFLAG_STREAM,
72 .Read = TCP_Client_Read,
73 .Write = TCP_Client_Write,
74 .IOCtl = TCP_Client_IOCtl,
75 .Close = TCP_Client_Close
79 int giTCP_NumHalfopen = 0;
80 tShortSpinlock glTCP_Listeners;
81 tTCPListener *gTCP_Listeners;
82 tShortSpinlock glTCP_OutbountCons;
83 tTCPConnection *gTCP_OutbountCons;
84 Uint32 gaTCP_PortBitmap[0x800];
85 int giTCP_NextOutPort = TCP_MIN_DYNPORT;
89 * \brief Initialise the TCP Layer
91 * Registers the client and server files and the GetPacket callback
93 void TCP_Initialise(void)
95 giTCP_NextOutPort += rand()%128;
96 IPStack_AddFile(&gTCP_ServerFile);
97 IPStack_AddFile(&gTCP_ClientFile);
98 IPv4_RegisterCallback(IP4PROT_TCP, TCP_GetPacket, TCP_IPError);
99 IPv6_RegisterCallback(IP4PROT_TCP, TCP_GetPacket);
103 * \brief Sends a packet from the specified connection, calculating the checksums
104 * \param Conn Connection
105 * \param Length Length of data
106 * \param Data Packet data (cast as a TCP Header)
108 void TCP_SendPacket( tTCPConnection *Conn, tTCPHeader *Header, size_t Length, const void *Data )
110 TCP_int_SendPacket(Conn->Interface, &Conn->RemoteIP, Header, Length, Data);
113 Uint16 TCP_int_CalculateChecksum(int AddrType, const void *LAddr, const void *RAddr,
114 size_t HeaderLength, const tTCPHeader *Header, size_t DataLength, const void *Data)
116 size_t packlen = HeaderLength + DataLength;
123 buf[0] = ((tIPv4*)LAddr)->L;
124 buf[1] = ((tIPv4*)RAddr)->L;
125 buf[2] = htonl( (packlen) | (IP4PROT_TCP<<16) | (0<<24) );
126 checksum[0] = htons( ~IPv4_Checksum(buf, sizeof(buf)) ); // Partial checksum
130 memcpy(&buf[0], LAddr, 16);
131 memcpy(&buf[4], RAddr, 16);
132 buf[8] = htonl(packlen);
133 buf[9] = htonl(IP4PROT_TCP);
134 checksum[0] = htons( ~IPv4_Checksum(buf, sizeof(buf)) ); // Partial checksum
139 checksum[1] = htons( ~IPv4_Checksum(Header, HeaderLength) );
140 checksum[2] = htons( ~IPv4_Checksum(Data, DataLength) );
142 return htons( IPv4_Checksum(checksum, sizeof(checksum)) );
145 void TCP_int_SendPacket(tInterface *Interface, const void *Dest, tTCPHeader *Header, size_t Length, const void *Data )
147 tIPStackBuffer *buffer = IPStack_Buffer_CreateBuffer(2 + IPV4_BUFFERS);
149 IPStack_Buffer_AppendSubBuffer(buffer, Length, 0, Data, NULL, NULL);
150 IPStack_Buffer_AppendSubBuffer(buffer, sizeof(*Header), 0, Header, NULL, NULL);
153 Log_Log("TCP", "TCP_int_SendPacket: <Local>:%i to [%s]:%i (%i data), Flags = %s%s%s%s%s%s%s%s",
154 ntohs(Header->SourcePort),
155 IPStack_PrintAddress(Interface->Type, Dest),
156 ntohs(Header->DestPort),
158 (Header->Flags & TCP_FLAG_CWR) ? "CWR " : "",
159 (Header->Flags & TCP_FLAG_ECE) ? "ECE " : "",
160 (Header->Flags & TCP_FLAG_URG) ? "URG " : "",
161 (Header->Flags & TCP_FLAG_ACK) ? "ACK " : "",
162 (Header->Flags & TCP_FLAG_PSH) ? "PSH " : "",
163 (Header->Flags & TCP_FLAG_RST) ? "RST " : "",
164 (Header->Flags & TCP_FLAG_SYN) ? "SYN " : "",
165 (Header->Flags & TCP_FLAG_FIN) ? "FIN " : ""
169 Header->Checksum = 0;
170 Header->Checksum = TCP_int_CalculateChecksum(Interface->Type, Interface->Address, Dest,
171 sizeof(tTCPHeader), Header, Length, Data);
173 // TODO: Fragment packet
175 switch( Interface->Type )
178 IPv4_SendPacket(Interface, *(tIPv4*)Dest, IP4PROT_TCP, 0, buffer);
181 IPv6_SendPacket(Interface, *(tIPv6*)Dest, IP4PROT_TCP, buffer);
186 void TCP_int_SendRSTTo(tInterface *Interface, const void *Address, size_t Length, const tTCPHeader *Header)
188 tTCPHeader out_hdr = {0};
190 out_hdr.DataOffset = (sizeof(out_hdr)/4) << 4;
191 out_hdr.DestPort = Header->SourcePort;
192 out_hdr.SourcePort = Header->DestPort;
194 size_t data_len = Length - (Header->DataOffset>>4)*4;
195 out_hdr.AcknowlegementNumber = htonl( ntohl(Header->SequenceNumber) + data_len );
196 if( Header->Flags & TCP_FLAG_ACK ) {
197 out_hdr.Flags = TCP_FLAG_RST;
198 out_hdr.SequenceNumber = Header->AcknowlegementNumber;
201 out_hdr.Flags = TCP_FLAG_RST|TCP_FLAG_ACK;
202 out_hdr.SequenceNumber = 0;
204 TCP_int_SendPacket(Interface, Address, &out_hdr, 0, NULL);
208 * \brief Handles a packet from the IP Layer
209 * \param Interface Interface the packet arrived from
210 * \param Address Pointer to the addres structure
211 * \param Length Size of packet in bytes
212 * \param Buffer Packet data
214 void TCP_GetPacket(tInterface *Interface, void *Address, int Length, void *Buffer)
216 tTCPHeader *hdr = Buffer;
219 Log_Log("TCP", "TCP_GetPacket: <Local>:%i from [%s]:%i, Flags = %s%s%s%s%s%s%s%s",
220 ntohs(hdr->DestPort),
221 IPStack_PrintAddress(Interface->Type, Address),
222 ntohs(hdr->SourcePort),
223 (hdr->Flags & TCP_FLAG_CWR) ? "CWR " : "",
224 (hdr->Flags & TCP_FLAG_ECE) ? "ECE " : "",
225 (hdr->Flags & TCP_FLAG_URG) ? "URG " : "",
226 (hdr->Flags & TCP_FLAG_ACK) ? "ACK " : "",
227 (hdr->Flags & TCP_FLAG_PSH) ? "PSH " : "",
228 (hdr->Flags & TCP_FLAG_RST) ? "RST " : "",
229 (hdr->Flags & TCP_FLAG_SYN) ? "SYN " : "",
230 (hdr->Flags & TCP_FLAG_FIN) ? "FIN " : ""
234 if( Length > (hdr->DataOffset >> 4)*4 )
236 LOG("SequenceNumber = 0x%x", ntohl(hdr->SequenceNumber));
239 "TCP_GetPacket: Packet Data = ",
240 (Uint8*)hdr + (hdr->DataOffset >> 4)*4,
241 Length - (hdr->DataOffset >> 4)*4
247 for( tTCPListener *srv = gTCP_Listeners; srv; srv = srv->Next )
249 // Check if the server is active
250 if(srv->Port == 0) continue;
251 // Check the interface
252 if(srv->Interface && srv->Interface != Interface) continue;
253 // Check the destination port
254 if(srv->Port != htons(hdr->DestPort)) continue;
256 Log_Log("TCP", "TCP_GetPacket: Matches server %p", srv);
257 // Is this in an established connection?
258 for( tTCPConnection *conn = srv->Connections; conn; conn = conn->Next )
260 // Check that it is coming in on the same interface
261 if(conn->Interface != Interface) continue;
263 if(conn->RemotePort != ntohs(hdr->SourcePort)) continue;
265 if( IPStack_CompareAddress(conn->Interface->Type, &conn->RemoteIP, Address, -1) == 0 )
268 Log_Log("TCP", "TCP_GetPacket: Matches connection %p", conn);
269 // We have a response!
270 if( TCP_INT_HandleConnectionPacket(conn, hdr, Length) == 0 )
275 TCP_INT_HandleServerPacket(Interface, srv, Address, hdr, Length);
279 // Check Open Connections
281 for( tTCPConnection *conn = gTCP_OutbountCons; conn; conn = conn->Next )
283 // Check that it is coming in on the same interface
284 if(conn->Interface != Interface) continue;
287 if(conn->RemotePort != ntohs(hdr->SourcePort)) continue;
290 if( IPStack_CompareAddress(conn->Interface->Type, &conn->RemoteIP, Address, -1) == 0 )
293 // Handle or fall through
294 if( TCP_INT_HandleConnectionPacket(conn, hdr, Length) == 0 )
300 Log_Log("TCP", "TCP_GetPacket: No Match");
301 // If not a RST, send a RST
302 if( !(hdr->Flags & TCP_FLAG_RST) )
304 TCP_int_SendRSTTo(Interface, Address, Length, hdr);
308 void TCP_IPError(tInterface *Interface, tIPErrorMode Mode, const void *Address, int Length, const void *Buffer)
310 if( Length < sizeof(tTCPHeader) ) return ;
312 const tTCPHeader *hdr = Buffer;
314 // TODO: Handle errors for server connections
316 for( tTCPConnection *conn = gTCP_OutbountCons; conn; conn = conn->Next )
318 if(conn->Interface != Interface)
320 if(conn->RemotePort != ntohs(hdr->SourcePort))
322 if( IPStack_CompareAddress(conn->Interface->Type, &conn->RemoteIP, Address, -1) == 0 )
325 // Mark an error on the interface
326 VFS_MarkError(&conn->Node, 1);
332 * Handle packets in LISTEN state
334 int TCP_INT_HandleServerPacket(tInterface *Interface, tTCPListener *Server, const void *Address, tTCPHeader *Header, size_t Length)
336 if( Header->Flags & TCP_FLAG_RST ) {
340 else if( Header->Flags & TCP_FLAG_ACK ) {
341 LOG("ACK, send RST");
342 TCP_int_SendRSTTo(Interface, Address, Length, Header);
345 else if( !(Header->Flags & TCP_FLAG_SYN) ) {
346 LOG("Other, ignore");
350 Log_Log("TCP", "TCP_GetPacket: Opening Connection");
352 // TODO: Check security (a TCP Option)
353 // TODO: Check SEG.PRC
354 // TODO: Check for halfopen max
356 tTCPConnection *conn = TCP_int_CreateConnection(Interface, TCP_ST_SYN_RCVD);
357 conn->LocalPort = Server->Port;
358 conn->RemotePort = ntohs(Header->SourcePort);
360 switch(Interface->Type)
362 case 4: conn->RemoteIP.v4 = *(tIPv4*)Address; break;
363 case 6: conn->RemoteIP.v6 = *(tIPv6*)Address; break;
364 default: ASSERTC(Interface->Type,==,4); return 0;
367 conn->NextSequenceRcv = ntohl( Header->SequenceNumber ) + 1;
368 conn->HighestSequenceRcvd = conn->NextSequenceRcv;
369 conn->NextSequenceSend = rand();
370 conn->LastACKSequence = ntohl( Header->SequenceNumber );
372 conn->Node.ImplInt = Server->NextID ++;
373 conn->Node.Size = -1;
375 // Hmm... Theoretically, this lock will never have to wait,
376 // as the interface is locked to the watching thread, and this
377 // runs in the watching thread. But, it's a good idea to have
379 // Oh, wait, there is a case where a wildcard can be used
380 // (Server->Interface == NULL) so having the lock is a good idea
381 SHORTLOCK(&Server->lConnections);
382 conn->Server = Server;
383 conn->Prev = Server->ConnectionsTail;
384 if(Server->Connections) {
385 ASSERT(Server->ConnectionsTail);
386 Server->ConnectionsTail->Next = conn;
389 ASSERT(!Server->ConnectionsTail);
390 Server->Connections = conn;
392 Server->ConnectionsTail = conn;
393 if(!Server->NewConnections)
394 Server->NewConnections = conn;
395 VFS_MarkAvaliable( &Server->Node, 1 );
396 SHORTREL(&Server->lConnections);
397 Semaphore_Signal(&Server->WaitingConnections, 1);
400 Header->Flags = TCP_FLAG_ACK|TCP_FLAG_SYN;
401 Header->AcknowlegementNumber = htonl(conn->NextSequenceRcv);
402 Header->SequenceNumber = htonl(conn->NextSequenceSend);
403 Header->DestPort = Header->SourcePort;
404 Header->SourcePort = htons(Server->Port);
405 Header->DataOffset = (sizeof(tTCPHeader)/4) << 4;
406 TCP_SendPacket( conn, Header, 0, NULL );
407 conn->NextSequenceSend ++;
412 * \brief Handles a packet sent to a specific connection
413 * \param Connection TCP Connection pointer
414 * \param Header TCP Packet pointer
415 * \param Length Length of the packet
417 int TCP_INT_HandleConnectionPacket(tTCPConnection *Connection, tTCPHeader *Header, int Length)
422 // Silently drop once finished
423 // TODO: Check if this needs to be here
424 if( Connection->State == TCP_ST_FINISHED ) {
425 Log_Log("TCP", "Packet ignored - connection finnished");
428 if( Connection->State == TCP_ST_FORCE_CLOSE ) {
429 Log_Log("TCP", "Packet ignored - connection reset");
433 // Syncronise sequence values
434 if(Header->Flags & TCP_FLAG_SYN) {
435 // TODO: What if the packet also has data?
436 if( Connection->LastACKSequence != Connection->NextSequenceRcv )
437 TCP_INT_SendACK(Connection, "SYN");
438 Connection->NextSequenceRcv = ntohl(Header->SequenceNumber);
439 // TODO: Process HighestSequenceRcvd
441 if( Connection->HighestSequenceRcvd == 0 )
442 Connection->HighestSequenceRcvd = Connection->NextSequenceRcv;
443 Connection->LastACKSequence = Connection->NextSequenceRcv;
446 // Ackowledge a sent packet
447 if(Header->Flags & TCP_FLAG_ACK) {
448 // TODO: Process an ACKed Packet
449 LOG("Conn %p, Sent packet 0x%x ACKed", Connection, Header->AcknowlegementNumber);
452 // Get length of data
453 dataLen = Length - (Header->DataOffset>>4)*4;
454 LOG("dataLen = %i", dataLen);
456 Log_Debug("TCP", "State %i, dataLen = %x", Connection->State, dataLen);
462 switch( Connection->State )
464 // Pre-init connection?
466 Log_Log("TCP", "Packets to a closed connection?!");
469 // --- Init States ---
470 // SYN sent, expecting SYN-ACK Connection Opening
471 case TCP_ST_SYN_SENT:
472 if( Header->Flags & TCP_FLAG_SYN )
474 if( Connection->HighestSequenceRcvd == Connection->NextSequenceRcv )
475 Connection->HighestSequenceRcvd ++;
476 Connection->NextSequenceRcv ++;
478 if( Header->Flags & TCP_FLAG_ACK )
480 Log_Log("TCP", "ACKing SYN-ACK");
481 Connection->State = TCP_ST_ESTABLISHED;
482 VFS_MarkFull(&Connection->Node, 0);
483 TCP_INT_SendACK(Connection, "SYN-ACK");
487 Log_Log("TCP", "ACKing SYN");
488 Connection->State = TCP_ST_SYN_RCVD;
489 TCP_INT_SendACK(Connection, "SYN");
494 // SYN-ACK sent, expecting ACK
495 case TCP_ST_SYN_RCVD:
496 if( Header->Flags & TCP_FLAG_RST )
498 Log_Log("TCP", "RST Received, closing");
499 Connection->State = TCP_ST_FORCE_CLOSE;
500 VFS_MarkError(&Connection->Node, 1);
503 if( Header->Flags & TCP_FLAG_ACK )
505 // TODO: Handle max half-open limit
506 Log_Log("TCP", "Connection fully opened");
507 Connection->State = TCP_ST_ESTABLISHED;
508 VFS_MarkFull(&Connection->Node, 0);
512 // --- Established State ---
513 case TCP_ST_ESTABLISHED:
514 // - Handle State changes
516 if( Header->Flags & TCP_FLAG_RST )
518 Log_Log("TCP", "Conn %p closed, received RST");
519 // Error outstanding transactions
520 Connection->State = TCP_ST_FORCE_CLOSE;
521 VFS_MarkError(&Connection->Node, 1);
524 if( Header->Flags & TCP_FLAG_FIN ) {
525 Log_Log("TCP", "Conn %p closed, recieved FIN", Connection);
526 VFS_MarkError(&Connection->Node, 1);
527 Connection->NextSequenceRcv ++;
528 TCP_INT_SendACK(Connection, "FIN Received");
529 Connection->State = TCP_ST_CLOSE_WAIT;
530 // CLOSE WAIT requires the client to close
534 // Check for an empty packet
536 if( Header->Flags == TCP_FLAG_ACK )
538 Log_Log("TCP", "ACK only packet");
541 // TODO: Is this right? (empty packet counts as one byte)
542 if( Connection->HighestSequenceRcvd == Connection->NextSequenceRcv )
543 Connection->HighestSequenceRcvd ++;
544 Connection->NextSequenceRcv ++;
545 Log_Log("TCP", "Empty Packet, inc and ACK the current sequence number");
546 TCP_INT_SendACK(Connection, "Empty");
555 sequence_num = ntohl(Header->SequenceNumber);
557 LOG("0x%08x <= 0x%08x < 0x%08x",
558 Connection->NextSequenceRcv,
559 ntohl(Header->SequenceNumber),
560 Connection->NextSequenceRcv + TCP_WINDOW_SIZE
563 // Is this packet the next expected packet?
564 if( sequence_num == Connection->NextSequenceRcv )
567 // Ooh, Goodie! Add it to the recieved list
568 rv = TCP_INT_AppendRecieved(Connection,
569 (Uint8*)Header + (Header->DataOffset>>4)*4,
573 Log_Notice("TCP", "TCP_INT_AppendRecieved rv %i", rv);
576 LOG("0x%08x += %i", Connection->NextSequenceRcv, dataLen);
577 if( Connection->HighestSequenceRcvd == Connection->NextSequenceRcv )
578 Connection->HighestSequenceRcvd += dataLen;
579 Connection->NextSequenceRcv += dataLen;
581 // TODO: This should be moved out of the watcher thread,
582 // so that a single lost packet on one connection doesn't cause
583 // all connections on the interface to lag.
584 // - Meh, no real issue, as the cache shouldn't be that large
585 TCP_INT_UpdateRecievedFromFuture(Connection);
588 // - Only send an ACK if we've had a burst
589 Uint32 bytes_since_last_ack = Connection->NextSequenceRcv - Connection->LastACKSequence;
590 LOG("bytes_since_last_ack = 0x%x", bytes_since_last_ack);
591 if( bytes_since_last_ack > TCP_DACK_THRESHOLD )
593 TCP_INT_SendACK(Connection, "DACK Burst");
594 // - Extend TCP deferred ACK timer
595 Time_RemoveTimer(Connection->DeferredACKTimer);
597 // - Schedule the deferred ACK timer (if already scheduled, this is a NOP)
598 Time_ScheduleTimer(Connection->DeferredACKTimer, TCP_DACK_TIMEOUT);
600 TCP_INT_SendACK(Connection, "RX");
603 // Check if the packet is in window
604 else if( sequence_num - Connection->NextSequenceRcv < TCP_WINDOW_SIZE )
606 Uint8 *dataptr = (Uint8*)Header + (Header->DataOffset>>4)*4;
607 Uint32 index = sequence_num % TCP_WINDOW_SIZE;
608 Uint32 max = Connection->NextSequenceRcv % TCP_WINDOW_SIZE;
609 if( !(Connection->FuturePacketValidBytes[index/8] & (1 << (index%8))) )
610 TCP_INT_SendACK(Connection, "Lost packet");
611 for( int i = 0; i < dataLen; i ++ )
613 Connection->FuturePacketValidBytes[index/8] |= 1 << (index%8);
614 Connection->FuturePacketData[index] = dataptr[i];
615 // Do a wrap increment
617 if(index == TCP_WINDOW_SIZE) index = 0;
618 if(index == max) break;
620 Uint32 rel_highest = Connection->HighestSequenceRcvd - Connection->NextSequenceRcv;
621 Uint32 rel_this = index - Connection->NextSequenceRcv;
622 LOG("Updating highest this(0x%x) > highest(%x)", rel_this, rel_highest);
623 if( rel_this > rel_highest )
625 Connection->HighestSequenceRcvd = index;
628 // Badly out of sequence packet
631 Log_Log("TCP", "Fully out of sequence packet (0x%08x not between 0x%08x and 0x%08x), dropped",
632 sequence_num, Connection->NextSequenceRcv, Connection->NextSequenceRcv+TCP_WINDOW_SIZE);
633 // Spec says we should send an empty ACK with the current state
634 TCP_INT_SendACK(Connection, "Bad Seq");
638 // --- Remote close states
639 case TCP_ST_CLOSE_WAIT:
641 // Ignore everything, CLOSE_WAIT is terminated by the client
642 Log_Debug("TCP", "CLOSE WAIT - Ignoring packets");
646 // LAST-ACK - Waiting for the ACK of FIN (from CLOSE WAIT)
647 case TCP_ST_LAST_ACK:
648 if( Header->Flags & TCP_FLAG_ACK )
650 Connection->State = TCP_ST_FINISHED; // Connection completed
651 Log_Log("TCP", "LAST-ACK to CLOSED - Connection remote closed");
652 TCP_int_FreeTCB(Connection);
656 // --- Local close States
657 case TCP_ST_FIN_WAIT1:
658 if( Header->Flags & TCP_FLAG_FIN )
660 Connection->State = TCP_ST_CLOSING;
661 Log_Debug("TCP", "Conn %p closed, sent FIN and recieved FIN", Connection);
662 VFS_MarkError(&Connection->Node, 1);
664 TCP_INT_SendACK(Connection, "FINWAIT-1 FIN");
668 // TODO: Make sure that the packet is actually ACKing the FIN
669 if( Header->Flags & TCP_FLAG_ACK )
671 Connection->State = TCP_ST_FIN_WAIT2;
672 Log_Debug("TCP", "Conn %p closed, sent FIN ACKed", Connection);
673 VFS_MarkError(&Connection->Node, 1);
678 case TCP_ST_FIN_WAIT2:
679 if( Header->Flags & TCP_FLAG_FIN )
681 Connection->State = TCP_ST_TIME_WAIT;
682 Log_Debug("TCP", "Conn %p FINWAIT-2 -> TIME WAIT", Connection);
683 TCP_INT_SendACK(Connection, "FINWAIT-2 FIN");
688 // TODO: Make sure that the packet is actually ACKing the FIN
689 if( Header->Flags & TCP_FLAG_ACK )
691 Connection->State = TCP_ST_TIME_WAIT;
692 Log_Debug("TCP", "Conn %p CLOSING -> TIME WAIT", Connection);
693 VFS_MarkError(&Connection->Node, 1);
698 // --- Closed (or near closed) states) ---
699 case TCP_ST_TIME_WAIT:
700 Log_Log("TCP", "Packets on Time-Wait, ignored");
703 case TCP_ST_FINISHED:
704 Log_Log("TCP", "Packets when CLOSED, ignoring");
706 case TCP_ST_FORCE_CLOSE:
707 Log_Log("TCP", "Packets when force CLOSED, ignoring");
711 // Log_Warning("TCP", "Unhandled TCP state %i", Connection->State);
720 * \brief Appends a packet to the recieved list
721 * \param Connection Connection structure
722 * \param Data Packet contents
723 * \param Length Length of \a Data
725 int TCP_INT_AppendRecieved(tTCPConnection *Connection, const void *Data, size_t Length)
727 Mutex_Acquire( &Connection->lRecievedPackets );
729 if(Connection->RecievedBuffer->Length + Length > Connection->RecievedBuffer->Space )
731 VFS_MarkAvaliable(&Connection->Node, 1);
732 Log_Error("TCP", "Buffer filled, packet dropped (:%i) - %i + %i > %i",
733 Connection->LocalPort, Connection->RecievedBuffer->Length, Length,
734 Connection->RecievedBuffer->Space
736 Mutex_Release( &Connection->lRecievedPackets );
740 RingBuffer_Write( Connection->RecievedBuffer, Data, Length );
742 VFS_MarkAvaliable(&Connection->Node, 1);
744 Mutex_Release( &Connection->lRecievedPackets );
749 * \brief Updates the connections recieved list from the future list
750 * \param Connection Connection structure
752 * Updates the recieved packets list with packets from the future (out
753 * of order) packets list that are now able to be added in direct
756 void TCP_INT_UpdateRecievedFromFuture(tTCPConnection *Connection)
758 // Calculate length of contiguous bytes
759 const size_t length = Connection->HighestSequenceRcvd - Connection->NextSequenceRcv;
760 Uint32 index = Connection->NextSequenceRcv % TCP_WINDOW_SIZE;
761 size_t runlength = length;
762 LOG("HSR=0x%x,NSR=0x%x", Connection->HighestSequenceRcvd, Connection->NextSequenceRcv);
763 if( Connection->HighestSequenceRcvd == Connection->NextSequenceRcv )
767 LOG("length=%u, index=0x%x", length, index);
768 for( int i = 0; i < length; i ++ )
771 Uint8 bitfield_byte = Connection->FuturePacketValidBytes[index / 8];
772 if( (bitfield_byte & (1 << bit)) == 0 ) {
774 LOG("Hit missing, break");
778 if( bitfield_byte == 0xFF ) {
786 if(index > TCP_WINDOW_SIZE)
787 index -= TCP_WINDOW_SIZE;
790 index = Connection->NextSequenceRcv % TCP_WINDOW_SIZE;
791 Connection->NextSequenceRcv += runlength;
793 // Write data to to the ring buffer
794 if( TCP_WINDOW_SIZE - index > runlength )
797 RingBuffer_Write( Connection->RecievedBuffer, Connection->FuturePacketData + index, runlength );
801 int endLen = TCP_WINDOW_SIZE - index;
803 RingBuffer_Write( Connection->RecievedBuffer, Connection->FuturePacketData + index, endLen );
804 RingBuffer_Write( Connection->RecievedBuffer, Connection->FuturePacketData, endLen - runlength );
807 // Mark (now saved) bytes as invalid
809 while(index % 8 && runlength > 0)
811 Connection->FuturePacketData[index] = 0;
812 Connection->FuturePacketValidBytes[index/8] &= ~(1 << (index%8));
814 if(index > TCP_WINDOW_SIZE)
815 index -= TCP_WINDOW_SIZE;
818 while( runlength > 7 )
820 Connection->FuturePacketData[index] = 0;
821 Connection->FuturePacketValidBytes[index/8] = 0;
824 if(index > TCP_WINDOW_SIZE)
825 index -= TCP_WINDOW_SIZE;
827 while( runlength > 0)
829 Connection->FuturePacketData[index] = 0;
830 Connection->FuturePacketData[index/8] &= ~(1 << (index%8));
832 if(index > TCP_WINDOW_SIZE)
833 index -= TCP_WINDOW_SIZE;
838 void TCP_int_SendDelayedACK(void *ConnPtr)
840 TCP_INT_SendACK(ConnPtr, "DACK Timeout");
843 void TCP_INT_SendACK(tTCPConnection *Connection, const char *Reason)
847 hdr.DataOffset = (sizeof(tTCPHeader)/4) << 4;
848 hdr.DestPort = htons(Connection->RemotePort);
849 hdr.SourcePort = htons(Connection->LocalPort);
850 hdr.AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
851 hdr.SequenceNumber = htonl(Connection->NextSequenceSend);
852 hdr.WindowSize = htons(TCP_WINDOW_SIZE);
853 hdr.Flags = TCP_FLAG_ACK; // TODO: Determine if SYN is wanted too
854 hdr.Checksum = 0; // TODO: Checksum
855 hdr.UrgentPointer = 0;
856 Log_Debug("TCP", "Sending ACK for 0x%08x (%s)", Connection->NextSequenceRcv, Reason);
857 TCP_SendPacket( Connection, &hdr, 0, NULL );
858 //Connection->NextSequenceSend ++;
859 Connection->LastACKSequence = Connection->NextSequenceRcv;
863 * \fn Uint16 TCP_GetUnusedPort()
864 * \brief Gets an unused port and allocates it
866 Uint16 TCP_GetUnusedPort()
870 // Get Next outbound port
871 ret = giTCP_NextOutPort++;
872 while( gaTCP_PortBitmap[ret/32] & (1UL << (ret%32)) )
876 if(giTCP_NextOutPort == 0x10000) {
877 ret = giTCP_NextOutPort = TCP_MIN_DYNPORT;
881 // Mark the new port as used
882 gaTCP_PortBitmap[ret/32] |= 1 << (ret%32);
888 * \fn int TCP_AllocatePort(Uint16 Port)
889 * \brief Marks a port as used
891 int TCP_AllocatePort(Uint16 Port)
893 // Check if the port has already been allocated
894 if( gaTCP_PortBitmap[Port/32] & (1 << (Port%32)) )
898 gaTCP_PortBitmap[Port/32] |= 1 << (Port%32);
904 * \fn int TCP_DeallocatePort(Uint16 Port)
905 * \brief Marks a port as unused
907 int TCP_DeallocatePort(Uint16 Port)
909 // Check if the port has already been allocated
910 if( !(gaTCP_PortBitmap[Port/32] & (1 << (Port%32))) )
914 gaTCP_PortBitmap[Port/32] &= ~(1 << (Port%32));
919 tTCPConnection *TCP_int_CreateConnection(tInterface *Interface, enum eTCPConnectionState State)
921 tTCPConnection *conn = calloc( sizeof(tTCPConnection) + TCP_WINDOW_SIZE + TCP_WINDOW_SIZE/8, 1 );
924 conn->Interface = Interface;
925 conn->LocalPort = -1;
926 conn->RemotePort = -1;
928 conn->Node.Size = -1;
929 conn->Node.ReferenceCount = 1;
930 conn->Node.ImplPtr = conn;
931 conn->Node.NumACLs = 1;
932 conn->Node.ACLs = &gVFS_ACL_EveryoneRW;
933 conn->Node.Type = &gTCP_ClientNodeType;
934 conn->Node.BufferFull = 1; // Cleared when connection opens
936 conn->RecievedBuffer = RingBuffer_Create( TCP_RECIEVE_BUFFER_SIZE );
938 conn->SentBuffer = RingBuffer_Create( TCP_SEND_BUFFER_SIZE );
939 Semaphore_Init(conn->SentBufferSpace, 0, TCP_SEND_BUFFER_SIZE, "TCP SentBuffer", conn->Name);
942 conn->HighestSequenceRcvd = 0;
943 #if CACHE_FUTURE_PACKETS_IN_BYTES
944 // Future recieved data (ahead of the expected sequence number)
945 conn->FuturePacketData = (Uint8*)conn + sizeof(tTCPConnection);
946 conn->FuturePacketValidBytes = conn->FuturePacketData + TCP_WINDOW_SIZE;
949 conn->DeferredACKTimer = Time_AllocateTimer( TCP_int_SendDelayedACK, conn);
953 void TCP_int_FreeTCB(tTCPConnection *Connection)
955 ASSERTC(Connection->State, ==, TCP_ST_FINISHED);
956 ASSERTC(Connection->Node.ReferenceCount, ==, 0);
958 if( Connection->Server )
960 tTCPListener *srv = Connection->Server;
961 SHORTLOCK(&srv->lConnections);
963 Connection->Prev->Next = Connection->Next;
965 srv->Connections = Connection->Next;
967 Connection->Next->Prev = Connection->Prev;
969 ASSERT(srv->ConnectionsTail == Connection);
970 srv->ConnectionsTail = Connection->Prev;
972 SHORTREL(&srv->lConnections);
976 SHORTLOCK(&glTCP_OutbountCons);
978 Connection->Prev->Next = Connection->Next;
980 gTCP_OutbountCons = Connection->Next;
982 Connection->Next->Prev = Connection->Prev;
985 SHORTREL(&glTCP_OutbountCons);
988 RingBuffer_Free(Connection->RecievedBuffer);
989 Time_FreeTimer(Connection->DeferredACKTimer);
990 // TODO: Force VFS to close handles? (they should all be closed);
995 tVFS_Node *TCP_Server_Init(tInterface *Interface)
999 srv = calloc( 1, sizeof(tTCPListener) );
1002 Log_Warning("TCP", "malloc failed for listener (%i) bytes", sizeof(tTCPListener));
1006 srv->Interface = Interface;
1009 srv->Connections = NULL;
1010 srv->ConnectionsTail = NULL;
1011 srv->NewConnections = NULL;
1013 srv->Node.Flags = VFS_FFLAG_DIRECTORY;
1014 srv->Node.Size = -1;
1015 srv->Node.ImplPtr = srv;
1016 srv->Node.NumACLs = 1;
1017 srv->Node.ACLs = &gVFS_ACL_EveryoneRW;
1018 srv->Node.Type = &gTCP_ServerNodeType;
1020 SHORTLOCK(&glTCP_Listeners);
1021 srv->Next = gTCP_Listeners;
1022 gTCP_Listeners = srv;
1023 SHORTREL(&glTCP_Listeners);
1029 * \brief Wait for a new connection and return the connection ID
1030 * \note Blocks until a new connection is made
1031 * \param Node Server node
1032 * \param Pos Position (ignored)
1034 int TCP_Server_ReadDir(tVFS_Node *Node, int Pos, char Dest[FILENAME_MAX])
1036 tTCPListener *srv = Node->ImplPtr;
1037 tTCPConnection *conn;
1039 ENTER("pNode iPos", Node, Pos);
1041 Log_Log("TCP", "Thread %i waiting for a connection", Threads_GetTID());
1042 Semaphore_Wait( &srv->WaitingConnections, 1 );
1044 SHORTLOCK(&srv->lConnections);
1045 // Increment the new list (the current connection is still on the
1047 conn = srv->NewConnections;
1048 srv->NewConnections = conn->Next;
1050 if( srv->NewConnections == NULL )
1051 VFS_MarkAvaliable( Node, 0 );
1053 SHORTREL( &srv->lConnections );
1055 LOG("conn = %p", conn);
1056 LOG("srv->Connections = %p", srv->Connections);
1057 LOG("srv->NewConnections = %p", srv->NewConnections);
1058 LOG("srv->ConnectionsTail = %p", srv->ConnectionsTail);
1060 itoa(Dest, conn->Node.ImplInt, 16, 8, '0');
1061 Log_Log("TCP", "Thread %i got connection '%s'", Threads_GetTID(), Dest);
1067 * \brief Gets a client connection node
1068 * \param Node Server node
1069 * \param Name Hexadecimal ID of the node
1071 tVFS_Node *TCP_Server_FindDir(tVFS_Node *Node, const char *Name, Uint Flags)
1073 tTCPConnection *conn;
1074 tTCPListener *srv = Node->ImplPtr;
1076 int id = atoi(Name);
1078 ENTER("pNode sName", Node, Name);
1080 // Check for a non-empty name
1084 itoa(tmp, id, 16, 8, '0');
1085 if(strcmp(tmp, Name) != 0) {
1086 LOG("'%s' != '%s' (%08x)", Name, tmp, id);
1091 Log_Debug("TCP", "srv->Connections = %p", srv->Connections);
1092 Log_Debug("TCP", "srv->NewConnections = %p", srv->NewConnections);
1093 Log_Debug("TCP", "srv->ConnectionsTail = %p", srv->ConnectionsTail);
1096 SHORTLOCK( &srv->lConnections );
1097 for(conn = srv->Connections;
1101 LOG("conn->Node.ImplInt = %i", conn->Node.ImplInt);
1102 if(conn->Node.ImplInt == id) break;
1104 SHORTREL( &srv->lConnections );
1106 // If not found, ret NULL
1108 LOG("Connection %i not found", id);
1113 // Empty Name - Check for a new connection and if it's there, open it
1116 SHORTLOCK( &srv->lConnections );
1117 conn = srv->NewConnections;
1119 srv->NewConnections = conn->Next;
1120 VFS_MarkAvaliable( Node, srv->NewConnections != NULL );
1121 SHORTREL( &srv->lConnections );
1123 LOG("No new connections");
1130 LEAVE('p', &conn->Node);
1135 * \brief Handle IOCtl calls
1137 int TCP_Server_IOCtl(tVFS_Node *Node, int ID, void *Data)
1139 tTCPListener *srv = Node->ImplPtr;
1143 case 4: // Get/Set Port
1144 if(!Data) // Get Port
1147 if(srv->Port) // Wait, you can't CHANGE the port
1150 if(!CheckMem(Data, sizeof(Uint16))) // Sanity check
1153 // Permissions check
1154 if(Threads_GetUID() != 0
1155 && *(Uint16*)Data != 0
1156 && *(Uint16*)Data < 1024)
1159 // TODO: Check if a port is in use
1162 srv->Port = *(Uint16*)Data;
1163 if(srv->Port == 0) // Allocate a random port
1164 srv->Port = TCP_GetUnusedPort();
1165 else // Else, mark this as used
1166 TCP_AllocatePort(srv->Port);
1168 Log_Log("TCP", "Server %p listening on port %i", srv, srv->Port);
1175 void TCP_Server_Close(tVFS_Node *Node)
1177 free(Node->ImplPtr);
1182 * \brief Create a client node
1184 tVFS_Node *TCP_Client_Init(tInterface *Interface)
1186 tTCPConnection *conn = TCP_int_CreateConnection(Interface, TCP_ST_CLOSED);
1188 SHORTLOCK(&glTCP_OutbountCons);
1189 conn->Server = NULL;
1191 conn->Next = gTCP_OutbountCons;
1192 if(gTCP_OutbountCons)
1193 gTCP_OutbountCons->Prev = conn;
1194 gTCP_OutbountCons = conn;
1195 SHORTREL(&glTCP_OutbountCons);
1201 * \brief Wait for a packet and return it
1202 * \note If \a Length is smaller than the size of the packet, the rest
1203 * of the packet's data will be discarded.
1205 size_t TCP_Client_Read(tVFS_Node *Node, off_t Offset, size_t Length, void *Buffer, Uint Flags)
1207 tTCPConnection *conn = Node->ImplPtr;
1210 ENTER("pNode XOffset xLength pBuffer", Node, Offset, Length, Buffer);
1211 LOG("conn = %p {State:%i}", conn, conn->State);
1213 // If the connection has been closed (state > ST_OPEN) then clear
1214 // any stale data in the buffer (until it is empty (until it is empty))
1215 if( conn->State > TCP_ST_ESTABLISHED )
1217 LOG("Connection closed");
1218 Mutex_Acquire( &conn->lRecievedPackets );
1219 len = RingBuffer_Read( Buffer, conn->RecievedBuffer, Length );
1220 Mutex_Release( &conn->lRecievedPackets );
1223 VFS_MarkAvaliable(Node, 0);
1235 tTime *timeout = NULL;
1236 tTime timeout_zero = 0;
1237 if( Flags & VFS_IOFLAG_NOBLOCK )
1238 timeout = &timeout_zero;
1239 if( !VFS_SelectNode(Node, VFS_SELECT_READ|VFS_SELECT_ERROR, timeout, "TCP_Client_Read") ) {
1240 errno = EWOULDBLOCK;
1246 // Lock list and read as much as possible (up to `Length`)
1247 Mutex_Acquire( &conn->lRecievedPackets );
1248 len = RingBuffer_Read( Buffer, conn->RecievedBuffer, Length );
1250 if( len == 0 || conn->RecievedBuffer->Length == 0 ) {
1251 LOG("Marking as none avaliable (len = %i)", len);
1252 VFS_MarkAvaliable(Node, 0);
1255 // Release the lock (we don't need it any more)
1256 Mutex_Release( &conn->lRecievedPackets );
1263 * \brief Send a data packet on a connection
1265 void TCP_INT_SendDataPacket(tTCPConnection *Connection, size_t Length, const void *Data)
1267 char buf[sizeof(tTCPHeader)+Length];
1268 tTCPHeader *packet = (void*)buf;
1270 // - Stop Delayed ACK timer (as this data packet ACKs)
1271 Time_RemoveTimer(Connection->DeferredACKTimer);
1273 // TODO: Don't exceed window size
1275 packet->SourcePort = htons(Connection->LocalPort);
1276 packet->DestPort = htons(Connection->RemotePort);
1277 packet->DataOffset = (sizeof(tTCPHeader)/4)*16;
1278 packet->WindowSize = htons(TCP_WINDOW_SIZE);
1280 packet->AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
1281 packet->SequenceNumber = htonl(Connection->NextSequenceSend);
1282 packet->Flags = TCP_FLAG_PSH|TCP_FLAG_ACK; // Hey, ACK if you can!
1283 packet->UrgentPointer = 0;
1285 memcpy(packet->Options, Data, Length);
1287 Log_Debug("TCP", "Send sequence 0x%08x", Connection->NextSequenceSend);
1288 #if HEXDUMP_OUTGOING
1289 Debug_HexDump("TCP_INT_SendDataPacket: Data = ", Data, Length);
1292 TCP_SendPacket( Connection, packet, Length, Data );
1294 // TODO: Start a retransmit time (if data is not ACKed in x seconds, send again)
1296 Connection->NextSequenceSend += Length;
1300 * \brief Send some bytes on a connection
1302 size_t TCP_Client_Write(tVFS_Node *Node, off_t Offset, size_t Length, const void *Buffer, Uint Flags)
1304 tTCPConnection *conn = Node->ImplPtr;
1305 size_t rem = Length;
1307 ENTER("pNode XOffset XLength pBuffer", Node, Offset, Length, Buffer);
1310 // Debug_HexDump("TCP_Client_Write: Buffer = ",
1314 // Don't allow a write to a closed connection
1315 if( conn->State > TCP_ST_ESTABLISHED ) {
1316 VFS_MarkError(Node, 1);
1324 tTime *timeout = NULL;
1325 tTime timeout_zero = 0;
1326 if( Flags & VFS_IOFLAG_NOBLOCK )
1327 timeout = &timeout_zero;
1328 if( !VFS_SelectNode(Node, VFS_SELECT_WRITE|VFS_SELECT_ERROR, timeout, "TCP_Client_Write") ) {
1329 errno = EWOULDBLOCK;
1337 int len = (rem < TCP_MAX_PACKET_SIZE) ? rem : TCP_MAX_PACKET_SIZE;
1340 // Wait for space in the buffer
1341 Semaphore_Signal( &Connection->SentBufferSpace, len );
1343 // Save data to buffer (and update the length read by the ammount written)
1344 len = RingBuffer_Write( &Connection->SentBuffer, Buffer, len);
1348 TCP_INT_SendDataPacket(conn, len, Buffer);
1359 * \brief Open a connection to another host using TCP
1360 * \param Conn Connection structure
1362 void TCP_StartConnection(tTCPConnection *Conn)
1364 tTCPHeader hdr = {0};
1366 Conn->State = TCP_ST_SYN_SENT;
1368 hdr.SourcePort = htons(Conn->LocalPort);
1369 hdr.DestPort = htons(Conn->RemotePort);
1370 Conn->NextSequenceSend = rand();
1371 hdr.SequenceNumber = htonl(Conn->NextSequenceSend);
1372 hdr.DataOffset = (sizeof(tTCPHeader)/4) << 4;
1373 hdr.Flags = TCP_FLAG_SYN;
1374 hdr.WindowSize = htons(TCP_WINDOW_SIZE); // Max
1375 hdr.Checksum = 0; // TODO
1377 TCP_SendPacket( Conn, &hdr, 0, NULL );
1379 Conn->NextSequenceSend ++;
1380 Conn->State = TCP_ST_SYN_SENT;
1386 * \brief Control a client socket
1388 int TCP_Client_IOCtl(tVFS_Node *Node, int ID, void *Data)
1390 tTCPConnection *conn = Node->ImplPtr;
1392 ENTER("pNode iID pData", Node, ID, Data);
1396 case 4: // Get/Set local port
1398 LEAVE_RET('i', conn->LocalPort);
1399 if(conn->State != TCP_ST_CLOSED)
1401 if(!CheckMem(Data, sizeof(Uint16)))
1404 if(Threads_GetUID() != 0 && *(Uint16*)Data < 1024)
1407 conn->LocalPort = *(Uint16*)Data;
1408 LEAVE_RET('i', conn->LocalPort);
1410 case 5: // Get/Set remote port
1411 if(!Data) LEAVE_RET('i', conn->RemotePort);
1412 if(conn->State != TCP_ST_CLOSED) LEAVE_RET('i', -1);
1413 if(!CheckMem(Data, sizeof(Uint16))) LEAVE_RET('i', -1);
1414 conn->RemotePort = *(Uint16*)Data;
1415 LEAVE_RET('i', conn->RemotePort);
1417 case 6: // Set Remote IP
1418 if( conn->State != TCP_ST_CLOSED )
1420 if( conn->Interface->Type == 4 )
1422 if(!CheckMem(Data, sizeof(tIPv4))) LEAVE_RET('i', -1);
1423 conn->RemoteIP.v4 = *(tIPv4*)Data;
1425 else if( conn->Interface->Type == 6 )
1427 if(!CheckMem(Data, sizeof(tIPv6))) LEAVE_RET('i', -1);
1428 conn->RemoteIP.v6 = *(tIPv6*)Data;
1433 if(conn->LocalPort == 0xFFFF)
1434 conn->LocalPort = TCP_GetUnusedPort();
1435 if(conn->RemotePort == -1)
1439 tTime timeout = conn->Interface->TimeoutDelay;
1441 TCP_StartConnection(conn);
1442 VFS_SelectNode(&conn->Node, VFS_SELECT_WRITE, &timeout, "TCP Connection");
1443 if( conn->State == TCP_ST_SYN_SENT )
1449 // Get recieve buffer length
1451 LEAVE_RET('i', conn->RecievedBuffer->Length);
1457 void TCP_Client_Close(tVFS_Node *Node)
1459 tTCPConnection *conn = Node->ImplPtr;
1462 ENTER("pNode", Node);
1464 ASSERT(Node->ReferenceCount != 0);
1466 if( Node->ReferenceCount > 1 ) {
1467 Node->ReferenceCount --;
1468 LOG("Dereference only");
1472 Node->ReferenceCount --;
1474 if( conn->State == TCP_ST_CLOSE_WAIT || conn->State == TCP_ST_ESTABLISHED )
1476 packet.SourcePort = htons(conn->LocalPort);
1477 packet.DestPort = htons(conn->RemotePort);
1478 packet.DataOffset = (sizeof(tTCPHeader)/4)*16;
1479 packet.WindowSize = TCP_WINDOW_SIZE;
1481 packet.AcknowlegementNumber = 0;
1482 packet.SequenceNumber = htonl(conn->NextSequenceSend);
1483 packet.Flags = TCP_FLAG_FIN;
1485 TCP_SendPacket( conn, &packet, 0, NULL );
1488 Time_RemoveTimer(conn->DeferredACKTimer);
1490 switch( conn->State )
1493 Log_Warning("TCP", "Closing connection that was never opened");
1494 TCP_int_FreeTCB(conn);
1496 case TCP_ST_FORCE_CLOSE:
1497 conn->State = TCP_ST_FINISHED;
1498 TCP_int_FreeTCB(conn);
1500 case TCP_ST_CLOSE_WAIT:
1501 conn->State = TCP_ST_LAST_ACK;
1503 case TCP_ST_ESTABLISHED:
1504 conn->State = TCP_ST_FIN_WAIT1;
1505 while( conn->State == TCP_ST_FIN_WAIT1 )
1507 // No free, freed after TIME_WAIT
1510 Log_Warning("TCP", "Unhandled connection state %i in TCP_Client_Close",
1519 * \brief Checks if a value is between two others (after taking into account wrapping)
1521 int WrapBetween(Uint32 Lower, Uint32 Value, Uint32 Higher, Uint32 MaxValue)
1523 if( MaxValue < 0xFFFFFFFF )
1525 Lower %= MaxValue + 1;
1526 Value %= MaxValue + 1;
1527 Higher %= MaxValue + 1;
1530 // Simple Case, no wrap ?
1531 // Lower Value Higher
1532 // | ... + ... + ... + ... |
1534 if( Lower < Higher ) {
1535 return Lower < Value && Value < Higher;
1537 // Higher has wrapped below lower
1540 // Higher Lower Value
1541 // | ... + ... + ... + ... |
1542 if( Value > Lower ) {
1547 // Value Higher Lower
1548 // | ... + ... + ... + ... |
1549 if( Value < Higher ) {
1555 Uint32 GetRelative(Uint32 Base, Uint32 Value)
1558 return Value - Base + 0xFFFFFFFF;
1560 return Value - Base;