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, 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};
54 int giTCP_NumHalfopen = 0;
55 tShortSpinlock glTCP_Listeners;
56 tTCPListener *gTCP_Listeners;
57 tShortSpinlock glTCP_OutbountCons;
58 tTCPConnection *gTCP_OutbountCons;
59 Uint32 gaTCP_PortBitmap[0x800];
60 int giTCP_NextOutPort = TCP_MIN_DYNPORT;
64 * \brief Initialise the TCP Layer
66 * Registers the client and server files and the GetPacket callback
68 void TCP_Initialise(void)
70 giTCP_NextOutPort += rand()%32;
71 IPStack_AddFile(&gTCP_ServerFile);
72 IPStack_AddFile(&gTCP_ClientFile);
73 IPv4_RegisterCallback(IP4PROT_TCP, TCP_GetPacket);
74 IPv6_RegisterCallback(IP4PROT_TCP, TCP_GetPacket);
78 * \brief Sends a packet from the specified connection, calculating the checksums
79 * \param Conn Connection
80 * \param Length Length of data
81 * \param Data Packet data (cast as a TCP Header)
83 void TCP_SendPacket( tTCPConnection *Conn, size_t Length, tTCPHeader *Data )
88 checksum[1] = htons( ~IPv4_Checksum( (void*)Data, Length ) ); // Partial checksum
90 ((Uint8*)Data)[Length] = 0;
92 // TODO: Fragment packet
94 switch( Conn->Interface->Type )
97 // Append IPv4 Pseudo Header
100 buf[0] = ((tIPv4*)Conn->Interface->Address)->L;
101 buf[1] = Conn->RemoteIP.v4.L;
102 buf[2] = (htons(Length)<<16) | (6<<8) | 0;
103 checksum[0] = htons( ~IPv4_Checksum(buf, sizeof(buf)) ); // Partial checksum
105 Data->Checksum = htons( IPv4_Checksum(checksum, 2*2) ); // Combine the two
106 IPv4_SendPacket(Conn->Interface, Conn->RemoteIP.v4, IP4PROT_TCP, 0, Length, Data);
110 // Append IPv6 Pseudo Header
113 memcpy(buf, Conn->Interface->Address, 16);
114 memcpy(&buf[4], &Conn->RemoteIP, 16);
115 buf[8] = htonl(Length);
117 checksum[0] = htons( ~IPv4_Checksum(buf, sizeof(buf)) ); // Partial checksum
119 Data->Checksum = htons( IPv4_Checksum(checksum, 2*2) ); // Combine the two
120 IPv6_SendPacket(Conn->Interface, Conn->RemoteIP.v6, IP4PROT_TCP, Length, Data);
126 * \brief Handles a packet from the IP Layer
127 * \param Interface Interface the packet arrived from
128 * \param Address Pointer to the addres structure
129 * \param Length Size of packet in bytes
130 * \param Buffer Packet data
132 void TCP_GetPacket(tInterface *Interface, void *Address, int Length, void *Buffer)
134 tTCPHeader *hdr = Buffer;
136 tTCPConnection *conn;
138 Log_Log("TCP", "TCP_GetPacket: <Local>:%i from [%s]:%i, Flags= %s%s%s%s%s%s%s%s",
139 ntohs(hdr->SourcePort),
140 IPStack_PrintAddress(Interface->Type, Address),
141 ntohs(hdr->DestPort),
142 (hdr->Flags & TCP_FLAG_CWR) ? "CWR " : "",
143 (hdr->Flags & TCP_FLAG_ECE) ? "ECE " : "",
144 (hdr->Flags & TCP_FLAG_URG) ? "URG " : "",
145 (hdr->Flags & TCP_FLAG_ACK) ? "ACK " : "",
146 (hdr->Flags & TCP_FLAG_PSH) ? "PSH " : "",
147 (hdr->Flags & TCP_FLAG_RST) ? "RST " : "",
148 (hdr->Flags & TCP_FLAG_SYN) ? "SYN " : "",
149 (hdr->Flags & TCP_FLAG_FIN) ? "FIN " : ""
152 if( Length > (hdr->DataOffset >> 4)*4 )
154 Log_Log("TCP", "TCP_GetPacket: SequenceNumber = 0x%x", ntohl(hdr->SequenceNumber));
157 "TCP_GetPacket: Packet Data = ",
158 (Uint8*)hdr + (hdr->DataOffset >> 4)*4,
159 Length - (hdr->DataOffset >> 4)*4
166 for( srv = gTCP_Listeners; srv; srv = srv->Next )
168 // Check if the server is active
169 if(srv->Port == 0) continue;
170 // Check the interface
171 if(srv->Interface && srv->Interface != Interface) continue;
172 // Check the destination port
173 if(srv->Port != htons(hdr->DestPort)) continue;
175 Log_Log("TCP", "TCP_GetPacket: Matches server %p", srv);
176 // Is this in an established connection?
177 for( conn = srv->Connections; conn; conn = conn->Next )
179 // Check that it is coming in on the same interface
180 if(conn->Interface != Interface) continue;
183 Log_Log("TCP", "TCP_GetPacket: conn->RemotePort(%i) == hdr->SourcePort(%i)",
184 conn->RemotePort, ntohs(hdr->SourcePort));
185 if(conn->RemotePort != ntohs(hdr->SourcePort)) continue;
188 if( IPStack_CompareAddress(conn->Interface->Type, &conn->RemoteIP, Address, -1) != 0 )
191 Log_Log("TCP", "TCP_GetPacket: Matches connection %p", conn);
192 // We have a response!
193 TCP_INT_HandleConnectionPacket(conn, hdr, Length);
198 Log_Log("TCP", "TCP_GetPacket: Opening Connection");
199 // Open a new connection (well, check that it's a SYN)
200 if(hdr->Flags != TCP_FLAG_SYN) {
201 Log_Log("TCP", "TCP_GetPacket: Packet is not a SYN");
205 // TODO: Check for halfopen max
207 conn = calloc(1, sizeof(tTCPConnection));
208 conn->State = TCP_ST_SYN_RCVD;
209 conn->LocalPort = srv->Port;
210 conn->RemotePort = ntohs(hdr->SourcePort);
211 conn->Interface = Interface;
213 switch(Interface->Type)
215 case 4: conn->RemoteIP.v4 = *(tIPv4*)Address; break;
216 case 6: conn->RemoteIP.v6 = *(tIPv6*)Address; break;
219 conn->RecievedBuffer = RingBuffer_Create( TCP_RECIEVE_BUFFER_SIZE );
221 conn->NextSequenceRcv = ntohl( hdr->SequenceNumber ) + 1;
222 conn->NextSequenceSend = rand();
225 conn->Node.NumACLs = 1;
226 conn->Node.ACLs = &gVFS_ACL_EveryoneRW;
227 conn->Node.ImplPtr = conn;
228 conn->Node.ImplInt = srv->NextID ++;
229 conn->Node.Read = TCP_Client_Read;
230 conn->Node.Write = TCP_Client_Write;
231 //conn->Node.Close = TCP_SrvConn_Close;
233 // Hmm... Theoretically, this lock will never have to wait,
234 // as the interface is locked to the watching thread, and this
235 // runs in the watching thread. But, it's a good idea to have
237 // Oh, wait, there is a case where a wildcard can be used
238 // (srv->Interface == NULL) so having the lock is a good idea
239 SHORTLOCK(&srv->lConnections);
240 if( !srv->Connections )
241 srv->Connections = conn;
243 srv->ConnectionsTail->Next = conn;
244 srv->ConnectionsTail = conn;
245 if(!srv->NewConnections)
246 srv->NewConnections = conn;
247 SHORTREL(&srv->lConnections);
250 hdr->Flags |= TCP_FLAG_ACK;
251 hdr->AcknowlegementNumber = htonl(conn->NextSequenceRcv);
252 hdr->SequenceNumber = htonl(conn->NextSequenceSend);
253 hdr->DestPort = hdr->SourcePort;
254 hdr->SourcePort = htons(srv->Port);
255 hdr->DataOffset = (sizeof(tTCPHeader)/4) << 4;
256 TCP_SendPacket( conn, sizeof(tTCPHeader), hdr );
257 conn->NextSequenceSend ++;
263 // Check Open Connections
265 for( conn = gTCP_OutbountCons; conn; conn = conn->Next )
267 // Check that it is coming in on the same interface
268 if(conn->Interface != Interface) continue;
271 if(conn->RemotePort != ntohs(hdr->SourcePort)) continue;
274 if(conn->Interface->Type == 6 && !IP6_EQU(conn->RemoteIP.v6, *(tIPv6*)Address))
276 if(conn->Interface->Type == 4 && !IP4_EQU(conn->RemoteIP.v4, *(tIPv4*)Address))
279 TCP_INT_HandleConnectionPacket(conn, hdr, Length);
284 Log_Log("TCP", "TCP_GetPacket: No Match");
288 * \brief Handles a packet sent to a specific connection
289 * \param Connection TCP Connection pointer
290 * \param Header TCP Packet pointer
291 * \param Length Length of the packet
293 void TCP_INT_HandleConnectionPacket(tTCPConnection *Connection, tTCPHeader *Header, int Length)
298 // Silently drop once finished
299 // TODO: Check if this needs to be here
300 if( Connection->State == TCP_ST_FINISHED ) {
301 Log_Log("TCP", "Packet ignored - connection finnished");
305 // Syncronise sequence values
306 if(Header->Flags & TCP_FLAG_SYN) {
307 // TODO: What if the packet also has data?
308 Connection->NextSequenceRcv = ntohl(Header->SequenceNumber);
311 // Ackowledge a sent packet
312 if(Header->Flags & TCP_FLAG_ACK) {
313 // TODO: Process an ACKed Packet
314 Log_Log("TCP", "Conn %p, Sent packet 0x%x ACKed", Connection, Header->AcknowlegementNumber);
317 // Get length of data
318 dataLen = Length - (Header->DataOffset>>4)*4;
319 Log_Log("TCP", "HandleConnectionPacket - dataLen = %i", dataLen);
324 switch( Connection->State )
326 // Pre-init connection?
328 Log_Log("TCP", "Packets to a closed connection?!");
331 // --- Init States ---
332 // SYN sent, expecting SYN-ACK Connection Opening
333 case TCP_ST_SYN_SENT:
334 if( Header->Flags & TCP_FLAG_SYN )
336 Connection->NextSequenceRcv ++;
337 Header->DestPort = Header->SourcePort;
338 Header->SourcePort = htons(Connection->LocalPort);
339 Header->AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
340 Header->SequenceNumber = htonl(Connection->NextSequenceSend);
341 Header->WindowSize = htons(TCP_WINDOW_SIZE);
342 Header->Flags = TCP_FLAG_ACK;
343 Header->DataOffset = (sizeof(tTCPHeader)/4) << 4;
344 TCP_SendPacket( Connection, sizeof(tTCPHeader), Header );
346 if( Header->Flags & TCP_FLAG_ACK )
348 Log_Log("TCP", "ACKing SYN-ACK");
349 Connection->State = TCP_ST_OPEN;
353 Log_Log("TCP", "ACKing SYN");
354 Connection->State = TCP_ST_SYN_RCVD;
359 // SYN-ACK sent, expecting ACK
360 case TCP_ST_SYN_RCVD:
361 if( Header->Flags & TCP_FLAG_ACK )
363 // TODO: Handle max half-open limit
364 Connection->State = TCP_ST_OPEN;
365 Log_Log("TCP", "Connection fully opened");
369 // --- Established State ---
371 // - Handle State changes
373 if( Header->Flags & TCP_FLAG_FIN ) {
374 Log_Log("TCP", "Conn %p closed, recieved FIN", Connection);
375 VFS_MarkError(&Connection->Node, 1);
376 Connection->State = TCP_ST_CLOSE_WAIT;
377 // Header->Flags &= ~TCP_FLAG_FIN;
378 // CLOSE WAIT requires the client to close (or does it?)
384 // Check for an empty packet
386 if( Header->Flags == TCP_FLAG_ACK )
388 Log_Log("TCP", "ACK only packet");
391 Connection->NextSequenceRcv ++; // TODO: Is this right? (empty packet counts as one byte)
392 Log_Log("TCP", "Empty Packet, inc and ACK the current sequence number");
393 Header->DestPort = Header->SourcePort;
394 Header->SourcePort = htons(Connection->LocalPort);
395 Header->AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
396 Header->SequenceNumber = htonl(Connection->NextSequenceSend);
397 Header->Flags |= TCP_FLAG_ACK;
398 TCP_SendPacket( Connection, sizeof(tTCPHeader), Header );
407 sequence_num = ntohl(Header->SequenceNumber);
409 Log_Log("TCP", "0x%08x <= 0x%08x < 0x%08x",
410 Connection->NextSequenceRcv,
411 ntohl(Header->SequenceNumber),
412 Connection->NextSequenceRcv + TCP_WINDOW_SIZE
415 // Is this packet the next expected packet?
416 if( sequence_num == Connection->NextSequenceRcv )
419 // Ooh, Goodie! Add it to the recieved list
420 rv = TCP_INT_AppendRecieved(Connection,
421 (Uint8*)Header + (Header->DataOffset>>4)*4,
427 Log_Log("TCP", "0x%08x += %i", Connection->NextSequenceRcv, dataLen);
428 Connection->NextSequenceRcv += dataLen;
430 // TODO: This should be moved out of the watcher thread,
431 // so that a single lost packet on one connection doesn't cause
432 // all connections on the interface to lag.
433 // - Meh, no real issue, as the cache shouldn't be that large
434 TCP_INT_UpdateRecievedFromFuture(Connection);
437 Header->DestPort = Header->SourcePort;
438 Header->SourcePort = htons(Connection->LocalPort);
439 Header->AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
440 Header->SequenceNumber = htonl(Connection->NextSequenceSend);
441 Header->WindowSize = htons(TCP_WINDOW_SIZE);
442 Header->Flags &= TCP_FLAG_SYN; // Eliminate all flags save for SYN
443 Header->Flags |= TCP_FLAG_ACK; // Add ACK
444 Log_Log("TCP", "Sending ACK for 0x%08x", Connection->NextSequenceRcv);
445 TCP_SendPacket( Connection, sizeof(tTCPHeader), Header );
446 //Connection->NextSequenceSend ++;
448 // Check if the packet is in window
449 else if( WrapBetween(Connection->NextSequenceRcv, sequence_num,
450 Connection->NextSequenceRcv+TCP_WINDOW_SIZE, 0xFFFFFFFF) )
452 Uint8 *dataptr = (Uint8*)Header + (Header->DataOffset>>4)*4;
453 #if CACHE_FUTURE_PACKETS_IN_BYTES
457 index = sequence_num % TCP_WINDOW_SIZE;
458 for( i = 0; i < dataLen; i ++ )
460 Connection->FuturePacketValidBytes[index/8] |= 1 << (index%8);
461 Connection->FuturePacketData[index] = dataptr[i];
462 // Do a wrap increment
464 if(index == TCP_WINDOW_SIZE) index = 0;
467 tTCPStoredPacket *pkt, *tmp, *prev = NULL;
469 // Allocate and fill cached packet
470 pkt = malloc( sizeof(tTCPStoredPacket) + dataLen );
472 pkt->Sequence = ntohl(Header->SequenceNumber);
473 pkt->Length = dataLen;
474 memcpy(pkt->Data, dataptr, dataLen);
476 Log_Log("TCP", "We missed a packet, caching",
477 pkt->Sequence, Connection->NextSequenceRcv);
479 // No? Well, let's cache it and look at it later
480 SHORTLOCK( &Connection->lFuturePackets );
481 for(tmp = Connection->FuturePackets;
483 prev = tmp, tmp = tmp->Next)
485 if(tmp->Sequence >= pkt->Sequence) break;
488 // Add if before first, or sequences don't match
489 if( !tmp || tmp->Sequence != pkt->Sequence )
494 Connection->FuturePackets = pkt;
498 else if(pkt->Length > tmp->Length)
502 pkt->Next = tmp->Next;
507 free(pkt); // TODO: Find some way to remove this
509 SHORTREL( &Connection->lFuturePackets );
512 // Badly out of sequence packet
515 Log_Log("TCP", "Fully out of sequence packet (0x%08x not between 0x%08x and 0x%08x), dropped",
516 sequence_num, Connection->NextSequenceRcv, Connection->NextSequenceRcv+TCP_WINDOW_SIZE);
517 // TODO: Spec says we should send an empty ACK with the current state
521 // --- Remote close states
522 case TCP_ST_CLOSE_WAIT:
524 // Ignore everything, CLOSE_WAIT is terminated by the client
525 Log_Debug("TCP", "CLOSE WAIT - Ignoring packets");
529 // LAST-ACK - Waiting for the ACK of FIN (from CLOSE WAIT)
530 case TCP_ST_LAST_ACK:
531 if( Header->Flags & TCP_FLAG_ACK )
533 Connection->State = TCP_ST_FINISHED; // Connection completed
534 Log_Log("TCP", "LAST-ACK to CLOSED - Connection remote closed");
535 // TODO: Destrory the TCB
539 // --- Local close States
540 case TCP_ST_FIN_WAIT1:
541 if( Header->Flags & TCP_FLAG_FIN )
543 Connection->State = TCP_ST_CLOSING;
544 Log_Debug("TCP", "Conn %p closed, sent FIN and recieved FIN", Connection);
545 VFS_MarkError(&Connection->Node, 1);
548 Header->DestPort = Header->SourcePort;
549 Header->SourcePort = htons(Connection->LocalPort);
550 Header->AcknowlegementNumber = Header->SequenceNumber;
551 Header->SequenceNumber = htonl(Connection->NextSequenceSend);
552 Header->WindowSize = htons(TCP_WINDOW_SIZE);
553 Header->Flags = TCP_FLAG_ACK;
554 TCP_SendPacket( Connection, sizeof(tTCPHeader), Header );
558 // TODO: Make sure that the packet is actually ACKing the FIN
559 if( Header->Flags & TCP_FLAG_ACK )
561 Connection->State = TCP_ST_FIN_WAIT2;
562 Log_Debug("TCP", "Conn %p closed, sent FIN ACKed", Connection);
563 VFS_MarkError(&Connection->Node, 1);
568 case TCP_ST_FIN_WAIT2:
569 if( Header->Flags & TCP_FLAG_FIN )
571 Connection->State = TCP_ST_TIME_WAIT;
572 Log_Debug("TCP", "FIN sent and recieved, ACKing and going into TIME WAIT %p FINWAIT-2 -> TIME WAIT", Connection);
574 Header->DestPort = Header->SourcePort;
575 Header->SourcePort = htons(Connection->LocalPort);
576 Header->AcknowlegementNumber = Header->SequenceNumber;
577 Header->SequenceNumber = htonl(Connection->NextSequenceSend);
578 Header->WindowSize = htons(TCP_WINDOW_SIZE);
579 Header->Flags = TCP_FLAG_ACK;
580 TCP_SendPacket( Connection, sizeof(tTCPHeader), Header );
585 // TODO: Make sure that the packet is actually ACKing the FIN
586 if( Header->Flags & TCP_FLAG_ACK )
588 Connection->State = TCP_ST_TIME_WAIT;
589 Log_Debug("TCP", "Conn %p CLOSING -> TIME WAIT", Connection);
590 VFS_MarkError(&Connection->Node, 1);
595 // --- Closed (or near closed) states) ---
596 case TCP_ST_TIME_WAIT:
597 Log_Log("TCP", "Packets on Time-Wait, ignored");
600 case TCP_ST_FINISHED:
601 Log_Log("TCP", "Packets when CLOSED, ignoring");
605 // Log_Warning("TCP", "Unhandled TCP state %i", Connection->State);
612 * \brief Appends a packet to the recieved list
613 * \param Connection Connection structure
614 * \param Data Packet contents
615 * \param Length Length of \a Data
617 int TCP_INT_AppendRecieved(tTCPConnection *Connection, const void *Data, size_t Length)
619 Mutex_Acquire( &Connection->lRecievedPackets );
621 if(Connection->RecievedBuffer->Length + Length > Connection->RecievedBuffer->Space )
623 VFS_MarkAvaliable(&Connection->Node, 1);
624 Log_Error("TCP", "Buffer filled, packet dropped (:%i) - %i + %i > %i",
625 Connection->LocalPort, Connection->RecievedBuffer->Length, Length,
626 Connection->RecievedBuffer->Space
628 Mutex_Release( &Connection->lRecievedPackets );
632 RingBuffer_Write( Connection->RecievedBuffer, Data, Length );
634 VFS_MarkAvaliable(&Connection->Node, 1);
636 Mutex_Release( &Connection->lRecievedPackets );
641 * \brief Updates the connections recieved list from the future list
642 * \param Connection Connection structure
644 * Updates the recieved packets list with packets from the future (out
645 * of order) packets list that are now able to be added in direct
648 void TCP_INT_UpdateRecievedFromFuture(tTCPConnection *Connection)
650 #if CACHE_FUTURE_PACKETS_IN_BYTES
654 // Calculate length of contiguous bytes
655 length = Connection->HighestSequenceRcvd - Connection->NextSequenceRcv;
656 index = Connection->NextSequenceRcv % TCP_WINDOW_SIZE;
657 for( i = 0; i < length; i ++ )
659 if( Connection->FuturePacketValidBytes[i / 8] == 0xFF ) {
663 else if( !(Connection->FuturePacketValidBytes[i / 8] & (1 << (i%8))) )
667 if(index > TCP_WINDOW_SIZE)
668 index -= TCP_WINDOW_SIZE;
672 index = Connection->NextSequenceRcv % TCP_WINDOW_SIZE;
674 // Write data to to the ring buffer
675 if( TCP_WINDOW_SIZE - index > length )
678 RingBuffer_Write( Connection->RecievedBuffer, Connection->FuturePacketData + index, length );
682 int endLen = TCP_WINDOW_SIZE - index;
684 RingBuffer_Write( Connection->RecievedBuffer, Connection->FuturePacketData + index, endLen );
685 RingBuffer_Write( Connection->RecievedBuffer, Connection->FuturePacketData, endLen - length );
688 // Mark (now saved) bytes as invalid
690 while(index % 8 && length)
692 Connection->FuturePacketData[index] = 0;
693 Connection->FuturePacketData[index/8] &= ~(1 << (index%8));
695 if(index > TCP_WINDOW_SIZE)
696 index -= TCP_WINDOW_SIZE;
701 Connection->FuturePacketData[index] = 0;
702 Connection->FuturePacketValidBytes[index/8] = 0;
705 if(index > TCP_WINDOW_SIZE)
706 index -= TCP_WINDOW_SIZE;
710 Connection->FuturePacketData[index] = 0;
711 Connection->FuturePacketData[index/8] &= ~(1 << (index%8));
713 if(index > TCP_WINDOW_SIZE)
714 index -= TCP_WINDOW_SIZE;
719 tTCPStoredPacket *pkt;
722 SHORTLOCK( &Connection->lFuturePackets );
724 // Clear out duplicates from cache
725 // - If a packet has just been recieved, and it is expected, then
726 // (since NextSequenceRcv = rcvd->Sequence + rcvd->Length) all
727 // packets in cache that are smaller than the next expected
729 pkt = Connection->FuturePackets;
730 while(pkt && pkt->Sequence < Connection->NextSequenceRcv)
732 tTCPStoredPacket *next = pkt->Next;
737 // If there's no packets left in cache, stop looking
738 if(!pkt || pkt->Sequence > Connection->NextSequenceRcv) {
739 SHORTREL( &Connection->lFuturePackets );
743 // Delete packet from future list
744 Connection->FuturePackets = pkt->Next;
747 SHORTREL( &Connection->lFuturePackets );
749 // Looks like we found one
750 TCP_INT_AppendRecieved(Connection, pkt);
751 Connection->NextSequenceRcv += pkt->Length;
758 * \fn Uint16 TCP_GetUnusedPort()
759 * \brief Gets an unused port and allocates it
761 Uint16 TCP_GetUnusedPort()
765 // Get Next outbound port
766 ret = giTCP_NextOutPort++;
767 while( gaTCP_PortBitmap[ret/32] & (1 << (ret%32)) )
771 if(giTCP_NextOutPort == 0x10000) {
772 ret = giTCP_NextOutPort = TCP_MIN_DYNPORT;
776 // Mark the new port as used
777 gaTCP_PortBitmap[ret/32] |= 1 << (ret%32);
783 * \fn int TCP_AllocatePort(Uint16 Port)
784 * \brief Marks a port as used
786 int TCP_AllocatePort(Uint16 Port)
788 // Check if the port has already been allocated
789 if( gaTCP_PortBitmap[Port/32] & (1 << (Port%32)) )
793 gaTCP_PortBitmap[Port/32] |= 1 << (Port%32);
799 * \fn int TCP_DeallocatePort(Uint16 Port)
800 * \brief Marks a port as unused
802 int TCP_DeallocatePort(Uint16 Port)
804 // Check if the port has already been allocated
805 if( !(gaTCP_PortBitmap[Port/32] & (1 << (Port%32))) )
809 gaTCP_PortBitmap[Port/32] &= ~(1 << (Port%32));
815 tVFS_Node *TCP_Server_Init(tInterface *Interface)
819 srv = malloc( sizeof(tTCPListener) );
822 Log_Warning("TCP", "malloc failed for listener (%i) bytes", sizeof(tTCPListener));
826 srv->Interface = Interface;
829 srv->Connections = NULL;
830 srv->ConnectionsTail = NULL;
831 srv->NewConnections = NULL;
833 srv->Node.Flags = VFS_FFLAG_DIRECTORY;
835 srv->Node.ImplPtr = srv;
836 srv->Node.NumACLs = 1;
837 srv->Node.ACLs = &gVFS_ACL_EveryoneRW;
838 srv->Node.ReadDir = TCP_Server_ReadDir;
839 srv->Node.FindDir = TCP_Server_FindDir;
840 srv->Node.IOCtl = TCP_Server_IOCtl;
841 srv->Node.Close = TCP_Server_Close;
843 SHORTLOCK(&glTCP_Listeners);
844 srv->Next = gTCP_Listeners;
845 gTCP_Listeners = srv;
846 SHORTREL(&glTCP_Listeners);
852 * \brief Wait for a new connection and return the connection ID
853 * \note Blocks until a new connection is made
854 * \param Node Server node
855 * \param Pos Position (ignored)
857 char *TCP_Server_ReadDir(tVFS_Node *Node, int Pos)
859 tTCPListener *srv = Node->ImplPtr;
860 tTCPConnection *conn;
863 ENTER("pNode iPos", Node, Pos);
865 Log_Log("TCP", "Thread %i waiting for a connection", Threads_GetTID());
868 SHORTLOCK( &srv->lConnections );
869 if( srv->NewConnections != NULL ) break;
870 SHORTREL( &srv->lConnections );
871 Threads_Yield(); // TODO: Sleep until poked
876 // Increment the new list (the current connection is still on the
878 conn = srv->NewConnections;
879 srv->NewConnections = conn->Next;
881 SHORTREL( &srv->lConnections );
883 LOG("conn = %p", conn);
884 LOG("srv->Connections = %p", srv->Connections);
885 LOG("srv->NewConnections = %p", srv->NewConnections);
886 LOG("srv->ConnectionsTail = %p", srv->ConnectionsTail);
889 itoa(ret, conn->Node.ImplInt, 16, 8, '0');
890 Log_Log("TCP", "Thread %i got '%s'", Threads_GetTID(), ret);
896 * \brief Gets a client connection node
897 * \param Node Server node
898 * \param Name Hexadecimal ID of the node
900 tVFS_Node *TCP_Server_FindDir(tVFS_Node *Node, const char *Name)
902 tTCPConnection *conn;
903 tTCPListener *srv = Node->ImplPtr;
907 ENTER("pNode sName", Node, Name);
910 itoa(tmp, id, 16, 8, '0');
911 if(strcmp(tmp, Name) != 0) {
912 LOG("'%s' != '%s' (%08x)", Name, tmp, id);
917 Log_Debug("TCP", "srv->Connections = %p", srv->Connections);
918 Log_Debug("TCP", "srv->NewConnections = %p", srv->NewConnections);
919 Log_Debug("TCP", "srv->ConnectionsTail = %p", srv->ConnectionsTail);
922 SHORTLOCK( &srv->lConnections );
923 for(conn = srv->Connections;
927 LOG("conn->Node.ImplInt = %i", conn->Node.ImplInt);
928 if(conn->Node.ImplInt == id) break;
930 SHORTREL( &srv->lConnections );
932 // If not found, ret NULL
934 LOG("Connection %i not found", id);
940 LEAVE('p', &conn->Node);
945 * \brief Handle IOCtl calls
947 int TCP_Server_IOCtl(tVFS_Node *Node, int ID, void *Data)
949 tTCPListener *srv = Node->ImplPtr;
953 case 4: // Get/Set Port
954 if(!Data) // Get Port
957 if(srv->Port) // Wait, you can't CHANGE the port
960 if(!CheckMem(Data, sizeof(Uint16))) // Sanity check
964 if(Threads_GetUID() != 0
965 && *(Uint16*)Data != 0
966 && *(Uint16*)Data < 1024)
969 // TODO: Check if a port is in use
972 srv->Port = *(Uint16*)Data;
973 if(srv->Port == 0) // Allocate a random port
974 srv->Port = TCP_GetUnusedPort();
975 else // Else, mark this as used
976 TCP_AllocatePort(srv->Port);
978 Log_Log("TCP", "Server %p listening on port %i", srv, srv->Port);
985 void TCP_Server_Close(tVFS_Node *Node)
992 * \brief Create a client node
994 tVFS_Node *TCP_Client_Init(tInterface *Interface)
996 tTCPConnection *conn = calloc( sizeof(tTCPConnection) + TCP_WINDOW_SIZE + TCP_WINDOW_SIZE/8, 1 );
998 conn->State = TCP_ST_CLOSED;
999 conn->Interface = Interface;
1000 conn->LocalPort = -1;
1001 conn->RemotePort = -1;
1003 conn->Node.ImplPtr = conn;
1004 conn->Node.NumACLs = 1;
1005 conn->Node.ACLs = &gVFS_ACL_EveryoneRW;
1006 conn->Node.Read = TCP_Client_Read;
1007 conn->Node.Write = TCP_Client_Write;
1008 conn->Node.IOCtl = TCP_Client_IOCtl;
1009 conn->Node.Close = TCP_Client_Close;
1011 conn->RecievedBuffer = RingBuffer_Create( TCP_RECIEVE_BUFFER_SIZE );
1013 conn->SentBuffer = RingBuffer_Create( TCP_SEND_BUFFER_SIZE );
1014 Semaphore_Init(conn->SentBufferSpace, 0, TCP_SEND_BUFFER_SIZE, "TCP SentBuffer", conn->Name);
1017 #if CACHE_FUTURE_PACKETS_IN_BYTES
1018 // Future recieved data (ahead of the expected sequence number)
1019 conn->FuturePacketData = (Uint8*)conn + sizeof(tTCPConnection);
1020 conn->FuturePacketValidBytes = conn->FuturePacketData + TCP_WINDOW_SIZE;
1023 SHORTLOCK(&glTCP_OutbountCons);
1024 conn->Next = gTCP_OutbountCons;
1025 gTCP_OutbountCons = conn;
1026 SHORTREL(&glTCP_OutbountCons);
1032 * \brief Wait for a packet and return it
1033 * \note If \a Length is smaller than the size of the packet, the rest
1034 * of the packet's data will be discarded.
1036 Uint64 TCP_Client_Read(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer)
1038 tTCPConnection *conn = Node->ImplPtr;
1041 ENTER("pNode XOffset XLength pBuffer", Node, Offset, Length, Buffer);
1042 LOG("conn = %p {State:%i}", conn, conn->State);
1044 // Check if connection is estabilishing
1045 // - TODO: Sleep instead (maybe using VFS_SelectNode to wait for the
1046 // data to be availiable
1047 while( conn->State == TCP_ST_SYN_RCVD || conn->State == TCP_ST_SYN_SENT )
1050 // If the conneciton is not open, then clean out the recieved buffer
1051 if( conn->State != TCP_ST_OPEN )
1053 Mutex_Acquire( &conn->lRecievedPackets );
1054 len = RingBuffer_Read( Buffer, conn->RecievedBuffer, Length );
1055 Mutex_Release( &conn->lRecievedPackets );
1058 VFS_MarkAvaliable(Node, 0);
1068 VFS_SelectNode(Node, VFS_SELECT_READ|VFS_SELECT_ERROR, NULL, "TCP_Client_Read");
1070 // Lock list and read as much as possible (up to `Length`)
1071 Mutex_Acquire( &conn->lRecievedPackets );
1072 len = RingBuffer_Read( Buffer, conn->RecievedBuffer, Length );
1074 if( len == 0 || conn->RecievedBuffer->Length == 0 ) {
1075 LOG("Marking as none avaliable (len = %i)", len);
1076 VFS_MarkAvaliable(Node, 0);
1079 // Release the lock (we don't need it any more)
1080 Mutex_Release( &conn->lRecievedPackets );
1087 * \brief Send a data packet on a connection
1089 void TCP_INT_SendDataPacket(tTCPConnection *Connection, size_t Length, void *Data)
1091 char buf[sizeof(tTCPHeader)+Length];
1092 tTCPHeader *packet = (void*)buf;
1094 packet->SourcePort = htons(Connection->LocalPort);
1095 packet->DestPort = htons(Connection->RemotePort);
1096 packet->DataOffset = (sizeof(tTCPHeader)/4)*16;
1097 packet->WindowSize = htons(TCP_WINDOW_SIZE);
1099 packet->AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
1100 packet->SequenceNumber = htonl(Connection->NextSequenceSend);
1101 packet->Flags = TCP_FLAG_PSH|TCP_FLAG_ACK; // Hey, ACK if you can!
1103 memcpy(packet->Options, Data, Length);
1105 Log_Debug("TCP", "Send sequence 0x%08x", Connection->NextSequenceSend);
1106 #if HEXDUMP_OUTGOING
1107 Debug_HexDump("TCP_INT_SendDataPacket: Data = ", Data, Length);
1110 TCP_SendPacket( Connection, sizeof(tTCPHeader)+Length, packet );
1112 Connection->NextSequenceSend += Length;
1116 * \brief Send some bytes on a connection
1118 Uint64 TCP_Client_Write(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer)
1120 tTCPConnection *conn = Node->ImplPtr;
1121 size_t rem = Length;
1123 ENTER("pNode XOffset XLength pBuffer", Node, Offset, Length, Buffer);
1126 // Debug_HexDump("TCP_Client_Write: Buffer = ",
1130 // Check if connection is open
1131 while( conn->State == TCP_ST_SYN_RCVD || conn->State == TCP_ST_SYN_SENT )
1134 if( conn->State != TCP_ST_OPEN ) {
1135 VFS_MarkError(Node, 1);
1142 int len = (rem < TCP_MAX_PACKET_SIZE) ? rem : TCP_MAX_PACKET_SIZE;
1145 // Wait for space in the buffer
1146 Semaphore_Signal( &Connection->SentBufferSpace, len );
1148 // Save data to buffer (and update the length read by the ammount written)
1149 len = RingBuffer_Write( &Connection->SentBuffer, Buffer, len);
1153 TCP_INT_SendDataPacket(conn, len, Buffer);
1164 * \brief Open a connection to another host using TCP
1165 * \param Conn Connection structure
1167 void TCP_StartConnection(tTCPConnection *Conn)
1169 tTCPHeader hdr = {0};
1171 Conn->State = TCP_ST_SYN_SENT;
1173 hdr.SourcePort = htons(Conn->LocalPort);
1174 hdr.DestPort = htons(Conn->RemotePort);
1175 Conn->NextSequenceSend = rand();
1176 hdr.SequenceNumber = htonl(Conn->NextSequenceSend);
1177 hdr.DataOffset = (sizeof(tTCPHeader)/4) << 4;
1178 hdr.Flags = TCP_FLAG_SYN;
1179 hdr.WindowSize = htons(TCP_WINDOW_SIZE); // Max
1180 hdr.Checksum = 0; // TODO
1182 TCP_SendPacket( Conn, sizeof(tTCPHeader), &hdr );
1184 Conn->NextSequenceSend ++;
1185 Conn->State = TCP_ST_SYN_SENT;
1191 * \brief Control a client socket
1193 int TCP_Client_IOCtl(tVFS_Node *Node, int ID, void *Data)
1195 tTCPConnection *conn = Node->ImplPtr;
1197 ENTER("pNode iID pData", Node, ID, Data);
1201 case 4: // Get/Set local port
1203 LEAVE_RET('i', conn->LocalPort);
1204 if(conn->State != TCP_ST_CLOSED)
1206 if(!CheckMem(Data, sizeof(Uint16)))
1209 if(Threads_GetUID() != 0 && *(Uint16*)Data < 1024)
1212 conn->LocalPort = *(Uint16*)Data;
1213 LEAVE_RET('i', conn->LocalPort);
1215 case 5: // Get/Set remote port
1216 if(!Data) LEAVE_RET('i', conn->RemotePort);
1217 if(conn->State != TCP_ST_CLOSED) LEAVE_RET('i', -1);
1218 if(!CheckMem(Data, sizeof(Uint16))) LEAVE_RET('i', -1);
1219 conn->RemotePort = *(Uint16*)Data;
1220 LEAVE_RET('i', conn->RemotePort);
1222 case 6: // Set Remote IP
1223 if( conn->State != TCP_ST_CLOSED )
1225 if( conn->Interface->Type == 4 )
1227 if(!CheckMem(Data, sizeof(tIPv4))) LEAVE_RET('i', -1);
1228 conn->RemoteIP.v4 = *(tIPv4*)Data;
1230 else if( conn->Interface->Type == 6 )
1232 if(!CheckMem(Data, sizeof(tIPv6))) LEAVE_RET('i', -1);
1233 conn->RemoteIP.v6 = *(tIPv6*)Data;
1238 if(conn->LocalPort == 0xFFFF)
1239 conn->LocalPort = TCP_GetUnusedPort();
1240 if(conn->RemotePort == -1)
1244 tTime timeout_end = now() + conn->Interface->TimeoutDelay;
1246 TCP_StartConnection(conn);
1247 // TODO: Wait for connection to open
1248 while( conn->State == TCP_ST_SYN_SENT && timeout_end > now() ) {
1251 if( conn->State == TCP_ST_SYN_SENT )
1257 // Get recieve buffer length
1259 LEAVE_RET('i', conn->RecievedBuffer->Length);
1265 void TCP_Client_Close(tVFS_Node *Node)
1267 tTCPConnection *conn = Node->ImplPtr;
1270 ENTER("pNode", Node);
1272 if( conn->State == TCP_ST_CLOSE_WAIT || conn->State == TCP_ST_OPEN )
1274 packet.SourcePort = htons(conn->LocalPort);
1275 packet.DestPort = htons(conn->RemotePort);
1276 packet.DataOffset = (sizeof(tTCPHeader)/4)*16;
1277 packet.WindowSize = TCP_WINDOW_SIZE;
1279 packet.AcknowlegementNumber = 0;
1280 packet.SequenceNumber = htonl(conn->NextSequenceSend);
1281 packet.Flags = TCP_FLAG_FIN;
1283 TCP_SendPacket( conn, sizeof(tTCPHeader), &packet );
1286 switch( conn->State )
1288 case TCP_ST_CLOSE_WAIT:
1289 conn->State = TCP_ST_LAST_ACK;
1292 conn->State = TCP_ST_FIN_WAIT1;
1293 while( conn->State == TCP_ST_FIN_WAIT1 ) Threads_Yield();
1296 Log_Warning("TCP", "Unhandled connection state in TCP_Client_Close");
1306 * \brief Checks if a value is between two others (after taking into account wrapping)
1308 int WrapBetween(Uint32 Lower, Uint32 Value, Uint32 Higher, Uint32 MaxValue)
1310 if( MaxValue < 0xFFFFFFFF )
1312 Lower %= MaxValue + 1;
1313 Value %= MaxValue + 1;
1314 Higher %= MaxValue + 1;
1317 // Simple Case, no wrap ?
1318 // Lower Value Higher
1319 // | ... + ... + ... + ... |
1321 if( Lower < Higher ) {
1322 return Lower < Value && Value < Higher;
1324 // Higher has wrapped below lower
1327 // Higher Lower Value
1328 // | ... + ... + ... + ... |
1329 if( Value > Lower ) {
1334 // Value Higher Lower
1335 // | ... + ... + ... + ... |
1336 if( Value < Higher ) {