12 #define HEXDUMP_INCOMING 0
13 #define HEXDUMP_OUTGOING 0
15 #define TCP_MIN_DYNPORT 0xC000
16 #define TCP_MAX_HALFOPEN 1024 // Should be enough
18 #define TCP_MAX_PACKET_SIZE 1024
19 #define TCP_WINDOW_SIZE 0x2000
20 #define TCP_RECIEVE_BUFFER_SIZE 0x8000
21 #define TCP_DACK_THRESHOLD 4096
22 #define TCP_DACK_TIMEOUT 500
24 #define TCP_DEBUG 0 // Set to non-0 to enable TCP packet logging
27 void TCP_Initialise(void);
28 void TCP_StartConnection(tTCPConnection *Conn);
29 void TCP_SendPacket(tTCPConnection *Conn, tTCPHeader *Header, size_t DataLen, const void *Data);
30 void TCP_GetPacket(tInterface *Interface, void *Address, int Length, void *Buffer);
31 void TCP_INT_HandleConnectionPacket(tTCPConnection *Connection, tTCPHeader *Header, int Length);
32 int TCP_INT_AppendRecieved(tTCPConnection *Connection, const void *Data, size_t Length);
33 void TCP_INT_UpdateRecievedFromFuture(tTCPConnection *Connection);
34 void TCP_int_SendDelayedACK(void *ConnPtr);
35 void TCP_INT_SendACK(tTCPConnection *Connection, const char *Reason);
36 Uint16 TCP_GetUnusedPort();
37 int TCP_AllocatePort(Uint16 Port);
38 int TCP_DeallocatePort(Uint16 Port);
39 tTCPConnection *TCP_int_CreateConnection(tInterface *Interface, enum eTCPConnectionState State);
41 tVFS_Node *TCP_Server_Init(tInterface *Interface);
42 int TCP_Server_ReadDir(tVFS_Node *Node, int Pos, char Name[FILENAME_MAX]);
43 tVFS_Node *TCP_Server_FindDir(tVFS_Node *Node, const char *Name, Uint Flags);
44 int TCP_Server_IOCtl(tVFS_Node *Node, int ID, void *Data);
45 void TCP_Server_Close(tVFS_Node *Node);
47 tVFS_Node *TCP_Client_Init(tInterface *Interface);
48 size_t TCP_Client_Read(tVFS_Node *Node, off_t Offset, size_t Length, void *Buffer, Uint Flags);
49 size_t TCP_Client_Write(tVFS_Node *Node, off_t Offset, size_t Length, const void *Buffer, Uint Flags);
50 int TCP_Client_IOCtl(tVFS_Node *Node, int ID, void *Data);
51 void TCP_Client_Close(tVFS_Node *Node);
53 int WrapBetween(Uint32 Lower, Uint32 Value, Uint32 Higher, Uint32 MaxValue);
56 tSocketFile gTCP_ServerFile = {NULL, "tcps", TCP_Server_Init};
57 tSocketFile gTCP_ClientFile = {NULL, "tcpc", TCP_Client_Init};
58 tVFS_NodeType gTCP_ServerNodeType = {
59 .TypeName = "TCP Server",
60 .ReadDir = TCP_Server_ReadDir,
61 .FindDir = TCP_Server_FindDir,
62 .IOCtl = TCP_Server_IOCtl,
63 .Close = TCP_Server_Close
65 tVFS_NodeType gTCP_ClientNodeType = {
66 .TypeName = "TCP Client/Connection",
67 .Read = TCP_Client_Read,
68 .Write = TCP_Client_Write,
69 .IOCtl = TCP_Client_IOCtl,
70 .Close = TCP_Client_Close
74 int giTCP_NumHalfopen = 0;
75 tShortSpinlock glTCP_Listeners;
76 tTCPListener *gTCP_Listeners;
77 tShortSpinlock glTCP_OutbountCons;
78 tTCPConnection *gTCP_OutbountCons;
79 Uint32 gaTCP_PortBitmap[0x800];
80 int giTCP_NextOutPort = TCP_MIN_DYNPORT;
84 * \brief Initialise the TCP Layer
86 * Registers the client and server files and the GetPacket callback
88 void TCP_Initialise(void)
90 giTCP_NextOutPort += rand()%32;
91 IPStack_AddFile(&gTCP_ServerFile);
92 IPStack_AddFile(&gTCP_ClientFile);
93 IPv4_RegisterCallback(IP4PROT_TCP, TCP_GetPacket);
94 IPv6_RegisterCallback(IP4PROT_TCP, TCP_GetPacket);
98 * \brief Sends a packet from the specified connection, calculating the checksums
99 * \param Conn Connection
100 * \param Length Length of data
101 * \param Data Packet data (cast as a TCP Header)
103 void TCP_SendPacket( tTCPConnection *Conn, tTCPHeader *Header, size_t Length, const void *Data )
105 tIPStackBuffer *buffer;
107 int packlen = sizeof(*Header) + Length;
109 buffer = IPStack_Buffer_CreateBuffer(2 + IPV4_BUFFERS);
111 IPStack_Buffer_AppendSubBuffer(buffer, Length, 0, Data, NULL, NULL);
112 IPStack_Buffer_AppendSubBuffer(buffer, sizeof(*Header), 0, Header, NULL, NULL);
114 LOG("Sending %i+%i to %s:%i", sizeof(*Header), Length,
115 IPStack_PrintAddress(Conn->Interface->Type, &Conn->RemoteIP),
119 Header->Checksum = 0;
120 checksum[1] = htons( ~IPv4_Checksum(Header, sizeof(tTCPHeader)) );
121 checksum[2] = htons( ~IPv4_Checksum(Data, Length) );
123 // TODO: Fragment packet
125 switch( Conn->Interface->Type )
128 // Get IPv4 pseudo-header checksum
131 buf[0] = ((tIPv4*)Conn->Interface->Address)->L;
132 buf[1] = Conn->RemoteIP.v4.L;
133 buf[2] = (htons(packlen)<<16) | (6<<8) | 0;
134 checksum[0] = htons( ~IPv4_Checksum(buf, sizeof(buf)) ); // Partial checksum
136 // - Combine checksums
137 Header->Checksum = htons( IPv4_Checksum(checksum, sizeof(checksum)) );
138 IPv4_SendPacket(Conn->Interface, Conn->RemoteIP.v4, IP4PROT_TCP, 0, buffer);
142 // Append IPv6 Pseudo Header
145 memcpy(buf, Conn->Interface->Address, 16);
146 memcpy(&buf[4], &Conn->RemoteIP, 16);
147 buf[8] = htonl(packlen);
149 checksum[0] = htons( ~IPv4_Checksum(buf, sizeof(buf)) ); // Partial checksum
151 Header->Checksum = htons( IPv4_Checksum(checksum, sizeof(checksum)) ); // Combine the two
152 IPv6_SendPacket(Conn->Interface, Conn->RemoteIP.v6, IP4PROT_TCP, Length, Data);
158 * \brief Handles a packet from the IP Layer
159 * \param Interface Interface the packet arrived from
160 * \param Address Pointer to the addres structure
161 * \param Length Size of packet in bytes
162 * \param Buffer Packet data
164 void TCP_GetPacket(tInterface *Interface, void *Address, int Length, void *Buffer)
166 tTCPHeader *hdr = Buffer;
168 tTCPConnection *conn;
171 Log_Log("TCP", "TCP_GetPacket: <Local>:%i from [%s]:%i, Flags = %s%s%s%s%s%s%s%s",
172 ntohs(hdr->DestPort),
173 IPStack_PrintAddress(Interface->Type, Address),
174 ntohs(hdr->SourcePort),
175 (hdr->Flags & TCP_FLAG_CWR) ? "CWR " : "",
176 (hdr->Flags & TCP_FLAG_ECE) ? "ECE " : "",
177 (hdr->Flags & TCP_FLAG_URG) ? "URG " : "",
178 (hdr->Flags & TCP_FLAG_ACK) ? "ACK " : "",
179 (hdr->Flags & TCP_FLAG_PSH) ? "PSH " : "",
180 (hdr->Flags & TCP_FLAG_RST) ? "RST " : "",
181 (hdr->Flags & TCP_FLAG_SYN) ? "SYN " : "",
182 (hdr->Flags & TCP_FLAG_FIN) ? "FIN " : ""
186 if( Length > (hdr->DataOffset >> 4)*4 )
188 LOG("SequenceNumber = 0x%x", ntohl(hdr->SequenceNumber));
191 "TCP_GetPacket: Packet Data = ",
192 (Uint8*)hdr + (hdr->DataOffset >> 4)*4,
193 Length - (hdr->DataOffset >> 4)*4
199 for( srv = gTCP_Listeners; srv; srv = srv->Next )
201 // Check if the server is active
202 if(srv->Port == 0) continue;
203 // Check the interface
204 if(srv->Interface && srv->Interface != Interface) continue;
205 // Check the destination port
206 if(srv->Port != htons(hdr->DestPort)) continue;
208 Log_Log("TCP", "TCP_GetPacket: Matches server %p", srv);
209 // Is this in an established connection?
210 for( conn = srv->Connections; conn; conn = conn->Next )
212 // Check that it is coming in on the same interface
213 if(conn->Interface != Interface) continue;
216 Log_Log("TCP", "TCP_GetPacket: conn->RemotePort(%i) == hdr->SourcePort(%i)",
217 conn->RemotePort, ntohs(hdr->SourcePort));
218 if(conn->RemotePort != ntohs(hdr->SourcePort)) continue;
221 Log_Debug("TCP", "TCP_GetPacket: conn->RemoteIP(%s)",
222 IPStack_PrintAddress(conn->Interface->Type, &conn->RemoteIP));
223 Log_Debug("TCP", " == Address(%s)",
224 IPStack_PrintAddress(conn->Interface->Type, Address));
225 if( IPStack_CompareAddress(conn->Interface->Type, &conn->RemoteIP, Address, -1) == 0 )
228 Log_Log("TCP", "TCP_GetPacket: Matches connection %p", conn);
229 // We have a response!
230 TCP_INT_HandleConnectionPacket(conn, hdr, Length);
235 Log_Log("TCP", "TCP_GetPacket: Opening Connection");
236 // Open a new connection (well, check that it's a SYN)
237 if(hdr->Flags != TCP_FLAG_SYN) {
238 Log_Log("TCP", "TCP_GetPacket: Packet is not a SYN");
242 // TODO: Check for halfopen max
244 conn = TCP_int_CreateConnection(Interface, TCP_ST_SYN_RCVD);
245 conn->LocalPort = srv->Port;
246 conn->RemotePort = ntohs(hdr->SourcePort);
248 switch(Interface->Type)
250 case 4: conn->RemoteIP.v4 = *(tIPv4*)Address; break;
251 case 6: conn->RemoteIP.v6 = *(tIPv6*)Address; break;
254 conn->NextSequenceRcv = ntohl( hdr->SequenceNumber ) + 1;
255 conn->NextSequenceSend = rand();
257 conn->Node.ImplInt = srv->NextID ++;
259 // Hmm... Theoretically, this lock will never have to wait,
260 // as the interface is locked to the watching thread, and this
261 // runs in the watching thread. But, it's a good idea to have
263 // Oh, wait, there is a case where a wildcard can be used
264 // (srv->Interface == NULL) so having the lock is a good idea
265 SHORTLOCK(&srv->lConnections);
266 if( !srv->Connections )
267 srv->Connections = conn;
269 srv->ConnectionsTail->Next = conn;
270 srv->ConnectionsTail = conn;
271 if(!srv->NewConnections)
272 srv->NewConnections = conn;
273 VFS_MarkAvaliable( &srv->Node, 1 );
274 SHORTREL(&srv->lConnections);
275 Semaphore_Signal(&srv->WaitingConnections, 1);
278 hdr->Flags |= TCP_FLAG_ACK;
279 hdr->AcknowlegementNumber = htonl(conn->NextSequenceRcv);
280 hdr->SequenceNumber = htonl(conn->NextSequenceSend);
281 hdr->DestPort = hdr->SourcePort;
282 hdr->SourcePort = htons(srv->Port);
283 hdr->DataOffset = (sizeof(tTCPHeader)/4) << 4;
284 TCP_SendPacket( conn, hdr, 0, NULL );
285 conn->NextSequenceSend ++;
289 // Check Open Connections
291 for( conn = gTCP_OutbountCons; conn; conn = conn->Next )
293 // Check that it is coming in on the same interface
294 if(conn->Interface != Interface) continue;
297 if(conn->RemotePort != ntohs(hdr->SourcePort)) continue;
300 if(conn->Interface->Type == 6 && !IP6_EQU(conn->RemoteIP.v6, *(tIPv6*)Address))
302 if(conn->Interface->Type == 4 && !IP4_EQU(conn->RemoteIP.v4, *(tIPv4*)Address))
305 TCP_INT_HandleConnectionPacket(conn, hdr, Length);
310 Log_Log("TCP", "TCP_GetPacket: No Match");
314 * \brief Handles a packet sent to a specific connection
315 * \param Connection TCP Connection pointer
316 * \param Header TCP Packet pointer
317 * \param Length Length of the packet
319 void TCP_INT_HandleConnectionPacket(tTCPConnection *Connection, tTCPHeader *Header, int Length)
324 // Silently drop once finished
325 // TODO: Check if this needs to be here
326 if( Connection->State == TCP_ST_FINISHED ) {
327 Log_Log("TCP", "Packet ignored - connection finnished");
331 // Syncronise sequence values
332 if(Header->Flags & TCP_FLAG_SYN) {
333 // TODO: What if the packet also has data?
334 if( Connection->LastACKSequence != Connection->NextSequenceRcv )
335 TCP_INT_SendACK(Connection, "SYN");
336 Connection->NextSequenceRcv = ntohl(Header->SequenceNumber);
337 Connection->LastACKSequence = Connection->NextSequenceRcv;
340 // Ackowledge a sent packet
341 if(Header->Flags & TCP_FLAG_ACK) {
342 // TODO: Process an ACKed Packet
343 LOG("Conn %p, Sent packet 0x%x ACKed", Connection, Header->AcknowlegementNumber);
346 // Get length of data
347 dataLen = Length - (Header->DataOffset>>4)*4;
348 LOG("dataLen = %i", dataLen);
350 Log_Debug("TCP", "State %i, dataLen = %x", Connection->State, dataLen);
356 switch( Connection->State )
358 // Pre-init connection?
360 Log_Log("TCP", "Packets to a closed connection?!");
363 // --- Init States ---
364 // SYN sent, expecting SYN-ACK Connection Opening
365 case TCP_ST_SYN_SENT:
366 if( Header->Flags & TCP_FLAG_SYN )
368 Connection->NextSequenceRcv ++;
370 if( Header->Flags & TCP_FLAG_ACK )
372 Log_Log("TCP", "ACKing SYN-ACK");
373 Connection->State = TCP_ST_OPEN;
374 VFS_MarkFull(&Connection->Node, 0);
378 Log_Log("TCP", "ACKing SYN");
379 Connection->State = TCP_ST_SYN_RCVD;
381 Header->DestPort = Header->SourcePort;
382 Header->SourcePort = htons(Connection->LocalPort);
383 Header->AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
384 Header->SequenceNumber = htonl(Connection->NextSequenceSend);
385 Header->WindowSize = htons(TCP_WINDOW_SIZE);
386 Header->Flags = TCP_FLAG_ACK;
387 Header->DataOffset = (sizeof(tTCPHeader)/4) << 4;
388 TCP_SendPacket( Connection, Header, 0, NULL );
392 // SYN-ACK sent, expecting ACK
393 case TCP_ST_SYN_RCVD:
394 if( Header->Flags & TCP_FLAG_ACK )
396 // TODO: Handle max half-open limit
397 Log_Log("TCP", "Connection fully opened");
398 Connection->State = TCP_ST_OPEN;
399 VFS_MarkFull(&Connection->Node, 0);
403 // --- Established State ---
405 // - Handle State changes
407 if( Header->Flags & TCP_FLAG_FIN ) {
408 Log_Log("TCP", "Conn %p closed, recieved FIN", Connection);
409 VFS_MarkError(&Connection->Node, 1);
410 Connection->State = TCP_ST_CLOSE_WAIT;
411 // Header->Flags &= ~TCP_FLAG_FIN;
412 // CLOSE WAIT requires the client to close (or does it?)
418 // Check for an empty packet
420 if( Header->Flags == TCP_FLAG_ACK )
422 Log_Log("TCP", "ACK only packet");
425 Connection->NextSequenceRcv ++; // TODO: Is this right? (empty packet counts as one byte)
426 Log_Log("TCP", "Empty Packet, inc and ACK the current sequence number");
427 TCP_INT_SendACK(Connection, "Empty");
429 Header->DestPort = Header->SourcePort;
430 Header->SourcePort = htons(Connection->LocalPort);
431 Header->AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
432 Header->SequenceNumber = htonl(Connection->NextSequenceSend);
433 Header->Flags |= TCP_FLAG_ACK;
434 TCP_SendPacket( Connection, Header, 0, NULL );
444 sequence_num = ntohl(Header->SequenceNumber);
446 LOG("0x%08x <= 0x%08x < 0x%08x",
447 Connection->NextSequenceRcv,
448 ntohl(Header->SequenceNumber),
449 Connection->NextSequenceRcv + TCP_WINDOW_SIZE
452 // Is this packet the next expected packet?
453 if( sequence_num == Connection->NextSequenceRcv )
456 // Ooh, Goodie! Add it to the recieved list
457 rv = TCP_INT_AppendRecieved(Connection,
458 (Uint8*)Header + (Header->DataOffset>>4)*4,
462 Log_Notice("TCP", "TCP_INT_AppendRecieved rv %i", rv);
465 LOG("0x%08x += %i", Connection->NextSequenceRcv, dataLen);
466 Connection->NextSequenceRcv += dataLen;
468 // TODO: This should be moved out of the watcher thread,
469 // so that a single lost packet on one connection doesn't cause
470 // all connections on the interface to lag.
471 // - Meh, no real issue, as the cache shouldn't be that large
472 TCP_INT_UpdateRecievedFromFuture(Connection);
475 // - Only send an ACK if we've had a burst
476 if( Connection->NextSequenceRcv > (Uint32)(TCP_DACK_THRESHOLD + Connection->LastACKSequence) )
478 TCP_INT_SendACK(Connection, "DACK Burst");
479 // - Extend TCP deferred ACK timer
480 Time_RemoveTimer(Connection->DeferredACKTimer);
482 // - Schedule the deferred ACK timer (if already scheduled, this is a NOP)
483 Time_ScheduleTimer(Connection->DeferredACKTimer, TCP_DACK_TIMEOUT);
485 TCP_INT_SendACK(Connection, "RX");
488 // Check if the packet is in window
489 else if( WrapBetween(Connection->NextSequenceRcv, sequence_num,
490 Connection->NextSequenceRcv+TCP_WINDOW_SIZE, 0xFFFFFFFF) )
492 Uint8 *dataptr = (Uint8*)Header + (Header->DataOffset>>4)*4;
493 #if CACHE_FUTURE_PACKETS_IN_BYTES
496 index = sequence_num % TCP_WINDOW_SIZE;
497 for( int i = 0; i < dataLen; i ++ )
499 Connection->FuturePacketValidBytes[index/8] |= 1 << (index%8);
500 Connection->FuturePacketData[index] = dataptr[i];
501 // Do a wrap increment
503 if(index == TCP_WINDOW_SIZE) index = 0;
506 tTCPStoredPacket *pkt, *tmp, *prev = NULL;
508 // Allocate and fill cached packet
509 pkt = malloc( sizeof(tTCPStoredPacket) + dataLen );
511 pkt->Sequence = ntohl(Header->SequenceNumber);
512 pkt->Length = dataLen;
513 memcpy(pkt->Data, dataptr, dataLen);
515 Log_Log("TCP", "We missed a packet, caching",
516 pkt->Sequence, Connection->NextSequenceRcv);
518 // No? Well, let's cache it and look at it later
519 SHORTLOCK( &Connection->lFuturePackets );
520 for(tmp = Connection->FuturePackets;
522 prev = tmp, tmp = tmp->Next)
524 if(tmp->Sequence >= pkt->Sequence) break;
527 // Add if before first, or sequences don't match
528 if( !tmp || tmp->Sequence != pkt->Sequence )
533 Connection->FuturePackets = pkt;
537 else if(pkt->Length > tmp->Length)
541 pkt->Next = tmp->Next;
546 free(pkt); // TODO: Find some way to remove this
548 SHORTREL( &Connection->lFuturePackets );
551 // Badly out of sequence packet
554 Log_Log("TCP", "Fully out of sequence packet (0x%08x not between 0x%08x and 0x%08x), dropped",
555 sequence_num, Connection->NextSequenceRcv, Connection->NextSequenceRcv+TCP_WINDOW_SIZE);
556 // Spec says we should send an empty ACK with the current state
557 TCP_INT_SendACK(Connection, "Bad Seq");
561 // --- Remote close states
562 case TCP_ST_CLOSE_WAIT:
564 // Ignore everything, CLOSE_WAIT is terminated by the client
565 Log_Debug("TCP", "CLOSE WAIT - Ignoring packets");
569 // LAST-ACK - Waiting for the ACK of FIN (from CLOSE WAIT)
570 case TCP_ST_LAST_ACK:
571 if( Header->Flags & TCP_FLAG_ACK )
573 Connection->State = TCP_ST_FINISHED; // Connection completed
574 Log_Log("TCP", "LAST-ACK to CLOSED - Connection remote closed");
575 // TODO: Destrory the TCB
579 // --- Local close States
580 case TCP_ST_FIN_WAIT1:
581 if( Header->Flags & TCP_FLAG_FIN )
583 Connection->State = TCP_ST_CLOSING;
584 Log_Debug("TCP", "Conn %p closed, sent FIN and recieved FIN", Connection);
585 VFS_MarkError(&Connection->Node, 1);
588 Header->DestPort = Header->SourcePort;
589 Header->SourcePort = htons(Connection->LocalPort);
590 Header->AcknowlegementNumber = Header->SequenceNumber;
591 Header->SequenceNumber = htonl(Connection->NextSequenceSend);
592 Header->WindowSize = htons(TCP_WINDOW_SIZE);
593 Header->Flags = TCP_FLAG_ACK;
594 TCP_SendPacket( Connection, Header, 0, NULL );
598 // TODO: Make sure that the packet is actually ACKing the FIN
599 if( Header->Flags & TCP_FLAG_ACK )
601 Connection->State = TCP_ST_FIN_WAIT2;
602 Log_Debug("TCP", "Conn %p closed, sent FIN ACKed", Connection);
603 VFS_MarkError(&Connection->Node, 1);
608 case TCP_ST_FIN_WAIT2:
609 if( Header->Flags & TCP_FLAG_FIN )
611 Connection->State = TCP_ST_TIME_WAIT;
612 Log_Debug("TCP", "FIN sent and recieved, ACKing and going into TIME WAIT %p FINWAIT-2 -> TIME WAIT", Connection);
614 Header->DestPort = Header->SourcePort;
615 Header->SourcePort = htons(Connection->LocalPort);
616 Header->AcknowlegementNumber = Header->SequenceNumber;
617 Header->SequenceNumber = htonl(Connection->NextSequenceSend);
618 Header->WindowSize = htons(TCP_WINDOW_SIZE);
619 Header->Flags = TCP_FLAG_ACK;
620 TCP_SendPacket( Connection, Header, 0, NULL );
625 // TODO: Make sure that the packet is actually ACKing the FIN
626 if( Header->Flags & TCP_FLAG_ACK )
628 Connection->State = TCP_ST_TIME_WAIT;
629 Log_Debug("TCP", "Conn %p CLOSING -> TIME WAIT", Connection);
630 VFS_MarkError(&Connection->Node, 1);
635 // --- Closed (or near closed) states) ---
636 case TCP_ST_TIME_WAIT:
637 Log_Log("TCP", "Packets on Time-Wait, ignored");
640 case TCP_ST_FINISHED:
641 Log_Log("TCP", "Packets when CLOSED, ignoring");
645 // Log_Warning("TCP", "Unhandled TCP state %i", Connection->State);
652 * \brief Appends a packet to the recieved list
653 * \param Connection Connection structure
654 * \param Data Packet contents
655 * \param Length Length of \a Data
657 int TCP_INT_AppendRecieved(tTCPConnection *Connection, const void *Data, size_t Length)
659 Mutex_Acquire( &Connection->lRecievedPackets );
661 if(Connection->RecievedBuffer->Length + Length > Connection->RecievedBuffer->Space )
663 VFS_MarkAvaliable(&Connection->Node, 1);
664 Log_Error("TCP", "Buffer filled, packet dropped (:%i) - %i + %i > %i",
665 Connection->LocalPort, Connection->RecievedBuffer->Length, Length,
666 Connection->RecievedBuffer->Space
668 Mutex_Release( &Connection->lRecievedPackets );
672 RingBuffer_Write( Connection->RecievedBuffer, Data, Length );
674 VFS_MarkAvaliable(&Connection->Node, 1);
676 Mutex_Release( &Connection->lRecievedPackets );
681 * \brief Updates the connections recieved list from the future list
682 * \param Connection Connection structure
684 * Updates the recieved packets list with packets from the future (out
685 * of order) packets list that are now able to be added in direct
688 void TCP_INT_UpdateRecievedFromFuture(tTCPConnection *Connection)
690 #if CACHE_FUTURE_PACKETS_IN_BYTES
691 // Calculate length of contiguous bytes
692 int length = Connection->HighestSequenceRcvd - Connection->NextSequenceRcv;
693 Uint32 index = Connection->NextSequenceRcv % TCP_WINDOW_SIZE;
694 for( int i = 0; i < length; i ++ )
697 Uint8 bitfield_byte = Connection->FuturePacketValidBytes[index / 8];
698 if( (bitfield_byte & (1 << bit)) == 0 ) {
703 if( bitfield_byte == 0xFF ) {
711 if(index > TCP_WINDOW_SIZE)
712 index -= TCP_WINDOW_SIZE;
715 index = Connection->NextSequenceRcv % TCP_WINDOW_SIZE;
717 // Write data to to the ring buffer
718 if( TCP_WINDOW_SIZE - index > length )
721 RingBuffer_Write( Connection->RecievedBuffer, Connection->FuturePacketData + index, length );
725 int endLen = TCP_WINDOW_SIZE - index;
727 RingBuffer_Write( Connection->RecievedBuffer, Connection->FuturePacketData + index, endLen );
728 RingBuffer_Write( Connection->RecievedBuffer, Connection->FuturePacketData, endLen - length );
731 // Mark (now saved) bytes as invalid
733 while(index % 8 && length)
735 Connection->FuturePacketData[index] = 0;
736 Connection->FuturePacketData[index/8] &= ~(1 << (index%8));
738 if(index > TCP_WINDOW_SIZE)
739 index -= TCP_WINDOW_SIZE;
744 Connection->FuturePacketData[index] = 0;
745 Connection->FuturePacketValidBytes[index/8] = 0;
748 if(index > TCP_WINDOW_SIZE)
749 index -= TCP_WINDOW_SIZE;
753 Connection->FuturePacketData[index] = 0;
754 Connection->FuturePacketData[index/8] &= ~(1 << (index%8));
756 if(index > TCP_WINDOW_SIZE)
757 index -= TCP_WINDOW_SIZE;
762 tTCPStoredPacket *pkt;
765 SHORTLOCK( &Connection->lFuturePackets );
767 // Clear out duplicates from cache
768 // - If a packet has just been recieved, and it is expected, then
769 // (since NextSequenceRcv = rcvd->Sequence + rcvd->Length) all
770 // packets in cache that are smaller than the next expected
772 pkt = Connection->FuturePackets;
773 while(pkt && pkt->Sequence < Connection->NextSequenceRcv)
775 tTCPStoredPacket *next = pkt->Next;
780 // If there's no packets left in cache, stop looking
781 if(!pkt || pkt->Sequence > Connection->NextSequenceRcv) {
782 SHORTREL( &Connection->lFuturePackets );
786 // Delete packet from future list
787 Connection->FuturePackets = pkt->Next;
790 SHORTREL( &Connection->lFuturePackets );
792 // Looks like we found one
793 TCP_INT_AppendRecieved(Connection, pkt->Data, pkt->Length);
794 Connection->NextSequenceRcv += pkt->Length;
800 void TCP_int_SendDelayedACK(void *ConnPtr)
802 TCP_INT_SendACK(ConnPtr, "DACK Timeout");
805 void TCP_INT_SendACK(tTCPConnection *Connection, const char *Reason)
809 hdr.DataOffset = (sizeof(tTCPHeader)/4) << 4;
810 hdr.DestPort = htons(Connection->RemotePort);
811 hdr.SourcePort = htons(Connection->LocalPort);
812 hdr.AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
813 hdr.SequenceNumber = htonl(Connection->NextSequenceSend);
814 hdr.WindowSize = htons(TCP_WINDOW_SIZE);
815 hdr.Flags = TCP_FLAG_ACK; // TODO: Determine if SYN is wanted too
816 hdr.Checksum = 0; // TODO: Checksum
817 hdr.UrgentPointer = 0;
818 Log_Debug("TCP", "Sending ACK for 0x%08x (%s)", Connection->NextSequenceRcv, Reason);
819 TCP_SendPacket( Connection, &hdr, 0, NULL );
820 //Connection->NextSequenceSend ++;
821 Connection->LastACKSequence = Connection->NextSequenceRcv;
825 * \fn Uint16 TCP_GetUnusedPort()
826 * \brief Gets an unused port and allocates it
828 Uint16 TCP_GetUnusedPort()
832 // Get Next outbound port
833 ret = giTCP_NextOutPort++;
834 while( gaTCP_PortBitmap[ret/32] & (1UL << (ret%32)) )
838 if(giTCP_NextOutPort == 0x10000) {
839 ret = giTCP_NextOutPort = TCP_MIN_DYNPORT;
843 // Mark the new port as used
844 gaTCP_PortBitmap[ret/32] |= 1 << (ret%32);
850 * \fn int TCP_AllocatePort(Uint16 Port)
851 * \brief Marks a port as used
853 int TCP_AllocatePort(Uint16 Port)
855 // Check if the port has already been allocated
856 if( gaTCP_PortBitmap[Port/32] & (1 << (Port%32)) )
860 gaTCP_PortBitmap[Port/32] |= 1 << (Port%32);
866 * \fn int TCP_DeallocatePort(Uint16 Port)
867 * \brief Marks a port as unused
869 int TCP_DeallocatePort(Uint16 Port)
871 // Check if the port has already been allocated
872 if( !(gaTCP_PortBitmap[Port/32] & (1 << (Port%32))) )
876 gaTCP_PortBitmap[Port/32] &= ~(1 << (Port%32));
881 tTCPConnection *TCP_int_CreateConnection(tInterface *Interface, enum eTCPConnectionState State)
883 tTCPConnection *conn = calloc( sizeof(tTCPConnection) + TCP_WINDOW_SIZE + TCP_WINDOW_SIZE/8, 1 );
886 conn->Interface = Interface;
887 conn->LocalPort = -1;
888 conn->RemotePort = -1;
890 conn->Node.ReferenceCount = 1;
891 conn->Node.ImplPtr = conn;
892 conn->Node.NumACLs = 1;
893 conn->Node.ACLs = &gVFS_ACL_EveryoneRW;
894 conn->Node.Type = &gTCP_ClientNodeType;
895 conn->Node.BufferFull = 1; // Cleared when connection opens
897 conn->RecievedBuffer = RingBuffer_Create( TCP_RECIEVE_BUFFER_SIZE );
899 conn->SentBuffer = RingBuffer_Create( TCP_SEND_BUFFER_SIZE );
900 Semaphore_Init(conn->SentBufferSpace, 0, TCP_SEND_BUFFER_SIZE, "TCP SentBuffer", conn->Name);
903 #if CACHE_FUTURE_PACKETS_IN_BYTES
904 // Future recieved data (ahead of the expected sequence number)
905 conn->FuturePacketData = (Uint8*)conn + sizeof(tTCPConnection);
906 conn->FuturePacketValidBytes = conn->FuturePacketData + TCP_WINDOW_SIZE;
909 conn->DeferredACKTimer = Time_AllocateTimer( TCP_int_SendDelayedACK, conn);
914 tVFS_Node *TCP_Server_Init(tInterface *Interface)
918 srv = calloc( 1, sizeof(tTCPListener) );
921 Log_Warning("TCP", "malloc failed for listener (%i) bytes", sizeof(tTCPListener));
925 srv->Interface = Interface;
928 srv->Connections = NULL;
929 srv->ConnectionsTail = NULL;
930 srv->NewConnections = NULL;
932 srv->Node.Flags = VFS_FFLAG_DIRECTORY;
934 srv->Node.ImplPtr = srv;
935 srv->Node.NumACLs = 1;
936 srv->Node.ACLs = &gVFS_ACL_EveryoneRW;
937 srv->Node.Type = &gTCP_ServerNodeType;
939 SHORTLOCK(&glTCP_Listeners);
940 srv->Next = gTCP_Listeners;
941 gTCP_Listeners = srv;
942 SHORTREL(&glTCP_Listeners);
948 * \brief Wait for a new connection and return the connection ID
949 * \note Blocks until a new connection is made
950 * \param Node Server node
951 * \param Pos Position (ignored)
953 int TCP_Server_ReadDir(tVFS_Node *Node, int Pos, char Dest[FILENAME_MAX])
955 tTCPListener *srv = Node->ImplPtr;
956 tTCPConnection *conn;
958 ENTER("pNode iPos", Node, Pos);
960 Log_Log("TCP", "Thread %i waiting for a connection", Threads_GetTID());
961 Semaphore_Wait( &srv->WaitingConnections, 1 );
963 SHORTLOCK(&srv->lConnections);
964 // Increment the new list (the current connection is still on the
966 conn = srv->NewConnections;
967 srv->NewConnections = conn->Next;
969 if( srv->NewConnections == NULL )
970 VFS_MarkAvaliable( Node, 0 );
972 SHORTREL( &srv->lConnections );
974 LOG("conn = %p", conn);
975 LOG("srv->Connections = %p", srv->Connections);
976 LOG("srv->NewConnections = %p", srv->NewConnections);
977 LOG("srv->ConnectionsTail = %p", srv->ConnectionsTail);
979 itoa(Dest, conn->Node.ImplInt, 16, 8, '0');
980 Log_Log("TCP", "Thread %i got connection '%s'", Threads_GetTID(), Dest);
986 * \brief Gets a client connection node
987 * \param Node Server node
988 * \param Name Hexadecimal ID of the node
990 tVFS_Node *TCP_Server_FindDir(tVFS_Node *Node, const char *Name, Uint Flags)
992 tTCPConnection *conn;
993 tTCPListener *srv = Node->ImplPtr;
997 ENTER("pNode sName", Node, Name);
999 // Check for a non-empty name
1003 itoa(tmp, id, 16, 8, '0');
1004 if(strcmp(tmp, Name) != 0) {
1005 LOG("'%s' != '%s' (%08x)", Name, tmp, id);
1010 Log_Debug("TCP", "srv->Connections = %p", srv->Connections);
1011 Log_Debug("TCP", "srv->NewConnections = %p", srv->NewConnections);
1012 Log_Debug("TCP", "srv->ConnectionsTail = %p", srv->ConnectionsTail);
1015 SHORTLOCK( &srv->lConnections );
1016 for(conn = srv->Connections;
1020 LOG("conn->Node.ImplInt = %i", conn->Node.ImplInt);
1021 if(conn->Node.ImplInt == id) break;
1023 SHORTREL( &srv->lConnections );
1025 // If not found, ret NULL
1027 LOG("Connection %i not found", id);
1032 // Empty Name - Check for a new connection and if it's there, open it
1035 SHORTLOCK( &srv->lConnections );
1036 conn = srv->NewConnections;
1038 srv->NewConnections = conn->Next;
1039 VFS_MarkAvaliable( Node, srv->NewConnections != NULL );
1040 SHORTREL( &srv->lConnections );
1042 LOG("No new connections");
1049 LEAVE('p', &conn->Node);
1054 * \brief Handle IOCtl calls
1056 int TCP_Server_IOCtl(tVFS_Node *Node, int ID, void *Data)
1058 tTCPListener *srv = Node->ImplPtr;
1062 case 4: // Get/Set Port
1063 if(!Data) // Get Port
1066 if(srv->Port) // Wait, you can't CHANGE the port
1069 if(!CheckMem(Data, sizeof(Uint16))) // Sanity check
1072 // Permissions check
1073 if(Threads_GetUID() != 0
1074 && *(Uint16*)Data != 0
1075 && *(Uint16*)Data < 1024)
1078 // TODO: Check if a port is in use
1081 srv->Port = *(Uint16*)Data;
1082 if(srv->Port == 0) // Allocate a random port
1083 srv->Port = TCP_GetUnusedPort();
1084 else // Else, mark this as used
1085 TCP_AllocatePort(srv->Port);
1087 Log_Log("TCP", "Server %p listening on port %i", srv, srv->Port);
1094 void TCP_Server_Close(tVFS_Node *Node)
1096 free(Node->ImplPtr);
1101 * \brief Create a client node
1103 tVFS_Node *TCP_Client_Init(tInterface *Interface)
1105 tTCPConnection *conn = TCP_int_CreateConnection(Interface, TCP_ST_CLOSED);
1107 SHORTLOCK(&glTCP_OutbountCons);
1108 conn->Next = gTCP_OutbountCons;
1109 gTCP_OutbountCons = conn;
1110 SHORTREL(&glTCP_OutbountCons);
1116 * \brief Wait for a packet and return it
1117 * \note If \a Length is smaller than the size of the packet, the rest
1118 * of the packet's data will be discarded.
1120 size_t TCP_Client_Read(tVFS_Node *Node, off_t Offset, size_t Length, void *Buffer, Uint Flags)
1122 tTCPConnection *conn = Node->ImplPtr;
1125 ENTER("pNode XOffset XLength pBuffer", Node, Offset, Length, Buffer);
1126 LOG("conn = %p {State:%i}", conn, conn->State);
1128 // If the connection has been closed (state > ST_OPEN) then clear
1129 // any stale data in the buffer (until it is empty (until it is empty))
1130 if( conn->State > TCP_ST_OPEN )
1132 Mutex_Acquire( &conn->lRecievedPackets );
1133 len = RingBuffer_Read( Buffer, conn->RecievedBuffer, Length );
1134 Mutex_Release( &conn->lRecievedPackets );
1137 VFS_MarkAvaliable(Node, 0);
1149 tTime *timeout = NULL;
1150 tTime timeout_zero = 0;
1151 if( Flags & VFS_IOFLAG_NOBLOCK )
1152 timeout = &timeout_zero;
1153 if( !VFS_SelectNode(Node, VFS_SELECT_READ|VFS_SELECT_ERROR, timeout, "TCP_Client_Read") ) {
1154 errno = EWOULDBLOCK;
1160 // Lock list and read as much as possible (up to `Length`)
1161 Mutex_Acquire( &conn->lRecievedPackets );
1162 len = RingBuffer_Read( Buffer, conn->RecievedBuffer, Length );
1164 if( len == 0 || conn->RecievedBuffer->Length == 0 ) {
1165 LOG("Marking as none avaliable (len = %i)", len);
1166 VFS_MarkAvaliable(Node, 0);
1169 // Release the lock (we don't need it any more)
1170 Mutex_Release( &conn->lRecievedPackets );
1177 * \brief Send a data packet on a connection
1179 void TCP_INT_SendDataPacket(tTCPConnection *Connection, size_t Length, const void *Data)
1181 char buf[sizeof(tTCPHeader)+Length];
1182 tTCPHeader *packet = (void*)buf;
1184 // - Stop Delayed ACK timer (as this data packet ACKs)
1185 Time_RemoveTimer(Connection->DeferredACKTimer);
1187 packet->SourcePort = htons(Connection->LocalPort);
1188 packet->DestPort = htons(Connection->RemotePort);
1189 packet->DataOffset = (sizeof(tTCPHeader)/4)*16;
1190 packet->WindowSize = htons(TCP_WINDOW_SIZE);
1192 packet->AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
1193 packet->SequenceNumber = htonl(Connection->NextSequenceSend);
1194 packet->Flags = TCP_FLAG_PSH|TCP_FLAG_ACK; // Hey, ACK if you can!
1195 packet->UrgentPointer = 0;
1197 memcpy(packet->Options, Data, Length);
1199 Log_Debug("TCP", "Send sequence 0x%08x", Connection->NextSequenceSend);
1200 #if HEXDUMP_OUTGOING
1201 Debug_HexDump("TCP_INT_SendDataPacket: Data = ", Data, Length);
1204 TCP_SendPacket( Connection, packet, Length, Data );
1206 Connection->NextSequenceSend += Length;
1210 * \brief Send some bytes on a connection
1212 size_t TCP_Client_Write(tVFS_Node *Node, off_t Offset, size_t Length, const void *Buffer, Uint Flags)
1214 tTCPConnection *conn = Node->ImplPtr;
1215 size_t rem = Length;
1217 ENTER("pNode XOffset XLength pBuffer", Node, Offset, Length, Buffer);
1220 // Debug_HexDump("TCP_Client_Write: Buffer = ",
1224 // Don't allow a write to a closed connection
1225 if( conn->State > TCP_ST_OPEN ) {
1226 VFS_MarkError(Node, 1);
1234 tTime *timeout = NULL;
1235 tTime timeout_zero = 0;
1236 if( Flags & VFS_IOFLAG_NOBLOCK )
1237 timeout = &timeout_zero;
1238 if( !VFS_SelectNode(Node, VFS_SELECT_WRITE|VFS_SELECT_ERROR, timeout, "TCP_Client_Write") ) {
1239 errno = EWOULDBLOCK;
1247 int len = (rem < TCP_MAX_PACKET_SIZE) ? rem : TCP_MAX_PACKET_SIZE;
1250 // Wait for space in the buffer
1251 Semaphore_Signal( &Connection->SentBufferSpace, len );
1253 // Save data to buffer (and update the length read by the ammount written)
1254 len = RingBuffer_Write( &Connection->SentBuffer, Buffer, len);
1258 TCP_INT_SendDataPacket(conn, len, Buffer);
1269 * \brief Open a connection to another host using TCP
1270 * \param Conn Connection structure
1272 void TCP_StartConnection(tTCPConnection *Conn)
1274 tTCPHeader hdr = {0};
1276 Conn->State = TCP_ST_SYN_SENT;
1278 hdr.SourcePort = htons(Conn->LocalPort);
1279 hdr.DestPort = htons(Conn->RemotePort);
1280 Conn->NextSequenceSend = rand();
1281 hdr.SequenceNumber = htonl(Conn->NextSequenceSend);
1282 hdr.DataOffset = (sizeof(tTCPHeader)/4) << 4;
1283 hdr.Flags = TCP_FLAG_SYN;
1284 hdr.WindowSize = htons(TCP_WINDOW_SIZE); // Max
1285 hdr.Checksum = 0; // TODO
1287 TCP_SendPacket( Conn, &hdr, 0, NULL );
1289 Conn->NextSequenceSend ++;
1290 Conn->State = TCP_ST_SYN_SENT;
1296 * \brief Control a client socket
1298 int TCP_Client_IOCtl(tVFS_Node *Node, int ID, void *Data)
1300 tTCPConnection *conn = Node->ImplPtr;
1302 ENTER("pNode iID pData", Node, ID, Data);
1306 case 4: // Get/Set local port
1308 LEAVE_RET('i', conn->LocalPort);
1309 if(conn->State != TCP_ST_CLOSED)
1311 if(!CheckMem(Data, sizeof(Uint16)))
1314 if(Threads_GetUID() != 0 && *(Uint16*)Data < 1024)
1317 conn->LocalPort = *(Uint16*)Data;
1318 LEAVE_RET('i', conn->LocalPort);
1320 case 5: // Get/Set remote port
1321 if(!Data) LEAVE_RET('i', conn->RemotePort);
1322 if(conn->State != TCP_ST_CLOSED) LEAVE_RET('i', -1);
1323 if(!CheckMem(Data, sizeof(Uint16))) LEAVE_RET('i', -1);
1324 conn->RemotePort = *(Uint16*)Data;
1325 LEAVE_RET('i', conn->RemotePort);
1327 case 6: // Set Remote IP
1328 if( conn->State != TCP_ST_CLOSED )
1330 if( conn->Interface->Type == 4 )
1332 if(!CheckMem(Data, sizeof(tIPv4))) LEAVE_RET('i', -1);
1333 conn->RemoteIP.v4 = *(tIPv4*)Data;
1335 else if( conn->Interface->Type == 6 )
1337 if(!CheckMem(Data, sizeof(tIPv6))) LEAVE_RET('i', -1);
1338 conn->RemoteIP.v6 = *(tIPv6*)Data;
1343 if(conn->LocalPort == 0xFFFF)
1344 conn->LocalPort = TCP_GetUnusedPort();
1345 if(conn->RemotePort == -1)
1349 tTime timeout = conn->Interface->TimeoutDelay;
1351 TCP_StartConnection(conn);
1352 VFS_SelectNode(&conn->Node, VFS_SELECT_WRITE, &timeout, "TCP Connection");
1353 if( conn->State == TCP_ST_SYN_SENT )
1359 // Get recieve buffer length
1361 LEAVE_RET('i', conn->RecievedBuffer->Length);
1367 void TCP_Client_Close(tVFS_Node *Node)
1369 tTCPConnection *conn = Node->ImplPtr;
1372 ENTER("pNode", Node);
1374 ASSERT(Node->ReferenceCount != 0);
1376 if( Node->ReferenceCount > 1 ) {
1377 Node->ReferenceCount --;
1378 LOG("Dereference only");
1383 if( conn->State == TCP_ST_CLOSE_WAIT || conn->State == TCP_ST_OPEN )
1385 packet.SourcePort = htons(conn->LocalPort);
1386 packet.DestPort = htons(conn->RemotePort);
1387 packet.DataOffset = (sizeof(tTCPHeader)/4)*16;
1388 packet.WindowSize = TCP_WINDOW_SIZE;
1390 packet.AcknowlegementNumber = 0;
1391 packet.SequenceNumber = htonl(conn->NextSequenceSend);
1392 packet.Flags = TCP_FLAG_FIN;
1394 TCP_SendPacket( conn, &packet, 0, NULL );
1397 switch( conn->State )
1400 Log_Warning("TCP", "Closing connection that was never opened");
1402 case TCP_ST_CLOSE_WAIT:
1403 conn->State = TCP_ST_LAST_ACK;
1406 conn->State = TCP_ST_FIN_WAIT1;
1407 while( conn->State == TCP_ST_FIN_WAIT1 ) Threads_Yield();
1410 Log_Warning("TCP", "Unhandled connection state %i in TCP_Client_Close",
1415 Time_RemoveTimer(conn->DeferredACKTimer);
1416 Time_FreeTimer(conn->DeferredACKTimer);
1423 * \brief Checks if a value is between two others (after taking into account wrapping)
1425 int WrapBetween(Uint32 Lower, Uint32 Value, Uint32 Higher, Uint32 MaxValue)
1427 if( MaxValue < 0xFFFFFFFF )
1429 Lower %= MaxValue + 1;
1430 Value %= MaxValue + 1;
1431 Higher %= MaxValue + 1;
1434 // Simple Case, no wrap ?
1435 // Lower Value Higher
1436 // | ... + ... + ... + ... |
1438 if( Lower < Higher ) {
1439 return Lower < Value && Value < Higher;
1441 // Higher has wrapped below lower
1444 // Higher Lower Value
1445 // | ... + ... + ... + ... |
1446 if( Value > Lower ) {
1451 // Value Higher Lower
1452 // | ... + ... + ... + ... |
1453 if( Value < Higher ) {