11 #define CACHE_FUTURE_PACKETS_IN_BYTES 1 // Use a ring buffer to cache out of order packets
13 #define TCP_MIN_DYNPORT 0xC000
14 #define TCP_MAX_HALFOPEN 1024 // Should be enough
16 #define TCP_MAX_PACKET_SIZE 1024
17 #define TCP_WINDOW_SIZE 0x2000
18 #define TCP_RECIEVE_BUFFER_SIZE 0x4000
21 void TCP_Initialise(void);
22 void TCP_StartConnection(tTCPConnection *Conn);
23 void TCP_SendPacket(tTCPConnection *Conn, size_t Length, tTCPHeader *Data);
24 void TCP_GetPacket(tInterface *Interface, void *Address, int Length, void *Buffer);
25 void TCP_INT_HandleConnectionPacket(tTCPConnection *Connection, tTCPHeader *Header, int Length);
26 void TCP_INT_AppendRecieved(tTCPConnection *Connection, tTCPStoredPacket *Ptk);
27 void TCP_INT_UpdateRecievedFromFuture(tTCPConnection *Connection);
28 Uint16 TCP_GetUnusedPort();
29 int TCP_AllocatePort(Uint16 Port);
30 int TCP_DeallocatePort(Uint16 Port);
32 tVFS_Node *TCP_Server_Init(tInterface *Interface);
33 char *TCP_Server_ReadDir(tVFS_Node *Node, int Pos);
34 tVFS_Node *TCP_Server_FindDir(tVFS_Node *Node, const char *Name);
35 int TCP_Server_IOCtl(tVFS_Node *Node, int ID, void *Data);
36 void TCP_Server_Close(tVFS_Node *Node);
38 tVFS_Node *TCP_Client_Init(tInterface *Interface);
39 Uint64 TCP_Client_Read(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer);
40 Uint64 TCP_Client_Write(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer);
41 int TCP_Client_IOCtl(tVFS_Node *Node, int ID, void *Data);
42 void TCP_Client_Close(tVFS_Node *Node);
44 int WrapBetween(Uint32 Lower, Uint32 Value, Uint32 Higher, Uint32 MaxValue);
47 tSocketFile gTCP_ServerFile = {NULL, "tcps", TCP_Server_Init};
48 tSocketFile gTCP_ClientFile = {NULL, "tcpc", TCP_Client_Init};
51 int giTCP_NumHalfopen = 0;
52 tShortSpinlock glTCP_Listeners;
53 tTCPListener *gTCP_Listeners;
54 tShortSpinlock glTCP_OutbountCons;
55 tTCPConnection *gTCP_OutbountCons;
56 Uint32 gaTCP_PortBitmap[0x800];
57 int giTCP_NextOutPort = TCP_MIN_DYNPORT;
61 * \brief Initialise the TCP Layer
63 * Registers the client and server files and the GetPacket callback
65 void TCP_Initialise(void)
67 IPStack_AddFile(&gTCP_ServerFile);
68 IPStack_AddFile(&gTCP_ClientFile);
69 IPv4_RegisterCallback(IP4PROT_TCP, TCP_GetPacket);
73 * \brief Sends a packet from the specified connection, calculating the checksums
74 * \param Conn Connection
75 * \param Length Length of data
76 * \param Data Packet data (cast as a TCP Header)
78 void TCP_SendPacket( tTCPConnection *Conn, size_t Length, tTCPHeader *Data )
82 switch( Conn->Interface->Type )
84 case 4: // Append IPv4 Pseudo Header
85 buflen = 4 + 4 + 4 + ((Length+1)&~1);
86 buf = malloc( buflen );
87 buf[0] = ((tIPv4*)Conn->Interface->Address)->L;
88 buf[1] = Conn->RemoteIP.v4.L;
89 buf[2] = (htons(Length)<<16) | (6<<8) | 0;
91 memcpy( &buf[3], Data, Length );
92 Data->Checksum = htons( IPv4_Checksum( buf, buflen ) );
94 IPv4_SendPacket(Conn->Interface, Conn->RemoteIP.v4, IP4PROT_TCP, 0, Length, Data);
100 * \brief Handles a packet from the IP Layer
101 * \param Interface Interface the packet arrived from
102 * \param Address Pointer to the addres structure
103 * \param Length Size of packet in bytes
104 * \param Buffer Packet data
106 void TCP_GetPacket(tInterface *Interface, void *Address, int Length, void *Buffer)
108 tTCPHeader *hdr = Buffer;
110 tTCPConnection *conn;
112 Log_Log("TCP", "TCP_GetPacket: SourcePort = %i, DestPort = %i",
113 ntohs(hdr->SourcePort), ntohs(hdr->DestPort));
115 Log_Log("TCP", "TCP_GetPacket: SequenceNumber = 0x%x", ntohl(hdr->SequenceNumber));
116 Log_Log("TCP", "TCP_GetPacket: AcknowlegementNumber = 0x%x", ntohl(hdr->AcknowlegementNumber));
117 Log_Log("TCP", "TCP_GetPacket: DataOffset = %i", hdr->DataOffset >> 4);
118 Log_Log("TCP", "TCP_GetPacket: WindowSize = %i", htons(hdr->WindowSize));
119 Log_Log("TCP", "TCP_GetPacket: Checksum = 0x%x", htons(hdr->Checksum));
120 Log_Log("TCP", "TCP_GetPacket: UrgentPointer = 0x%x", htons(hdr->UrgentPointer));
122 Log_Log("TCP", "TCP_GetPacket: Flags = %s%s%s%s%s%s%s%s",
123 (hdr->Flags & TCP_FLAG_CWR) ? "CWR " : "",
124 (hdr->Flags & TCP_FLAG_ECE) ? "ECE " : "",
125 (hdr->Flags & TCP_FLAG_URG) ? "URG " : "",
126 (hdr->Flags & TCP_FLAG_ACK) ? "ACK " : "",
127 (hdr->Flags & TCP_FLAG_PSH) ? "PSH " : "",
128 (hdr->Flags & TCP_FLAG_RST) ? "RST " : "",
129 (hdr->Flags & TCP_FLAG_SYN) ? "SYN " : "",
130 (hdr->Flags & TCP_FLAG_FIN) ? "FIN " : ""
133 if( Length > (hdr->DataOffset >> 4)*4 )
135 Log_Log("TCP", "TCP_GetPacket: SequenceNumber = 0x%x", ntohl(hdr->SequenceNumber));
137 "[TCP ] Packet Data = ",
138 (Uint8*)hdr + (hdr->DataOffset >> 4)*4,
139 Length - (hdr->DataOffset >> 4)*4
145 for( srv = gTCP_Listeners; srv; srv = srv->Next )
147 // Check if the server is active
148 if(srv->Port == 0) continue;
149 // Check the interface
150 if(srv->Interface && srv->Interface != Interface) continue;
151 // Check the destination port
152 if(srv->Port != htons(hdr->DestPort)) continue;
154 Log_Log("TCP", "TCP_GetPacket: Matches server %p", srv);
155 // Is this in an established connection?
156 for( conn = srv->Connections; conn; conn = conn->Next )
158 Log_Log("TCP", "TCP_GetPacket: conn->Interface(%p) == Interface(%p)",
159 conn->Interface, Interface);
160 // Check that it is coming in on the same interface
161 if(conn->Interface != Interface) continue;
164 Log_Log("TCP", "TCP_GetPacket: conn->RemotePort(%i) == hdr->SourcePort(%i)",
165 conn->RemotePort, ntohs(hdr->SourcePort));
166 if(conn->RemotePort != ntohs(hdr->SourcePort)) continue;
169 if(conn->Interface->Type == 6 && !IP6_EQU(conn->RemoteIP.v6, *(tIPv6*)Address))
171 if(conn->Interface->Type == 4 && !IP4_EQU(conn->RemoteIP.v4, *(tIPv4*)Address))
174 Log_Log("TCP", "TCP_GetPacket: Matches connection %p", conn);
175 // We have a response!
176 TCP_INT_HandleConnectionPacket(conn, hdr, Length);
181 Log_Log("TCP", "TCP_GetPacket: Opening Connection");
182 // Open a new connection (well, check that it's a SYN)
183 if(hdr->Flags != TCP_FLAG_SYN) {
184 Log_Log("TCP", "TCP_GetPacket: Packet is not a SYN");
188 // TODO: Check for halfopen max
190 conn = calloc(1, sizeof(tTCPConnection));
191 conn->State = TCP_ST_SYN_RCVD;
192 conn->LocalPort = srv->Port;
193 conn->RemotePort = ntohs(hdr->SourcePort);
194 conn->Interface = Interface;
196 switch(Interface->Type)
198 case 4: conn->RemoteIP.v4 = *(tIPv4*)Address; break;
199 case 6: conn->RemoteIP.v6 = *(tIPv6*)Address; break;
202 conn->RecievedBuffer = RingBuffer_Create( TCP_RECIEVE_BUFFER_SIZE );
204 conn->NextSequenceRcv = ntohl( hdr->SequenceNumber ) + 1;
205 conn->NextSequenceSend = rand();
208 conn->Node.NumACLs = 1;
209 conn->Node.ACLs = &gVFS_ACL_EveryoneRW;
210 conn->Node.ImplPtr = conn;
211 conn->Node.ImplInt = srv->NextID ++;
212 conn->Node.Read = TCP_Client_Read;
213 conn->Node.Write = TCP_Client_Write;
214 //conn->Node.Close = TCP_SrvConn_Close;
216 // Hmm... Theoretically, this lock will never have to wait,
217 // as the interface is locked to the watching thread, and this
218 // runs in the watching thread. But, it's a good idea to have
220 // Oh, wait, there is a case where a wildcard can be used
221 // (srv->Interface == NULL) so having the lock is a good idea
222 SHORTLOCK(&srv->lConnections);
223 if( !srv->Connections )
224 srv->Connections = conn;
226 srv->ConnectionsTail->Next = conn;
227 srv->ConnectionsTail = conn;
228 if(!srv->NewConnections)
229 srv->NewConnections = conn;
230 SHORTREL(&srv->lConnections);
233 hdr->Flags |= TCP_FLAG_ACK;
234 hdr->AcknowlegementNumber = htonl(conn->NextSequenceRcv);
235 hdr->SequenceNumber = htonl(conn->NextSequenceSend);
236 hdr->DestPort = hdr->SourcePort;
237 hdr->SourcePort = htons(srv->Port);
238 hdr->DataOffset = (sizeof(tTCPHeader)/4) << 4;
239 TCP_SendPacket( conn, sizeof(tTCPHeader), hdr );
240 conn->NextSequenceSend ++;
246 // Check Open Connections
248 for( conn = gTCP_OutbountCons; conn; conn = conn->Next )
250 // Check that it is coming in on the same interface
251 if(conn->Interface != Interface) continue;
254 if(conn->RemotePort != ntohs(hdr->SourcePort)) continue;
257 if(conn->Interface->Type == 6 && !IP6_EQU(conn->RemoteIP.v6, *(tIPv6*)Address))
259 if(conn->Interface->Type == 4 && !IP4_EQU(conn->RemoteIP.v4, *(tIPv4*)Address))
262 TCP_INT_HandleConnectionPacket(conn, hdr, Length);
267 Log_Log("TCP", "TCP_GetPacket: No Match");
271 * \brief Handles a packet sent to a specific connection
272 * \param Connection TCP Connection pointer
273 * \param Header TCP Packet pointer
274 * \param Length Length of the packet
276 void TCP_INT_HandleConnectionPacket(tTCPConnection *Connection, tTCPHeader *Header, int Length)
278 tTCPStoredPacket *pkt;
281 // Silently drop once finished
282 // TODO: Check if this needs to be here
283 if( Connection->State == TCP_ST_FINISHED ) {
284 Log_Log("TCP", "Packet ignored - connection finnished");
288 // Syncronise sequence values
289 if(Header->Flags & TCP_FLAG_SYN) {
290 // TODO: What if the packet also has data?
291 Connection->NextSequenceRcv = ntohl(Header->SequenceNumber);
294 // Ackowledge a sent packet
295 if(Header->Flags & TCP_FLAG_ACK) {
296 // TODO: Process an ACKed Packet
297 Log_Log("TCP", "Conn %p, Sent packet 0x%x ACKed", Connection, Header->AcknowlegementNumber);
300 // Get length of data
301 dataLen = Length - (Header->DataOffset>>4)*4;
302 Log_Log("TCP", "HandleConnectionPacket - dataLen = %i", dataLen);
307 switch( Connection->State )
309 // Pre-init conneciton?
311 Log_Log("TCP", "Packets to a closed connection?!");
314 // --- Init States ---
315 // SYN sent, expecting SYN-ACK Connection Opening
316 case TCP_ST_SYN_SENT:
317 if( Header->Flags & TCP_FLAG_SYN )
319 Connection->NextSequenceRcv ++;
320 Header->DestPort = Header->SourcePort;
321 Header->SourcePort = htons(Connection->LocalPort);
322 Header->AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
323 Header->SequenceNumber = htonl(Connection->NextSequenceSend);
324 Header->WindowSize = htons(TCP_WINDOW_SIZE);
325 Header->Flags = TCP_FLAG_ACK;
326 Header->DataOffset = (sizeof(tTCPHeader)/4) << 4;
327 TCP_SendPacket( Connection, sizeof(tTCPHeader), Header );
329 if( Header->Flags & TCP_FLAG_ACK )
331 Log_Log("TCP", "ACKing SYN-ACK");
332 Connection->State = TCP_ST_OPEN;
336 Log_Log("TCP", "ACKing SYN");
337 Connection->State = TCP_ST_SYN_RCVD;
342 // SYN-ACK sent, expecting ACK
343 case TCP_ST_SYN_RCVD:
344 if( Header->Flags & TCP_FLAG_ACK )
346 // TODO: Handle max half-open limit
347 Connection->State = TCP_ST_OPEN;
348 Log_Log("TCP", "Connection fully opened");
352 // --- Established State ---
354 // - Handle State changes
356 if( Header->Flags & TCP_FLAG_FIN ) {
357 Log_Log("TCP", "Conn %p closed, recieved FIN", Connection);
358 VFS_MarkError(&Connection->Node, 1);
359 Connection->State = TCP_ST_CLOSE_WAIT;
360 // Header->Flags &= ~TCP_FLAG_FIN;
361 // CLOSE WAIT requires the client to close (or does it?)
367 // Check for an empty packet
369 if( Header->Flags == TCP_FLAG_ACK )
371 Log_Log("TCP", "ACK only packet");
374 Connection->NextSequenceRcv ++; // TODO: Is this right? (empty packet counts as one byte)
375 Log_Log("TCP", "Empty Packet, inc and ACK the current sequence number");
376 Header->DestPort = Header->SourcePort;
377 Header->SourcePort = htons(Connection->LocalPort);
378 Header->AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
379 Header->SequenceNumber = htonl(Connection->NextSequenceSend);
380 Header->Flags |= TCP_FLAG_ACK;
381 TCP_SendPacket( Connection, sizeof(tTCPHeader), Header );
390 // Allocate and fill cached packet
391 pkt = malloc( sizeof(tTCPStoredPacket) + dataLen );
393 pkt->Sequence = ntohl(Header->SequenceNumber);
394 pkt->Length = dataLen;
395 memcpy(pkt->Data, (Uint8*)Header + (Header->DataOffset>>4)*4, dataLen);
397 Log_Log("TCP", "0x%08x <= 0x%08x < 0x%08x",
398 Connection->NextSequenceRcv,
400 Connection->NextSequenceRcv + TCP_WINDOW_SIZE
403 // Is this packet the next expected packet?
404 if( pkt->Sequence == Connection->NextSequenceRcv )
406 // Ooh, Goodie! Add it to the recieved list
407 TCP_INT_AppendRecieved(Connection, pkt);
409 Log_Log("TCP", "0x%08x += %i", Connection->NextSequenceRcv, dataLen);
410 Connection->NextSequenceRcv += dataLen;
412 // TODO: This should be moved out of the watcher thread,
413 // so that a single lost packet on one connection doesn't cause
414 // all connections on the interface to lag.
415 TCP_INT_UpdateRecievedFromFuture(Connection);
418 Header->DestPort = Header->SourcePort;
419 Header->SourcePort = htons(Connection->LocalPort);
420 Header->AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
421 Header->SequenceNumber = htonl(Connection->NextSequenceSend);
422 Header->WindowSize = htons(TCP_WINDOW_SIZE);
423 Header->Flags &= TCP_FLAG_SYN; // Eliminate all flags save for SYN
424 Header->Flags |= TCP_FLAG_ACK; // Add ACK
425 Log_Log("TCP", "Sending ACK for 0x%08x", Connection->NextSequenceRcv);
426 TCP_SendPacket( Connection, sizeof(tTCPHeader), Header );
427 //Connection->NextSequenceSend ++;
429 // Check if the packet is in window
430 else if( WrapBetween(Connection->NextSequenceRcv, pkt->Sequence,
431 Connection->NextSequenceRcv+TCP_WINDOW_SIZE, 0xFFFFFFFF) )
433 #if CACHE_FUTURE_PACKETS_IN_BYTES
437 index = pkt->Sequence % TCP_WINDOW_SIZE;
438 for( i = 0; i < pkt->Length; i ++ )
440 Connection->FuturePacketValidBytes[index/8] |= 1 << (index%8);
441 Connection->FuturePacketValidBytes[index] = pkt->Data[i];
442 // Do a wrap increment
444 if(index == TCP_WINDOW_SIZE) index = 0;
447 tTCPStoredPacket *tmp, *prev = NULL;
449 Log_Log("TCP", "We missed a packet, caching",
450 pkt->Sequence, Connection->NextSequenceRcv);
452 // No? Well, let's cache it and look at it later
453 SHORTLOCK( &Connection->lFuturePackets );
454 for(tmp = Connection->FuturePackets;
456 prev = tmp, tmp = tmp->Next)
458 if(tmp->Sequence >= pkt->Sequence) break;
461 // Add if before first, or sequences don't match
462 if( !tmp || tmp->Sequence != pkt->Sequence )
467 Connection->FuturePackets = pkt;
471 else if(pkt->Length > tmp->Length)
475 pkt->Next = tmp->Next;
482 SHORTREL( &Connection->lFuturePackets );
485 // Badly out of sequence packet
488 Log_Log("TCP", "Fully out of sequence packet (0x%08x not between 0x%08x and 0x%08x), dropped",
489 pkt->Sequence, Connection->NextSequenceRcv, Connection->NextSequenceRcv+TCP_WINDOW_SIZE);
491 // TODO: Spec says we should send an empty ACK with the current state
495 // --- Remote close states
496 case TCP_ST_CLOSE_WAIT:
498 // Ignore everything, CLOSE_WAIT is terminated by the client
499 Log_Debug("TCP", "CLOSE WAIT - Ignoring packets");
503 // LAST-ACK - Waiting for the ACK of FIN (from CLOSE WAIT)
504 case TCP_ST_LAST_ACK:
505 if( Header->Flags & TCP_FLAG_ACK )
507 Connection->State = TCP_ST_FINISHED; // Connection completed
508 Log_Log("TCP", "LAST-ACK to CLOSED - Connection remote closed");
509 // TODO: Destrory the TCB
513 // --- Local close States
514 case TCP_ST_FIN_WAIT1:
515 if( Header->Flags & TCP_FLAG_FIN )
517 Connection->State = TCP_ST_CLOSING;
518 Log_Debug("TCP", "Conn %p closed, sent FIN and recieved FIN", Connection);
519 VFS_MarkError(&Connection->Node, 1);
522 Header->DestPort = Header->SourcePort;
523 Header->SourcePort = htons(Connection->LocalPort);
524 Header->AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
525 Header->SequenceNumber = htonl(Connection->NextSequenceSend);
526 Header->WindowSize = htons(TCP_WINDOW_SIZE);
527 Header->Flags = TCP_FLAG_ACK;
528 TCP_SendPacket( Connection, sizeof(tTCPHeader), Header );
532 // TODO: Make sure that the packet is actually ACKing the FIN
533 if( Header->Flags & TCP_FLAG_ACK )
535 Connection->State = TCP_ST_FIN_WAIT2;
536 Log_Debug("TCP", "Conn %p closed, sent FIN ACKed", Connection);
537 VFS_MarkError(&Connection->Node, 1);
542 case TCP_ST_FIN_WAIT2:
543 if( Header->Flags & TCP_FLAG_FIN )
545 Connection->State = TCP_ST_TIME_WAIT;
546 Log_Debug("TCP", "FIN sent and recieved, ACKing and going into TIME WAIT %p FINWAIT-2 -> TIME WAIT", Connection);
548 Header->DestPort = Header->SourcePort;
549 Header->SourcePort = htons(Connection->LocalPort);
550 Header->AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
551 Header->SequenceNumber = htonl(Connection->NextSequenceSend);
552 Header->WindowSize = htons(TCP_WINDOW_SIZE);
553 Header->Flags = TCP_FLAG_ACK;
554 TCP_SendPacket( Connection, sizeof(tTCPHeader), Header );
559 // TODO: Make sure that the packet is actually ACKing the FIN
560 if( Header->Flags & TCP_FLAG_ACK )
562 Connection->State = TCP_ST_TIME_WAIT;
563 Log_Debug("TCP", "Conn %p CLOSING -> TIME WAIT", Connection);
564 VFS_MarkError(&Connection->Node, 1);
569 // --- Closed (or near closed) states) ---
570 case TCP_ST_TIME_WAIT:
571 Log_Log("TCP", "Packets on Time-Wait, ignored");
574 case TCP_ST_FINISHED:
575 Log_Log("TCP", "Packets when CLOSED, ignoring");
579 // Log_Warning("TCP", "Unhandled TCP state %i", Connection->State);
586 * \brief Appends a packet to the recieved list
587 * \param Connection Connection structure
588 * \param Pkt Packet structure on heap
590 void TCP_INT_AppendRecieved(tTCPConnection *Connection, tTCPStoredPacket *Pkt)
592 Mutex_Acquire( &Connection->lRecievedPackets );
593 if(Connection->RecievedBuffer->Length + Pkt->Length > Connection->RecievedBuffer->Space )
595 Log_Error("TCP", "Buffer filled, packet dropped (%s)",
596 // TCP_INT_DumpConnection(Connection)
602 RingBuffer_Write( Connection->RecievedBuffer, Pkt->Data, Pkt->Length );
605 VFS_MarkAvaliable(&Connection->Node, 1);
608 Mutex_Release( &Connection->lRecievedPackets );
612 * \brief Updates the connections recieved list from the future list
613 * \param Connection Connection structure
615 * Updates the recieved packets list with packets from the future (out
616 * of order) packets list that are now able to be added in direct
619 void TCP_INT_UpdateRecievedFromFuture(tTCPConnection *Connection)
621 #if CACHE_FUTURE_PACKETS_IN_BYTES
625 // Calculate length of contiguous bytes
626 length = Connection->HighestSequenceRcvd - Connection->NextSequenceRcv;
627 index = Connection->NextSequenceRcv % TCP_WINDOW_SIZE;
628 for( i = 0; i < length; i ++ )
630 if( Connection->FuturePacketValidBytes[i / 8] == 0xFF ) {
634 else if( !(Connection->FuturePacketValidBytes[i / 8] & (1 << (i%8))) )
638 if(index > TCP_WINDOW_SIZE)
639 index -= TCP_WINDOW_SIZE;
643 index = Connection->NextSequenceRcv % TCP_WINDOW_SIZE;
645 // Write data to to the ring buffer
646 if( TCP_WINDOW_SIZE - index > length )
649 RingBuffer_Write( Connection->RecievedBuffer, Connection->FuturePacketData + index, length );
653 int endLen = TCP_WINDOW_SIZE - index;
655 RingBuffer_Write( Connection->RecievedBuffer, Connection->FuturePacketData + index, endLen );
656 RingBuffer_Write( Connection->RecievedBuffer, Connection->FuturePacketData, endLen - length );
659 // Mark (now saved) bytes as invalid
661 while(index % 8 && length)
663 Connection->FuturePacketData[index] = 0;
664 Connection->FuturePacketData[index/8] &= ~(1 << (index%8));
666 if(index > TCP_WINDOW_SIZE)
667 index -= TCP_WINDOW_SIZE;
672 Connection->FuturePacketData[index] = 0;
673 Connection->FuturePacketValidBytes[index/8] = 0;
676 if(index > TCP_WINDOW_SIZE)
677 index -= TCP_WINDOW_SIZE;
681 Connection->FuturePacketData[index] = 0;
682 Connection->FuturePacketData[index/8] &= ~(1 << (index%8));
684 if(index > TCP_WINDOW_SIZE)
685 index -= TCP_WINDOW_SIZE;
690 tTCPStoredPacket *pkt;
693 SHORTLOCK( &Connection->lFuturePackets );
695 // Clear out duplicates from cache
696 // - If a packet has just been recieved, and it is expected, then
697 // (since NextSequenceRcv = rcvd->Sequence + rcvd->Length) all
698 // packets in cache that are smaller than the next expected
700 pkt = Connection->FuturePackets;
701 while(pkt && pkt->Sequence < Connection->NextSequenceRcv)
703 tTCPStoredPacket *next = pkt->Next;
708 // If there's no packets left in cache, stop looking
709 if(!pkt || pkt->Sequence > Connection->NextSequenceRcv) {
710 SHORTREL( &Connection->lFuturePackets );
714 // Delete packet from future list
715 Connection->FuturePackets = pkt->Next;
718 SHORTREL( &Connection->lFuturePackets );
720 // Looks like we found one
721 TCP_INT_AppendRecieved(Connection, pkt);
722 Connection->NextSequenceRcv += pkt->Length;
729 * \fn Uint16 TCP_GetUnusedPort()
730 * \brief Gets an unused port and allocates it
732 Uint16 TCP_GetUnusedPort()
736 // Get Next outbound port
737 ret = giTCP_NextOutPort++;
738 while( gaTCP_PortBitmap[ret/32] & (1 << (ret%32)) )
742 if(giTCP_NextOutPort == 0x10000) {
743 ret = giTCP_NextOutPort = TCP_MIN_DYNPORT;
747 // Mark the new port as used
748 gaTCP_PortBitmap[ret/32] |= 1 << (ret%32);
754 * \fn int TCP_AllocatePort(Uint16 Port)
755 * \brief Marks a port as used
757 int TCP_AllocatePort(Uint16 Port)
759 // Check if the port has already been allocated
760 if( gaTCP_PortBitmap[Port/32] & (1 << (Port%32)) )
764 gaTCP_PortBitmap[Port/32] |= 1 << (Port%32);
770 * \fn int TCP_DeallocatePort(Uint16 Port)
771 * \brief Marks a port as unused
773 int TCP_DeallocatePort(Uint16 Port)
775 // Check if the port has already been allocated
776 if( !(gaTCP_PortBitmap[Port/32] & (1 << (Port%32))) )
780 gaTCP_PortBitmap[Port/32] &= ~(1 << (Port%32));
786 tVFS_Node *TCP_Server_Init(tInterface *Interface)
790 srv = malloc( sizeof(tTCPListener) );
793 Log_Warning("TCP", "malloc failed for listener (%i) bytes", sizeof(tTCPListener));
797 srv->Interface = Interface;
800 srv->Connections = NULL;
801 srv->ConnectionsTail = NULL;
802 srv->NewConnections = NULL;
804 srv->Node.Flags = VFS_FFLAG_DIRECTORY;
806 srv->Node.ImplPtr = srv;
807 srv->Node.NumACLs = 1;
808 srv->Node.ACLs = &gVFS_ACL_EveryoneRW;
809 srv->Node.ReadDir = TCP_Server_ReadDir;
810 srv->Node.FindDir = TCP_Server_FindDir;
811 srv->Node.IOCtl = TCP_Server_IOCtl;
812 srv->Node.Close = TCP_Server_Close;
814 SHORTLOCK(&glTCP_Listeners);
815 srv->Next = gTCP_Listeners;
816 gTCP_Listeners = srv;
817 SHORTREL(&glTCP_Listeners);
823 * \brief Wait for a new connection and return the connection ID
824 * \note Blocks until a new connection is made
825 * \param Node Server node
826 * \param Pos Position (ignored)
828 char *TCP_Server_ReadDir(tVFS_Node *Node, int Pos)
830 tTCPListener *srv = Node->ImplPtr;
831 tTCPConnection *conn;
834 ENTER("pNode iPos", Node, Pos);
836 Log_Log("TCP", "Thread %i waiting for a connection", Threads_GetTID());
839 SHORTLOCK( &srv->lConnections );
840 if( srv->NewConnections != NULL ) break;
841 SHORTREL( &srv->lConnections );
842 Threads_Yield(); // TODO: Sleep until poked
847 // Increment the new list (the current connection is still on the
849 conn = srv->NewConnections;
850 srv->NewConnections = conn->Next;
852 SHORTREL( &srv->lConnections );
854 LOG("conn = %p", conn);
855 LOG("srv->Connections = %p", srv->Connections);
856 LOG("srv->NewConnections = %p", srv->NewConnections);
857 LOG("srv->ConnectionsTail = %p", srv->ConnectionsTail);
860 itoa(ret, conn->Node.ImplInt, 16, 8, '0');
861 Log_Log("TCP", "Thread %i got '%s'", Threads_GetTID(), ret);
867 * \brief Gets a client connection node
868 * \param Node Server node
869 * \param Name Hexadecimal ID of the node
871 tVFS_Node *TCP_Server_FindDir(tVFS_Node *Node, const char *Name)
873 tTCPConnection *conn;
874 tTCPListener *srv = Node->ImplPtr;
878 ENTER("pNode sName", Node, Name);
881 itoa(tmp, id, 16, 8, '0');
882 if(strcmp(tmp, Name) != 0) {
883 LOG("'%s' != '%s' (%08x)", Name, tmp, id);
888 Log_Debug("TCP", "srv->Connections = %p", srv->Connections);
889 Log_Debug("TCP", "srv->NewConnections = %p", srv->NewConnections);
890 Log_Debug("TCP", "srv->ConnectionsTail = %p", srv->ConnectionsTail);
893 SHORTLOCK( &srv->lConnections );
894 for(conn = srv->Connections;
898 LOG("conn->Node.ImplInt = %i", conn->Node.ImplInt);
899 if(conn->Node.ImplInt == id) break;
901 SHORTREL( &srv->lConnections );
903 // If not found, ret NULL
905 LOG("Connection %i not found", id);
911 LEAVE('p', &conn->Node);
916 * \brief Handle IOCtl calls
918 int TCP_Server_IOCtl(tVFS_Node *Node, int ID, void *Data)
920 tTCPListener *srv = Node->ImplPtr;
924 case 4: // Get/Set Port
925 if(!Data) // Get Port
928 if(srv->Port) // Wait, you can't CHANGE the port
931 if(!CheckMem(Data, sizeof(Uint16))) // Sanity check
935 if(Threads_GetUID() != 0
936 && *(Uint16*)Data != 0
937 && *(Uint16*)Data < 1024)
940 // TODO: Check if a port is in use
943 srv->Port = *(Uint16*)Data;
944 if(srv->Port == 0) // Allocate a random port
945 srv->Port = TCP_GetUnusedPort();
946 else // Else, mark this as used
947 TCP_AllocatePort(srv->Port);
949 Log_Log("TCP", "Server %p listening on port %i", srv, srv->Port);
956 void TCP_Server_Close(tVFS_Node *Node)
963 * \brief Create a client node
965 tVFS_Node *TCP_Client_Init(tInterface *Interface)
967 tTCPConnection *conn = calloc( sizeof(tTCPConnection) + TCP_WINDOW_SIZE + TCP_WINDOW_SIZE/8, 1 );
969 conn->State = TCP_ST_CLOSED;
970 conn->Interface = Interface;
971 conn->LocalPort = -1;
972 conn->RemotePort = -1;
974 conn->Node.ImplPtr = conn;
975 conn->Node.NumACLs = 1;
976 conn->Node.ACLs = &gVFS_ACL_EveryoneRW;
977 conn->Node.Read = TCP_Client_Read;
978 conn->Node.Write = TCP_Client_Write;
979 conn->Node.IOCtl = TCP_Client_IOCtl;
980 conn->Node.Close = TCP_Client_Close;
982 conn->RecievedBuffer = RingBuffer_Create( TCP_RECIEVE_BUFFER_SIZE );
984 conn->SentBuffer = RingBuffer_Create( TCP_SEND_BUFFER_SIZE );
985 Semaphore_Init(conn->SentBufferSpace, 0, TCP_SEND_BUFFER_SIZE, "TCP SentBuffer", conn->Name);
988 #if CACHE_FUTURE_PACKETS_IN_BYTES
989 // Future recieved data (ahead of the expected sequence number)
990 conn->FuturePacketData = (Uint8*)conn + sizeof(tTCPConnection);
991 conn->FuturePacketValidBytes = conn->FuturePacketData + TCP_WINDOW_SIZE;
994 SHORTLOCK(&glTCP_OutbountCons);
995 conn->Next = gTCP_OutbountCons;
996 gTCP_OutbountCons = conn;
997 SHORTREL(&glTCP_OutbountCons);
1003 * \brief Wait for a packet and return it
1004 * \note If \a Length is smaller than the size of the packet, the rest
1005 * of the packet's data will be discarded.
1007 Uint64 TCP_Client_Read(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer)
1009 tTCPConnection *conn = Node->ImplPtr;
1012 ENTER("pNode XOffset XLength pBuffer", Node, Offset, Length, Buffer);
1013 LOG("conn = %p {State:%i}", conn, conn->State);
1015 // Check if connection is estabilishing
1016 // - TODO: Sleep instead (maybe using VFS_SelectNode to wait for the
1017 // data to be availiable
1018 while( conn->State == TCP_ST_SYN_RCVD || conn->State == TCP_ST_SYN_SENT )
1021 // If the conneciton is not nope, then clean out the recieved buffer
1022 if( conn->State != TCP_ST_OPEN )
1024 Mutex_Acquire( &conn->lRecievedPackets );
1025 len = RingBuffer_Read( Buffer, conn->RecievedBuffer, Length );
1026 Mutex_Release( &conn->lRecievedPackets );
1029 VFS_MarkAvaliable(Node, 0);
1039 VFS_SelectNode(Node, VFS_SELECT_READ, NULL, "TCP_Client_Read");
1041 // Lock list and read as much as possible (up to `Length`)
1042 Mutex_Acquire( &conn->lRecievedPackets );
1043 len = RingBuffer_Read( Buffer, conn->RecievedBuffer, Length );
1045 if( len == 0 || conn->RecievedBuffer->Length == 0 ) {
1046 LOG("Marking as none avaliable (len = %i)", len);
1047 VFS_MarkAvaliable(Node, 0);
1050 // Release the lock (we don't need it any more)
1051 Mutex_Release( &conn->lRecievedPackets );
1058 * \brief Send a data packet on a connection
1060 void TCP_INT_SendDataPacket(tTCPConnection *Connection, size_t Length, void *Data)
1062 char buf[sizeof(tTCPHeader)+Length];
1063 tTCPHeader *packet = (void*)buf;
1065 packet->SourcePort = htons(Connection->LocalPort);
1066 packet->DestPort = htons(Connection->RemotePort);
1067 packet->DataOffset = (sizeof(tTCPHeader)/4)*16;
1068 packet->WindowSize = TCP_WINDOW_SIZE;
1070 packet->AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
1071 packet->SequenceNumber = htonl(Connection->NextSequenceSend);
1072 packet->Flags = TCP_FLAG_PSH|TCP_FLAG_ACK; // Hey, ACK if you can!
1074 memcpy(packet->Options, Data, Length);
1076 Log_Debug("TCP", "Send sequence 0x%08x", Connection->NextSequenceSend);
1077 Debug_HexDump("[TCP ] TCP_INT_SendDataPacket: Data = ",
1080 TCP_SendPacket( Connection, sizeof(tTCPHeader)+Length, packet );
1082 Connection->NextSequenceSend += Length;
1086 * \brief Send some bytes on a connection
1088 Uint64 TCP_Client_Write(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer)
1090 tTCPConnection *conn = Node->ImplPtr;
1091 size_t rem = Length;
1093 ENTER("pNode XOffset XLength pBuffer", Node, Offset, Length, Buffer);
1096 // Debug_HexDump("TCP_Client_Write: Buffer = ",
1100 // Check if connection is open
1101 while( conn->State == TCP_ST_SYN_RCVD || conn->State == TCP_ST_SYN_SENT )
1104 if( conn->State != TCP_ST_OPEN ) {
1105 VFS_MarkError(Node, 1);
1112 int len = (rem < TCP_MAX_PACKET_SIZE) ? rem : TCP_MAX_PACKET_SIZE;
1115 // Wait for space in the buffer
1116 Semaphore_Signal( &Connection->SentBufferSpace, len );
1118 // Save data to buffer (and update the length read by the ammount written)
1119 len = RingBuffer_Write( &Connection->SentBuffer, Buffer, len);
1123 TCP_INT_SendDataPacket(conn, len, Buffer);
1134 * \brief Open a connection to another host using TCP
1135 * \param Conn Connection structure
1137 void TCP_StartConnection(tTCPConnection *Conn)
1139 tTCPHeader hdr = {0};
1141 Conn->State = TCP_ST_SYN_SENT;
1143 hdr.SourcePort = htons(Conn->LocalPort);
1144 hdr.DestPort = htons(Conn->RemotePort);
1145 Conn->NextSequenceSend = rand();
1146 hdr.SequenceNumber = htonl(Conn->NextSequenceSend);
1147 hdr.DataOffset = (sizeof(tTCPHeader)/4) << 4;
1148 hdr.Flags = TCP_FLAG_SYN;
1149 hdr.WindowSize = htons(TCP_WINDOW_SIZE); // Max
1150 hdr.Checksum = 0; // TODO
1152 TCP_SendPacket( Conn, sizeof(tTCPHeader), &hdr );
1154 Conn->NextSequenceSend ++;
1155 Conn->State = TCP_ST_SYN_SENT;
1160 * \brief Control a client socket
1162 int TCP_Client_IOCtl(tVFS_Node *Node, int ID, void *Data)
1164 tTCPConnection *conn = Node->ImplPtr;
1166 ENTER("pNode iID pData", Node, ID, Data);
1170 case 4: // Get/Set local port
1172 LEAVE_RET('i', conn->LocalPort);
1173 if(conn->State != TCP_ST_CLOSED)
1175 if(!CheckMem(Data, sizeof(Uint16)))
1178 if(Threads_GetUID() != 0 && *(Uint16*)Data < 1024)
1181 conn->LocalPort = *(Uint16*)Data;
1182 LEAVE_RET('i', conn->LocalPort);
1184 case 5: // Get/Set remote port
1185 if(!Data) LEAVE_RET('i', conn->RemotePort);
1186 if(conn->State != TCP_ST_CLOSED) LEAVE_RET('i', -1);
1187 if(!CheckMem(Data, sizeof(Uint16))) LEAVE_RET('i', -1);
1188 conn->RemotePort = *(Uint16*)Data;
1189 LEAVE_RET('i', conn->RemotePort);
1191 case 6: // Set Remote IP
1192 if( conn->State != TCP_ST_CLOSED )
1194 if( conn->Interface->Type == 4 )
1196 if(!CheckMem(Data, sizeof(tIPv4))) LEAVE_RET('i', -1);
1197 conn->RemoteIP.v4 = *(tIPv4*)Data;
1199 else if( conn->Interface->Type == 6 )
1201 if(!CheckMem(Data, sizeof(tIPv6))) LEAVE_RET('i', -1);
1202 conn->RemoteIP.v6 = *(tIPv6*)Data;
1207 if(conn->LocalPort == 0xFFFF)
1208 conn->LocalPort = TCP_GetUnusedPort();
1209 if(conn->RemotePort == -1)
1212 TCP_StartConnection(conn);
1215 // Get recieve buffer length
1217 LEAVE_RET('i', conn->RecievedBuffer->Length);
1223 void TCP_Client_Close(tVFS_Node *Node)
1225 tTCPConnection *conn = Node->ImplPtr;
1228 ENTER("pNode", Node);
1230 if( conn->State == TCP_ST_CLOSE_WAIT || conn->State == TCP_ST_OPEN )
1232 packet.SourcePort = htons(conn->LocalPort);
1233 packet.DestPort = htons(conn->RemotePort);
1234 packet.DataOffset = (sizeof(tTCPHeader)/4)*16;
1235 packet.WindowSize = TCP_WINDOW_SIZE;
1237 packet.AcknowlegementNumber = 0;
1238 packet.SequenceNumber = htonl(conn->NextSequenceSend);
1239 packet.Flags = TCP_FLAG_FIN|TCP_FLAG_ACK;
1241 TCP_SendPacket( conn, sizeof(tTCPHeader), &packet );
1244 switch( conn->State )
1246 case TCP_ST_CLOSE_WAIT:
1247 conn->State = TCP_ST_CLOSED;
1250 conn->State = TCP_ST_FIN_WAIT1;
1251 while( conn->State == TCP_ST_FIN_WAIT1 ) Threads_Yield();
1254 Log_Warning("TCP", "Unhandled connection state in TCP_Client_Close");
1264 * \brief Checks if a value is between two others (after taking into account wrapping)
1266 int WrapBetween(Uint32 Lower, Uint32 Value, Uint32 Higher, Uint32 MaxValue)
1268 if( MaxValue < 0xFFFFFFFF )
1270 Lower %= MaxValue + 1;
1271 Value %= MaxValue + 1;
1272 Higher %= MaxValue + 1;
1275 // Simple Case, no wrap ?
1276 // Lower Value Higher
1277 // | ... + ... + ... + ... |
1279 if( Lower < Higher ) {
1280 return Lower < Value && Value < Higher;
1282 // Higher has wrapped below lower
1285 // Higher Lower Value
1286 // | ... + ... + ... + ... |
1287 if( Value > Lower ) {
1292 // Value Higher Lower
1293 // | ... + ... + ... + ... |
1294 if( Value < Higher ) {