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 0x8000
22 #define TCP_DACK_THRESHOLD 4096
23 #define TCP_DACK_TIMEOUT 500
25 #define TCP_DEBUG 0 // Set to non-0 to enable TCP packet logging
28 void TCP_Initialise(void);
29 void TCP_StartConnection(tTCPConnection *Conn);
30 void TCP_SendPacket(tTCPConnection *Conn, tTCPHeader *Header, size_t DataLen, const void *Data);
31 void TCP_GetPacket(tInterface *Interface, void *Address, int Length, void *Buffer);
32 void TCP_INT_HandleConnectionPacket(tTCPConnection *Connection, tTCPHeader *Header, int Length);
33 int TCP_INT_AppendRecieved(tTCPConnection *Connection, const void *Data, size_t Length);
34 void TCP_INT_UpdateRecievedFromFuture(tTCPConnection *Connection);
35 void TCP_int_SendDelayedACK(void *ConnPtr);
36 void TCP_INT_SendACK(tTCPConnection *Connection, const char *Reason);
37 Uint16 TCP_GetUnusedPort();
38 int TCP_AllocatePort(Uint16 Port);
39 int TCP_DeallocatePort(Uint16 Port);
41 tVFS_Node *TCP_Server_Init(tInterface *Interface);
42 int TCP_Server_ReadDir(tVFS_Node *Node, int Pos, char Name[FILENAME_MAX]);
43 tVFS_Node *TCP_Server_FindDir(tVFS_Node *Node, const char *Name, Uint Flags);
44 int TCP_Server_IOCtl(tVFS_Node *Node, int ID, void *Data);
45 void TCP_Server_Close(tVFS_Node *Node);
47 tVFS_Node *TCP_Client_Init(tInterface *Interface);
48 size_t TCP_Client_Read(tVFS_Node *Node, off_t Offset, size_t Length, void *Buffer, Uint Flags);
49 size_t TCP_Client_Write(tVFS_Node *Node, off_t Offset, size_t Length, const void *Buffer, Uint Flags);
50 int TCP_Client_IOCtl(tVFS_Node *Node, int ID, void *Data);
51 void TCP_Client_Close(tVFS_Node *Node);
53 int WrapBetween(Uint32 Lower, Uint32 Value, Uint32 Higher, Uint32 MaxValue);
56 tSocketFile gTCP_ServerFile = {NULL, "tcps", TCP_Server_Init};
57 tSocketFile gTCP_ClientFile = {NULL, "tcpc", TCP_Client_Init};
58 tVFS_NodeType gTCP_ServerNodeType = {
59 .TypeName = "TCP Server",
60 .ReadDir = TCP_Server_ReadDir,
61 .FindDir = TCP_Server_FindDir,
62 .IOCtl = TCP_Server_IOCtl,
63 .Close = TCP_Server_Close
65 tVFS_NodeType gTCP_ClientNodeType = {
66 .TypeName = "TCP Client/Connection",
67 .Read = TCP_Client_Read,
68 .Write = TCP_Client_Write,
69 .IOCtl = TCP_Client_IOCtl,
70 .Close = TCP_Client_Close
74 int giTCP_NumHalfopen = 0;
75 tShortSpinlock glTCP_Listeners;
76 tTCPListener *gTCP_Listeners;
77 tShortSpinlock glTCP_OutbountCons;
78 tTCPConnection *gTCP_OutbountCons;
79 Uint32 gaTCP_PortBitmap[0x800];
80 int giTCP_NextOutPort = TCP_MIN_DYNPORT;
84 * \brief Initialise the TCP Layer
86 * Registers the client and server files and the GetPacket callback
88 void TCP_Initialise(void)
90 giTCP_NextOutPort += rand()%32;
91 IPStack_AddFile(&gTCP_ServerFile);
92 IPStack_AddFile(&gTCP_ClientFile);
93 IPv4_RegisterCallback(IP4PROT_TCP, TCP_GetPacket);
94 IPv6_RegisterCallback(IP4PROT_TCP, TCP_GetPacket);
98 * \brief Sends a packet from the specified connection, calculating the checksums
99 * \param Conn Connection
100 * \param Length Length of data
101 * \param Data Packet data (cast as a TCP Header)
103 void TCP_SendPacket( tTCPConnection *Conn, tTCPHeader *Header, size_t Length, const void *Data )
105 tIPStackBuffer *buffer;
107 int packlen = sizeof(*Header) + Length;
109 buffer = IPStack_Buffer_CreateBuffer(2 + IPV4_BUFFERS);
111 IPStack_Buffer_AppendSubBuffer(buffer, Length, 0, Data, NULL, NULL);
112 IPStack_Buffer_AppendSubBuffer(buffer, sizeof(*Header), 0, Header, NULL, NULL);
114 LOG("Sending %i+%i to %s:%i", sizeof(*Header), Length,
115 IPStack_PrintAddress(Conn->Interface->Type, &Conn->RemoteIP),
119 Header->Checksum = 0;
120 checksum[1] = htons( ~IPv4_Checksum(Header, sizeof(tTCPHeader)) );
121 checksum[2] = htons( ~IPv4_Checksum(Data, Length) );
123 // TODO: Fragment packet
125 switch( Conn->Interface->Type )
128 // Get IPv4 pseudo-header checksum
131 buf[0] = ((tIPv4*)Conn->Interface->Address)->L;
132 buf[1] = Conn->RemoteIP.v4.L;
133 buf[2] = (htons(packlen)<<16) | (6<<8) | 0;
134 checksum[0] = htons( ~IPv4_Checksum(buf, sizeof(buf)) ); // Partial checksum
136 // - Combine checksums
137 Header->Checksum = htons( IPv4_Checksum(checksum, sizeof(checksum)) );
138 IPv4_SendPacket(Conn->Interface, Conn->RemoteIP.v4, IP4PROT_TCP, 0, buffer);
142 // Append IPv6 Pseudo Header
145 memcpy(buf, Conn->Interface->Address, 16);
146 memcpy(&buf[4], &Conn->RemoteIP, 16);
147 buf[8] = htonl(packlen);
149 checksum[0] = htons( ~IPv4_Checksum(buf, sizeof(buf)) ); // Partial checksum
151 Header->Checksum = htons( IPv4_Checksum(checksum, sizeof(checksum)) ); // Combine the two
152 IPv6_SendPacket(Conn->Interface, Conn->RemoteIP.v6, IP4PROT_TCP, Length, Data);
158 * \brief Handles a packet from the IP Layer
159 * \param Interface Interface the packet arrived from
160 * \param Address Pointer to the addres structure
161 * \param Length Size of packet in bytes
162 * \param Buffer Packet data
164 void TCP_GetPacket(tInterface *Interface, void *Address, int Length, void *Buffer)
166 tTCPHeader *hdr = Buffer;
168 tTCPConnection *conn;
171 Log_Log("TCP", "TCP_GetPacket: <Local>:%i from [%s]:%i, Flags = %s%s%s%s%s%s%s%s",
172 ntohs(hdr->DestPort),
173 IPStack_PrintAddress(Interface->Type, Address),
174 ntohs(hdr->SourcePort),
175 (hdr->Flags & TCP_FLAG_CWR) ? "CWR " : "",
176 (hdr->Flags & TCP_FLAG_ECE) ? "ECE " : "",
177 (hdr->Flags & TCP_FLAG_URG) ? "URG " : "",
178 (hdr->Flags & TCP_FLAG_ACK) ? "ACK " : "",
179 (hdr->Flags & TCP_FLAG_PSH) ? "PSH " : "",
180 (hdr->Flags & TCP_FLAG_RST) ? "RST " : "",
181 (hdr->Flags & TCP_FLAG_SYN) ? "SYN " : "",
182 (hdr->Flags & TCP_FLAG_FIN) ? "FIN " : ""
186 if( Length > (hdr->DataOffset >> 4)*4 )
188 LOG("SequenceNumber = 0x%x", ntohl(hdr->SequenceNumber));
191 "TCP_GetPacket: Packet Data = ",
192 (Uint8*)hdr + (hdr->DataOffset >> 4)*4,
193 Length - (hdr->DataOffset >> 4)*4
199 for( srv = gTCP_Listeners; srv; srv = srv->Next )
201 // Check if the server is active
202 if(srv->Port == 0) continue;
203 // Check the interface
204 if(srv->Interface && srv->Interface != Interface) continue;
205 // Check the destination port
206 if(srv->Port != htons(hdr->DestPort)) continue;
208 Log_Log("TCP", "TCP_GetPacket: Matches server %p", srv);
209 // Is this in an established connection?
210 for( conn = srv->Connections; conn; conn = conn->Next )
212 // Check that it is coming in on the same interface
213 if(conn->Interface != Interface) continue;
216 Log_Log("TCP", "TCP_GetPacket: conn->RemotePort(%i) == hdr->SourcePort(%i)",
217 conn->RemotePort, ntohs(hdr->SourcePort));
218 if(conn->RemotePort != ntohs(hdr->SourcePort)) continue;
221 Log_Debug("TCP", "TCP_GetPacket: conn->RemoteIP(%s)",
222 IPStack_PrintAddress(conn->Interface->Type, &conn->RemoteIP));
223 Log_Debug("TCP", " == Address(%s)",
224 IPStack_PrintAddress(conn->Interface->Type, Address));
225 if( IPStack_CompareAddress(conn->Interface->Type, &conn->RemoteIP, Address, -1) == 0 )
228 Log_Log("TCP", "TCP_GetPacket: Matches connection %p", conn);
229 // We have a response!
230 TCP_INT_HandleConnectionPacket(conn, hdr, Length);
235 Log_Log("TCP", "TCP_GetPacket: Opening Connection");
236 // Open a new connection (well, check that it's a SYN)
237 if(hdr->Flags != TCP_FLAG_SYN) {
238 Log_Log("TCP", "TCP_GetPacket: Packet is not a SYN");
242 // TODO: Check for halfopen max
244 conn = calloc(1, sizeof(tTCPConnection));
245 conn->State = TCP_ST_SYN_RCVD;
246 conn->LocalPort = srv->Port;
247 conn->RemotePort = ntohs(hdr->SourcePort);
248 conn->Interface = Interface;
250 switch(Interface->Type)
252 case 4: conn->RemoteIP.v4 = *(tIPv4*)Address; break;
253 case 6: conn->RemoteIP.v6 = *(tIPv6*)Address; break;
256 conn->RecievedBuffer = RingBuffer_Create( TCP_RECIEVE_BUFFER_SIZE );
258 conn->NextSequenceRcv = ntohl( hdr->SequenceNumber ) + 1;
259 conn->NextSequenceSend = rand();
262 conn->Node.NumACLs = 1;
263 conn->Node.ACLs = &gVFS_ACL_EveryoneRW;
264 conn->Node.ImplPtr = conn;
265 conn->Node.ImplInt = srv->NextID ++;
266 conn->Node.Type = &gTCP_ClientNodeType; // TODO: Special type for the server end?
268 // Hmm... Theoretically, this lock will never have to wait,
269 // as the interface is locked to the watching thread, and this
270 // runs in the watching thread. But, it's a good idea to have
272 // Oh, wait, there is a case where a wildcard can be used
273 // (srv->Interface == NULL) so having the lock is a good idea
274 SHORTLOCK(&srv->lConnections);
275 if( !srv->Connections )
276 srv->Connections = conn;
278 srv->ConnectionsTail->Next = conn;
279 srv->ConnectionsTail = conn;
280 if(!srv->NewConnections)
281 srv->NewConnections = conn;
282 VFS_MarkAvaliable( &srv->Node, 1 );
283 SHORTREL(&srv->lConnections);
284 Semaphore_Signal(&srv->WaitingConnections, 1);
287 hdr->Flags |= TCP_FLAG_ACK;
288 hdr->AcknowlegementNumber = htonl(conn->NextSequenceRcv);
289 hdr->SequenceNumber = htonl(conn->NextSequenceSend);
290 hdr->DestPort = hdr->SourcePort;
291 hdr->SourcePort = htons(srv->Port);
292 hdr->DataOffset = (sizeof(tTCPHeader)/4) << 4;
293 TCP_SendPacket( conn, hdr, 0, NULL );
294 conn->NextSequenceSend ++;
298 // Check Open Connections
300 for( conn = gTCP_OutbountCons; conn; conn = conn->Next )
302 // Check that it is coming in on the same interface
303 if(conn->Interface != Interface) continue;
306 if(conn->RemotePort != ntohs(hdr->SourcePort)) continue;
309 if(conn->Interface->Type == 6 && !IP6_EQU(conn->RemoteIP.v6, *(tIPv6*)Address))
311 if(conn->Interface->Type == 4 && !IP4_EQU(conn->RemoteIP.v4, *(tIPv4*)Address))
314 TCP_INT_HandleConnectionPacket(conn, hdr, Length);
319 Log_Log("TCP", "TCP_GetPacket: No Match");
323 * \brief Handles a packet sent to a specific connection
324 * \param Connection TCP Connection pointer
325 * \param Header TCP Packet pointer
326 * \param Length Length of the packet
328 void TCP_INT_HandleConnectionPacket(tTCPConnection *Connection, tTCPHeader *Header, int Length)
333 // Silently drop once finished
334 // TODO: Check if this needs to be here
335 if( Connection->State == TCP_ST_FINISHED ) {
336 Log_Log("TCP", "Packet ignored - connection finnished");
340 // Syncronise sequence values
341 if(Header->Flags & TCP_FLAG_SYN) {
342 // TODO: What if the packet also has data?
343 if( Connection->LastACKSequence != Connection->NextSequenceRcv )
344 TCP_INT_SendACK(Connection, "SYN");
345 Connection->NextSequenceRcv = ntohl(Header->SequenceNumber);
346 Connection->LastACKSequence = Connection->NextSequenceRcv;
349 // Ackowledge a sent packet
350 if(Header->Flags & TCP_FLAG_ACK) {
351 // TODO: Process an ACKed Packet
352 LOG("Conn %p, Sent packet 0x%x ACKed", Connection, Header->AcknowlegementNumber);
355 // Get length of data
356 dataLen = Length - (Header->DataOffset>>4)*4;
357 LOG("dataLen = %i", dataLen);
359 Log_Debug("TCP", "State %i, dataLen = %x", Connection->State, dataLen);
365 switch( Connection->State )
367 // Pre-init connection?
369 Log_Log("TCP", "Packets to a closed connection?!");
372 // --- Init States ---
373 // SYN sent, expecting SYN-ACK Connection Opening
374 case TCP_ST_SYN_SENT:
375 if( Header->Flags & TCP_FLAG_SYN )
377 Connection->NextSequenceRcv ++;
379 if( Header->Flags & TCP_FLAG_ACK )
381 Log_Log("TCP", "ACKing SYN-ACK");
382 Connection->State = TCP_ST_OPEN;
383 VFS_MarkFull(&Connection->Node, 0);
387 Log_Log("TCP", "ACKing SYN");
388 Connection->State = TCP_ST_SYN_RCVD;
390 Header->DestPort = Header->SourcePort;
391 Header->SourcePort = htons(Connection->LocalPort);
392 Header->AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
393 Header->SequenceNumber = htonl(Connection->NextSequenceSend);
394 Header->WindowSize = htons(TCP_WINDOW_SIZE);
395 Header->Flags = TCP_FLAG_ACK;
396 Header->DataOffset = (sizeof(tTCPHeader)/4) << 4;
397 TCP_SendPacket( Connection, Header, 0, NULL );
401 // SYN-ACK sent, expecting ACK
402 case TCP_ST_SYN_RCVD:
403 if( Header->Flags & TCP_FLAG_ACK )
405 // TODO: Handle max half-open limit
406 Log_Log("TCP", "Connection fully opened");
407 Connection->State = TCP_ST_OPEN;
408 VFS_MarkFull(&Connection->Node, 0);
412 // --- Established State ---
414 // - Handle State changes
416 if( Header->Flags & TCP_FLAG_FIN ) {
417 Log_Log("TCP", "Conn %p closed, recieved FIN", Connection);
418 VFS_MarkError(&Connection->Node, 1);
419 Connection->State = TCP_ST_CLOSE_WAIT;
420 // Header->Flags &= ~TCP_FLAG_FIN;
421 // CLOSE WAIT requires the client to close (or does it?)
427 // Check for an empty packet
429 if( Header->Flags == TCP_FLAG_ACK )
431 Log_Log("TCP", "ACK only packet");
434 Connection->NextSequenceRcv ++; // TODO: Is this right? (empty packet counts as one byte)
435 Log_Log("TCP", "Empty Packet, inc and ACK the current sequence number");
436 TCP_INT_SendACK(Connection, "Empty");
438 Header->DestPort = Header->SourcePort;
439 Header->SourcePort = htons(Connection->LocalPort);
440 Header->AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
441 Header->SequenceNumber = htonl(Connection->NextSequenceSend);
442 Header->Flags |= TCP_FLAG_ACK;
443 TCP_SendPacket( Connection, Header, 0, NULL );
453 sequence_num = ntohl(Header->SequenceNumber);
455 LOG("0x%08x <= 0x%08x < 0x%08x",
456 Connection->NextSequenceRcv,
457 ntohl(Header->SequenceNumber),
458 Connection->NextSequenceRcv + TCP_WINDOW_SIZE
461 // Is this packet the next expected packet?
462 if( sequence_num == Connection->NextSequenceRcv )
465 // Ooh, Goodie! Add it to the recieved list
466 rv = TCP_INT_AppendRecieved(Connection,
467 (Uint8*)Header + (Header->DataOffset>>4)*4,
471 Log_Notice("TCP", "TCP_INT_AppendRecieved rv %i", rv);
474 LOG("0x%08x += %i", Connection->NextSequenceRcv, dataLen);
475 Connection->NextSequenceRcv += dataLen;
477 // TODO: This should be moved out of the watcher thread,
478 // so that a single lost packet on one connection doesn't cause
479 // all connections on the interface to lag.
480 // - Meh, no real issue, as the cache shouldn't be that large
481 TCP_INT_UpdateRecievedFromFuture(Connection);
484 // - Only send an ACK if we've had a burst
485 if( Connection->NextSequenceRcv > (Uint32)(TCP_DACK_THRESHOLD + Connection->LastACKSequence) )
487 TCP_INT_SendACK(Connection, "DACK Burst");
488 // - Extend TCP deferred ACK timer
489 Time_RemoveTimer(Connection->DeferredACKTimer);
491 // - Schedule the deferred ACK timer (if already scheduled, this is a NOP)
492 Time_ScheduleTimer(Connection->DeferredACKTimer, TCP_DACK_TIMEOUT);
494 TCP_INT_SendACK(Connection, "RX");
497 // Check if the packet is in window
498 else if( WrapBetween(Connection->NextSequenceRcv, sequence_num,
499 Connection->NextSequenceRcv+TCP_WINDOW_SIZE, 0xFFFFFFFF) )
501 Uint8 *dataptr = (Uint8*)Header + (Header->DataOffset>>4)*4;
502 #if CACHE_FUTURE_PACKETS_IN_BYTES
506 index = sequence_num % TCP_WINDOW_SIZE;
507 for( i = 0; i < dataLen; i ++ )
509 Connection->FuturePacketValidBytes[index/8] |= 1 << (index%8);
510 Connection->FuturePacketData[index] = dataptr[i];
511 // Do a wrap increment
513 if(index == TCP_WINDOW_SIZE) index = 0;
516 tTCPStoredPacket *pkt, *tmp, *prev = NULL;
518 // Allocate and fill cached packet
519 pkt = malloc( sizeof(tTCPStoredPacket) + dataLen );
521 pkt->Sequence = ntohl(Header->SequenceNumber);
522 pkt->Length = dataLen;
523 memcpy(pkt->Data, dataptr, dataLen);
525 Log_Log("TCP", "We missed a packet, caching",
526 pkt->Sequence, Connection->NextSequenceRcv);
528 // No? Well, let's cache it and look at it later
529 SHORTLOCK( &Connection->lFuturePackets );
530 for(tmp = Connection->FuturePackets;
532 prev = tmp, tmp = tmp->Next)
534 if(tmp->Sequence >= pkt->Sequence) break;
537 // Add if before first, or sequences don't match
538 if( !tmp || tmp->Sequence != pkt->Sequence )
543 Connection->FuturePackets = pkt;
547 else if(pkt->Length > tmp->Length)
551 pkt->Next = tmp->Next;
556 free(pkt); // TODO: Find some way to remove this
558 SHORTREL( &Connection->lFuturePackets );
561 // Badly out of sequence packet
564 Log_Log("TCP", "Fully out of sequence packet (0x%08x not between 0x%08x and 0x%08x), dropped",
565 sequence_num, Connection->NextSequenceRcv, Connection->NextSequenceRcv+TCP_WINDOW_SIZE);
566 // Spec says we should send an empty ACK with the current state
567 TCP_INT_SendACK(Connection, "Bad Seq");
571 // --- Remote close states
572 case TCP_ST_CLOSE_WAIT:
574 // Ignore everything, CLOSE_WAIT is terminated by the client
575 Log_Debug("TCP", "CLOSE WAIT - Ignoring packets");
579 // LAST-ACK - Waiting for the ACK of FIN (from CLOSE WAIT)
580 case TCP_ST_LAST_ACK:
581 if( Header->Flags & TCP_FLAG_ACK )
583 Connection->State = TCP_ST_FINISHED; // Connection completed
584 Log_Log("TCP", "LAST-ACK to CLOSED - Connection remote closed");
585 // TODO: Destrory the TCB
589 // --- Local close States
590 case TCP_ST_FIN_WAIT1:
591 if( Header->Flags & TCP_FLAG_FIN )
593 Connection->State = TCP_ST_CLOSING;
594 Log_Debug("TCP", "Conn %p closed, sent FIN and recieved FIN", Connection);
595 VFS_MarkError(&Connection->Node, 1);
598 Header->DestPort = Header->SourcePort;
599 Header->SourcePort = htons(Connection->LocalPort);
600 Header->AcknowlegementNumber = Header->SequenceNumber;
601 Header->SequenceNumber = htonl(Connection->NextSequenceSend);
602 Header->WindowSize = htons(TCP_WINDOW_SIZE);
603 Header->Flags = TCP_FLAG_ACK;
604 TCP_SendPacket( Connection, Header, 0, NULL );
608 // TODO: Make sure that the packet is actually ACKing the FIN
609 if( Header->Flags & TCP_FLAG_ACK )
611 Connection->State = TCP_ST_FIN_WAIT2;
612 Log_Debug("TCP", "Conn %p closed, sent FIN ACKed", Connection);
613 VFS_MarkError(&Connection->Node, 1);
618 case TCP_ST_FIN_WAIT2:
619 if( Header->Flags & TCP_FLAG_FIN )
621 Connection->State = TCP_ST_TIME_WAIT;
622 Log_Debug("TCP", "FIN sent and recieved, ACKing and going into TIME WAIT %p FINWAIT-2 -> TIME WAIT", Connection);
624 Header->DestPort = Header->SourcePort;
625 Header->SourcePort = htons(Connection->LocalPort);
626 Header->AcknowlegementNumber = Header->SequenceNumber;
627 Header->SequenceNumber = htonl(Connection->NextSequenceSend);
628 Header->WindowSize = htons(TCP_WINDOW_SIZE);
629 Header->Flags = TCP_FLAG_ACK;
630 TCP_SendPacket( Connection, Header, 0, NULL );
635 // TODO: Make sure that the packet is actually ACKing the FIN
636 if( Header->Flags & TCP_FLAG_ACK )
638 Connection->State = TCP_ST_TIME_WAIT;
639 Log_Debug("TCP", "Conn %p CLOSING -> TIME WAIT", Connection);
640 VFS_MarkError(&Connection->Node, 1);
645 // --- Closed (or near closed) states) ---
646 case TCP_ST_TIME_WAIT:
647 Log_Log("TCP", "Packets on Time-Wait, ignored");
650 case TCP_ST_FINISHED:
651 Log_Log("TCP", "Packets when CLOSED, ignoring");
655 // Log_Warning("TCP", "Unhandled TCP state %i", Connection->State);
662 * \brief Appends a packet to the recieved list
663 * \param Connection Connection structure
664 * \param Data Packet contents
665 * \param Length Length of \a Data
667 int TCP_INT_AppendRecieved(tTCPConnection *Connection, const void *Data, size_t Length)
669 Mutex_Acquire( &Connection->lRecievedPackets );
671 if(Connection->RecievedBuffer->Length + Length > Connection->RecievedBuffer->Space )
673 VFS_MarkAvaliable(&Connection->Node, 1);
674 Log_Error("TCP", "Buffer filled, packet dropped (:%i) - %i + %i > %i",
675 Connection->LocalPort, Connection->RecievedBuffer->Length, Length,
676 Connection->RecievedBuffer->Space
678 Mutex_Release( &Connection->lRecievedPackets );
682 RingBuffer_Write( Connection->RecievedBuffer, Data, Length );
684 VFS_MarkAvaliable(&Connection->Node, 1);
686 Mutex_Release( &Connection->lRecievedPackets );
691 * \brief Updates the connections recieved list from the future list
692 * \param Connection Connection structure
694 * Updates the recieved packets list with packets from the future (out
695 * of order) packets list that are now able to be added in direct
698 void TCP_INT_UpdateRecievedFromFuture(tTCPConnection *Connection)
700 #if CACHE_FUTURE_PACKETS_IN_BYTES
704 // Calculate length of contiguous bytes
705 length = Connection->HighestSequenceRcvd - Connection->NextSequenceRcv;
706 index = Connection->NextSequenceRcv % TCP_WINDOW_SIZE;
707 for( i = 0; i < length; i ++ )
709 if( Connection->FuturePacketValidBytes[i / 8] == 0xFF ) {
713 else if( !(Connection->FuturePacketValidBytes[i / 8] & (1 << (i%8))) )
717 if(index > TCP_WINDOW_SIZE)
718 index -= TCP_WINDOW_SIZE;
722 index = Connection->NextSequenceRcv % TCP_WINDOW_SIZE;
724 // Write data to to the ring buffer
725 if( TCP_WINDOW_SIZE - index > length )
728 RingBuffer_Write( Connection->RecievedBuffer, Connection->FuturePacketData + index, length );
732 int endLen = TCP_WINDOW_SIZE - index;
734 RingBuffer_Write( Connection->RecievedBuffer, Connection->FuturePacketData + index, endLen );
735 RingBuffer_Write( Connection->RecievedBuffer, Connection->FuturePacketData, endLen - length );
738 // Mark (now saved) bytes as invalid
740 while(index % 8 && length)
742 Connection->FuturePacketData[index] = 0;
743 Connection->FuturePacketData[index/8] &= ~(1 << (index%8));
745 if(index > TCP_WINDOW_SIZE)
746 index -= TCP_WINDOW_SIZE;
751 Connection->FuturePacketData[index] = 0;
752 Connection->FuturePacketValidBytes[index/8] = 0;
755 if(index > TCP_WINDOW_SIZE)
756 index -= TCP_WINDOW_SIZE;
760 Connection->FuturePacketData[index] = 0;
761 Connection->FuturePacketData[index/8] &= ~(1 << (index%8));
763 if(index > TCP_WINDOW_SIZE)
764 index -= TCP_WINDOW_SIZE;
769 tTCPStoredPacket *pkt;
772 SHORTLOCK( &Connection->lFuturePackets );
774 // Clear out duplicates from cache
775 // - If a packet has just been recieved, and it is expected, then
776 // (since NextSequenceRcv = rcvd->Sequence + rcvd->Length) all
777 // packets in cache that are smaller than the next expected
779 pkt = Connection->FuturePackets;
780 while(pkt && pkt->Sequence < Connection->NextSequenceRcv)
782 tTCPStoredPacket *next = pkt->Next;
787 // If there's no packets left in cache, stop looking
788 if(!pkt || pkt->Sequence > Connection->NextSequenceRcv) {
789 SHORTREL( &Connection->lFuturePackets );
793 // Delete packet from future list
794 Connection->FuturePackets = pkt->Next;
797 SHORTREL( &Connection->lFuturePackets );
799 // Looks like we found one
800 TCP_INT_AppendRecieved(Connection, pkt);
801 Connection->NextSequenceRcv += pkt->Length;
807 void TCP_int_SendDelayedACK(void *ConnPtr)
809 TCP_INT_SendACK(ConnPtr, "DACK Timeout");
812 void TCP_INT_SendACK(tTCPConnection *Connection, const char *Reason)
816 hdr.DataOffset = (sizeof(tTCPHeader)/4) << 4;
817 hdr.DestPort = htons(Connection->RemotePort);
818 hdr.SourcePort = htons(Connection->LocalPort);
819 hdr.AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
820 hdr.SequenceNumber = htonl(Connection->NextSequenceSend);
821 hdr.WindowSize = htons(TCP_WINDOW_SIZE);
822 hdr.Flags = TCP_FLAG_ACK; // TODO: Determine if SYN is wanted too
823 hdr.Checksum = 0; // TODO: Checksum
824 hdr.UrgentPointer = 0;
825 Log_Debug("TCP", "Sending ACK for 0x%08x (%s)", Connection->NextSequenceRcv, Reason);
826 TCP_SendPacket( Connection, &hdr, 0, NULL );
827 //Connection->NextSequenceSend ++;
828 Connection->LastACKSequence = Connection->NextSequenceRcv;
832 * \fn Uint16 TCP_GetUnusedPort()
833 * \brief Gets an unused port and allocates it
835 Uint16 TCP_GetUnusedPort()
839 // Get Next outbound port
840 ret = giTCP_NextOutPort++;
841 while( gaTCP_PortBitmap[ret/32] & (1UL << (ret%32)) )
845 if(giTCP_NextOutPort == 0x10000) {
846 ret = giTCP_NextOutPort = TCP_MIN_DYNPORT;
850 // Mark the new port as used
851 gaTCP_PortBitmap[ret/32] |= 1 << (ret%32);
857 * \fn int TCP_AllocatePort(Uint16 Port)
858 * \brief Marks a port as used
860 int TCP_AllocatePort(Uint16 Port)
862 // Check if the port has already been allocated
863 if( gaTCP_PortBitmap[Port/32] & (1 << (Port%32)) )
867 gaTCP_PortBitmap[Port/32] |= 1 << (Port%32);
873 * \fn int TCP_DeallocatePort(Uint16 Port)
874 * \brief Marks a port as unused
876 int TCP_DeallocatePort(Uint16 Port)
878 // Check if the port has already been allocated
879 if( !(gaTCP_PortBitmap[Port/32] & (1 << (Port%32))) )
883 gaTCP_PortBitmap[Port/32] &= ~(1 << (Port%32));
889 tVFS_Node *TCP_Server_Init(tInterface *Interface)
893 srv = calloc( 1, sizeof(tTCPListener) );
896 Log_Warning("TCP", "malloc failed for listener (%i) bytes", sizeof(tTCPListener));
900 srv->Interface = Interface;
903 srv->Connections = NULL;
904 srv->ConnectionsTail = NULL;
905 srv->NewConnections = NULL;
907 srv->Node.Flags = VFS_FFLAG_DIRECTORY;
909 srv->Node.ImplPtr = srv;
910 srv->Node.NumACLs = 1;
911 srv->Node.ACLs = &gVFS_ACL_EveryoneRW;
912 srv->Node.Type = &gTCP_ServerNodeType;
914 SHORTLOCK(&glTCP_Listeners);
915 srv->Next = gTCP_Listeners;
916 gTCP_Listeners = srv;
917 SHORTREL(&glTCP_Listeners);
923 * \brief Wait for a new connection and return the connection ID
924 * \note Blocks until a new connection is made
925 * \param Node Server node
926 * \param Pos Position (ignored)
928 int TCP_Server_ReadDir(tVFS_Node *Node, int Pos, char Dest[FILENAME_MAX])
930 tTCPListener *srv = Node->ImplPtr;
931 tTCPConnection *conn;
933 ENTER("pNode iPos", Node, Pos);
935 Log_Log("TCP", "Thread %i waiting for a connection", Threads_GetTID());
936 Semaphore_Wait( &srv->WaitingConnections, 1 );
938 SHORTLOCK(&srv->lConnections);
939 // Increment the new list (the current connection is still on the
941 conn = srv->NewConnections;
942 srv->NewConnections = conn->Next;
944 if( srv->NewConnections == NULL )
945 VFS_MarkAvaliable( Node, 0 );
947 SHORTREL( &srv->lConnections );
949 LOG("conn = %p", conn);
950 LOG("srv->Connections = %p", srv->Connections);
951 LOG("srv->NewConnections = %p", srv->NewConnections);
952 LOG("srv->ConnectionsTail = %p", srv->ConnectionsTail);
954 itoa(Dest, conn->Node.ImplInt, 16, 8, '0');
955 Log_Log("TCP", "Thread %i got connection '%s'", Threads_GetTID(), Dest);
961 * \brief Gets a client connection node
962 * \param Node Server node
963 * \param Name Hexadecimal ID of the node
965 tVFS_Node *TCP_Server_FindDir(tVFS_Node *Node, const char *Name, Uint Flags)
967 tTCPConnection *conn;
968 tTCPListener *srv = Node->ImplPtr;
972 ENTER("pNode sName", Node, Name);
974 // Check for a non-empty name
978 itoa(tmp, id, 16, 8, '0');
979 if(strcmp(tmp, Name) != 0) {
980 LOG("'%s' != '%s' (%08x)", Name, tmp, id);
985 Log_Debug("TCP", "srv->Connections = %p", srv->Connections);
986 Log_Debug("TCP", "srv->NewConnections = %p", srv->NewConnections);
987 Log_Debug("TCP", "srv->ConnectionsTail = %p", srv->ConnectionsTail);
990 SHORTLOCK( &srv->lConnections );
991 for(conn = srv->Connections;
995 LOG("conn->Node.ImplInt = %i", conn->Node.ImplInt);
996 if(conn->Node.ImplInt == id) break;
998 SHORTREL( &srv->lConnections );
1000 // If not found, ret NULL
1002 LOG("Connection %i not found", id);
1007 // Empty Name - Check for a new connection and if it's there, open it
1010 SHORTLOCK( &srv->lConnections );
1011 conn = srv->NewConnections;
1013 srv->NewConnections = conn->Next;
1014 VFS_MarkAvaliable( Node, srv->NewConnections != NULL );
1015 SHORTREL( &srv->lConnections );
1017 LOG("No new connections");
1024 LEAVE('p', &conn->Node);
1029 * \brief Handle IOCtl calls
1031 int TCP_Server_IOCtl(tVFS_Node *Node, int ID, void *Data)
1033 tTCPListener *srv = Node->ImplPtr;
1037 case 4: // Get/Set Port
1038 if(!Data) // Get Port
1041 if(srv->Port) // Wait, you can't CHANGE the port
1044 if(!CheckMem(Data, sizeof(Uint16))) // Sanity check
1047 // Permissions check
1048 if(Threads_GetUID() != 0
1049 && *(Uint16*)Data != 0
1050 && *(Uint16*)Data < 1024)
1053 // TODO: Check if a port is in use
1056 srv->Port = *(Uint16*)Data;
1057 if(srv->Port == 0) // Allocate a random port
1058 srv->Port = TCP_GetUnusedPort();
1059 else // Else, mark this as used
1060 TCP_AllocatePort(srv->Port);
1062 Log_Log("TCP", "Server %p listening on port %i", srv, srv->Port);
1069 void TCP_Server_Close(tVFS_Node *Node)
1071 free(Node->ImplPtr);
1076 * \brief Create a client node
1078 tVFS_Node *TCP_Client_Init(tInterface *Interface)
1080 tTCPConnection *conn = calloc( sizeof(tTCPConnection) + TCP_WINDOW_SIZE + TCP_WINDOW_SIZE/8, 1 );
1082 conn->State = TCP_ST_CLOSED;
1083 conn->Interface = Interface;
1084 conn->LocalPort = -1;
1085 conn->RemotePort = -1;
1087 conn->Node.ImplPtr = conn;
1088 conn->Node.NumACLs = 1;
1089 conn->Node.ACLs = &gVFS_ACL_EveryoneRW;
1090 conn->Node.Type = &gTCP_ClientNodeType;
1091 conn->Node.BufferFull = 1; // Cleared when connection opens
1093 conn->RecievedBuffer = RingBuffer_Create( TCP_RECIEVE_BUFFER_SIZE );
1095 conn->SentBuffer = RingBuffer_Create( TCP_SEND_BUFFER_SIZE );
1096 Semaphore_Init(conn->SentBufferSpace, 0, TCP_SEND_BUFFER_SIZE, "TCP SentBuffer", conn->Name);
1099 #if CACHE_FUTURE_PACKETS_IN_BYTES
1100 // Future recieved data (ahead of the expected sequence number)
1101 conn->FuturePacketData = (Uint8*)conn + sizeof(tTCPConnection);
1102 conn->FuturePacketValidBytes = conn->FuturePacketData + TCP_WINDOW_SIZE;
1105 conn->DeferredACKTimer = Time_AllocateTimer( TCP_int_SendDelayedACK, conn);
1107 SHORTLOCK(&glTCP_OutbountCons);
1108 conn->Next = gTCP_OutbountCons;
1109 gTCP_OutbountCons = conn;
1110 SHORTREL(&glTCP_OutbountCons);
1116 * \brief Wait for a packet and return it
1117 * \note If \a Length is smaller than the size of the packet, the rest
1118 * of the packet's data will be discarded.
1120 size_t TCP_Client_Read(tVFS_Node *Node, off_t Offset, size_t Length, void *Buffer, Uint Flags)
1122 tTCPConnection *conn = Node->ImplPtr;
1125 ENTER("pNode XOffset XLength pBuffer", Node, Offset, Length, Buffer);
1126 LOG("conn = %p {State:%i}", conn, conn->State);
1128 // If the connection has been closed (state > ST_OPEN) then clear
1129 // any stale data in the buffer (until it is empty (until it is empty))
1130 if( conn->State > TCP_ST_OPEN )
1132 Mutex_Acquire( &conn->lRecievedPackets );
1133 len = RingBuffer_Read( Buffer, conn->RecievedBuffer, Length );
1134 Mutex_Release( &conn->lRecievedPackets );
1137 VFS_MarkAvaliable(Node, 0);
1149 tTime *timeout = NULL;
1150 tTime timeout_zero = 0;
1151 if( Flags & VFS_IOFLAG_NOBLOCK )
1152 timeout = &timeout_zero;
1153 if( !VFS_SelectNode(Node, VFS_SELECT_READ|VFS_SELECT_ERROR, timeout, "TCP_Client_Read") ) {
1154 errno = EWOULDBLOCK;
1160 // Lock list and read as much as possible (up to `Length`)
1161 Mutex_Acquire( &conn->lRecievedPackets );
1162 len = RingBuffer_Read( Buffer, conn->RecievedBuffer, Length );
1164 if( len == 0 || conn->RecievedBuffer->Length == 0 ) {
1165 LOG("Marking as none avaliable (len = %i)", len);
1166 VFS_MarkAvaliable(Node, 0);
1169 // Release the lock (we don't need it any more)
1170 Mutex_Release( &conn->lRecievedPackets );
1177 * \brief Send a data packet on a connection
1179 void TCP_INT_SendDataPacket(tTCPConnection *Connection, size_t Length, const void *Data)
1181 char buf[sizeof(tTCPHeader)+Length];
1182 tTCPHeader *packet = (void*)buf;
1184 packet->SourcePort = htons(Connection->LocalPort);
1185 packet->DestPort = htons(Connection->RemotePort);
1186 packet->DataOffset = (sizeof(tTCPHeader)/4)*16;
1187 packet->WindowSize = htons(TCP_WINDOW_SIZE);
1189 packet->AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
1190 packet->SequenceNumber = htonl(Connection->NextSequenceSend);
1191 packet->Flags = TCP_FLAG_PSH|TCP_FLAG_ACK; // Hey, ACK if you can!
1193 memcpy(packet->Options, Data, Length);
1195 Log_Debug("TCP", "Send sequence 0x%08x", Connection->NextSequenceSend);
1196 #if HEXDUMP_OUTGOING
1197 Debug_HexDump("TCP_INT_SendDataPacket: Data = ", Data, Length);
1200 TCP_SendPacket( Connection, packet, Length, Data );
1202 Connection->NextSequenceSend += Length;
1206 * \brief Send some bytes on a connection
1208 size_t TCP_Client_Write(tVFS_Node *Node, off_t Offset, size_t Length, const void *Buffer, Uint Flags)
1210 tTCPConnection *conn = Node->ImplPtr;
1211 size_t rem = Length;
1213 ENTER("pNode XOffset XLength pBuffer", Node, Offset, Length, Buffer);
1216 // Debug_HexDump("TCP_Client_Write: Buffer = ",
1220 // Don't allow a write to a closed connection
1221 if( conn->State > TCP_ST_OPEN ) {
1222 VFS_MarkError(Node, 1);
1230 tTime *timeout = NULL;
1231 tTime timeout_zero = 0;
1232 if( Flags & VFS_IOFLAG_NOBLOCK )
1233 timeout = &timeout_zero;
1234 if( !VFS_SelectNode(Node, VFS_SELECT_WRITE|VFS_SELECT_ERROR, timeout, "TCP_Client_Write") ) {
1235 errno = EWOULDBLOCK;
1243 int len = (rem < TCP_MAX_PACKET_SIZE) ? rem : TCP_MAX_PACKET_SIZE;
1246 // Wait for space in the buffer
1247 Semaphore_Signal( &Connection->SentBufferSpace, len );
1249 // Save data to buffer (and update the length read by the ammount written)
1250 len = RingBuffer_Write( &Connection->SentBuffer, Buffer, len);
1254 TCP_INT_SendDataPacket(conn, len, Buffer);
1265 * \brief Open a connection to another host using TCP
1266 * \param Conn Connection structure
1268 void TCP_StartConnection(tTCPConnection *Conn)
1270 tTCPHeader hdr = {0};
1272 Conn->State = TCP_ST_SYN_SENT;
1274 hdr.SourcePort = htons(Conn->LocalPort);
1275 hdr.DestPort = htons(Conn->RemotePort);
1276 Conn->NextSequenceSend = rand();
1277 hdr.SequenceNumber = htonl(Conn->NextSequenceSend);
1278 hdr.DataOffset = (sizeof(tTCPHeader)/4) << 4;
1279 hdr.Flags = TCP_FLAG_SYN;
1280 hdr.WindowSize = htons(TCP_WINDOW_SIZE); // Max
1281 hdr.Checksum = 0; // TODO
1283 TCP_SendPacket( Conn, &hdr, 0, NULL );
1285 Conn->NextSequenceSend ++;
1286 Conn->State = TCP_ST_SYN_SENT;
1292 * \brief Control a client socket
1294 int TCP_Client_IOCtl(tVFS_Node *Node, int ID, void *Data)
1296 tTCPConnection *conn = Node->ImplPtr;
1298 ENTER("pNode iID pData", Node, ID, Data);
1302 case 4: // Get/Set local port
1304 LEAVE_RET('i', conn->LocalPort);
1305 if(conn->State != TCP_ST_CLOSED)
1307 if(!CheckMem(Data, sizeof(Uint16)))
1310 if(Threads_GetUID() != 0 && *(Uint16*)Data < 1024)
1313 conn->LocalPort = *(Uint16*)Data;
1314 LEAVE_RET('i', conn->LocalPort);
1316 case 5: // Get/Set remote port
1317 if(!Data) LEAVE_RET('i', conn->RemotePort);
1318 if(conn->State != TCP_ST_CLOSED) LEAVE_RET('i', -1);
1319 if(!CheckMem(Data, sizeof(Uint16))) LEAVE_RET('i', -1);
1320 conn->RemotePort = *(Uint16*)Data;
1321 LEAVE_RET('i', conn->RemotePort);
1323 case 6: // Set Remote IP
1324 if( conn->State != TCP_ST_CLOSED )
1326 if( conn->Interface->Type == 4 )
1328 if(!CheckMem(Data, sizeof(tIPv4))) LEAVE_RET('i', -1);
1329 conn->RemoteIP.v4 = *(tIPv4*)Data;
1331 else if( conn->Interface->Type == 6 )
1333 if(!CheckMem(Data, sizeof(tIPv6))) LEAVE_RET('i', -1);
1334 conn->RemoteIP.v6 = *(tIPv6*)Data;
1339 if(conn->LocalPort == 0xFFFF)
1340 conn->LocalPort = TCP_GetUnusedPort();
1341 if(conn->RemotePort == -1)
1345 tTime timeout = conn->Interface->TimeoutDelay;
1347 TCP_StartConnection(conn);
1348 VFS_SelectNode(&conn->Node, VFS_SELECT_WRITE, &timeout, "TCP Connection");
1349 if( conn->State == TCP_ST_SYN_SENT )
1355 // Get recieve buffer length
1357 LEAVE_RET('i', conn->RecievedBuffer->Length);
1363 void TCP_Client_Close(tVFS_Node *Node)
1365 tTCPConnection *conn = Node->ImplPtr;
1368 ENTER("pNode", Node);
1370 if( conn->State == TCP_ST_CLOSE_WAIT || conn->State == TCP_ST_OPEN )
1372 packet.SourcePort = htons(conn->LocalPort);
1373 packet.DestPort = htons(conn->RemotePort);
1374 packet.DataOffset = (sizeof(tTCPHeader)/4)*16;
1375 packet.WindowSize = TCP_WINDOW_SIZE;
1377 packet.AcknowlegementNumber = 0;
1378 packet.SequenceNumber = htonl(conn->NextSequenceSend);
1379 packet.Flags = TCP_FLAG_FIN;
1381 TCP_SendPacket( conn, &packet, 0, NULL );
1384 switch( conn->State )
1386 case TCP_ST_CLOSE_WAIT:
1387 conn->State = TCP_ST_LAST_ACK;
1390 conn->State = TCP_ST_FIN_WAIT1;
1391 while( conn->State == TCP_ST_FIN_WAIT1 ) Threads_Yield();
1394 Log_Warning("TCP", "Unhandled connection state %i in TCP_Client_Close",
1399 Time_RemoveTimer(conn->DeferredACKTimer);
1400 Time_FreeTimer(conn->DeferredACKTimer);
1407 * \brief Checks if a value is between two others (after taking into account wrapping)
1409 int WrapBetween(Uint32 Lower, Uint32 Value, Uint32 Higher, Uint32 MaxValue)
1411 if( MaxValue < 0xFFFFFFFF )
1413 Lower %= MaxValue + 1;
1414 Value %= MaxValue + 1;
1415 Higher %= MaxValue + 1;
1418 // Simple Case, no wrap ?
1419 // Lower Value Higher
1420 // | ... + ... + ... + ... |
1422 if( Lower < Higher ) {
1423 return Lower < Value && Value < Higher;
1425 // Higher has wrapped below lower
1428 // Higher Lower Value
1429 // | ... + ... + ... + ... |
1430 if( Value > Lower ) {
1435 // Value Higher Lower
1436 // | ... + ... + ... + ... |
1437 if( Value < Higher ) {