12 #define HEXDUMP_INCOMING 0
13 #define HEXDUMP_OUTGOING 0
14 #define CACHE_FUTURE_PACKETS_IN_BYTES 1 // Use a ring buffer to cache out of order packets
16 #define TCP_MIN_DYNPORT 0xC000
17 #define TCP_MAX_HALFOPEN 1024 // Should be enough
19 #define TCP_MAX_PACKET_SIZE 1024
20 #define TCP_WINDOW_SIZE 0x2000
21 #define TCP_RECIEVE_BUFFER_SIZE 0x4000
24 void TCP_Initialise(void);
25 void TCP_StartConnection(tTCPConnection *Conn);
26 void TCP_SendPacket(tTCPConnection *Conn, size_t Length, tTCPHeader *Data);
27 void TCP_GetPacket(tInterface *Interface, void *Address, int Length, void *Buffer);
28 void TCP_INT_HandleConnectionPacket(tTCPConnection *Connection, tTCPHeader *Header, int Length);
29 int TCP_INT_AppendRecieved(tTCPConnection *Connection, const void *Data, size_t Length);
30 void TCP_INT_UpdateRecievedFromFuture(tTCPConnection *Connection);
31 Uint16 TCP_GetUnusedPort();
32 int TCP_AllocatePort(Uint16 Port);
33 int TCP_DeallocatePort(Uint16 Port);
35 tVFS_Node *TCP_Server_Init(tInterface *Interface);
36 char *TCP_Server_ReadDir(tVFS_Node *Node, int Pos);
37 tVFS_Node *TCP_Server_FindDir(tVFS_Node *Node, const char *Name);
38 int TCP_Server_IOCtl(tVFS_Node *Node, int ID, void *Data);
39 void TCP_Server_Close(tVFS_Node *Node);
41 tVFS_Node *TCP_Client_Init(tInterface *Interface);
42 Uint64 TCP_Client_Read(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer);
43 Uint64 TCP_Client_Write(tVFS_Node *Node, Uint64 Offset, Uint64 Length, const void *Buffer);
44 int TCP_Client_IOCtl(tVFS_Node *Node, int ID, void *Data);
45 void TCP_Client_Close(tVFS_Node *Node);
47 int WrapBetween(Uint32 Lower, Uint32 Value, Uint32 Higher, Uint32 MaxValue);
50 tSocketFile gTCP_ServerFile = {NULL, "tcps", TCP_Server_Init};
51 tSocketFile gTCP_ClientFile = {NULL, "tcpc", TCP_Client_Init};
52 tVFS_NodeType gTCP_ServerNodeType = {
53 .TypeName = "TCP Server",
54 .ReadDir = TCP_Server_ReadDir,
55 .FindDir = TCP_Server_FindDir,
56 .IOCtl = TCP_Server_IOCtl,
57 .Close = TCP_Server_Close
59 tVFS_NodeType gTCP_ClientNodeType = {
60 .TypeName = "TCP Client/Connection",
61 .Read = TCP_Client_Read,
62 .Write = TCP_Client_Write,
63 .IOCtl = TCP_Client_IOCtl,
64 .Close = TCP_Client_Close
68 int giTCP_NumHalfopen = 0;
69 tShortSpinlock glTCP_Listeners;
70 tTCPListener *gTCP_Listeners;
71 tShortSpinlock glTCP_OutbountCons;
72 tTCPConnection *gTCP_OutbountCons;
73 Uint32 gaTCP_PortBitmap[0x800];
74 int giTCP_NextOutPort = TCP_MIN_DYNPORT;
78 * \brief Initialise the TCP Layer
80 * Registers the client and server files and the GetPacket callback
82 void TCP_Initialise(void)
84 giTCP_NextOutPort += rand()%32;
85 IPStack_AddFile(&gTCP_ServerFile);
86 IPStack_AddFile(&gTCP_ClientFile);
87 IPv4_RegisterCallback(IP4PROT_TCP, TCP_GetPacket);
88 IPv6_RegisterCallback(IP4PROT_TCP, TCP_GetPacket);
92 * \brief Sends a packet from the specified connection, calculating the checksums
93 * \param Conn Connection
94 * \param Length Length of data
95 * \param Data Packet data (cast as a TCP Header)
97 void TCP_SendPacket( tTCPConnection *Conn, size_t Length, tTCPHeader *Data )
102 checksum[1] = htons( ~IPv4_Checksum( (void*)Data, Length ) ); // Partial checksum
104 ((Uint8*)Data)[Length] = 0;
106 // TODO: Fragment packet
108 switch( Conn->Interface->Type )
111 // Append IPv4 Pseudo Header
114 buf[0] = ((tIPv4*)Conn->Interface->Address)->L;
115 buf[1] = Conn->RemoteIP.v4.L;
116 buf[2] = (htons(Length)<<16) | (6<<8) | 0;
117 checksum[0] = htons( ~IPv4_Checksum(buf, sizeof(buf)) ); // Partial checksum
119 Data->Checksum = htons( IPv4_Checksum(checksum, 2*2) ); // Combine the two
120 IPv4_SendPacket(Conn->Interface, Conn->RemoteIP.v4, IP4PROT_TCP, 0, Length, Data);
124 // Append IPv6 Pseudo Header
127 memcpy(buf, Conn->Interface->Address, 16);
128 memcpy(&buf[4], &Conn->RemoteIP, 16);
129 buf[8] = htonl(Length);
131 checksum[0] = htons( ~IPv4_Checksum(buf, sizeof(buf)) ); // Partial checksum
133 Data->Checksum = htons( IPv4_Checksum(checksum, 2*2) ); // Combine the two
134 IPv6_SendPacket(Conn->Interface, Conn->RemoteIP.v6, IP4PROT_TCP, Length, Data);
140 * \brief Handles a packet from the IP Layer
141 * \param Interface Interface the packet arrived from
142 * \param Address Pointer to the addres structure
143 * \param Length Size of packet in bytes
144 * \param Buffer Packet data
146 void TCP_GetPacket(tInterface *Interface, void *Address, int Length, void *Buffer)
148 tTCPHeader *hdr = Buffer;
150 tTCPConnection *conn;
152 Log_Log("TCP", "TCP_GetPacket: <Local>:%i from [%s]:%i, Flags= %s%s%s%s%s%s%s%s",
153 ntohs(hdr->SourcePort),
154 IPStack_PrintAddress(Interface->Type, Address),
155 ntohs(hdr->DestPort),
156 (hdr->Flags & TCP_FLAG_CWR) ? "CWR " : "",
157 (hdr->Flags & TCP_FLAG_ECE) ? "ECE " : "",
158 (hdr->Flags & TCP_FLAG_URG) ? "URG " : "",
159 (hdr->Flags & TCP_FLAG_ACK) ? "ACK " : "",
160 (hdr->Flags & TCP_FLAG_PSH) ? "PSH " : "",
161 (hdr->Flags & TCP_FLAG_RST) ? "RST " : "",
162 (hdr->Flags & TCP_FLAG_SYN) ? "SYN " : "",
163 (hdr->Flags & TCP_FLAG_FIN) ? "FIN " : ""
166 if( Length > (hdr->DataOffset >> 4)*4 )
168 Log_Log("TCP", "TCP_GetPacket: SequenceNumber = 0x%x", ntohl(hdr->SequenceNumber));
171 "TCP_GetPacket: Packet Data = ",
172 (Uint8*)hdr + (hdr->DataOffset >> 4)*4,
173 Length - (hdr->DataOffset >> 4)*4
180 for( srv = gTCP_Listeners; srv; srv = srv->Next )
182 // Check if the server is active
183 if(srv->Port == 0) continue;
184 // Check the interface
185 if(srv->Interface && srv->Interface != Interface) continue;
186 // Check the destination port
187 if(srv->Port != htons(hdr->DestPort)) continue;
189 Log_Log("TCP", "TCP_GetPacket: Matches server %p", srv);
190 // Is this in an established connection?
191 for( conn = srv->Connections; conn; conn = conn->Next )
193 // Check that it is coming in on the same interface
194 if(conn->Interface != Interface) continue;
197 Log_Log("TCP", "TCP_GetPacket: conn->RemotePort(%i) == hdr->SourcePort(%i)",
198 conn->RemotePort, ntohs(hdr->SourcePort));
199 if(conn->RemotePort != ntohs(hdr->SourcePort)) continue;
202 if( IPStack_CompareAddress(conn->Interface->Type, &conn->RemoteIP, Address, -1) != 0 )
205 Log_Log("TCP", "TCP_GetPacket: Matches connection %p", conn);
206 // We have a response!
207 TCP_INT_HandleConnectionPacket(conn, hdr, Length);
212 Log_Log("TCP", "TCP_GetPacket: Opening Connection");
213 // Open a new connection (well, check that it's a SYN)
214 if(hdr->Flags != TCP_FLAG_SYN) {
215 Log_Log("TCP", "TCP_GetPacket: Packet is not a SYN");
219 // TODO: Check for halfopen max
221 conn = calloc(1, sizeof(tTCPConnection));
222 conn->State = TCP_ST_SYN_RCVD;
223 conn->LocalPort = srv->Port;
224 conn->RemotePort = ntohs(hdr->SourcePort);
225 conn->Interface = Interface;
227 switch(Interface->Type)
229 case 4: conn->RemoteIP.v4 = *(tIPv4*)Address; break;
230 case 6: conn->RemoteIP.v6 = *(tIPv6*)Address; break;
233 conn->RecievedBuffer = RingBuffer_Create( TCP_RECIEVE_BUFFER_SIZE );
235 conn->NextSequenceRcv = ntohl( hdr->SequenceNumber ) + 1;
236 conn->NextSequenceSend = rand();
239 conn->Node.NumACLs = 1;
240 conn->Node.ACLs = &gVFS_ACL_EveryoneRW;
241 conn->Node.ImplPtr = conn;
242 conn->Node.ImplInt = srv->NextID ++;
243 conn->Node.Type = &gTCP_ClientNodeType; // TODO: Special type for the server end?
245 // Hmm... Theoretically, this lock will never have to wait,
246 // as the interface is locked to the watching thread, and this
247 // runs in the watching thread. But, it's a good idea to have
249 // Oh, wait, there is a case where a wildcard can be used
250 // (srv->Interface == NULL) so having the lock is a good idea
251 SHORTLOCK(&srv->lConnections);
252 if( !srv->Connections )
253 srv->Connections = conn;
255 srv->ConnectionsTail->Next = conn;
256 srv->ConnectionsTail = conn;
257 if(!srv->NewConnections)
258 srv->NewConnections = conn;
259 SHORTREL(&srv->lConnections);
262 hdr->Flags |= TCP_FLAG_ACK;
263 hdr->AcknowlegementNumber = htonl(conn->NextSequenceRcv);
264 hdr->SequenceNumber = htonl(conn->NextSequenceSend);
265 hdr->DestPort = hdr->SourcePort;
266 hdr->SourcePort = htons(srv->Port);
267 hdr->DataOffset = (sizeof(tTCPHeader)/4) << 4;
268 TCP_SendPacket( conn, sizeof(tTCPHeader), hdr );
269 conn->NextSequenceSend ++;
275 // Check Open Connections
277 for( conn = gTCP_OutbountCons; conn; conn = conn->Next )
279 // Check that it is coming in on the same interface
280 if(conn->Interface != Interface) continue;
283 if(conn->RemotePort != ntohs(hdr->SourcePort)) continue;
286 if(conn->Interface->Type == 6 && !IP6_EQU(conn->RemoteIP.v6, *(tIPv6*)Address))
288 if(conn->Interface->Type == 4 && !IP4_EQU(conn->RemoteIP.v4, *(tIPv4*)Address))
291 TCP_INT_HandleConnectionPacket(conn, hdr, Length);
296 Log_Log("TCP", "TCP_GetPacket: No Match");
300 * \brief Handles a packet sent to a specific connection
301 * \param Connection TCP Connection pointer
302 * \param Header TCP Packet pointer
303 * \param Length Length of the packet
305 void TCP_INT_HandleConnectionPacket(tTCPConnection *Connection, tTCPHeader *Header, int Length)
310 // Silently drop once finished
311 // TODO: Check if this needs to be here
312 if( Connection->State == TCP_ST_FINISHED ) {
313 Log_Log("TCP", "Packet ignored - connection finnished");
317 // Syncronise sequence values
318 if(Header->Flags & TCP_FLAG_SYN) {
319 // TODO: What if the packet also has data?
320 Connection->NextSequenceRcv = ntohl(Header->SequenceNumber);
323 // Ackowledge a sent packet
324 if(Header->Flags & TCP_FLAG_ACK) {
325 // TODO: Process an ACKed Packet
326 Log_Log("TCP", "Conn %p, Sent packet 0x%x ACKed", Connection, Header->AcknowlegementNumber);
329 // Get length of data
330 dataLen = Length - (Header->DataOffset>>4)*4;
331 Log_Log("TCP", "HandleConnectionPacket - dataLen = %i", dataLen);
336 switch( Connection->State )
338 // Pre-init connection?
340 Log_Log("TCP", "Packets to a closed connection?!");
343 // --- Init States ---
344 // SYN sent, expecting SYN-ACK Connection Opening
345 case TCP_ST_SYN_SENT:
346 if( Header->Flags & TCP_FLAG_SYN )
348 Connection->NextSequenceRcv ++;
349 Header->DestPort = Header->SourcePort;
350 Header->SourcePort = htons(Connection->LocalPort);
351 Header->AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
352 Header->SequenceNumber = htonl(Connection->NextSequenceSend);
353 Header->WindowSize = htons(TCP_WINDOW_SIZE);
354 Header->Flags = TCP_FLAG_ACK;
355 Header->DataOffset = (sizeof(tTCPHeader)/4) << 4;
356 TCP_SendPacket( Connection, sizeof(tTCPHeader), Header );
358 if( Header->Flags & TCP_FLAG_ACK )
360 Log_Log("TCP", "ACKing SYN-ACK");
361 Connection->State = TCP_ST_OPEN;
365 Log_Log("TCP", "ACKing SYN");
366 Connection->State = TCP_ST_SYN_RCVD;
371 // SYN-ACK sent, expecting ACK
372 case TCP_ST_SYN_RCVD:
373 if( Header->Flags & TCP_FLAG_ACK )
375 // TODO: Handle max half-open limit
376 Connection->State = TCP_ST_OPEN;
377 Log_Log("TCP", "Connection fully opened");
381 // --- Established State ---
383 // - Handle State changes
385 if( Header->Flags & TCP_FLAG_FIN ) {
386 Log_Log("TCP", "Conn %p closed, recieved FIN", Connection);
387 VFS_MarkError(&Connection->Node, 1);
388 Connection->State = TCP_ST_CLOSE_WAIT;
389 // Header->Flags &= ~TCP_FLAG_FIN;
390 // CLOSE WAIT requires the client to close (or does it?)
396 // Check for an empty packet
398 if( Header->Flags == TCP_FLAG_ACK )
400 Log_Log("TCP", "ACK only packet");
403 Connection->NextSequenceRcv ++; // TODO: Is this right? (empty packet counts as one byte)
404 Log_Log("TCP", "Empty Packet, inc and ACK the current sequence number");
405 Header->DestPort = Header->SourcePort;
406 Header->SourcePort = htons(Connection->LocalPort);
407 Header->AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
408 Header->SequenceNumber = htonl(Connection->NextSequenceSend);
409 Header->Flags |= TCP_FLAG_ACK;
410 TCP_SendPacket( Connection, sizeof(tTCPHeader), Header );
419 sequence_num = ntohl(Header->SequenceNumber);
421 Log_Log("TCP", "0x%08x <= 0x%08x < 0x%08x",
422 Connection->NextSequenceRcv,
423 ntohl(Header->SequenceNumber),
424 Connection->NextSequenceRcv + TCP_WINDOW_SIZE
427 // Is this packet the next expected packet?
428 if( sequence_num == Connection->NextSequenceRcv )
431 // Ooh, Goodie! Add it to the recieved list
432 rv = TCP_INT_AppendRecieved(Connection,
433 (Uint8*)Header + (Header->DataOffset>>4)*4,
439 Log_Log("TCP", "0x%08x += %i", Connection->NextSequenceRcv, dataLen);
440 Connection->NextSequenceRcv += dataLen;
442 // TODO: This should be moved out of the watcher thread,
443 // so that a single lost packet on one connection doesn't cause
444 // all connections on the interface to lag.
445 // - Meh, no real issue, as the cache shouldn't be that large
446 TCP_INT_UpdateRecievedFromFuture(Connection);
449 Header->DestPort = Header->SourcePort;
450 Header->SourcePort = htons(Connection->LocalPort);
451 Header->AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
452 Header->SequenceNumber = htonl(Connection->NextSequenceSend);
453 Header->WindowSize = htons(TCP_WINDOW_SIZE);
454 Header->Flags &= TCP_FLAG_SYN; // Eliminate all flags save for SYN
455 Header->Flags |= TCP_FLAG_ACK; // Add ACK
456 Log_Log("TCP", "Sending ACK for 0x%08x", Connection->NextSequenceRcv);
457 TCP_SendPacket( Connection, sizeof(tTCPHeader), Header );
458 //Connection->NextSequenceSend ++;
460 // Check if the packet is in window
461 else if( WrapBetween(Connection->NextSequenceRcv, sequence_num,
462 Connection->NextSequenceRcv+TCP_WINDOW_SIZE, 0xFFFFFFFF) )
464 Uint8 *dataptr = (Uint8*)Header + (Header->DataOffset>>4)*4;
465 #if CACHE_FUTURE_PACKETS_IN_BYTES
469 index = sequence_num % TCP_WINDOW_SIZE;
470 for( i = 0; i < dataLen; i ++ )
472 Connection->FuturePacketValidBytes[index/8] |= 1 << (index%8);
473 Connection->FuturePacketData[index] = dataptr[i];
474 // Do a wrap increment
476 if(index == TCP_WINDOW_SIZE) index = 0;
479 tTCPStoredPacket *pkt, *tmp, *prev = NULL;
481 // Allocate and fill cached packet
482 pkt = malloc( sizeof(tTCPStoredPacket) + dataLen );
484 pkt->Sequence = ntohl(Header->SequenceNumber);
485 pkt->Length = dataLen;
486 memcpy(pkt->Data, dataptr, dataLen);
488 Log_Log("TCP", "We missed a packet, caching",
489 pkt->Sequence, Connection->NextSequenceRcv);
491 // No? Well, let's cache it and look at it later
492 SHORTLOCK( &Connection->lFuturePackets );
493 for(tmp = Connection->FuturePackets;
495 prev = tmp, tmp = tmp->Next)
497 if(tmp->Sequence >= pkt->Sequence) break;
500 // Add if before first, or sequences don't match
501 if( !tmp || tmp->Sequence != pkt->Sequence )
506 Connection->FuturePackets = pkt;
510 else if(pkt->Length > tmp->Length)
514 pkt->Next = tmp->Next;
519 free(pkt); // TODO: Find some way to remove this
521 SHORTREL( &Connection->lFuturePackets );
524 // Badly out of sequence packet
527 Log_Log("TCP", "Fully out of sequence packet (0x%08x not between 0x%08x and 0x%08x), dropped",
528 sequence_num, Connection->NextSequenceRcv, Connection->NextSequenceRcv+TCP_WINDOW_SIZE);
529 // TODO: Spec says we should send an empty ACK with the current state
533 // --- Remote close states
534 case TCP_ST_CLOSE_WAIT:
536 // Ignore everything, CLOSE_WAIT is terminated by the client
537 Log_Debug("TCP", "CLOSE WAIT - Ignoring packets");
541 // LAST-ACK - Waiting for the ACK of FIN (from CLOSE WAIT)
542 case TCP_ST_LAST_ACK:
543 if( Header->Flags & TCP_FLAG_ACK )
545 Connection->State = TCP_ST_FINISHED; // Connection completed
546 Log_Log("TCP", "LAST-ACK to CLOSED - Connection remote closed");
547 // TODO: Destrory the TCB
551 // --- Local close States
552 case TCP_ST_FIN_WAIT1:
553 if( Header->Flags & TCP_FLAG_FIN )
555 Connection->State = TCP_ST_CLOSING;
556 Log_Debug("TCP", "Conn %p closed, sent FIN and recieved FIN", Connection);
557 VFS_MarkError(&Connection->Node, 1);
560 Header->DestPort = Header->SourcePort;
561 Header->SourcePort = htons(Connection->LocalPort);
562 Header->AcknowlegementNumber = Header->SequenceNumber;
563 Header->SequenceNumber = htonl(Connection->NextSequenceSend);
564 Header->WindowSize = htons(TCP_WINDOW_SIZE);
565 Header->Flags = TCP_FLAG_ACK;
566 TCP_SendPacket( Connection, sizeof(tTCPHeader), Header );
570 // TODO: Make sure that the packet is actually ACKing the FIN
571 if( Header->Flags & TCP_FLAG_ACK )
573 Connection->State = TCP_ST_FIN_WAIT2;
574 Log_Debug("TCP", "Conn %p closed, sent FIN ACKed", Connection);
575 VFS_MarkError(&Connection->Node, 1);
580 case TCP_ST_FIN_WAIT2:
581 if( Header->Flags & TCP_FLAG_FIN )
583 Connection->State = TCP_ST_TIME_WAIT;
584 Log_Debug("TCP", "FIN sent and recieved, ACKing and going into TIME WAIT %p FINWAIT-2 -> TIME WAIT", Connection);
586 Header->DestPort = Header->SourcePort;
587 Header->SourcePort = htons(Connection->LocalPort);
588 Header->AcknowlegementNumber = Header->SequenceNumber;
589 Header->SequenceNumber = htonl(Connection->NextSequenceSend);
590 Header->WindowSize = htons(TCP_WINDOW_SIZE);
591 Header->Flags = TCP_FLAG_ACK;
592 TCP_SendPacket( Connection, sizeof(tTCPHeader), Header );
597 // TODO: Make sure that the packet is actually ACKing the FIN
598 if( Header->Flags & TCP_FLAG_ACK )
600 Connection->State = TCP_ST_TIME_WAIT;
601 Log_Debug("TCP", "Conn %p CLOSING -> TIME WAIT", Connection);
602 VFS_MarkError(&Connection->Node, 1);
607 // --- Closed (or near closed) states) ---
608 case TCP_ST_TIME_WAIT:
609 Log_Log("TCP", "Packets on Time-Wait, ignored");
612 case TCP_ST_FINISHED:
613 Log_Log("TCP", "Packets when CLOSED, ignoring");
617 // Log_Warning("TCP", "Unhandled TCP state %i", Connection->State);
624 * \brief Appends a packet to the recieved list
625 * \param Connection Connection structure
626 * \param Data Packet contents
627 * \param Length Length of \a Data
629 int TCP_INT_AppendRecieved(tTCPConnection *Connection, const void *Data, size_t Length)
631 Mutex_Acquire( &Connection->lRecievedPackets );
633 if(Connection->RecievedBuffer->Length + Length > Connection->RecievedBuffer->Space )
635 VFS_MarkAvaliable(&Connection->Node, 1);
636 Log_Error("TCP", "Buffer filled, packet dropped (:%i) - %i + %i > %i",
637 Connection->LocalPort, Connection->RecievedBuffer->Length, Length,
638 Connection->RecievedBuffer->Space
640 Mutex_Release( &Connection->lRecievedPackets );
644 RingBuffer_Write( Connection->RecievedBuffer, Data, Length );
646 VFS_MarkAvaliable(&Connection->Node, 1);
648 Mutex_Release( &Connection->lRecievedPackets );
653 * \brief Updates the connections recieved list from the future list
654 * \param Connection Connection structure
656 * Updates the recieved packets list with packets from the future (out
657 * of order) packets list that are now able to be added in direct
660 void TCP_INT_UpdateRecievedFromFuture(tTCPConnection *Connection)
662 #if CACHE_FUTURE_PACKETS_IN_BYTES
666 // Calculate length of contiguous bytes
667 length = Connection->HighestSequenceRcvd - Connection->NextSequenceRcv;
668 index = Connection->NextSequenceRcv % TCP_WINDOW_SIZE;
669 for( i = 0; i < length; i ++ )
671 if( Connection->FuturePacketValidBytes[i / 8] == 0xFF ) {
675 else if( !(Connection->FuturePacketValidBytes[i / 8] & (1 << (i%8))) )
679 if(index > TCP_WINDOW_SIZE)
680 index -= TCP_WINDOW_SIZE;
684 index = Connection->NextSequenceRcv % TCP_WINDOW_SIZE;
686 // Write data to to the ring buffer
687 if( TCP_WINDOW_SIZE - index > length )
690 RingBuffer_Write( Connection->RecievedBuffer, Connection->FuturePacketData + index, length );
694 int endLen = TCP_WINDOW_SIZE - index;
696 RingBuffer_Write( Connection->RecievedBuffer, Connection->FuturePacketData + index, endLen );
697 RingBuffer_Write( Connection->RecievedBuffer, Connection->FuturePacketData, endLen - length );
700 // Mark (now saved) bytes as invalid
702 while(index % 8 && length)
704 Connection->FuturePacketData[index] = 0;
705 Connection->FuturePacketData[index/8] &= ~(1 << (index%8));
707 if(index > TCP_WINDOW_SIZE)
708 index -= TCP_WINDOW_SIZE;
713 Connection->FuturePacketData[index] = 0;
714 Connection->FuturePacketValidBytes[index/8] = 0;
717 if(index > TCP_WINDOW_SIZE)
718 index -= TCP_WINDOW_SIZE;
722 Connection->FuturePacketData[index] = 0;
723 Connection->FuturePacketData[index/8] &= ~(1 << (index%8));
725 if(index > TCP_WINDOW_SIZE)
726 index -= TCP_WINDOW_SIZE;
731 tTCPStoredPacket *pkt;
734 SHORTLOCK( &Connection->lFuturePackets );
736 // Clear out duplicates from cache
737 // - If a packet has just been recieved, and it is expected, then
738 // (since NextSequenceRcv = rcvd->Sequence + rcvd->Length) all
739 // packets in cache that are smaller than the next expected
741 pkt = Connection->FuturePackets;
742 while(pkt && pkt->Sequence < Connection->NextSequenceRcv)
744 tTCPStoredPacket *next = pkt->Next;
749 // If there's no packets left in cache, stop looking
750 if(!pkt || pkt->Sequence > Connection->NextSequenceRcv) {
751 SHORTREL( &Connection->lFuturePackets );
755 // Delete packet from future list
756 Connection->FuturePackets = pkt->Next;
759 SHORTREL( &Connection->lFuturePackets );
761 // Looks like we found one
762 TCP_INT_AppendRecieved(Connection, pkt);
763 Connection->NextSequenceRcv += pkt->Length;
770 * \fn Uint16 TCP_GetUnusedPort()
771 * \brief Gets an unused port and allocates it
773 Uint16 TCP_GetUnusedPort()
777 // Get Next outbound port
778 ret = giTCP_NextOutPort++;
779 while( gaTCP_PortBitmap[ret/32] & (1UL << (ret%32)) )
783 if(giTCP_NextOutPort == 0x10000) {
784 ret = giTCP_NextOutPort = TCP_MIN_DYNPORT;
788 // Mark the new port as used
789 gaTCP_PortBitmap[ret/32] |= 1 << (ret%32);
795 * \fn int TCP_AllocatePort(Uint16 Port)
796 * \brief Marks a port as used
798 int TCP_AllocatePort(Uint16 Port)
800 // Check if the port has already been allocated
801 if( gaTCP_PortBitmap[Port/32] & (1 << (Port%32)) )
805 gaTCP_PortBitmap[Port/32] |= 1 << (Port%32);
811 * \fn int TCP_DeallocatePort(Uint16 Port)
812 * \brief Marks a port as unused
814 int TCP_DeallocatePort(Uint16 Port)
816 // Check if the port has already been allocated
817 if( !(gaTCP_PortBitmap[Port/32] & (1 << (Port%32))) )
821 gaTCP_PortBitmap[Port/32] &= ~(1 << (Port%32));
827 tVFS_Node *TCP_Server_Init(tInterface *Interface)
831 srv = malloc( sizeof(tTCPListener) );
834 Log_Warning("TCP", "malloc failed for listener (%i) bytes", sizeof(tTCPListener));
838 srv->Interface = Interface;
841 srv->Connections = NULL;
842 srv->ConnectionsTail = NULL;
843 srv->NewConnections = NULL;
845 srv->Node.Flags = VFS_FFLAG_DIRECTORY;
847 srv->Node.ImplPtr = srv;
848 srv->Node.NumACLs = 1;
849 srv->Node.ACLs = &gVFS_ACL_EveryoneRW;
850 srv->Node.Type = &gTCP_ServerNodeType;
852 SHORTLOCK(&glTCP_Listeners);
853 srv->Next = gTCP_Listeners;
854 gTCP_Listeners = srv;
855 SHORTREL(&glTCP_Listeners);
861 * \brief Wait for a new connection and return the connection ID
862 * \note Blocks until a new connection is made
863 * \param Node Server node
864 * \param Pos Position (ignored)
866 char *TCP_Server_ReadDir(tVFS_Node *Node, int Pos)
868 tTCPListener *srv = Node->ImplPtr;
869 tTCPConnection *conn;
872 ENTER("pNode iPos", Node, Pos);
874 Log_Log("TCP", "Thread %i waiting for a connection", Threads_GetTID());
877 SHORTLOCK( &srv->lConnections );
878 if( srv->NewConnections != NULL ) break;
879 SHORTREL( &srv->lConnections );
880 Threads_Yield(); // TODO: Sleep until poked
885 // Increment the new list (the current connection is still on the
887 conn = srv->NewConnections;
888 srv->NewConnections = conn->Next;
890 SHORTREL( &srv->lConnections );
892 LOG("conn = %p", conn);
893 LOG("srv->Connections = %p", srv->Connections);
894 LOG("srv->NewConnections = %p", srv->NewConnections);
895 LOG("srv->ConnectionsTail = %p", srv->ConnectionsTail);
898 itoa(ret, conn->Node.ImplInt, 16, 8, '0');
899 Log_Log("TCP", "Thread %i got '%s'", Threads_GetTID(), ret);
905 * \brief Gets a client connection node
906 * \param Node Server node
907 * \param Name Hexadecimal ID of the node
909 tVFS_Node *TCP_Server_FindDir(tVFS_Node *Node, const char *Name)
911 tTCPConnection *conn;
912 tTCPListener *srv = Node->ImplPtr;
916 ENTER("pNode sName", Node, Name);
919 itoa(tmp, id, 16, 8, '0');
920 if(strcmp(tmp, Name) != 0) {
921 LOG("'%s' != '%s' (%08x)", Name, tmp, id);
926 Log_Debug("TCP", "srv->Connections = %p", srv->Connections);
927 Log_Debug("TCP", "srv->NewConnections = %p", srv->NewConnections);
928 Log_Debug("TCP", "srv->ConnectionsTail = %p", srv->ConnectionsTail);
931 SHORTLOCK( &srv->lConnections );
932 for(conn = srv->Connections;
936 LOG("conn->Node.ImplInt = %i", conn->Node.ImplInt);
937 if(conn->Node.ImplInt == id) break;
939 SHORTREL( &srv->lConnections );
941 // If not found, ret NULL
943 LOG("Connection %i not found", id);
949 LEAVE('p', &conn->Node);
954 * \brief Handle IOCtl calls
956 int TCP_Server_IOCtl(tVFS_Node *Node, int ID, void *Data)
958 tTCPListener *srv = Node->ImplPtr;
962 case 4: // Get/Set Port
963 if(!Data) // Get Port
966 if(srv->Port) // Wait, you can't CHANGE the port
969 if(!CheckMem(Data, sizeof(Uint16))) // Sanity check
973 if(Threads_GetUID() != 0
974 && *(Uint16*)Data != 0
975 && *(Uint16*)Data < 1024)
978 // TODO: Check if a port is in use
981 srv->Port = *(Uint16*)Data;
982 if(srv->Port == 0) // Allocate a random port
983 srv->Port = TCP_GetUnusedPort();
984 else // Else, mark this as used
985 TCP_AllocatePort(srv->Port);
987 Log_Log("TCP", "Server %p listening on port %i", srv, srv->Port);
994 void TCP_Server_Close(tVFS_Node *Node)
1001 * \brief Create a client node
1003 tVFS_Node *TCP_Client_Init(tInterface *Interface)
1005 tTCPConnection *conn = calloc( sizeof(tTCPConnection) + TCP_WINDOW_SIZE + TCP_WINDOW_SIZE/8, 1 );
1007 conn->State = TCP_ST_CLOSED;
1008 conn->Interface = Interface;
1009 conn->LocalPort = -1;
1010 conn->RemotePort = -1;
1012 conn->Node.ImplPtr = conn;
1013 conn->Node.NumACLs = 1;
1014 conn->Node.ACLs = &gVFS_ACL_EveryoneRW;
1015 conn->Node.Type = &gTCP_ClientNodeType;
1017 conn->RecievedBuffer = RingBuffer_Create( TCP_RECIEVE_BUFFER_SIZE );
1019 conn->SentBuffer = RingBuffer_Create( TCP_SEND_BUFFER_SIZE );
1020 Semaphore_Init(conn->SentBufferSpace, 0, TCP_SEND_BUFFER_SIZE, "TCP SentBuffer", conn->Name);
1023 #if CACHE_FUTURE_PACKETS_IN_BYTES
1024 // Future recieved data (ahead of the expected sequence number)
1025 conn->FuturePacketData = (Uint8*)conn + sizeof(tTCPConnection);
1026 conn->FuturePacketValidBytes = conn->FuturePacketData + TCP_WINDOW_SIZE;
1029 SHORTLOCK(&glTCP_OutbountCons);
1030 conn->Next = gTCP_OutbountCons;
1031 gTCP_OutbountCons = conn;
1032 SHORTREL(&glTCP_OutbountCons);
1038 * \brief Wait for a packet and return it
1039 * \note If \a Length is smaller than the size of the packet, the rest
1040 * of the packet's data will be discarded.
1042 Uint64 TCP_Client_Read(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer)
1044 tTCPConnection *conn = Node->ImplPtr;
1047 ENTER("pNode XOffset XLength pBuffer", Node, Offset, Length, Buffer);
1048 LOG("conn = %p {State:%i}", conn, conn->State);
1050 // Check if connection is estabilishing
1051 // - TODO: Sleep instead (maybe using VFS_SelectNode to wait for the
1052 // data to be availiable
1053 while( conn->State == TCP_ST_SYN_RCVD || conn->State == TCP_ST_SYN_SENT )
1056 // If the conneciton is not open, then clean out the recieved buffer
1057 if( conn->State != TCP_ST_OPEN )
1059 Mutex_Acquire( &conn->lRecievedPackets );
1060 len = RingBuffer_Read( Buffer, conn->RecievedBuffer, Length );
1061 Mutex_Release( &conn->lRecievedPackets );
1064 VFS_MarkAvaliable(Node, 0);
1074 VFS_SelectNode(Node, VFS_SELECT_READ|VFS_SELECT_ERROR, NULL, "TCP_Client_Read");
1076 // Lock list and read as much as possible (up to `Length`)
1077 Mutex_Acquire( &conn->lRecievedPackets );
1078 len = RingBuffer_Read( Buffer, conn->RecievedBuffer, Length );
1080 if( len == 0 || conn->RecievedBuffer->Length == 0 ) {
1081 LOG("Marking as none avaliable (len = %i)", len);
1082 VFS_MarkAvaliable(Node, 0);
1085 // Release the lock (we don't need it any more)
1086 Mutex_Release( &conn->lRecievedPackets );
1093 * \brief Send a data packet on a connection
1095 void TCP_INT_SendDataPacket(tTCPConnection *Connection, size_t Length, const void *Data)
1097 char buf[sizeof(tTCPHeader)+Length];
1098 tTCPHeader *packet = (void*)buf;
1100 packet->SourcePort = htons(Connection->LocalPort);
1101 packet->DestPort = htons(Connection->RemotePort);
1102 packet->DataOffset = (sizeof(tTCPHeader)/4)*16;
1103 packet->WindowSize = htons(TCP_WINDOW_SIZE);
1105 packet->AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
1106 packet->SequenceNumber = htonl(Connection->NextSequenceSend);
1107 packet->Flags = TCP_FLAG_PSH|TCP_FLAG_ACK; // Hey, ACK if you can!
1109 memcpy(packet->Options, Data, Length);
1111 Log_Debug("TCP", "Send sequence 0x%08x", Connection->NextSequenceSend);
1112 #if HEXDUMP_OUTGOING
1113 Debug_HexDump("TCP_INT_SendDataPacket: Data = ", Data, Length);
1116 TCP_SendPacket( Connection, sizeof(tTCPHeader)+Length, packet );
1118 Connection->NextSequenceSend += Length;
1122 * \brief Send some bytes on a connection
1124 Uint64 TCP_Client_Write(tVFS_Node *Node, Uint64 Offset, Uint64 Length, const void *Buffer)
1126 tTCPConnection *conn = Node->ImplPtr;
1127 size_t rem = Length;
1129 ENTER("pNode XOffset XLength pBuffer", Node, Offset, Length, Buffer);
1132 // Debug_HexDump("TCP_Client_Write: Buffer = ",
1136 // Check if connection is open
1137 while( conn->State == TCP_ST_SYN_RCVD || conn->State == TCP_ST_SYN_SENT )
1140 if( conn->State != TCP_ST_OPEN ) {
1141 VFS_MarkError(Node, 1);
1148 int len = (rem < TCP_MAX_PACKET_SIZE) ? rem : TCP_MAX_PACKET_SIZE;
1151 // Wait for space in the buffer
1152 Semaphore_Signal( &Connection->SentBufferSpace, len );
1154 // Save data to buffer (and update the length read by the ammount written)
1155 len = RingBuffer_Write( &Connection->SentBuffer, Buffer, len);
1159 TCP_INT_SendDataPacket(conn, len, Buffer);
1170 * \brief Open a connection to another host using TCP
1171 * \param Conn Connection structure
1173 void TCP_StartConnection(tTCPConnection *Conn)
1175 tTCPHeader hdr = {0};
1177 Conn->State = TCP_ST_SYN_SENT;
1179 hdr.SourcePort = htons(Conn->LocalPort);
1180 hdr.DestPort = htons(Conn->RemotePort);
1181 Conn->NextSequenceSend = rand();
1182 hdr.SequenceNumber = htonl(Conn->NextSequenceSend);
1183 hdr.DataOffset = (sizeof(tTCPHeader)/4) << 4;
1184 hdr.Flags = TCP_FLAG_SYN;
1185 hdr.WindowSize = htons(TCP_WINDOW_SIZE); // Max
1186 hdr.Checksum = 0; // TODO
1188 TCP_SendPacket( Conn, sizeof(tTCPHeader), &hdr );
1190 Conn->NextSequenceSend ++;
1191 Conn->State = TCP_ST_SYN_SENT;
1197 * \brief Control a client socket
1199 int TCP_Client_IOCtl(tVFS_Node *Node, int ID, void *Data)
1201 tTCPConnection *conn = Node->ImplPtr;
1203 ENTER("pNode iID pData", Node, ID, Data);
1207 case 4: // Get/Set local port
1209 LEAVE_RET('i', conn->LocalPort);
1210 if(conn->State != TCP_ST_CLOSED)
1212 if(!CheckMem(Data, sizeof(Uint16)))
1215 if(Threads_GetUID() != 0 && *(Uint16*)Data < 1024)
1218 conn->LocalPort = *(Uint16*)Data;
1219 LEAVE_RET('i', conn->LocalPort);
1221 case 5: // Get/Set remote port
1222 if(!Data) LEAVE_RET('i', conn->RemotePort);
1223 if(conn->State != TCP_ST_CLOSED) LEAVE_RET('i', -1);
1224 if(!CheckMem(Data, sizeof(Uint16))) LEAVE_RET('i', -1);
1225 conn->RemotePort = *(Uint16*)Data;
1226 LEAVE_RET('i', conn->RemotePort);
1228 case 6: // Set Remote IP
1229 if( conn->State != TCP_ST_CLOSED )
1231 if( conn->Interface->Type == 4 )
1233 if(!CheckMem(Data, sizeof(tIPv4))) LEAVE_RET('i', -1);
1234 conn->RemoteIP.v4 = *(tIPv4*)Data;
1236 else if( conn->Interface->Type == 6 )
1238 if(!CheckMem(Data, sizeof(tIPv6))) LEAVE_RET('i', -1);
1239 conn->RemoteIP.v6 = *(tIPv6*)Data;
1244 if(conn->LocalPort == 0xFFFF)
1245 conn->LocalPort = TCP_GetUnusedPort();
1246 if(conn->RemotePort == -1)
1250 tTime timeout_end = now() + conn->Interface->TimeoutDelay;
1252 TCP_StartConnection(conn);
1253 // TODO: Wait for connection to open
1254 while( conn->State == TCP_ST_SYN_SENT && timeout_end > now() ) {
1257 if( conn->State == TCP_ST_SYN_SENT )
1263 // Get recieve buffer length
1265 LEAVE_RET('i', conn->RecievedBuffer->Length);
1271 void TCP_Client_Close(tVFS_Node *Node)
1273 tTCPConnection *conn = Node->ImplPtr;
1276 ENTER("pNode", Node);
1278 if( conn->State == TCP_ST_CLOSE_WAIT || conn->State == TCP_ST_OPEN )
1280 packet.SourcePort = htons(conn->LocalPort);
1281 packet.DestPort = htons(conn->RemotePort);
1282 packet.DataOffset = (sizeof(tTCPHeader)/4)*16;
1283 packet.WindowSize = TCP_WINDOW_SIZE;
1285 packet.AcknowlegementNumber = 0;
1286 packet.SequenceNumber = htonl(conn->NextSequenceSend);
1287 packet.Flags = TCP_FLAG_FIN;
1289 TCP_SendPacket( conn, sizeof(tTCPHeader), &packet );
1292 switch( conn->State )
1294 case TCP_ST_CLOSE_WAIT:
1295 conn->State = TCP_ST_LAST_ACK;
1298 conn->State = TCP_ST_FIN_WAIT1;
1299 while( conn->State == TCP_ST_FIN_WAIT1 ) Threads_Yield();
1302 Log_Warning("TCP", "Unhandled connection state in TCP_Client_Close");
1312 * \brief Checks if a value is between two others (after taking into account wrapping)
1314 int WrapBetween(Uint32 Lower, Uint32 Value, Uint32 Higher, Uint32 MaxValue)
1316 if( MaxValue < 0xFFFFFFFF )
1318 Lower %= MaxValue + 1;
1319 Value %= MaxValue + 1;
1320 Higher %= MaxValue + 1;
1323 // Simple Case, no wrap ?
1324 // Lower Value Higher
1325 // | ... + ... + ... + ... |
1327 if( Lower < Higher ) {
1328 return Lower < Value && Value < Higher;
1330 // Higher has wrapped below lower
1333 // Higher Lower Value
1334 // | ... + ... + ... + ... |
1335 if( Value > Lower ) {
1340 // Value Higher Lower
1341 // | ... + ... + ... + ... |
1342 if( Value < Higher ) {