11 #define HEXDUMP_INCOMING 0
12 #define HEXDUMP_OUTGOING 0
14 #define TCP_MIN_DYNPORT 0xC000
15 #define TCP_MAX_HALFOPEN 1024 // Should be enough
17 #define TCP_MAX_PACKET_SIZE 1024
18 #define TCP_WINDOW_SIZE 0x2000
19 #define TCP_RECIEVE_BUFFER_SIZE 0x8000
20 #define TCP_DACK_THRESHOLD 4096
21 #define TCP_DACK_TIMEOUT 500
23 #define TCP_DEBUG 0 // Set to non-0 to enable TCP packet logging
26 void TCP_Initialise(void);
27 void TCP_StartConnection(tTCPConnection *Conn);
28 void TCP_SendPacket(tTCPConnection *Conn, tTCPHeader *Header, size_t DataLen, const void *Data);
29 void TCP_int_SendPacket(tInterface *Interface, const void *Dest, tTCPHeader *Header, size_t Length, const void *Data);
30 void TCP_GetPacket(tInterface *Interface, void *Address, int Length, void *Buffer);
31 void TCP_INT_HandleConnectionPacket(tTCPConnection *Connection, tTCPHeader *Header, int Length);
32 int TCP_INT_AppendRecieved(tTCPConnection *Connection, const void *Data, size_t Length);
33 void TCP_INT_UpdateRecievedFromFuture(tTCPConnection *Connection);
34 void TCP_int_SendDelayedACK(void *ConnPtr);
35 void TCP_INT_SendACK(tTCPConnection *Connection, const char *Reason);
36 Uint16 TCP_GetUnusedPort();
37 int TCP_AllocatePort(Uint16 Port);
38 int TCP_DeallocatePort(Uint16 Port);
39 tTCPConnection *TCP_int_CreateConnection(tInterface *Interface, enum eTCPConnectionState State);
40 void TCP_int_FreeTCB(tTCPConnection *Connection);
42 tVFS_Node *TCP_Server_Init(tInterface *Interface);
43 int TCP_Server_ReadDir(tVFS_Node *Node, int Pos, char Name[FILENAME_MAX]);
44 tVFS_Node *TCP_Server_FindDir(tVFS_Node *Node, const char *Name, Uint Flags);
45 int TCP_Server_IOCtl(tVFS_Node *Node, int ID, void *Data);
46 void TCP_Server_Close(tVFS_Node *Node);
48 tVFS_Node *TCP_Client_Init(tInterface *Interface);
49 size_t TCP_Client_Read(tVFS_Node *Node, off_t Offset, size_t Length, void *Buffer, Uint Flags);
50 size_t TCP_Client_Write(tVFS_Node *Node, off_t Offset, size_t Length, const void *Buffer, Uint Flags);
51 int TCP_Client_IOCtl(tVFS_Node *Node, int ID, void *Data);
52 void TCP_Client_Close(tVFS_Node *Node);
54 int WrapBetween(Uint32 Lower, Uint32 Value, Uint32 Higher, Uint32 MaxValue);
55 Uint32 GetRelative(Uint32 Base, Uint32 Value);
58 tSocketFile gTCP_ServerFile = {NULL, "tcps", TCP_Server_Init};
59 tSocketFile gTCP_ClientFile = {NULL, "tcpc", TCP_Client_Init};
60 tVFS_NodeType gTCP_ServerNodeType = {
61 .TypeName = "TCP Server",
62 .ReadDir = TCP_Server_ReadDir,
63 .FindDir = TCP_Server_FindDir,
64 .IOCtl = TCP_Server_IOCtl,
65 .Close = TCP_Server_Close
67 tVFS_NodeType gTCP_ClientNodeType = {
68 .TypeName = "TCP Client/Connection",
69 .Read = TCP_Client_Read,
70 .Write = TCP_Client_Write,
71 .IOCtl = TCP_Client_IOCtl,
72 .Close = TCP_Client_Close
76 int giTCP_NumHalfopen = 0;
77 tShortSpinlock glTCP_Listeners;
78 tTCPListener *gTCP_Listeners;
79 tShortSpinlock glTCP_OutbountCons;
80 tTCPConnection *gTCP_OutbountCons;
81 Uint32 gaTCP_PortBitmap[0x800];
82 int giTCP_NextOutPort = TCP_MIN_DYNPORT;
86 * \brief Initialise the TCP Layer
88 * Registers the client and server files and the GetPacket callback
90 void TCP_Initialise(void)
92 giTCP_NextOutPort += rand()%128;
93 IPStack_AddFile(&gTCP_ServerFile);
94 IPStack_AddFile(&gTCP_ClientFile);
95 IPv4_RegisterCallback(IP4PROT_TCP, TCP_GetPacket);
96 IPv6_RegisterCallback(IP4PROT_TCP, TCP_GetPacket);
100 * \brief Sends a packet from the specified connection, calculating the checksums
101 * \param Conn Connection
102 * \param Length Length of data
103 * \param Data Packet data (cast as a TCP Header)
105 void TCP_SendPacket( tTCPConnection *Conn, tTCPHeader *Header, size_t Length, const void *Data )
107 TCP_int_SendPacket(Conn->Interface, &Conn->RemoteIP, Header, Length, Data);
110 Uint16 TCP_int_CalculateChecksum(int AddrType, const void *LAddr, const void *RAddr,
111 size_t HeaderLength, const tTCPHeader *Header, size_t DataLength, const void *Data)
113 size_t packlen = HeaderLength + DataLength;
120 buf[0] = ((tIPv4*)LAddr)->L;
121 buf[1] = ((tIPv4*)RAddr)->L;
122 buf[2] = htonl( (packlen) | (IP4PROT_TCP<<16) | (0<<24) );
123 checksum[0] = htons( ~IPv4_Checksum(buf, sizeof(buf)) ); // Partial checksum
127 memcpy(&buf[0], LAddr, 16);
128 memcpy(&buf[4], RAddr, 16);
129 buf[8] = htonl(packlen);
130 buf[9] = htonl(IP4PROT_TCP);
131 checksum[0] = htons( ~IPv4_Checksum(buf, sizeof(buf)) ); // Partial checksum
136 checksum[1] = htons( ~IPv4_Checksum(Header, HeaderLength) );
137 checksum[2] = htons( ~IPv4_Checksum(Data, DataLength) );
139 return htons( IPv4_Checksum(checksum, sizeof(checksum)) );
142 void TCP_int_SendPacket(tInterface *Interface, const void *Dest, tTCPHeader *Header, size_t Length, const void *Data )
144 tIPStackBuffer *buffer = IPStack_Buffer_CreateBuffer(2 + IPV4_BUFFERS);
146 IPStack_Buffer_AppendSubBuffer(buffer, Length, 0, Data, NULL, NULL);
147 IPStack_Buffer_AppendSubBuffer(buffer, sizeof(*Header), 0, Header, NULL, NULL);
149 LOG("Sending %i+%i to %s:%i", sizeof(*Header), Length,
150 IPStack_PrintAddress(Interface->Type, Dest),
151 ntohs(Header->DestPort)
154 Header->Checksum = 0;
155 Header->Checksum = TCP_int_CalculateChecksum(Interface->Type, Interface->Address, Dest,
156 sizeof(tTCPHeader), Header, Length, Data);
158 // TODO: Fragment packet
160 switch( Interface->Type )
163 IPv4_SendPacket(Interface, *(tIPv4*)Dest, IP4PROT_TCP, 0, buffer);
166 IPv6_SendPacket(Interface, *(tIPv6*)Dest, IP4PROT_TCP, buffer);
171 void TCP_int_SendRSTTo(tInterface *Interface, void *Address, size_t Length, const tTCPHeader *Header)
173 tTCPHeader out_hdr = {0};
175 out_hdr.DataOffset = (sizeof(out_hdr)/4) << 4;
176 out_hdr.DestPort = Header->SourcePort;
177 out_hdr.SourcePort = Header->DestPort;
179 size_t data_len = Length - (Header->DataOffset>>4)*4;
180 out_hdr.AcknowlegementNumber = htonl( ntohl(Header->SequenceNumber) + data_len );
181 if( Header->Flags & TCP_FLAG_ACK ) {
182 out_hdr.Flags = TCP_FLAG_RST;
183 out_hdr.SequenceNumber = Header->AcknowlegementNumber;
186 out_hdr.Flags = TCP_FLAG_RST|TCP_FLAG_ACK;
187 out_hdr.SequenceNumber = 0;
189 TCP_int_SendPacket(Interface, Address, &out_hdr, 0, NULL);
193 * \brief Handles a packet from the IP Layer
194 * \param Interface Interface the packet arrived from
195 * \param Address Pointer to the addres structure
196 * \param Length Size of packet in bytes
197 * \param Buffer Packet data
199 void TCP_GetPacket(tInterface *Interface, void *Address, int Length, void *Buffer)
201 tTCPHeader *hdr = Buffer;
204 Log_Log("TCP", "TCP_GetPacket: <Local>:%i from [%s]:%i, Flags = %s%s%s%s%s%s%s%s",
205 ntohs(hdr->DestPort),
206 IPStack_PrintAddress(Interface->Type, Address),
207 ntohs(hdr->SourcePort),
208 (hdr->Flags & TCP_FLAG_CWR) ? "CWR " : "",
209 (hdr->Flags & TCP_FLAG_ECE) ? "ECE " : "",
210 (hdr->Flags & TCP_FLAG_URG) ? "URG " : "",
211 (hdr->Flags & TCP_FLAG_ACK) ? "ACK " : "",
212 (hdr->Flags & TCP_FLAG_PSH) ? "PSH " : "",
213 (hdr->Flags & TCP_FLAG_RST) ? "RST " : "",
214 (hdr->Flags & TCP_FLAG_SYN) ? "SYN " : "",
215 (hdr->Flags & TCP_FLAG_FIN) ? "FIN " : ""
219 if( Length > (hdr->DataOffset >> 4)*4 )
221 LOG("SequenceNumber = 0x%x", ntohl(hdr->SequenceNumber));
224 "TCP_GetPacket: Packet Data = ",
225 (Uint8*)hdr + (hdr->DataOffset >> 4)*4,
226 Length - (hdr->DataOffset >> 4)*4
232 for( tTCPListener *srv = gTCP_Listeners; srv; srv = srv->Next )
234 // Check if the server is active
235 if(srv->Port == 0) continue;
236 // Check the interface
237 if(srv->Interface && srv->Interface != Interface) continue;
238 // Check the destination port
239 if(srv->Port != htons(hdr->DestPort)) continue;
241 Log_Log("TCP", "TCP_GetPacket: Matches server %p", srv);
242 // Is this in an established connection?
243 for( tTCPConnection *conn = srv->Connections; conn; conn = conn->Next )
245 // Check that it is coming in on the same interface
246 if(conn->Interface != Interface) continue;
249 Log_Log("TCP", "TCP_GetPacket: conn->RemotePort(%i) == hdr->SourcePort(%i)",
250 conn->RemotePort, ntohs(hdr->SourcePort));
251 if(conn->RemotePort != ntohs(hdr->SourcePort)) continue;
254 Log_Debug("TCP", "TCP_GetPacket: conn->RemoteIP(%s)",
255 IPStack_PrintAddress(conn->Interface->Type, &conn->RemoteIP));
256 Log_Debug("TCP", " == Address(%s)",
257 IPStack_PrintAddress(conn->Interface->Type, Address));
258 if( IPStack_CompareAddress(conn->Interface->Type, &conn->RemoteIP, Address, -1) == 0 )
261 Log_Log("TCP", "TCP_GetPacket: Matches connection %p", conn);
262 // We have a response!
263 TCP_INT_HandleConnectionPacket(conn, hdr, Length);
269 if( hdr->Flags & TCP_FLAG_RST ) {
273 else if( hdr->Flags & TCP_FLAG_ACK ) {
274 LOG("ACK, send RST");
275 TCP_int_SendRSTTo(Interface, Address, Length, hdr);
278 else if( !(hdr->Flags & TCP_FLAG_SYN) ) {
279 LOG("Other, ignore");
282 Log_Log("TCP", "TCP_GetPacket: Opening Connection");
284 // TODO: Check for halfopen max
286 tTCPConnection *conn = TCP_int_CreateConnection(Interface, TCP_ST_SYN_RCVD);
287 conn->LocalPort = srv->Port;
288 conn->RemotePort = ntohs(hdr->SourcePort);
290 switch(Interface->Type)
292 case 4: conn->RemoteIP.v4 = *(tIPv4*)Address; break;
293 case 6: conn->RemoteIP.v6 = *(tIPv6*)Address; break;
294 default: ASSERTC(Interface->Type,==,4); return;
297 conn->NextSequenceRcv = ntohl( hdr->SequenceNumber ) + 1;
298 conn->HighestSequenceRcvd = conn->NextSequenceRcv;
299 conn->NextSequenceSend = rand();
300 conn->LastACKSequence = ntohl( hdr->SequenceNumber );
302 conn->Node.ImplInt = srv->NextID ++;
304 // Hmm... Theoretically, this lock will never have to wait,
305 // as the interface is locked to the watching thread, and this
306 // runs in the watching thread. But, it's a good idea to have
308 // Oh, wait, there is a case where a wildcard can be used
309 // (srv->Interface == NULL) so having the lock is a good idea
310 SHORTLOCK(&srv->lConnections);
312 conn->Prev = srv->ConnectionsTail;
313 if(srv->Connections) {
314 ASSERT(srv->ConnectionsTail);
315 srv->ConnectionsTail->Next = conn;
318 ASSERT(!srv->ConnectionsTail);
319 srv->Connections = conn;
321 srv->ConnectionsTail = conn;
322 if(!srv->NewConnections)
323 srv->NewConnections = conn;
324 VFS_MarkAvaliable( &srv->Node, 1 );
325 SHORTREL(&srv->lConnections);
326 Semaphore_Signal(&srv->WaitingConnections, 1);
329 hdr->Flags |= TCP_FLAG_ACK;
330 hdr->AcknowlegementNumber = htonl(conn->NextSequenceRcv);
331 hdr->SequenceNumber = htonl(conn->NextSequenceSend);
332 hdr->DestPort = hdr->SourcePort;
333 hdr->SourcePort = htons(srv->Port);
334 hdr->DataOffset = (sizeof(tTCPHeader)/4) << 4;
335 TCP_SendPacket( conn, hdr, 0, NULL );
336 conn->NextSequenceSend ++;
340 // Check Open Connections
342 for( tTCPConnection *conn = gTCP_OutbountCons; conn; conn = conn->Next )
344 // Check that it is coming in on the same interface
345 if(conn->Interface != Interface) continue;
348 if(conn->RemotePort != ntohs(hdr->SourcePort)) continue;
351 if(conn->Interface->Type == 6 && !IP6_EQU(conn->RemoteIP.v6, *(tIPv6*)Address))
353 if(conn->Interface->Type == 4 && !IP4_EQU(conn->RemoteIP.v4, *(tIPv4*)Address))
356 TCP_INT_HandleConnectionPacket(conn, hdr, Length);
361 Log_Log("TCP", "TCP_GetPacket: No Match");
362 // If not a RST, send a RST
363 if( !(hdr->Flags & TCP_FLAG_RST) )
365 TCP_int_SendRSTTo(Interface, Address, Length, hdr);
370 * \brief Handles a packet sent to a specific connection
371 * \param Connection TCP Connection pointer
372 * \param Header TCP Packet pointer
373 * \param Length Length of the packet
375 void TCP_INT_HandleConnectionPacket(tTCPConnection *Connection, tTCPHeader *Header, int Length)
380 // Silently drop once finished
381 // TODO: Check if this needs to be here
382 if( Connection->State == TCP_ST_FINISHED ) {
383 Log_Log("TCP", "Packet ignored - connection finnished");
387 // Syncronise sequence values
388 if(Header->Flags & TCP_FLAG_SYN) {
389 // TODO: What if the packet also has data?
390 if( Connection->LastACKSequence != Connection->NextSequenceRcv )
391 TCP_INT_SendACK(Connection, "SYN");
392 Connection->NextSequenceRcv = ntohl(Header->SequenceNumber);
393 // TODO: Process HighestSequenceRcvd
395 if( Connection->HighestSequenceRcvd == 0 )
396 Connection->HighestSequenceRcvd = Connection->NextSequenceRcv;
397 Connection->LastACKSequence = Connection->NextSequenceRcv;
400 // Ackowledge a sent packet
401 if(Header->Flags & TCP_FLAG_ACK) {
402 // TODO: Process an ACKed Packet
403 LOG("Conn %p, Sent packet 0x%x ACKed", Connection, Header->AcknowlegementNumber);
406 // Get length of data
407 dataLen = Length - (Header->DataOffset>>4)*4;
408 LOG("dataLen = %i", dataLen);
410 Log_Debug("TCP", "State %i, dataLen = %x", Connection->State, dataLen);
416 switch( Connection->State )
418 // Pre-init connection?
420 Log_Log("TCP", "Packets to a closed connection?!");
423 // --- Init States ---
424 // SYN sent, expecting SYN-ACK Connection Opening
425 case TCP_ST_SYN_SENT:
426 if( Header->Flags & TCP_FLAG_SYN )
428 if( Connection->HighestSequenceRcvd == Connection->NextSequenceRcv )
429 Connection->HighestSequenceRcvd ++;
430 Connection->NextSequenceRcv ++;
432 if( Header->Flags & TCP_FLAG_ACK )
434 Log_Log("TCP", "ACKing SYN-ACK");
435 Connection->State = TCP_ST_OPEN;
436 VFS_MarkFull(&Connection->Node, 0);
437 TCP_INT_SendACK(Connection, "SYN-ACK");
441 Log_Log("TCP", "ACKing SYN");
442 Connection->State = TCP_ST_SYN_RCVD;
443 TCP_INT_SendACK(Connection, "SYN");
448 // SYN-ACK sent, expecting ACK
449 case TCP_ST_SYN_RCVD:
450 if( Header->Flags & TCP_FLAG_ACK )
452 // TODO: Handle max half-open limit
453 Log_Log("TCP", "Connection fully opened");
454 Connection->State = TCP_ST_OPEN;
455 VFS_MarkFull(&Connection->Node, 0);
459 // --- Established State ---
461 // - Handle State changes
463 if( Header->Flags & TCP_FLAG_FIN ) {
464 Log_Log("TCP", "Conn %p closed, recieved FIN", Connection);
465 VFS_MarkError(&Connection->Node, 1);
466 Connection->NextSequenceRcv ++;
467 TCP_INT_SendACK(Connection, "FIN Received");
468 Connection->State = TCP_ST_CLOSE_WAIT;
469 // CLOSE WAIT requires the client to close
473 // Check for an empty packet
475 if( Header->Flags == TCP_FLAG_ACK )
477 Log_Log("TCP", "ACK only packet");
480 // TODO: Is this right? (empty packet counts as one byte)
481 if( Connection->HighestSequenceRcvd == Connection->NextSequenceRcv )
482 Connection->HighestSequenceRcvd ++;
483 Connection->NextSequenceRcv ++;
484 Log_Log("TCP", "Empty Packet, inc and ACK the current sequence number");
485 TCP_INT_SendACK(Connection, "Empty");
494 sequence_num = ntohl(Header->SequenceNumber);
496 LOG("0x%08x <= 0x%08x < 0x%08x",
497 Connection->NextSequenceRcv,
498 ntohl(Header->SequenceNumber),
499 Connection->NextSequenceRcv + TCP_WINDOW_SIZE
502 // Is this packet the next expected packet?
503 if( sequence_num == Connection->NextSequenceRcv )
506 // Ooh, Goodie! Add it to the recieved list
507 rv = TCP_INT_AppendRecieved(Connection,
508 (Uint8*)Header + (Header->DataOffset>>4)*4,
512 Log_Notice("TCP", "TCP_INT_AppendRecieved rv %i", rv);
515 LOG("0x%08x += %i", Connection->NextSequenceRcv, dataLen);
516 if( Connection->HighestSequenceRcvd == Connection->NextSequenceRcv )
517 Connection->HighestSequenceRcvd += dataLen;
518 Connection->NextSequenceRcv += dataLen;
520 // TODO: This should be moved out of the watcher thread,
521 // so that a single lost packet on one connection doesn't cause
522 // all connections on the interface to lag.
523 // - Meh, no real issue, as the cache shouldn't be that large
524 TCP_INT_UpdateRecievedFromFuture(Connection);
527 // - Only send an ACK if we've had a burst
528 Uint32 bytes_since_last_ack = Connection->NextSequenceRcv - Connection->LastACKSequence;
529 LOG("bytes_since_last_ack = 0x%x", bytes_since_last_ack);
530 if( bytes_since_last_ack > TCP_DACK_THRESHOLD )
532 TCP_INT_SendACK(Connection, "DACK Burst");
533 // - Extend TCP deferred ACK timer
534 Time_RemoveTimer(Connection->DeferredACKTimer);
536 // - Schedule the deferred ACK timer (if already scheduled, this is a NOP)
537 Time_ScheduleTimer(Connection->DeferredACKTimer, TCP_DACK_TIMEOUT);
539 TCP_INT_SendACK(Connection, "RX");
542 // Check if the packet is in window
543 else if( sequence_num - Connection->NextSequenceRcv < TCP_WINDOW_SIZE )
545 Uint8 *dataptr = (Uint8*)Header + (Header->DataOffset>>4)*4;
546 Uint32 index = sequence_num % TCP_WINDOW_SIZE;
547 Uint32 max = Connection->NextSequenceRcv % TCP_WINDOW_SIZE;
548 if( !(Connection->FuturePacketValidBytes[index/8] & (1 << (index%8))) )
549 TCP_INT_SendACK(Connection, "Lost packet");
550 for( int i = 0; i < dataLen; i ++ )
552 Connection->FuturePacketValidBytes[index/8] |= 1 << (index%8);
553 Connection->FuturePacketData[index] = dataptr[i];
554 // Do a wrap increment
556 if(index == TCP_WINDOW_SIZE) index = 0;
557 if(index == max) break;
559 Uint32 rel_highest = Connection->HighestSequenceRcvd - Connection->NextSequenceRcv;
560 Uint32 rel_this = index - Connection->NextSequenceRcv;
561 LOG("Updating highest this(0x%x) > highest(%x)", rel_this, rel_highest);
562 if( rel_this > rel_highest )
564 Connection->HighestSequenceRcvd = index;
567 // Badly out of sequence packet
570 Log_Log("TCP", "Fully out of sequence packet (0x%08x not between 0x%08x and 0x%08x), dropped",
571 sequence_num, Connection->NextSequenceRcv, Connection->NextSequenceRcv+TCP_WINDOW_SIZE);
572 // Spec says we should send an empty ACK with the current state
573 TCP_INT_SendACK(Connection, "Bad Seq");
577 // --- Remote close states
578 case TCP_ST_CLOSE_WAIT:
580 // Ignore everything, CLOSE_WAIT is terminated by the client
581 Log_Debug("TCP", "CLOSE WAIT - Ignoring packets");
585 // LAST-ACK - Waiting for the ACK of FIN (from CLOSE WAIT)
586 case TCP_ST_LAST_ACK:
587 if( Header->Flags & TCP_FLAG_ACK )
589 Connection->State = TCP_ST_FINISHED; // Connection completed
590 Log_Log("TCP", "LAST-ACK to CLOSED - Connection remote closed");
591 TCP_int_FreeTCB(Connection);
595 // --- Local close States
596 case TCP_ST_FIN_WAIT1:
597 if( Header->Flags & TCP_FLAG_FIN )
599 Connection->State = TCP_ST_CLOSING;
600 Log_Debug("TCP", "Conn %p closed, sent FIN and recieved FIN", Connection);
601 VFS_MarkError(&Connection->Node, 1);
603 TCP_INT_SendACK(Connection, "FINWAIT-1 FIN");
607 // TODO: Make sure that the packet is actually ACKing the FIN
608 if( Header->Flags & TCP_FLAG_ACK )
610 Connection->State = TCP_ST_FIN_WAIT2;
611 Log_Debug("TCP", "Conn %p closed, sent FIN ACKed", Connection);
612 VFS_MarkError(&Connection->Node, 1);
617 case TCP_ST_FIN_WAIT2:
618 if( Header->Flags & TCP_FLAG_FIN )
620 Connection->State = TCP_ST_TIME_WAIT;
621 Log_Debug("TCP", "Conn %p FINWAIT-2 -> TIME WAIT", Connection);
622 TCP_INT_SendACK(Connection, "FINWAIT-2 FIN");
627 // TODO: Make sure that the packet is actually ACKing the FIN
628 if( Header->Flags & TCP_FLAG_ACK )
630 Connection->State = TCP_ST_TIME_WAIT;
631 Log_Debug("TCP", "Conn %p CLOSING -> TIME WAIT", Connection);
632 VFS_MarkError(&Connection->Node, 1);
637 // --- Closed (or near closed) states) ---
638 case TCP_ST_TIME_WAIT:
639 Log_Log("TCP", "Packets on Time-Wait, ignored");
642 case TCP_ST_FINISHED:
643 Log_Log("TCP", "Packets when CLOSED, ignoring");
647 // Log_Warning("TCP", "Unhandled TCP state %i", Connection->State);
654 * \brief Appends a packet to the recieved list
655 * \param Connection Connection structure
656 * \param Data Packet contents
657 * \param Length Length of \a Data
659 int TCP_INT_AppendRecieved(tTCPConnection *Connection, const void *Data, size_t Length)
661 Mutex_Acquire( &Connection->lRecievedPackets );
663 if(Connection->RecievedBuffer->Length + Length > Connection->RecievedBuffer->Space )
665 VFS_MarkAvaliable(&Connection->Node, 1);
666 Log_Error("TCP", "Buffer filled, packet dropped (:%i) - %i + %i > %i",
667 Connection->LocalPort, Connection->RecievedBuffer->Length, Length,
668 Connection->RecievedBuffer->Space
670 Mutex_Release( &Connection->lRecievedPackets );
674 RingBuffer_Write( Connection->RecievedBuffer, Data, Length );
676 VFS_MarkAvaliable(&Connection->Node, 1);
678 Mutex_Release( &Connection->lRecievedPackets );
683 * \brief Updates the connections recieved list from the future list
684 * \param Connection Connection structure
686 * Updates the recieved packets list with packets from the future (out
687 * of order) packets list that are now able to be added in direct
690 void TCP_INT_UpdateRecievedFromFuture(tTCPConnection *Connection)
692 // Calculate length of contiguous bytes
693 const int length = Connection->HighestSequenceRcvd - Connection->NextSequenceRcv;
694 Uint32 index = Connection->NextSequenceRcv % TCP_WINDOW_SIZE;
695 size_t runlength = length;
696 LOG("length=%i, index=0x%x", length, index);
697 for( int i = 0; i < length; i ++ )
700 Uint8 bitfield_byte = Connection->FuturePacketValidBytes[index / 8];
701 if( (bitfield_byte & (1 << bit)) == 0 ) {
703 LOG("Hit missing, break");
707 if( bitfield_byte == 0xFF ) {
715 if(index > TCP_WINDOW_SIZE)
716 index -= TCP_WINDOW_SIZE;
719 index = Connection->NextSequenceRcv % TCP_WINDOW_SIZE;
720 Connection->NextSequenceRcv += runlength;
722 // Write data to to the ring buffer
723 if( TCP_WINDOW_SIZE - index > runlength )
726 RingBuffer_Write( Connection->RecievedBuffer, Connection->FuturePacketData + index, runlength );
730 int endLen = TCP_WINDOW_SIZE - index;
732 RingBuffer_Write( Connection->RecievedBuffer, Connection->FuturePacketData + index, endLen );
733 RingBuffer_Write( Connection->RecievedBuffer, Connection->FuturePacketData, endLen - runlength );
736 // Mark (now saved) bytes as invalid
738 while(index % 8 && runlength > 0)
740 Connection->FuturePacketData[index] = 0;
741 Connection->FuturePacketValidBytes[index/8] &= ~(1 << (index%8));
743 if(index > TCP_WINDOW_SIZE)
744 index -= TCP_WINDOW_SIZE;
747 while( runlength > 7 )
749 Connection->FuturePacketData[index] = 0;
750 Connection->FuturePacketValidBytes[index/8] = 0;
753 if(index > TCP_WINDOW_SIZE)
754 index -= TCP_WINDOW_SIZE;
756 while( runlength > 0)
758 Connection->FuturePacketData[index] = 0;
759 Connection->FuturePacketData[index/8] &= ~(1 << (index%8));
761 if(index > TCP_WINDOW_SIZE)
762 index -= TCP_WINDOW_SIZE;
767 void TCP_int_SendDelayedACK(void *ConnPtr)
769 TCP_INT_SendACK(ConnPtr, "DACK Timeout");
772 void TCP_INT_SendACK(tTCPConnection *Connection, const char *Reason)
776 hdr.DataOffset = (sizeof(tTCPHeader)/4) << 4;
777 hdr.DestPort = htons(Connection->RemotePort);
778 hdr.SourcePort = htons(Connection->LocalPort);
779 hdr.AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
780 hdr.SequenceNumber = htonl(Connection->NextSequenceSend);
781 hdr.WindowSize = htons(TCP_WINDOW_SIZE);
782 hdr.Flags = TCP_FLAG_ACK; // TODO: Determine if SYN is wanted too
783 hdr.Checksum = 0; // TODO: Checksum
784 hdr.UrgentPointer = 0;
785 Log_Debug("TCP", "Sending ACK for 0x%08x (%s)", Connection->NextSequenceRcv, Reason);
786 TCP_SendPacket( Connection, &hdr, 0, NULL );
787 //Connection->NextSequenceSend ++;
788 Connection->LastACKSequence = Connection->NextSequenceRcv;
792 * \fn Uint16 TCP_GetUnusedPort()
793 * \brief Gets an unused port and allocates it
795 Uint16 TCP_GetUnusedPort()
799 // Get Next outbound port
800 ret = giTCP_NextOutPort++;
801 while( gaTCP_PortBitmap[ret/32] & (1UL << (ret%32)) )
805 if(giTCP_NextOutPort == 0x10000) {
806 ret = giTCP_NextOutPort = TCP_MIN_DYNPORT;
810 // Mark the new port as used
811 gaTCP_PortBitmap[ret/32] |= 1 << (ret%32);
817 * \fn int TCP_AllocatePort(Uint16 Port)
818 * \brief Marks a port as used
820 int TCP_AllocatePort(Uint16 Port)
822 // Check if the port has already been allocated
823 if( gaTCP_PortBitmap[Port/32] & (1 << (Port%32)) )
827 gaTCP_PortBitmap[Port/32] |= 1 << (Port%32);
833 * \fn int TCP_DeallocatePort(Uint16 Port)
834 * \brief Marks a port as unused
836 int TCP_DeallocatePort(Uint16 Port)
838 // Check if the port has already been allocated
839 if( !(gaTCP_PortBitmap[Port/32] & (1 << (Port%32))) )
843 gaTCP_PortBitmap[Port/32] &= ~(1 << (Port%32));
848 tTCPConnection *TCP_int_CreateConnection(tInterface *Interface, enum eTCPConnectionState State)
850 tTCPConnection *conn = calloc( sizeof(tTCPConnection) + TCP_WINDOW_SIZE + TCP_WINDOW_SIZE/8, 1 );
853 conn->Interface = Interface;
854 conn->LocalPort = -1;
855 conn->RemotePort = -1;
857 conn->Node.ReferenceCount = 1;
858 conn->Node.ImplPtr = conn;
859 conn->Node.NumACLs = 1;
860 conn->Node.ACLs = &gVFS_ACL_EveryoneRW;
861 conn->Node.Type = &gTCP_ClientNodeType;
862 conn->Node.BufferFull = 1; // Cleared when connection opens
864 conn->RecievedBuffer = RingBuffer_Create( TCP_RECIEVE_BUFFER_SIZE );
866 conn->SentBuffer = RingBuffer_Create( TCP_SEND_BUFFER_SIZE );
867 Semaphore_Init(conn->SentBufferSpace, 0, TCP_SEND_BUFFER_SIZE, "TCP SentBuffer", conn->Name);
870 #if CACHE_FUTURE_PACKETS_IN_BYTES
871 // Future recieved data (ahead of the expected sequence number)
872 conn->FuturePacketData = (Uint8*)conn + sizeof(tTCPConnection);
873 conn->FuturePacketValidBytes = conn->FuturePacketData + TCP_WINDOW_SIZE;
876 conn->DeferredACKTimer = Time_AllocateTimer( TCP_int_SendDelayedACK, conn);
880 void TCP_int_FreeTCB(tTCPConnection *Connection)
882 ASSERTC(Connection->State, ==, TCP_ST_FINISHED);
883 ASSERTC(Connection->Node.ReferenceCount, ==, 0);
885 if( Connection->Server )
887 tTCPListener *srv = Connection->Server;
888 SHORTLOCK(&srv->lConnections);
890 Connection->Prev->Next = Connection->Next;
892 srv->Connections = Connection->Next;
894 Connection->Next->Prev = Connection->Prev;
896 ASSERT(srv->ConnectionsTail == Connection);
897 srv->ConnectionsTail = Connection->Prev;
899 SHORTREL(&srv->lConnections);
903 SHORTLOCK(&glTCP_OutbountCons);
905 Connection->Prev->Next = Connection->Next;
907 gTCP_OutbountCons = Connection->Next;
909 Connection->Next->Prev = Connection->Prev;
912 SHORTREL(&glTCP_OutbountCons);
915 RingBuffer_Free(Connection->RecievedBuffer);
916 Time_FreeTimer(Connection->DeferredACKTimer);
917 // TODO: Force VFS to close handles? (they should all be closed);
922 tVFS_Node *TCP_Server_Init(tInterface *Interface)
926 srv = calloc( 1, sizeof(tTCPListener) );
929 Log_Warning("TCP", "malloc failed for listener (%i) bytes", sizeof(tTCPListener));
933 srv->Interface = Interface;
936 srv->Connections = NULL;
937 srv->ConnectionsTail = NULL;
938 srv->NewConnections = NULL;
940 srv->Node.Flags = VFS_FFLAG_DIRECTORY;
942 srv->Node.ImplPtr = srv;
943 srv->Node.NumACLs = 1;
944 srv->Node.ACLs = &gVFS_ACL_EveryoneRW;
945 srv->Node.Type = &gTCP_ServerNodeType;
947 SHORTLOCK(&glTCP_Listeners);
948 srv->Next = gTCP_Listeners;
949 gTCP_Listeners = srv;
950 SHORTREL(&glTCP_Listeners);
956 * \brief Wait for a new connection and return the connection ID
957 * \note Blocks until a new connection is made
958 * \param Node Server node
959 * \param Pos Position (ignored)
961 int TCP_Server_ReadDir(tVFS_Node *Node, int Pos, char Dest[FILENAME_MAX])
963 tTCPListener *srv = Node->ImplPtr;
964 tTCPConnection *conn;
966 ENTER("pNode iPos", Node, Pos);
968 Log_Log("TCP", "Thread %i waiting for a connection", Threads_GetTID());
969 Semaphore_Wait( &srv->WaitingConnections, 1 );
971 SHORTLOCK(&srv->lConnections);
972 // Increment the new list (the current connection is still on the
974 conn = srv->NewConnections;
975 srv->NewConnections = conn->Next;
977 if( srv->NewConnections == NULL )
978 VFS_MarkAvaliable( Node, 0 );
980 SHORTREL( &srv->lConnections );
982 LOG("conn = %p", conn);
983 LOG("srv->Connections = %p", srv->Connections);
984 LOG("srv->NewConnections = %p", srv->NewConnections);
985 LOG("srv->ConnectionsTail = %p", srv->ConnectionsTail);
987 itoa(Dest, conn->Node.ImplInt, 16, 8, '0');
988 Log_Log("TCP", "Thread %i got connection '%s'", Threads_GetTID(), Dest);
994 * \brief Gets a client connection node
995 * \param Node Server node
996 * \param Name Hexadecimal ID of the node
998 tVFS_Node *TCP_Server_FindDir(tVFS_Node *Node, const char *Name, Uint Flags)
1000 tTCPConnection *conn;
1001 tTCPListener *srv = Node->ImplPtr;
1003 int id = atoi(Name);
1005 ENTER("pNode sName", Node, Name);
1007 // Check for a non-empty name
1011 itoa(tmp, id, 16, 8, '0');
1012 if(strcmp(tmp, Name) != 0) {
1013 LOG("'%s' != '%s' (%08x)", Name, tmp, id);
1018 Log_Debug("TCP", "srv->Connections = %p", srv->Connections);
1019 Log_Debug("TCP", "srv->NewConnections = %p", srv->NewConnections);
1020 Log_Debug("TCP", "srv->ConnectionsTail = %p", srv->ConnectionsTail);
1023 SHORTLOCK( &srv->lConnections );
1024 for(conn = srv->Connections;
1028 LOG("conn->Node.ImplInt = %i", conn->Node.ImplInt);
1029 if(conn->Node.ImplInt == id) break;
1031 SHORTREL( &srv->lConnections );
1033 // If not found, ret NULL
1035 LOG("Connection %i not found", id);
1040 // Empty Name - Check for a new connection and if it's there, open it
1043 SHORTLOCK( &srv->lConnections );
1044 conn = srv->NewConnections;
1046 srv->NewConnections = conn->Next;
1047 VFS_MarkAvaliable( Node, srv->NewConnections != NULL );
1048 SHORTREL( &srv->lConnections );
1050 LOG("No new connections");
1057 LEAVE('p', &conn->Node);
1062 * \brief Handle IOCtl calls
1064 int TCP_Server_IOCtl(tVFS_Node *Node, int ID, void *Data)
1066 tTCPListener *srv = Node->ImplPtr;
1070 case 4: // Get/Set Port
1071 if(!Data) // Get Port
1074 if(srv->Port) // Wait, you can't CHANGE the port
1077 if(!CheckMem(Data, sizeof(Uint16))) // Sanity check
1080 // Permissions check
1081 if(Threads_GetUID() != 0
1082 && *(Uint16*)Data != 0
1083 && *(Uint16*)Data < 1024)
1086 // TODO: Check if a port is in use
1089 srv->Port = *(Uint16*)Data;
1090 if(srv->Port == 0) // Allocate a random port
1091 srv->Port = TCP_GetUnusedPort();
1092 else // Else, mark this as used
1093 TCP_AllocatePort(srv->Port);
1095 Log_Log("TCP", "Server %p listening on port %i", srv, srv->Port);
1102 void TCP_Server_Close(tVFS_Node *Node)
1104 free(Node->ImplPtr);
1109 * \brief Create a client node
1111 tVFS_Node *TCP_Client_Init(tInterface *Interface)
1113 tTCPConnection *conn = TCP_int_CreateConnection(Interface, TCP_ST_CLOSED);
1115 SHORTLOCK(&glTCP_OutbountCons);
1116 conn->Server = NULL;
1118 conn->Next = gTCP_OutbountCons;
1119 gTCP_OutbountCons->Prev = conn;
1120 gTCP_OutbountCons = conn;
1121 SHORTREL(&glTCP_OutbountCons);
1127 * \brief Wait for a packet and return it
1128 * \note If \a Length is smaller than the size of the packet, the rest
1129 * of the packet's data will be discarded.
1131 size_t TCP_Client_Read(tVFS_Node *Node, off_t Offset, size_t Length, void *Buffer, Uint Flags)
1133 tTCPConnection *conn = Node->ImplPtr;
1136 ENTER("pNode XOffset XLength pBuffer", Node, Offset, Length, Buffer);
1137 LOG("conn = %p {State:%i}", conn, conn->State);
1139 // If the connection has been closed (state > ST_OPEN) then clear
1140 // any stale data in the buffer (until it is empty (until it is empty))
1141 if( conn->State > TCP_ST_OPEN )
1143 Mutex_Acquire( &conn->lRecievedPackets );
1144 len = RingBuffer_Read( Buffer, conn->RecievedBuffer, Length );
1145 Mutex_Release( &conn->lRecievedPackets );
1148 VFS_MarkAvaliable(Node, 0);
1160 tTime *timeout = NULL;
1161 tTime timeout_zero = 0;
1162 if( Flags & VFS_IOFLAG_NOBLOCK )
1163 timeout = &timeout_zero;
1164 if( !VFS_SelectNode(Node, VFS_SELECT_READ|VFS_SELECT_ERROR, timeout, "TCP_Client_Read") ) {
1165 errno = EWOULDBLOCK;
1171 // Lock list and read as much as possible (up to `Length`)
1172 Mutex_Acquire( &conn->lRecievedPackets );
1173 len = RingBuffer_Read( Buffer, conn->RecievedBuffer, Length );
1175 if( len == 0 || conn->RecievedBuffer->Length == 0 ) {
1176 LOG("Marking as none avaliable (len = %i)", len);
1177 VFS_MarkAvaliable(Node, 0);
1180 // Release the lock (we don't need it any more)
1181 Mutex_Release( &conn->lRecievedPackets );
1188 * \brief Send a data packet on a connection
1190 void TCP_INT_SendDataPacket(tTCPConnection *Connection, size_t Length, const void *Data)
1192 char buf[sizeof(tTCPHeader)+Length];
1193 tTCPHeader *packet = (void*)buf;
1195 // - Stop Delayed ACK timer (as this data packet ACKs)
1196 Time_RemoveTimer(Connection->DeferredACKTimer);
1198 // TODO: Don't exceed window size
1200 packet->SourcePort = htons(Connection->LocalPort);
1201 packet->DestPort = htons(Connection->RemotePort);
1202 packet->DataOffset = (sizeof(tTCPHeader)/4)*16;
1203 packet->WindowSize = htons(TCP_WINDOW_SIZE);
1205 packet->AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
1206 packet->SequenceNumber = htonl(Connection->NextSequenceSend);
1207 packet->Flags = TCP_FLAG_PSH|TCP_FLAG_ACK; // Hey, ACK if you can!
1208 packet->UrgentPointer = 0;
1210 memcpy(packet->Options, Data, Length);
1212 Log_Debug("TCP", "Send sequence 0x%08x", Connection->NextSequenceSend);
1213 #if HEXDUMP_OUTGOING
1214 Debug_HexDump("TCP_INT_SendDataPacket: Data = ", Data, Length);
1217 TCP_SendPacket( Connection, packet, Length, Data );
1219 Connection->NextSequenceSend += Length;
1223 * \brief Send some bytes on a connection
1225 size_t TCP_Client_Write(tVFS_Node *Node, off_t Offset, size_t Length, const void *Buffer, Uint Flags)
1227 tTCPConnection *conn = Node->ImplPtr;
1228 size_t rem = Length;
1230 ENTER("pNode XOffset XLength pBuffer", Node, Offset, Length, Buffer);
1233 // Debug_HexDump("TCP_Client_Write: Buffer = ",
1237 // Don't allow a write to a closed connection
1238 if( conn->State > TCP_ST_OPEN ) {
1239 VFS_MarkError(Node, 1);
1247 tTime *timeout = NULL;
1248 tTime timeout_zero = 0;
1249 if( Flags & VFS_IOFLAG_NOBLOCK )
1250 timeout = &timeout_zero;
1251 if( !VFS_SelectNode(Node, VFS_SELECT_WRITE|VFS_SELECT_ERROR, timeout, "TCP_Client_Write") ) {
1252 errno = EWOULDBLOCK;
1260 int len = (rem < TCP_MAX_PACKET_SIZE) ? rem : TCP_MAX_PACKET_SIZE;
1263 // Wait for space in the buffer
1264 Semaphore_Signal( &Connection->SentBufferSpace, len );
1266 // Save data to buffer (and update the length read by the ammount written)
1267 len = RingBuffer_Write( &Connection->SentBuffer, Buffer, len);
1271 TCP_INT_SendDataPacket(conn, len, Buffer);
1282 * \brief Open a connection to another host using TCP
1283 * \param Conn Connection structure
1285 void TCP_StartConnection(tTCPConnection *Conn)
1287 tTCPHeader hdr = {0};
1289 Conn->State = TCP_ST_SYN_SENT;
1291 hdr.SourcePort = htons(Conn->LocalPort);
1292 hdr.DestPort = htons(Conn->RemotePort);
1293 Conn->NextSequenceSend = rand();
1294 hdr.SequenceNumber = htonl(Conn->NextSequenceSend);
1295 hdr.DataOffset = (sizeof(tTCPHeader)/4) << 4;
1296 hdr.Flags = TCP_FLAG_SYN;
1297 hdr.WindowSize = htons(TCP_WINDOW_SIZE); // Max
1298 hdr.Checksum = 0; // TODO
1300 TCP_SendPacket( Conn, &hdr, 0, NULL );
1302 Conn->NextSequenceSend ++;
1303 Conn->State = TCP_ST_SYN_SENT;
1309 * \brief Control a client socket
1311 int TCP_Client_IOCtl(tVFS_Node *Node, int ID, void *Data)
1313 tTCPConnection *conn = Node->ImplPtr;
1315 ENTER("pNode iID pData", Node, ID, Data);
1319 case 4: // Get/Set local port
1321 LEAVE_RET('i', conn->LocalPort);
1322 if(conn->State != TCP_ST_CLOSED)
1324 if(!CheckMem(Data, sizeof(Uint16)))
1327 if(Threads_GetUID() != 0 && *(Uint16*)Data < 1024)
1330 conn->LocalPort = *(Uint16*)Data;
1331 LEAVE_RET('i', conn->LocalPort);
1333 case 5: // Get/Set remote port
1334 if(!Data) LEAVE_RET('i', conn->RemotePort);
1335 if(conn->State != TCP_ST_CLOSED) LEAVE_RET('i', -1);
1336 if(!CheckMem(Data, sizeof(Uint16))) LEAVE_RET('i', -1);
1337 conn->RemotePort = *(Uint16*)Data;
1338 LEAVE_RET('i', conn->RemotePort);
1340 case 6: // Set Remote IP
1341 if( conn->State != TCP_ST_CLOSED )
1343 if( conn->Interface->Type == 4 )
1345 if(!CheckMem(Data, sizeof(tIPv4))) LEAVE_RET('i', -1);
1346 conn->RemoteIP.v4 = *(tIPv4*)Data;
1348 else if( conn->Interface->Type == 6 )
1350 if(!CheckMem(Data, sizeof(tIPv6))) LEAVE_RET('i', -1);
1351 conn->RemoteIP.v6 = *(tIPv6*)Data;
1356 if(conn->LocalPort == 0xFFFF)
1357 conn->LocalPort = TCP_GetUnusedPort();
1358 if(conn->RemotePort == -1)
1362 tTime timeout = conn->Interface->TimeoutDelay;
1364 TCP_StartConnection(conn);
1365 VFS_SelectNode(&conn->Node, VFS_SELECT_WRITE, &timeout, "TCP Connection");
1366 if( conn->State == TCP_ST_SYN_SENT )
1372 // Get recieve buffer length
1374 LEAVE_RET('i', conn->RecievedBuffer->Length);
1380 void TCP_Client_Close(tVFS_Node *Node)
1382 tTCPConnection *conn = Node->ImplPtr;
1385 ENTER("pNode", Node);
1387 ASSERT(Node->ReferenceCount != 0);
1389 if( Node->ReferenceCount > 1 ) {
1390 Node->ReferenceCount --;
1391 LOG("Dereference only");
1395 Node->ReferenceCount --;
1397 if( conn->State == TCP_ST_CLOSE_WAIT || conn->State == TCP_ST_OPEN )
1399 packet.SourcePort = htons(conn->LocalPort);
1400 packet.DestPort = htons(conn->RemotePort);
1401 packet.DataOffset = (sizeof(tTCPHeader)/4)*16;
1402 packet.WindowSize = TCP_WINDOW_SIZE;
1404 packet.AcknowlegementNumber = 0;
1405 packet.SequenceNumber = htonl(conn->NextSequenceSend);
1406 packet.Flags = TCP_FLAG_FIN;
1408 TCP_SendPacket( conn, &packet, 0, NULL );
1411 Time_RemoveTimer(conn->DeferredACKTimer);
1413 switch( conn->State )
1416 Log_Warning("TCP", "Closing connection that was never opened");
1417 TCP_int_FreeTCB(conn);
1419 case TCP_ST_CLOSE_WAIT:
1420 conn->State = TCP_ST_LAST_ACK;
1423 conn->State = TCP_ST_FIN_WAIT1;
1424 while( conn->State == TCP_ST_FIN_WAIT1 )
1426 // No free, freed after TIME_WAIT
1429 Log_Warning("TCP", "Unhandled connection state %i in TCP_Client_Close",
1438 * \brief Checks if a value is between two others (after taking into account wrapping)
1440 int WrapBetween(Uint32 Lower, Uint32 Value, Uint32 Higher, Uint32 MaxValue)
1442 if( MaxValue < 0xFFFFFFFF )
1444 Lower %= MaxValue + 1;
1445 Value %= MaxValue + 1;
1446 Higher %= MaxValue + 1;
1449 // Simple Case, no wrap ?
1450 // Lower Value Higher
1451 // | ... + ... + ... + ... |
1453 if( Lower < Higher ) {
1454 return Lower < Value && Value < Higher;
1456 // Higher has wrapped below lower
1459 // Higher Lower Value
1460 // | ... + ... + ... + ... |
1461 if( Value > Lower ) {
1466 // Value Higher Lower
1467 // | ... + ... + ... + ... |
1468 if( Value < Higher ) {
1474 Uint32 GetRelative(Uint32 Base, Uint32 Value)
1477 return Value - Base + 0xFFFFFFFF;
1479 return Value - Base;