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);
918 // Check for a non-empty name
922 itoa(tmp, id, 16, 8, '0');
923 if(strcmp(tmp, Name) != 0) {
924 LOG("'%s' != '%s' (%08x)", Name, tmp, id);
929 Log_Debug("TCP", "srv->Connections = %p", srv->Connections);
930 Log_Debug("TCP", "srv->NewConnections = %p", srv->NewConnections);
931 Log_Debug("TCP", "srv->ConnectionsTail = %p", srv->ConnectionsTail);
934 SHORTLOCK( &srv->lConnections );
935 for(conn = srv->Connections;
939 LOG("conn->Node.ImplInt = %i", conn->Node.ImplInt);
940 if(conn->Node.ImplInt == id) break;
942 SHORTREL( &srv->lConnections );
944 // Empty Name - Check for a new connection and if it's there, open it
947 SHORTLOCK( &srv->lConnections );
948 conn = srv->NewConnections;
950 srv->NewConnections = conn->Next;
951 SHORTREL( &srv->lConnections );
954 // If not found, ret NULL
956 LOG("Connection %i not found", id);
962 LEAVE('p', &conn->Node);
967 * \brief Handle IOCtl calls
969 int TCP_Server_IOCtl(tVFS_Node *Node, int ID, void *Data)
971 tTCPListener *srv = Node->ImplPtr;
975 case 4: // Get/Set Port
976 if(!Data) // Get Port
979 if(srv->Port) // Wait, you can't CHANGE the port
982 if(!CheckMem(Data, sizeof(Uint16))) // Sanity check
986 if(Threads_GetUID() != 0
987 && *(Uint16*)Data != 0
988 && *(Uint16*)Data < 1024)
991 // TODO: Check if a port is in use
994 srv->Port = *(Uint16*)Data;
995 if(srv->Port == 0) // Allocate a random port
996 srv->Port = TCP_GetUnusedPort();
997 else // Else, mark this as used
998 TCP_AllocatePort(srv->Port);
1000 Log_Log("TCP", "Server %p listening on port %i", srv, srv->Port);
1007 void TCP_Server_Close(tVFS_Node *Node)
1009 free(Node->ImplPtr);
1014 * \brief Create a client node
1016 tVFS_Node *TCP_Client_Init(tInterface *Interface)
1018 tTCPConnection *conn = calloc( sizeof(tTCPConnection) + TCP_WINDOW_SIZE + TCP_WINDOW_SIZE/8, 1 );
1020 conn->State = TCP_ST_CLOSED;
1021 conn->Interface = Interface;
1022 conn->LocalPort = -1;
1023 conn->RemotePort = -1;
1025 conn->Node.ImplPtr = conn;
1026 conn->Node.NumACLs = 1;
1027 conn->Node.ACLs = &gVFS_ACL_EveryoneRW;
1028 conn->Node.Type = &gTCP_ClientNodeType;
1030 conn->RecievedBuffer = RingBuffer_Create( TCP_RECIEVE_BUFFER_SIZE );
1032 conn->SentBuffer = RingBuffer_Create( TCP_SEND_BUFFER_SIZE );
1033 Semaphore_Init(conn->SentBufferSpace, 0, TCP_SEND_BUFFER_SIZE, "TCP SentBuffer", conn->Name);
1036 #if CACHE_FUTURE_PACKETS_IN_BYTES
1037 // Future recieved data (ahead of the expected sequence number)
1038 conn->FuturePacketData = (Uint8*)conn + sizeof(tTCPConnection);
1039 conn->FuturePacketValidBytes = conn->FuturePacketData + TCP_WINDOW_SIZE;
1042 SHORTLOCK(&glTCP_OutbountCons);
1043 conn->Next = gTCP_OutbountCons;
1044 gTCP_OutbountCons = conn;
1045 SHORTREL(&glTCP_OutbountCons);
1051 * \brief Wait for a packet and return it
1052 * \note If \a Length is smaller than the size of the packet, the rest
1053 * of the packet's data will be discarded.
1055 Uint64 TCP_Client_Read(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer)
1057 tTCPConnection *conn = Node->ImplPtr;
1060 ENTER("pNode XOffset XLength pBuffer", Node, Offset, Length, Buffer);
1061 LOG("conn = %p {State:%i}", conn, conn->State);
1063 // Check if connection is estabilishing
1064 // - TODO: Sleep instead (maybe using VFS_SelectNode to wait for the
1065 // data to be availiable
1066 while( conn->State == TCP_ST_SYN_RCVD || conn->State == TCP_ST_SYN_SENT )
1069 // If the conneciton is not open, then clean out the recieved buffer
1070 if( conn->State != TCP_ST_OPEN )
1072 Mutex_Acquire( &conn->lRecievedPackets );
1073 len = RingBuffer_Read( Buffer, conn->RecievedBuffer, Length );
1074 Mutex_Release( &conn->lRecievedPackets );
1077 VFS_MarkAvaliable(Node, 0);
1087 VFS_SelectNode(Node, VFS_SELECT_READ|VFS_SELECT_ERROR, NULL, "TCP_Client_Read");
1089 // Lock list and read as much as possible (up to `Length`)
1090 Mutex_Acquire( &conn->lRecievedPackets );
1091 len = RingBuffer_Read( Buffer, conn->RecievedBuffer, Length );
1093 if( len == 0 || conn->RecievedBuffer->Length == 0 ) {
1094 LOG("Marking as none avaliable (len = %i)", len);
1095 VFS_MarkAvaliable(Node, 0);
1098 // Release the lock (we don't need it any more)
1099 Mutex_Release( &conn->lRecievedPackets );
1106 * \brief Send a data packet on a connection
1108 void TCP_INT_SendDataPacket(tTCPConnection *Connection, size_t Length, const void *Data)
1110 char buf[sizeof(tTCPHeader)+Length];
1111 tTCPHeader *packet = (void*)buf;
1113 packet->SourcePort = htons(Connection->LocalPort);
1114 packet->DestPort = htons(Connection->RemotePort);
1115 packet->DataOffset = (sizeof(tTCPHeader)/4)*16;
1116 packet->WindowSize = htons(TCP_WINDOW_SIZE);
1118 packet->AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
1119 packet->SequenceNumber = htonl(Connection->NextSequenceSend);
1120 packet->Flags = TCP_FLAG_PSH|TCP_FLAG_ACK; // Hey, ACK if you can!
1122 memcpy(packet->Options, Data, Length);
1124 Log_Debug("TCP", "Send sequence 0x%08x", Connection->NextSequenceSend);
1125 #if HEXDUMP_OUTGOING
1126 Debug_HexDump("TCP_INT_SendDataPacket: Data = ", Data, Length);
1129 TCP_SendPacket( Connection, sizeof(tTCPHeader)+Length, packet );
1131 Connection->NextSequenceSend += Length;
1135 * \brief Send some bytes on a connection
1137 Uint64 TCP_Client_Write(tVFS_Node *Node, Uint64 Offset, Uint64 Length, const void *Buffer)
1139 tTCPConnection *conn = Node->ImplPtr;
1140 size_t rem = Length;
1142 ENTER("pNode XOffset XLength pBuffer", Node, Offset, Length, Buffer);
1145 // Debug_HexDump("TCP_Client_Write: Buffer = ",
1149 // Check if connection is open
1150 while( conn->State == TCP_ST_SYN_RCVD || conn->State == TCP_ST_SYN_SENT )
1153 if( conn->State != TCP_ST_OPEN ) {
1154 VFS_MarkError(Node, 1);
1161 int len = (rem < TCP_MAX_PACKET_SIZE) ? rem : TCP_MAX_PACKET_SIZE;
1164 // Wait for space in the buffer
1165 Semaphore_Signal( &Connection->SentBufferSpace, len );
1167 // Save data to buffer (and update the length read by the ammount written)
1168 len = RingBuffer_Write( &Connection->SentBuffer, Buffer, len);
1172 TCP_INT_SendDataPacket(conn, len, Buffer);
1183 * \brief Open a connection to another host using TCP
1184 * \param Conn Connection structure
1186 void TCP_StartConnection(tTCPConnection *Conn)
1188 tTCPHeader hdr = {0};
1190 Conn->State = TCP_ST_SYN_SENT;
1192 hdr.SourcePort = htons(Conn->LocalPort);
1193 hdr.DestPort = htons(Conn->RemotePort);
1194 Conn->NextSequenceSend = rand();
1195 hdr.SequenceNumber = htonl(Conn->NextSequenceSend);
1196 hdr.DataOffset = (sizeof(tTCPHeader)/4) << 4;
1197 hdr.Flags = TCP_FLAG_SYN;
1198 hdr.WindowSize = htons(TCP_WINDOW_SIZE); // Max
1199 hdr.Checksum = 0; // TODO
1201 TCP_SendPacket( Conn, sizeof(tTCPHeader), &hdr );
1203 Conn->NextSequenceSend ++;
1204 Conn->State = TCP_ST_SYN_SENT;
1210 * \brief Control a client socket
1212 int TCP_Client_IOCtl(tVFS_Node *Node, int ID, void *Data)
1214 tTCPConnection *conn = Node->ImplPtr;
1216 ENTER("pNode iID pData", Node, ID, Data);
1220 case 4: // Get/Set local port
1222 LEAVE_RET('i', conn->LocalPort);
1223 if(conn->State != TCP_ST_CLOSED)
1225 if(!CheckMem(Data, sizeof(Uint16)))
1228 if(Threads_GetUID() != 0 && *(Uint16*)Data < 1024)
1231 conn->LocalPort = *(Uint16*)Data;
1232 LEAVE_RET('i', conn->LocalPort);
1234 case 5: // Get/Set remote port
1235 if(!Data) LEAVE_RET('i', conn->RemotePort);
1236 if(conn->State != TCP_ST_CLOSED) LEAVE_RET('i', -1);
1237 if(!CheckMem(Data, sizeof(Uint16))) LEAVE_RET('i', -1);
1238 conn->RemotePort = *(Uint16*)Data;
1239 LEAVE_RET('i', conn->RemotePort);
1241 case 6: // Set Remote IP
1242 if( conn->State != TCP_ST_CLOSED )
1244 if( conn->Interface->Type == 4 )
1246 if(!CheckMem(Data, sizeof(tIPv4))) LEAVE_RET('i', -1);
1247 conn->RemoteIP.v4 = *(tIPv4*)Data;
1249 else if( conn->Interface->Type == 6 )
1251 if(!CheckMem(Data, sizeof(tIPv6))) LEAVE_RET('i', -1);
1252 conn->RemoteIP.v6 = *(tIPv6*)Data;
1257 if(conn->LocalPort == 0xFFFF)
1258 conn->LocalPort = TCP_GetUnusedPort();
1259 if(conn->RemotePort == -1)
1263 tTime timeout_end = now() + conn->Interface->TimeoutDelay;
1265 TCP_StartConnection(conn);
1266 // TODO: Wait for connection to open
1267 while( conn->State == TCP_ST_SYN_SENT && timeout_end > now() ) {
1270 if( conn->State == TCP_ST_SYN_SENT )
1276 // Get recieve buffer length
1278 LEAVE_RET('i', conn->RecievedBuffer->Length);
1284 void TCP_Client_Close(tVFS_Node *Node)
1286 tTCPConnection *conn = Node->ImplPtr;
1289 ENTER("pNode", Node);
1291 if( conn->State == TCP_ST_CLOSE_WAIT || conn->State == TCP_ST_OPEN )
1293 packet.SourcePort = htons(conn->LocalPort);
1294 packet.DestPort = htons(conn->RemotePort);
1295 packet.DataOffset = (sizeof(tTCPHeader)/4)*16;
1296 packet.WindowSize = TCP_WINDOW_SIZE;
1298 packet.AcknowlegementNumber = 0;
1299 packet.SequenceNumber = htonl(conn->NextSequenceSend);
1300 packet.Flags = TCP_FLAG_FIN;
1302 TCP_SendPacket( conn, sizeof(tTCPHeader), &packet );
1305 switch( conn->State )
1307 case TCP_ST_CLOSE_WAIT:
1308 conn->State = TCP_ST_LAST_ACK;
1311 conn->State = TCP_ST_FIN_WAIT1;
1312 while( conn->State == TCP_ST_FIN_WAIT1 ) Threads_Yield();
1315 Log_Warning("TCP", "Unhandled connection state in TCP_Client_Close");
1325 * \brief Checks if a value is between two others (after taking into account wrapping)
1327 int WrapBetween(Uint32 Lower, Uint32 Value, Uint32 Higher, Uint32 MaxValue)
1329 if( MaxValue < 0xFFFFFFFF )
1331 Lower %= MaxValue + 1;
1332 Value %= MaxValue + 1;
1333 Higher %= MaxValue + 1;
1336 // Simple Case, no wrap ?
1337 // Lower Value Higher
1338 // | ... + ... + ... + ... |
1340 if( Lower < Higher ) {
1341 return Lower < Value && Value < Higher;
1343 // Higher has wrapped below lower
1346 // Higher Lower Value
1347 // | ... + ... + ... + ... |
1348 if( Value > Lower ) {
1353 // Value Higher Lower
1354 // | ... + ... + ... + ... |
1355 if( Value < Higher ) {