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 giTCP_NextOutPort += rand()%32;
68 IPStack_AddFile(&gTCP_ServerFile);
69 IPStack_AddFile(&gTCP_ClientFile);
70 IPv4_RegisterCallback(IP4PROT_TCP, TCP_GetPacket);
74 * \brief Sends a packet from the specified connection, calculating the checksums
75 * \param Conn Connection
76 * \param Length Length of data
77 * \param Data Packet data (cast as a TCP Header)
79 void TCP_SendPacket( tTCPConnection *Conn, size_t Length, tTCPHeader *Data )
83 switch( Conn->Interface->Type )
85 case 4: // Append IPv4 Pseudo Header
86 buflen = 4 + 4 + 4 + ((Length+1)&~1);
87 buf = malloc( buflen );
88 buf[0] = ((tIPv4*)Conn->Interface->Address)->L;
89 buf[1] = Conn->RemoteIP.v4.L;
90 buf[2] = (htons(Length)<<16) | (6<<8) | 0;
92 memcpy( &buf[3], Data, Length );
94 ((Uint8*)buf)[12+Length] = 0;
95 Data->Checksum = htons( IPv4_Checksum( buf, buflen ) );
97 IPv4_SendPacket(Conn->Interface, Conn->RemoteIP.v4, IP4PROT_TCP, 0, Length, Data);
103 * \brief Handles a packet from the IP Layer
104 * \param Interface Interface the packet arrived from
105 * \param Address Pointer to the addres structure
106 * \param Length Size of packet in bytes
107 * \param Buffer Packet data
109 void TCP_GetPacket(tInterface *Interface, void *Address, int Length, void *Buffer)
111 tTCPHeader *hdr = Buffer;
113 tTCPConnection *conn;
115 Log_Log("TCP", "TCP_GetPacket: SourcePort = %i, DestPort = %i",
116 ntohs(hdr->SourcePort), ntohs(hdr->DestPort));
118 Log_Log("TCP", "TCP_GetPacket: SequenceNumber = 0x%x", ntohl(hdr->SequenceNumber));
119 Log_Log("TCP", "TCP_GetPacket: AcknowlegementNumber = 0x%x", ntohl(hdr->AcknowlegementNumber));
120 Log_Log("TCP", "TCP_GetPacket: DataOffset = %i", hdr->DataOffset >> 4);
121 Log_Log("TCP", "TCP_GetPacket: WindowSize = %i", htons(hdr->WindowSize));
122 Log_Log("TCP", "TCP_GetPacket: Checksum = 0x%x", htons(hdr->Checksum));
123 Log_Log("TCP", "TCP_GetPacket: UrgentPointer = 0x%x", htons(hdr->UrgentPointer));
125 Log_Log("TCP", "TCP_GetPacket: Flags = %s%s%s%s%s%s%s%s",
126 (hdr->Flags & TCP_FLAG_CWR) ? "CWR " : "",
127 (hdr->Flags & TCP_FLAG_ECE) ? "ECE " : "",
128 (hdr->Flags & TCP_FLAG_URG) ? "URG " : "",
129 (hdr->Flags & TCP_FLAG_ACK) ? "ACK " : "",
130 (hdr->Flags & TCP_FLAG_PSH) ? "PSH " : "",
131 (hdr->Flags & TCP_FLAG_RST) ? "RST " : "",
132 (hdr->Flags & TCP_FLAG_SYN) ? "SYN " : "",
133 (hdr->Flags & TCP_FLAG_FIN) ? "FIN " : ""
136 if( Length > (hdr->DataOffset >> 4)*4 )
138 Log_Log("TCP", "TCP_GetPacket: SequenceNumber = 0x%x", ntohl(hdr->SequenceNumber));
140 "[TCP ] Packet Data = ",
141 (Uint8*)hdr + (hdr->DataOffset >> 4)*4,
142 Length - (hdr->DataOffset >> 4)*4
148 for( srv = gTCP_Listeners; srv; srv = srv->Next )
150 // Check if the server is active
151 if(srv->Port == 0) continue;
152 // Check the interface
153 if(srv->Interface && srv->Interface != Interface) continue;
154 // Check the destination port
155 if(srv->Port != htons(hdr->DestPort)) continue;
157 Log_Log("TCP", "TCP_GetPacket: Matches server %p", srv);
158 // Is this in an established connection?
159 for( conn = srv->Connections; conn; conn = conn->Next )
161 Log_Log("TCP", "TCP_GetPacket: conn->Interface(%p) == Interface(%p)",
162 conn->Interface, Interface);
163 // Check that it is coming in on the same interface
164 if(conn->Interface != Interface) continue;
167 Log_Log("TCP", "TCP_GetPacket: conn->RemotePort(%i) == hdr->SourcePort(%i)",
168 conn->RemotePort, ntohs(hdr->SourcePort));
169 if(conn->RemotePort != ntohs(hdr->SourcePort)) continue;
172 if(conn->Interface->Type == 6 && !IP6_EQU(conn->RemoteIP.v6, *(tIPv6*)Address))
174 if(conn->Interface->Type == 4 && !IP4_EQU(conn->RemoteIP.v4, *(tIPv4*)Address))
177 Log_Log("TCP", "TCP_GetPacket: Matches connection %p", conn);
178 // We have a response!
179 TCP_INT_HandleConnectionPacket(conn, hdr, Length);
184 Log_Log("TCP", "TCP_GetPacket: Opening Connection");
185 // Open a new connection (well, check that it's a SYN)
186 if(hdr->Flags != TCP_FLAG_SYN) {
187 Log_Log("TCP", "TCP_GetPacket: Packet is not a SYN");
191 // TODO: Check for halfopen max
193 conn = calloc(1, sizeof(tTCPConnection));
194 conn->State = TCP_ST_SYN_RCVD;
195 conn->LocalPort = srv->Port;
196 conn->RemotePort = ntohs(hdr->SourcePort);
197 conn->Interface = Interface;
199 switch(Interface->Type)
201 case 4: conn->RemoteIP.v4 = *(tIPv4*)Address; break;
202 case 6: conn->RemoteIP.v6 = *(tIPv6*)Address; break;
205 conn->RecievedBuffer = RingBuffer_Create( TCP_RECIEVE_BUFFER_SIZE );
207 conn->NextSequenceRcv = ntohl( hdr->SequenceNumber ) + 1;
208 conn->NextSequenceSend = rand();
211 conn->Node.NumACLs = 1;
212 conn->Node.ACLs = &gVFS_ACL_EveryoneRW;
213 conn->Node.ImplPtr = conn;
214 conn->Node.ImplInt = srv->NextID ++;
215 conn->Node.Read = TCP_Client_Read;
216 conn->Node.Write = TCP_Client_Write;
217 //conn->Node.Close = TCP_SrvConn_Close;
219 // Hmm... Theoretically, this lock will never have to wait,
220 // as the interface is locked to the watching thread, and this
221 // runs in the watching thread. But, it's a good idea to have
223 // Oh, wait, there is a case where a wildcard can be used
224 // (srv->Interface == NULL) so having the lock is a good idea
225 SHORTLOCK(&srv->lConnections);
226 if( !srv->Connections )
227 srv->Connections = conn;
229 srv->ConnectionsTail->Next = conn;
230 srv->ConnectionsTail = conn;
231 if(!srv->NewConnections)
232 srv->NewConnections = conn;
233 SHORTREL(&srv->lConnections);
236 hdr->Flags |= TCP_FLAG_ACK;
237 hdr->AcknowlegementNumber = htonl(conn->NextSequenceRcv);
238 hdr->SequenceNumber = htonl(conn->NextSequenceSend);
239 hdr->DestPort = hdr->SourcePort;
240 hdr->SourcePort = htons(srv->Port);
241 hdr->DataOffset = (sizeof(tTCPHeader)/4) << 4;
242 TCP_SendPacket( conn, sizeof(tTCPHeader), hdr );
243 conn->NextSequenceSend ++;
249 // Check Open Connections
251 for( conn = gTCP_OutbountCons; conn; conn = conn->Next )
253 // Check that it is coming in on the same interface
254 if(conn->Interface != Interface) continue;
257 if(conn->RemotePort != ntohs(hdr->SourcePort)) continue;
260 if(conn->Interface->Type == 6 && !IP6_EQU(conn->RemoteIP.v6, *(tIPv6*)Address))
262 if(conn->Interface->Type == 4 && !IP4_EQU(conn->RemoteIP.v4, *(tIPv4*)Address))
265 TCP_INT_HandleConnectionPacket(conn, hdr, Length);
270 Log_Log("TCP", "TCP_GetPacket: No Match");
274 * \brief Handles a packet sent to a specific connection
275 * \param Connection TCP Connection pointer
276 * \param Header TCP Packet pointer
277 * \param Length Length of the packet
279 void TCP_INT_HandleConnectionPacket(tTCPConnection *Connection, tTCPHeader *Header, int Length)
281 tTCPStoredPacket *pkt;
284 // Silently drop once finished
285 // TODO: Check if this needs to be here
286 if( Connection->State == TCP_ST_FINISHED ) {
287 Log_Log("TCP", "Packet ignored - connection finnished");
291 // Syncronise sequence values
292 if(Header->Flags & TCP_FLAG_SYN) {
293 // TODO: What if the packet also has data?
294 Connection->NextSequenceRcv = ntohl(Header->SequenceNumber);
297 // Ackowledge a sent packet
298 if(Header->Flags & TCP_FLAG_ACK) {
299 // TODO: Process an ACKed Packet
300 Log_Log("TCP", "Conn %p, Sent packet 0x%x ACKed", Connection, Header->AcknowlegementNumber);
303 // Get length of data
304 dataLen = Length - (Header->DataOffset>>4)*4;
305 Log_Log("TCP", "HandleConnectionPacket - dataLen = %i", dataLen);
310 switch( Connection->State )
312 // Pre-init conneciton?
314 Log_Log("TCP", "Packets to a closed connection?!");
317 // --- Init States ---
318 // SYN sent, expecting SYN-ACK Connection Opening
319 case TCP_ST_SYN_SENT:
320 if( Header->Flags & TCP_FLAG_SYN )
322 Connection->NextSequenceRcv ++;
323 Header->DestPort = Header->SourcePort;
324 Header->SourcePort = htons(Connection->LocalPort);
325 Header->AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
326 Header->SequenceNumber = htonl(Connection->NextSequenceSend);
327 Header->WindowSize = htons(TCP_WINDOW_SIZE);
328 Header->Flags = TCP_FLAG_ACK;
329 Header->DataOffset = (sizeof(tTCPHeader)/4) << 4;
330 TCP_SendPacket( Connection, sizeof(tTCPHeader), Header );
332 if( Header->Flags & TCP_FLAG_ACK )
334 Log_Log("TCP", "ACKing SYN-ACK");
335 Connection->State = TCP_ST_OPEN;
339 Log_Log("TCP", "ACKing SYN");
340 Connection->State = TCP_ST_SYN_RCVD;
345 // SYN-ACK sent, expecting ACK
346 case TCP_ST_SYN_RCVD:
347 if( Header->Flags & TCP_FLAG_ACK )
349 // TODO: Handle max half-open limit
350 Connection->State = TCP_ST_OPEN;
351 Log_Log("TCP", "Connection fully opened");
355 // --- Established State ---
357 // - Handle State changes
359 if( Header->Flags & TCP_FLAG_FIN ) {
360 Log_Log("TCP", "Conn %p closed, recieved FIN", Connection);
361 VFS_MarkError(&Connection->Node, 1);
362 Connection->State = TCP_ST_CLOSE_WAIT;
363 // Header->Flags &= ~TCP_FLAG_FIN;
364 // CLOSE WAIT requires the client to close (or does it?)
370 // Check for an empty packet
372 if( Header->Flags == TCP_FLAG_ACK )
374 Log_Log("TCP", "ACK only packet");
377 Connection->NextSequenceRcv ++; // TODO: Is this right? (empty packet counts as one byte)
378 Log_Log("TCP", "Empty Packet, inc and ACK the current sequence number");
379 Header->DestPort = Header->SourcePort;
380 Header->SourcePort = htons(Connection->LocalPort);
381 Header->AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
382 Header->SequenceNumber = htonl(Connection->NextSequenceSend);
383 Header->Flags |= TCP_FLAG_ACK;
384 TCP_SendPacket( Connection, sizeof(tTCPHeader), Header );
393 // Allocate and fill cached packet
394 pkt = malloc( sizeof(tTCPStoredPacket) + dataLen );
396 pkt->Sequence = ntohl(Header->SequenceNumber);
397 pkt->Length = dataLen;
398 memcpy(pkt->Data, (Uint8*)Header + (Header->DataOffset>>4)*4, dataLen);
400 Log_Log("TCP", "0x%08x <= 0x%08x < 0x%08x",
401 Connection->NextSequenceRcv,
403 Connection->NextSequenceRcv + TCP_WINDOW_SIZE
406 // Is this packet the next expected packet?
407 if( pkt->Sequence == Connection->NextSequenceRcv )
409 // Ooh, Goodie! Add it to the recieved list
410 TCP_INT_AppendRecieved(Connection, pkt);
412 Log_Log("TCP", "0x%08x += %i", Connection->NextSequenceRcv, dataLen);
413 Connection->NextSequenceRcv += dataLen;
415 // TODO: This should be moved out of the watcher thread,
416 // so that a single lost packet on one connection doesn't cause
417 // all connections on the interface to lag.
418 // - Meh, no real issue, as the cache shouldn't be that large
419 TCP_INT_UpdateRecievedFromFuture(Connection);
422 Header->DestPort = Header->SourcePort;
423 Header->SourcePort = htons(Connection->LocalPort);
424 Header->AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
425 Header->SequenceNumber = htonl(Connection->NextSequenceSend);
426 Header->WindowSize = htons(TCP_WINDOW_SIZE);
427 Header->Flags &= TCP_FLAG_SYN; // Eliminate all flags save for SYN
428 Header->Flags |= TCP_FLAG_ACK; // Add ACK
429 Log_Log("TCP", "Sending ACK for 0x%08x", Connection->NextSequenceRcv);
430 TCP_SendPacket( Connection, sizeof(tTCPHeader), Header );
431 //Connection->NextSequenceSend ++;
433 // Check if the packet is in window
434 else if( WrapBetween(Connection->NextSequenceRcv, pkt->Sequence,
435 Connection->NextSequenceRcv+TCP_WINDOW_SIZE, 0xFFFFFFFF) )
437 #if CACHE_FUTURE_PACKETS_IN_BYTES
441 index = pkt->Sequence % TCP_WINDOW_SIZE;
442 for( i = 0; i < pkt->Length; i ++ )
444 Connection->FuturePacketValidBytes[index/8] |= 1 << (index%8);
445 Connection->FuturePacketValidBytes[index] = pkt->Data[i];
446 // Do a wrap increment
448 if(index == TCP_WINDOW_SIZE) index = 0;
451 tTCPStoredPacket *tmp, *prev = NULL;
453 Log_Log("TCP", "We missed a packet, caching",
454 pkt->Sequence, Connection->NextSequenceRcv);
456 // No? Well, let's cache it and look at it later
457 SHORTLOCK( &Connection->lFuturePackets );
458 for(tmp = Connection->FuturePackets;
460 prev = tmp, tmp = tmp->Next)
462 if(tmp->Sequence >= pkt->Sequence) break;
465 // Add if before first, or sequences don't match
466 if( !tmp || tmp->Sequence != pkt->Sequence )
471 Connection->FuturePackets = pkt;
475 else if(pkt->Length > tmp->Length)
479 pkt->Next = tmp->Next;
486 SHORTREL( &Connection->lFuturePackets );
489 // Badly out of sequence packet
492 Log_Log("TCP", "Fully out of sequence packet (0x%08x not between 0x%08x and 0x%08x), dropped",
493 pkt->Sequence, Connection->NextSequenceRcv, Connection->NextSequenceRcv+TCP_WINDOW_SIZE);
495 // TODO: Spec says we should send an empty ACK with the current state
499 // --- Remote close states
500 case TCP_ST_CLOSE_WAIT:
502 // Ignore everything, CLOSE_WAIT is terminated by the client
503 Log_Debug("TCP", "CLOSE WAIT - Ignoring packets");
507 // LAST-ACK - Waiting for the ACK of FIN (from CLOSE WAIT)
508 case TCP_ST_LAST_ACK:
509 if( Header->Flags & TCP_FLAG_ACK )
511 Connection->State = TCP_ST_FINISHED; // Connection completed
512 Log_Log("TCP", "LAST-ACK to CLOSED - Connection remote closed");
513 // TODO: Destrory the TCB
517 // --- Local close States
518 case TCP_ST_FIN_WAIT1:
519 if( Header->Flags & TCP_FLAG_FIN )
521 Connection->State = TCP_ST_CLOSING;
522 Log_Debug("TCP", "Conn %p closed, sent FIN and recieved FIN", Connection);
523 VFS_MarkError(&Connection->Node, 1);
526 Header->DestPort = Header->SourcePort;
527 Header->SourcePort = htons(Connection->LocalPort);
528 Header->AcknowlegementNumber = Header->SequenceNumber;
529 Header->SequenceNumber = htonl(Connection->NextSequenceSend);
530 Header->WindowSize = htons(TCP_WINDOW_SIZE);
531 Header->Flags = TCP_FLAG_ACK;
532 TCP_SendPacket( Connection, sizeof(tTCPHeader), Header );
536 // TODO: Make sure that the packet is actually ACKing the FIN
537 if( Header->Flags & TCP_FLAG_ACK )
539 Connection->State = TCP_ST_FIN_WAIT2;
540 Log_Debug("TCP", "Conn %p closed, sent FIN ACKed", Connection);
541 VFS_MarkError(&Connection->Node, 1);
546 case TCP_ST_FIN_WAIT2:
547 if( Header->Flags & TCP_FLAG_FIN )
549 Connection->State = TCP_ST_TIME_WAIT;
550 Log_Debug("TCP", "FIN sent and recieved, ACKing and going into TIME WAIT %p FINWAIT-2 -> TIME WAIT", Connection);
552 Header->DestPort = Header->SourcePort;
553 Header->SourcePort = htons(Connection->LocalPort);
554 Header->AcknowlegementNumber = Header->SequenceNumber;
555 Header->SequenceNumber = htonl(Connection->NextSequenceSend);
556 Header->WindowSize = htons(TCP_WINDOW_SIZE);
557 Header->Flags = TCP_FLAG_ACK;
558 TCP_SendPacket( Connection, sizeof(tTCPHeader), Header );
563 // TODO: Make sure that the packet is actually ACKing the FIN
564 if( Header->Flags & TCP_FLAG_ACK )
566 Connection->State = TCP_ST_TIME_WAIT;
567 Log_Debug("TCP", "Conn %p CLOSING -> TIME WAIT", Connection);
568 VFS_MarkError(&Connection->Node, 1);
573 // --- Closed (or near closed) states) ---
574 case TCP_ST_TIME_WAIT:
575 Log_Log("TCP", "Packets on Time-Wait, ignored");
578 case TCP_ST_FINISHED:
579 Log_Log("TCP", "Packets when CLOSED, ignoring");
583 // Log_Warning("TCP", "Unhandled TCP state %i", Connection->State);
590 * \brief Appends a packet to the recieved list
591 * \param Connection Connection structure
592 * \param Pkt Packet structure on heap
594 void TCP_INT_AppendRecieved(tTCPConnection *Connection, tTCPStoredPacket *Pkt)
596 Mutex_Acquire( &Connection->lRecievedPackets );
597 if(Connection->RecievedBuffer->Length + Pkt->Length > Connection->RecievedBuffer->Space )
599 Log_Error("TCP", "Buffer filled, packet dropped (%s)",
600 // TCP_INT_DumpConnection(Connection)
606 RingBuffer_Write( Connection->RecievedBuffer, Pkt->Data, Pkt->Length );
608 VFS_MarkAvaliable(&Connection->Node, 1);
610 Mutex_Release( &Connection->lRecievedPackets );
614 * \brief Updates the connections recieved list from the future list
615 * \param Connection Connection structure
617 * Updates the recieved packets list with packets from the future (out
618 * of order) packets list that are now able to be added in direct
621 void TCP_INT_UpdateRecievedFromFuture(tTCPConnection *Connection)
623 #if CACHE_FUTURE_PACKETS_IN_BYTES
627 // Calculate length of contiguous bytes
628 length = Connection->HighestSequenceRcvd - Connection->NextSequenceRcv;
629 index = Connection->NextSequenceRcv % TCP_WINDOW_SIZE;
630 for( i = 0; i < length; i ++ )
632 if( Connection->FuturePacketValidBytes[i / 8] == 0xFF ) {
636 else if( !(Connection->FuturePacketValidBytes[i / 8] & (1 << (i%8))) )
640 if(index > TCP_WINDOW_SIZE)
641 index -= TCP_WINDOW_SIZE;
645 index = Connection->NextSequenceRcv % TCP_WINDOW_SIZE;
647 // Write data to to the ring buffer
648 if( TCP_WINDOW_SIZE - index > length )
651 RingBuffer_Write( Connection->RecievedBuffer, Connection->FuturePacketData + index, length );
655 int endLen = TCP_WINDOW_SIZE - index;
657 RingBuffer_Write( Connection->RecievedBuffer, Connection->FuturePacketData + index, endLen );
658 RingBuffer_Write( Connection->RecievedBuffer, Connection->FuturePacketData, endLen - length );
661 // Mark (now saved) bytes as invalid
663 while(index % 8 && length)
665 Connection->FuturePacketData[index] = 0;
666 Connection->FuturePacketData[index/8] &= ~(1 << (index%8));
668 if(index > TCP_WINDOW_SIZE)
669 index -= TCP_WINDOW_SIZE;
674 Connection->FuturePacketData[index] = 0;
675 Connection->FuturePacketValidBytes[index/8] = 0;
678 if(index > TCP_WINDOW_SIZE)
679 index -= TCP_WINDOW_SIZE;
683 Connection->FuturePacketData[index] = 0;
684 Connection->FuturePacketData[index/8] &= ~(1 << (index%8));
686 if(index > TCP_WINDOW_SIZE)
687 index -= TCP_WINDOW_SIZE;
692 tTCPStoredPacket *pkt;
695 SHORTLOCK( &Connection->lFuturePackets );
697 // Clear out duplicates from cache
698 // - If a packet has just been recieved, and it is expected, then
699 // (since NextSequenceRcv = rcvd->Sequence + rcvd->Length) all
700 // packets in cache that are smaller than the next expected
702 pkt = Connection->FuturePackets;
703 while(pkt && pkt->Sequence < Connection->NextSequenceRcv)
705 tTCPStoredPacket *next = pkt->Next;
710 // If there's no packets left in cache, stop looking
711 if(!pkt || pkt->Sequence > Connection->NextSequenceRcv) {
712 SHORTREL( &Connection->lFuturePackets );
716 // Delete packet from future list
717 Connection->FuturePackets = pkt->Next;
720 SHORTREL( &Connection->lFuturePackets );
722 // Looks like we found one
723 TCP_INT_AppendRecieved(Connection, pkt);
724 Connection->NextSequenceRcv += pkt->Length;
731 * \fn Uint16 TCP_GetUnusedPort()
732 * \brief Gets an unused port and allocates it
734 Uint16 TCP_GetUnusedPort()
738 // Get Next outbound port
739 ret = giTCP_NextOutPort++;
740 while( gaTCP_PortBitmap[ret/32] & (1 << (ret%32)) )
744 if(giTCP_NextOutPort == 0x10000) {
745 ret = giTCP_NextOutPort = TCP_MIN_DYNPORT;
749 // Mark the new port as used
750 gaTCP_PortBitmap[ret/32] |= 1 << (ret%32);
756 * \fn int TCP_AllocatePort(Uint16 Port)
757 * \brief Marks a port as used
759 int TCP_AllocatePort(Uint16 Port)
761 // Check if the port has already been allocated
762 if( gaTCP_PortBitmap[Port/32] & (1 << (Port%32)) )
766 gaTCP_PortBitmap[Port/32] |= 1 << (Port%32);
772 * \fn int TCP_DeallocatePort(Uint16 Port)
773 * \brief Marks a port as unused
775 int TCP_DeallocatePort(Uint16 Port)
777 // Check if the port has already been allocated
778 if( !(gaTCP_PortBitmap[Port/32] & (1 << (Port%32))) )
782 gaTCP_PortBitmap[Port/32] &= ~(1 << (Port%32));
788 tVFS_Node *TCP_Server_Init(tInterface *Interface)
792 srv = malloc( sizeof(tTCPListener) );
795 Log_Warning("TCP", "malloc failed for listener (%i) bytes", sizeof(tTCPListener));
799 srv->Interface = Interface;
802 srv->Connections = NULL;
803 srv->ConnectionsTail = NULL;
804 srv->NewConnections = NULL;
806 srv->Node.Flags = VFS_FFLAG_DIRECTORY;
808 srv->Node.ImplPtr = srv;
809 srv->Node.NumACLs = 1;
810 srv->Node.ACLs = &gVFS_ACL_EveryoneRW;
811 srv->Node.ReadDir = TCP_Server_ReadDir;
812 srv->Node.FindDir = TCP_Server_FindDir;
813 srv->Node.IOCtl = TCP_Server_IOCtl;
814 srv->Node.Close = TCP_Server_Close;
816 SHORTLOCK(&glTCP_Listeners);
817 srv->Next = gTCP_Listeners;
818 gTCP_Listeners = srv;
819 SHORTREL(&glTCP_Listeners);
825 * \brief Wait for a new connection and return the connection ID
826 * \note Blocks until a new connection is made
827 * \param Node Server node
828 * \param Pos Position (ignored)
830 char *TCP_Server_ReadDir(tVFS_Node *Node, int Pos)
832 tTCPListener *srv = Node->ImplPtr;
833 tTCPConnection *conn;
836 ENTER("pNode iPos", Node, Pos);
838 Log_Log("TCP", "Thread %i waiting for a connection", Threads_GetTID());
841 SHORTLOCK( &srv->lConnections );
842 if( srv->NewConnections != NULL ) break;
843 SHORTREL( &srv->lConnections );
844 Threads_Yield(); // TODO: Sleep until poked
849 // Increment the new list (the current connection is still on the
851 conn = srv->NewConnections;
852 srv->NewConnections = conn->Next;
854 SHORTREL( &srv->lConnections );
856 LOG("conn = %p", conn);
857 LOG("srv->Connections = %p", srv->Connections);
858 LOG("srv->NewConnections = %p", srv->NewConnections);
859 LOG("srv->ConnectionsTail = %p", srv->ConnectionsTail);
862 itoa(ret, conn->Node.ImplInt, 16, 8, '0');
863 Log_Log("TCP", "Thread %i got '%s'", Threads_GetTID(), ret);
869 * \brief Gets a client connection node
870 * \param Node Server node
871 * \param Name Hexadecimal ID of the node
873 tVFS_Node *TCP_Server_FindDir(tVFS_Node *Node, const char *Name)
875 tTCPConnection *conn;
876 tTCPListener *srv = Node->ImplPtr;
880 ENTER("pNode sName", Node, Name);
883 itoa(tmp, id, 16, 8, '0');
884 if(strcmp(tmp, Name) != 0) {
885 LOG("'%s' != '%s' (%08x)", Name, tmp, id);
890 Log_Debug("TCP", "srv->Connections = %p", srv->Connections);
891 Log_Debug("TCP", "srv->NewConnections = %p", srv->NewConnections);
892 Log_Debug("TCP", "srv->ConnectionsTail = %p", srv->ConnectionsTail);
895 SHORTLOCK( &srv->lConnections );
896 for(conn = srv->Connections;
900 LOG("conn->Node.ImplInt = %i", conn->Node.ImplInt);
901 if(conn->Node.ImplInt == id) break;
903 SHORTREL( &srv->lConnections );
905 // If not found, ret NULL
907 LOG("Connection %i not found", id);
913 LEAVE('p', &conn->Node);
918 * \brief Handle IOCtl calls
920 int TCP_Server_IOCtl(tVFS_Node *Node, int ID, void *Data)
922 tTCPListener *srv = Node->ImplPtr;
926 case 4: // Get/Set Port
927 if(!Data) // Get Port
930 if(srv->Port) // Wait, you can't CHANGE the port
933 if(!CheckMem(Data, sizeof(Uint16))) // Sanity check
937 if(Threads_GetUID() != 0
938 && *(Uint16*)Data != 0
939 && *(Uint16*)Data < 1024)
942 // TODO: Check if a port is in use
945 srv->Port = *(Uint16*)Data;
946 if(srv->Port == 0) // Allocate a random port
947 srv->Port = TCP_GetUnusedPort();
948 else // Else, mark this as used
949 TCP_AllocatePort(srv->Port);
951 Log_Log("TCP", "Server %p listening on port %i", srv, srv->Port);
958 void TCP_Server_Close(tVFS_Node *Node)
965 * \brief Create a client node
967 tVFS_Node *TCP_Client_Init(tInterface *Interface)
969 tTCPConnection *conn = calloc( sizeof(tTCPConnection) + TCP_WINDOW_SIZE + TCP_WINDOW_SIZE/8, 1 );
971 conn->State = TCP_ST_CLOSED;
972 conn->Interface = Interface;
973 conn->LocalPort = -1;
974 conn->RemotePort = -1;
976 conn->Node.ImplPtr = conn;
977 conn->Node.NumACLs = 1;
978 conn->Node.ACLs = &gVFS_ACL_EveryoneRW;
979 conn->Node.Read = TCP_Client_Read;
980 conn->Node.Write = TCP_Client_Write;
981 conn->Node.IOCtl = TCP_Client_IOCtl;
982 conn->Node.Close = TCP_Client_Close;
984 conn->RecievedBuffer = RingBuffer_Create( TCP_RECIEVE_BUFFER_SIZE );
986 conn->SentBuffer = RingBuffer_Create( TCP_SEND_BUFFER_SIZE );
987 Semaphore_Init(conn->SentBufferSpace, 0, TCP_SEND_BUFFER_SIZE, "TCP SentBuffer", conn->Name);
990 #if CACHE_FUTURE_PACKETS_IN_BYTES
991 // Future recieved data (ahead of the expected sequence number)
992 conn->FuturePacketData = (Uint8*)conn + sizeof(tTCPConnection);
993 conn->FuturePacketValidBytes = conn->FuturePacketData + TCP_WINDOW_SIZE;
996 SHORTLOCK(&glTCP_OutbountCons);
997 conn->Next = gTCP_OutbountCons;
998 gTCP_OutbountCons = conn;
999 SHORTREL(&glTCP_OutbountCons);
1005 * \brief Wait for a packet and return it
1006 * \note If \a Length is smaller than the size of the packet, the rest
1007 * of the packet's data will be discarded.
1009 Uint64 TCP_Client_Read(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer)
1011 tTCPConnection *conn = Node->ImplPtr;
1014 ENTER("pNode XOffset XLength pBuffer", Node, Offset, Length, Buffer);
1015 LOG("conn = %p {State:%i}", conn, conn->State);
1017 // Check if connection is estabilishing
1018 // - TODO: Sleep instead (maybe using VFS_SelectNode to wait for the
1019 // data to be availiable
1020 while( conn->State == TCP_ST_SYN_RCVD || conn->State == TCP_ST_SYN_SENT )
1023 // If the conneciton is not open, then clean out the recieved buffer
1024 if( conn->State != TCP_ST_OPEN )
1026 Mutex_Acquire( &conn->lRecievedPackets );
1027 len = RingBuffer_Read( Buffer, conn->RecievedBuffer, Length );
1028 Mutex_Release( &conn->lRecievedPackets );
1031 VFS_MarkAvaliable(Node, 0);
1041 VFS_SelectNode(Node, VFS_SELECT_READ|VFS_SELECT_ERROR, NULL, "TCP_Client_Read");
1043 // Lock list and read as much as possible (up to `Length`)
1044 Mutex_Acquire( &conn->lRecievedPackets );
1045 len = RingBuffer_Read( Buffer, conn->RecievedBuffer, Length );
1047 if( len == 0 || conn->RecievedBuffer->Length == 0 ) {
1048 LOG("Marking as none avaliable (len = %i)", len);
1049 VFS_MarkAvaliable(Node, 0);
1052 // Release the lock (we don't need it any more)
1053 Mutex_Release( &conn->lRecievedPackets );
1060 * \brief Send a data packet on a connection
1062 void TCP_INT_SendDataPacket(tTCPConnection *Connection, size_t Length, void *Data)
1064 char buf[sizeof(tTCPHeader)+Length];
1065 tTCPHeader *packet = (void*)buf;
1067 packet->SourcePort = htons(Connection->LocalPort);
1068 packet->DestPort = htons(Connection->RemotePort);
1069 packet->DataOffset = (sizeof(tTCPHeader)/4)*16;
1070 packet->WindowSize = htons(TCP_WINDOW_SIZE);
1072 packet->AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
1073 packet->SequenceNumber = htonl(Connection->NextSequenceSend);
1074 packet->Flags = TCP_FLAG_PSH|TCP_FLAG_ACK; // Hey, ACK if you can!
1076 memcpy(packet->Options, Data, Length);
1078 Log_Debug("TCP", "Send sequence 0x%08x", Connection->NextSequenceSend);
1079 Debug_HexDump("[TCP ] TCP_INT_SendDataPacket: Data = ",
1082 TCP_SendPacket( Connection, sizeof(tTCPHeader)+Length, packet );
1084 Connection->NextSequenceSend += Length;
1088 * \brief Send some bytes on a connection
1090 Uint64 TCP_Client_Write(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer)
1092 tTCPConnection *conn = Node->ImplPtr;
1093 size_t rem = Length;
1095 ENTER("pNode XOffset XLength pBuffer", Node, Offset, Length, Buffer);
1098 // Debug_HexDump("TCP_Client_Write: Buffer = ",
1102 // Check if connection is open
1103 while( conn->State == TCP_ST_SYN_RCVD || conn->State == TCP_ST_SYN_SENT )
1106 if( conn->State != TCP_ST_OPEN ) {
1107 VFS_MarkError(Node, 1);
1114 int len = (rem < TCP_MAX_PACKET_SIZE) ? rem : TCP_MAX_PACKET_SIZE;
1117 // Wait for space in the buffer
1118 Semaphore_Signal( &Connection->SentBufferSpace, len );
1120 // Save data to buffer (and update the length read by the ammount written)
1121 len = RingBuffer_Write( &Connection->SentBuffer, Buffer, len);
1125 TCP_INT_SendDataPacket(conn, len, Buffer);
1136 * \brief Open a connection to another host using TCP
1137 * \param Conn Connection structure
1139 void TCP_StartConnection(tTCPConnection *Conn)
1141 tTCPHeader hdr = {0};
1143 Conn->State = TCP_ST_SYN_SENT;
1145 hdr.SourcePort = htons(Conn->LocalPort);
1146 hdr.DestPort = htons(Conn->RemotePort);
1147 Conn->NextSequenceSend = rand();
1148 hdr.SequenceNumber = htonl(Conn->NextSequenceSend);
1149 hdr.DataOffset = (sizeof(tTCPHeader)/4) << 4;
1150 hdr.Flags = TCP_FLAG_SYN;
1151 hdr.WindowSize = htons(TCP_WINDOW_SIZE); // Max
1152 hdr.Checksum = 0; // TODO
1154 TCP_SendPacket( Conn, sizeof(tTCPHeader), &hdr );
1156 Conn->NextSequenceSend ++;
1157 Conn->State = TCP_ST_SYN_SENT;
1163 * \brief Control a client socket
1165 int TCP_Client_IOCtl(tVFS_Node *Node, int ID, void *Data)
1167 tTCPConnection *conn = Node->ImplPtr;
1169 ENTER("pNode iID pData", Node, ID, Data);
1173 case 4: // Get/Set local port
1175 LEAVE_RET('i', conn->LocalPort);
1176 if(conn->State != TCP_ST_CLOSED)
1178 if(!CheckMem(Data, sizeof(Uint16)))
1181 if(Threads_GetUID() != 0 && *(Uint16*)Data < 1024)
1184 conn->LocalPort = *(Uint16*)Data;
1185 LEAVE_RET('i', conn->LocalPort);
1187 case 5: // Get/Set remote port
1188 if(!Data) LEAVE_RET('i', conn->RemotePort);
1189 if(conn->State != TCP_ST_CLOSED) LEAVE_RET('i', -1);
1190 if(!CheckMem(Data, sizeof(Uint16))) LEAVE_RET('i', -1);
1191 conn->RemotePort = *(Uint16*)Data;
1192 LEAVE_RET('i', conn->RemotePort);
1194 case 6: // Set Remote IP
1195 if( conn->State != TCP_ST_CLOSED )
1197 if( conn->Interface->Type == 4 )
1199 if(!CheckMem(Data, sizeof(tIPv4))) LEAVE_RET('i', -1);
1200 conn->RemoteIP.v4 = *(tIPv4*)Data;
1202 else if( conn->Interface->Type == 6 )
1204 if(!CheckMem(Data, sizeof(tIPv6))) LEAVE_RET('i', -1);
1205 conn->RemoteIP.v6 = *(tIPv6*)Data;
1210 if(conn->LocalPort == 0xFFFF)
1211 conn->LocalPort = TCP_GetUnusedPort();
1212 if(conn->RemotePort == -1)
1216 tTime timeout_end = now() + conn->Interface->TimeoutDelay;
1218 TCP_StartConnection(conn);
1219 // TODO: Wait for connection to open
1220 while( conn->State == TCP_ST_SYN_SENT && timeout_end > now() ) {
1223 if( conn->State == TCP_ST_SYN_SENT )
1229 // Get recieve buffer length
1231 LEAVE_RET('i', conn->RecievedBuffer->Length);
1237 void TCP_Client_Close(tVFS_Node *Node)
1239 tTCPConnection *conn = Node->ImplPtr;
1242 ENTER("pNode", Node);
1244 if( conn->State == TCP_ST_CLOSE_WAIT || conn->State == TCP_ST_OPEN )
1246 packet.SourcePort = htons(conn->LocalPort);
1247 packet.DestPort = htons(conn->RemotePort);
1248 packet.DataOffset = (sizeof(tTCPHeader)/4)*16;
1249 packet.WindowSize = TCP_WINDOW_SIZE;
1251 packet.AcknowlegementNumber = 0;
1252 packet.SequenceNumber = htonl(conn->NextSequenceSend);
1253 packet.Flags = TCP_FLAG_FIN;
1255 TCP_SendPacket( conn, sizeof(tTCPHeader), &packet );
1258 switch( conn->State )
1260 case TCP_ST_CLOSE_WAIT:
1261 conn->State = TCP_ST_LAST_ACK;
1264 conn->State = TCP_ST_FIN_WAIT1;
1265 while( conn->State == TCP_ST_FIN_WAIT1 ) Threads_Yield();
1268 Log_Warning("TCP", "Unhandled connection state in TCP_Client_Close");
1278 * \brief Checks if a value is between two others (after taking into account wrapping)
1280 int WrapBetween(Uint32 Lower, Uint32 Value, Uint32 Higher, Uint32 MaxValue)
1282 if( MaxValue < 0xFFFFFFFF )
1284 Lower %= MaxValue + 1;
1285 Value %= MaxValue + 1;
1286 Higher %= MaxValue + 1;
1289 // Simple Case, no wrap ?
1290 // Lower Value Higher
1291 // | ... + ... + ... + ... |
1293 if( Lower < Higher ) {
1294 return Lower < Value && Value < Higher;
1296 // Higher has wrapped below lower
1299 // Higher Lower Value
1300 // | ... + ... + ... + ... |
1301 if( Value > Lower ) {
1306 // Value Higher Lower
1307 // | ... + ... + ... + ... |
1308 if( Value < Higher ) {