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 void TCP_int_SendPacket(tInterface *Interface, const void *Dest, tTCPHeader *Header, size_t Length, const void *Data )
112 tIPStackBuffer *buffer;
114 int packlen = sizeof(*Header) + Length;
116 buffer = IPStack_Buffer_CreateBuffer(2 + IPV4_BUFFERS);
118 IPStack_Buffer_AppendSubBuffer(buffer, Length, 0, Data, NULL, NULL);
119 IPStack_Buffer_AppendSubBuffer(buffer, sizeof(*Header), 0, Header, NULL, NULL);
121 LOG("Sending %i+%i to %s:%i", sizeof(*Header), Length,
122 IPStack_PrintAddress(Interface->Type, Dest),
123 ntohs(Header->DestPort)
126 Header->Checksum = 0;
127 checksum[1] = htons( ~IPv4_Checksum(Header, sizeof(tTCPHeader)) );
128 checksum[2] = htons( ~IPv4_Checksum(Data, Length) );
130 // TODO: Fragment packet
132 switch( Interface->Type )
135 // Get IPv4 pseudo-header checksum
138 buf[0] = ((tIPv4*)Interface->Address)->L;
139 buf[1] = ((tIPv4*)Dest)->L;
140 buf[2] = htonl( (packlen) | (IP4PROT_TCP<<16) | (0<<24) );
141 checksum[0] = htons( ~IPv4_Checksum(buf, sizeof(buf)) ); // Partial checksum
143 // - Combine checksums
144 Header->Checksum = htons( IPv4_Checksum(checksum, sizeof(checksum)) );
145 IPv4_SendPacket(Interface, *(tIPv4*)Dest, IP4PROT_TCP, 0, buffer);
149 // Append IPv6 Pseudo Header
152 memcpy(buf, Interface->Address, 16);
153 memcpy(&buf[4], Dest, 16);
154 buf[8] = htonl(packlen);
155 buf[9] = htonl(IP4PROT_TCP);
156 checksum[0] = htons( ~IPv4_Checksum(buf, sizeof(buf)) ); // Partial checksum
158 Header->Checksum = htons( IPv4_Checksum(checksum, sizeof(checksum)) ); // Combine the two
159 IPv6_SendPacket(Interface, *(tIPv6*)Dest, IP4PROT_TCP, buffer);
164 void TCP_int_SendRSTTo(tInterface *Interface, void *Address, size_t Length, const tTCPHeader *Header)
166 tTCPHeader out_hdr = {0};
168 out_hdr.DataOffset = (sizeof(out_hdr)/4) << 4;
169 out_hdr.DestPort = Header->SourcePort;
170 out_hdr.SourcePort = Header->DestPort;
172 size_t data_len = Length - (Header->DataOffset>>4)*4;
173 out_hdr.AcknowlegementNumber = htonl( ntohl(Header->SequenceNumber) + data_len );
174 if( Header->Flags & TCP_FLAG_ACK ) {
175 out_hdr.Flags = TCP_FLAG_RST;
176 out_hdr.SequenceNumber = Header->AcknowlegementNumber;
179 out_hdr.Flags = TCP_FLAG_RST|TCP_FLAG_ACK;
180 out_hdr.SequenceNumber = 0;
182 TCP_int_SendPacket(Interface, Address, &out_hdr, 0, NULL);
186 * \brief Handles a packet from the IP Layer
187 * \param Interface Interface the packet arrived from
188 * \param Address Pointer to the addres structure
189 * \param Length Size of packet in bytes
190 * \param Buffer Packet data
192 void TCP_GetPacket(tInterface *Interface, void *Address, int Length, void *Buffer)
194 tTCPHeader *hdr = Buffer;
197 Log_Log("TCP", "TCP_GetPacket: <Local>:%i from [%s]:%i, Flags = %s%s%s%s%s%s%s%s",
198 ntohs(hdr->DestPort),
199 IPStack_PrintAddress(Interface->Type, Address),
200 ntohs(hdr->SourcePort),
201 (hdr->Flags & TCP_FLAG_CWR) ? "CWR " : "",
202 (hdr->Flags & TCP_FLAG_ECE) ? "ECE " : "",
203 (hdr->Flags & TCP_FLAG_URG) ? "URG " : "",
204 (hdr->Flags & TCP_FLAG_ACK) ? "ACK " : "",
205 (hdr->Flags & TCP_FLAG_PSH) ? "PSH " : "",
206 (hdr->Flags & TCP_FLAG_RST) ? "RST " : "",
207 (hdr->Flags & TCP_FLAG_SYN) ? "SYN " : "",
208 (hdr->Flags & TCP_FLAG_FIN) ? "FIN " : ""
212 if( Length > (hdr->DataOffset >> 4)*4 )
214 LOG("SequenceNumber = 0x%x", ntohl(hdr->SequenceNumber));
217 "TCP_GetPacket: Packet Data = ",
218 (Uint8*)hdr + (hdr->DataOffset >> 4)*4,
219 Length - (hdr->DataOffset >> 4)*4
225 for( tTCPListener *srv = gTCP_Listeners; srv; srv = srv->Next )
227 // Check if the server is active
228 if(srv->Port == 0) continue;
229 // Check the interface
230 if(srv->Interface && srv->Interface != Interface) continue;
231 // Check the destination port
232 if(srv->Port != htons(hdr->DestPort)) continue;
234 Log_Log("TCP", "TCP_GetPacket: Matches server %p", srv);
235 // Is this in an established connection?
236 for( tTCPConnection *conn = srv->Connections; conn; conn = conn->Next )
238 // Check that it is coming in on the same interface
239 if(conn->Interface != Interface) continue;
242 Log_Log("TCP", "TCP_GetPacket: conn->RemotePort(%i) == hdr->SourcePort(%i)",
243 conn->RemotePort, ntohs(hdr->SourcePort));
244 if(conn->RemotePort != ntohs(hdr->SourcePort)) continue;
247 Log_Debug("TCP", "TCP_GetPacket: conn->RemoteIP(%s)",
248 IPStack_PrintAddress(conn->Interface->Type, &conn->RemoteIP));
249 Log_Debug("TCP", " == Address(%s)",
250 IPStack_PrintAddress(conn->Interface->Type, Address));
251 if( IPStack_CompareAddress(conn->Interface->Type, &conn->RemoteIP, Address, -1) == 0 )
254 Log_Log("TCP", "TCP_GetPacket: Matches connection %p", conn);
255 // We have a response!
256 TCP_INT_HandleConnectionPacket(conn, hdr, Length);
262 if( hdr->Flags & TCP_FLAG_RST ) {
266 else if( hdr->Flags & TCP_FLAG_ACK ) {
267 LOG("ACK, send RST");
268 TCP_int_SendRSTTo(Interface, Address, Length, hdr);
271 else if( !(hdr->Flags & TCP_FLAG_SYN) ) {
272 LOG("Other, ignore");
275 Log_Log("TCP", "TCP_GetPacket: Opening Connection");
277 // TODO: Check for halfopen max
279 tTCPConnection *conn = TCP_int_CreateConnection(Interface, TCP_ST_SYN_RCVD);
280 conn->LocalPort = srv->Port;
281 conn->RemotePort = ntohs(hdr->SourcePort);
283 switch(Interface->Type)
285 case 4: conn->RemoteIP.v4 = *(tIPv4*)Address; break;
286 case 6: conn->RemoteIP.v6 = *(tIPv6*)Address; break;
287 default: ASSERTC(Interface->Type,==,4); return;
290 conn->NextSequenceRcv = ntohl( hdr->SequenceNumber ) + 1;
291 conn->HighestSequenceRcvd = conn->NextSequenceRcv;
292 conn->NextSequenceSend = rand();
293 conn->LastACKSequence = ntohl( hdr->SequenceNumber );
295 conn->Node.ImplInt = srv->NextID ++;
297 // Hmm... Theoretically, this lock will never have to wait,
298 // as the interface is locked to the watching thread, and this
299 // runs in the watching thread. But, it's a good idea to have
301 // Oh, wait, there is a case where a wildcard can be used
302 // (srv->Interface == NULL) so having the lock is a good idea
303 SHORTLOCK(&srv->lConnections);
305 conn->Prev = srv->ConnectionsTail;
306 if(srv->Connections) {
307 ASSERT(srv->ConnectionsTail);
308 srv->ConnectionsTail->Next = conn;
311 ASSERT(!srv->ConnectionsTail);
312 srv->Connections = conn;
314 srv->ConnectionsTail = conn;
315 if(!srv->NewConnections)
316 srv->NewConnections = conn;
317 VFS_MarkAvaliable( &srv->Node, 1 );
318 SHORTREL(&srv->lConnections);
319 Semaphore_Signal(&srv->WaitingConnections, 1);
322 hdr->Flags |= TCP_FLAG_ACK;
323 hdr->AcknowlegementNumber = htonl(conn->NextSequenceRcv);
324 hdr->SequenceNumber = htonl(conn->NextSequenceSend);
325 hdr->DestPort = hdr->SourcePort;
326 hdr->SourcePort = htons(srv->Port);
327 hdr->DataOffset = (sizeof(tTCPHeader)/4) << 4;
328 TCP_SendPacket( conn, hdr, 0, NULL );
329 conn->NextSequenceSend ++;
333 // Check Open Connections
335 for( tTCPConnection *conn = gTCP_OutbountCons; conn; conn = conn->Next )
337 // Check that it is coming in on the same interface
338 if(conn->Interface != Interface) continue;
341 if(conn->RemotePort != ntohs(hdr->SourcePort)) continue;
344 if(conn->Interface->Type == 6 && !IP6_EQU(conn->RemoteIP.v6, *(tIPv6*)Address))
346 if(conn->Interface->Type == 4 && !IP4_EQU(conn->RemoteIP.v4, *(tIPv4*)Address))
349 TCP_INT_HandleConnectionPacket(conn, hdr, Length);
354 Log_Log("TCP", "TCP_GetPacket: No Match");
355 // If not a RST, send a RST
356 if( !(hdr->Flags & TCP_FLAG_RST) )
358 TCP_int_SendRSTTo(Interface, Address, Length, hdr);
363 * \brief Handles a packet sent to a specific connection
364 * \param Connection TCP Connection pointer
365 * \param Header TCP Packet pointer
366 * \param Length Length of the packet
368 void TCP_INT_HandleConnectionPacket(tTCPConnection *Connection, tTCPHeader *Header, int Length)
373 // Silently drop once finished
374 // TODO: Check if this needs to be here
375 if( Connection->State == TCP_ST_FINISHED ) {
376 Log_Log("TCP", "Packet ignored - connection finnished");
380 // Syncronise sequence values
381 if(Header->Flags & TCP_FLAG_SYN) {
382 // TODO: What if the packet also has data?
383 if( Connection->LastACKSequence != Connection->NextSequenceRcv )
384 TCP_INT_SendACK(Connection, "SYN");
385 Connection->NextSequenceRcv = ntohl(Header->SequenceNumber);
386 // TODO: Process HighestSequenceRcvd
388 if( Connection->HighestSequenceRcvd == 0 )
389 Connection->HighestSequenceRcvd = Connection->NextSequenceRcv;
390 Connection->LastACKSequence = Connection->NextSequenceRcv;
393 // Ackowledge a sent packet
394 if(Header->Flags & TCP_FLAG_ACK) {
395 // TODO: Process an ACKed Packet
396 LOG("Conn %p, Sent packet 0x%x ACKed", Connection, Header->AcknowlegementNumber);
399 // Get length of data
400 dataLen = Length - (Header->DataOffset>>4)*4;
401 LOG("dataLen = %i", dataLen);
403 Log_Debug("TCP", "State %i, dataLen = %x", Connection->State, dataLen);
409 switch( Connection->State )
411 // Pre-init connection?
413 Log_Log("TCP", "Packets to a closed connection?!");
416 // --- Init States ---
417 // SYN sent, expecting SYN-ACK Connection Opening
418 case TCP_ST_SYN_SENT:
419 if( Header->Flags & TCP_FLAG_SYN )
421 if( Connection->HighestSequenceRcvd == Connection->NextSequenceRcv )
422 Connection->HighestSequenceRcvd ++;
423 Connection->NextSequenceRcv ++;
425 if( Header->Flags & TCP_FLAG_ACK )
427 Log_Log("TCP", "ACKing SYN-ACK");
428 Connection->State = TCP_ST_OPEN;
429 VFS_MarkFull(&Connection->Node, 0);
430 TCP_INT_SendACK(Connection, "SYN-ACK");
434 Log_Log("TCP", "ACKing SYN");
435 Connection->State = TCP_ST_SYN_RCVD;
436 TCP_INT_SendACK(Connection, "SYN");
441 // SYN-ACK sent, expecting ACK
442 case TCP_ST_SYN_RCVD:
443 if( Header->Flags & TCP_FLAG_ACK )
445 // TODO: Handle max half-open limit
446 Log_Log("TCP", "Connection fully opened");
447 Connection->State = TCP_ST_OPEN;
448 VFS_MarkFull(&Connection->Node, 0);
452 // --- Established State ---
454 // - Handle State changes
456 if( Header->Flags & TCP_FLAG_FIN ) {
457 Log_Log("TCP", "Conn %p closed, recieved FIN", Connection);
458 VFS_MarkError(&Connection->Node, 1);
459 Connection->NextSequenceRcv ++;
460 TCP_INT_SendACK(Connection, "FIN Received");
461 Connection->State = TCP_ST_CLOSE_WAIT;
462 // CLOSE WAIT requires the client to close
466 // Check for an empty packet
468 if( Header->Flags == TCP_FLAG_ACK )
470 Log_Log("TCP", "ACK only packet");
473 // TODO: Is this right? (empty packet counts as one byte)
474 if( Connection->HighestSequenceRcvd == Connection->NextSequenceRcv )
475 Connection->HighestSequenceRcvd ++;
476 Connection->NextSequenceRcv ++;
477 Log_Log("TCP", "Empty Packet, inc and ACK the current sequence number");
478 TCP_INT_SendACK(Connection, "Empty");
487 sequence_num = ntohl(Header->SequenceNumber);
489 LOG("0x%08x <= 0x%08x < 0x%08x",
490 Connection->NextSequenceRcv,
491 ntohl(Header->SequenceNumber),
492 Connection->NextSequenceRcv + TCP_WINDOW_SIZE
495 // Is this packet the next expected packet?
496 if( sequence_num == Connection->NextSequenceRcv )
499 // Ooh, Goodie! Add it to the recieved list
500 rv = TCP_INT_AppendRecieved(Connection,
501 (Uint8*)Header + (Header->DataOffset>>4)*4,
505 Log_Notice("TCP", "TCP_INT_AppendRecieved rv %i", rv);
508 LOG("0x%08x += %i", Connection->NextSequenceRcv, dataLen);
509 if( Connection->HighestSequenceRcvd == Connection->NextSequenceRcv )
510 Connection->HighestSequenceRcvd += dataLen;
511 Connection->NextSequenceRcv += dataLen;
513 // TODO: This should be moved out of the watcher thread,
514 // so that a single lost packet on one connection doesn't cause
515 // all connections on the interface to lag.
516 // - Meh, no real issue, as the cache shouldn't be that large
517 TCP_INT_UpdateRecievedFromFuture(Connection);
520 // - Only send an ACK if we've had a burst
521 Uint32 bytes_since_last_ack = Connection->NextSequenceRcv - Connection->LastACKSequence;
522 LOG("bytes_since_last_ack = 0x%x", bytes_since_last_ack);
523 if( bytes_since_last_ack > TCP_DACK_THRESHOLD )
525 TCP_INT_SendACK(Connection, "DACK Burst");
526 // - Extend TCP deferred ACK timer
527 Time_RemoveTimer(Connection->DeferredACKTimer);
529 // - Schedule the deferred ACK timer (if already scheduled, this is a NOP)
530 Time_ScheduleTimer(Connection->DeferredACKTimer, TCP_DACK_TIMEOUT);
532 TCP_INT_SendACK(Connection, "RX");
535 // Check if the packet is in window
536 else if( sequence_num - Connection->NextSequenceRcv < TCP_WINDOW_SIZE )
538 Uint8 *dataptr = (Uint8*)Header + (Header->DataOffset>>4)*4;
539 Uint32 index = sequence_num % TCP_WINDOW_SIZE;
540 Uint32 max = Connection->NextSequenceRcv % TCP_WINDOW_SIZE;
541 if( !(Connection->FuturePacketValidBytes[index/8] & (1 << (index%8))) )
542 TCP_INT_SendACK(Connection, "Lost packet");
543 for( int i = 0; i < dataLen; i ++ )
545 Connection->FuturePacketValidBytes[index/8] |= 1 << (index%8);
546 Connection->FuturePacketData[index] = dataptr[i];
547 // Do a wrap increment
549 if(index == TCP_WINDOW_SIZE) index = 0;
550 if(index == max) break;
552 Uint32 rel_highest = Connection->HighestSequenceRcvd - Connection->NextSequenceRcv;
553 Uint32 rel_this = index - Connection->NextSequenceRcv;
554 LOG("Updating highest this(0x%x) > highest(%x)", rel_this, rel_highest);
555 if( rel_this > rel_highest )
557 Connection->HighestSequenceRcvd = index;
560 // Badly out of sequence packet
563 Log_Log("TCP", "Fully out of sequence packet (0x%08x not between 0x%08x and 0x%08x), dropped",
564 sequence_num, Connection->NextSequenceRcv, Connection->NextSequenceRcv+TCP_WINDOW_SIZE);
565 // Spec says we should send an empty ACK with the current state
566 TCP_INT_SendACK(Connection, "Bad Seq");
570 // --- Remote close states
571 case TCP_ST_CLOSE_WAIT:
573 // Ignore everything, CLOSE_WAIT is terminated by the client
574 Log_Debug("TCP", "CLOSE WAIT - Ignoring packets");
578 // LAST-ACK - Waiting for the ACK of FIN (from CLOSE WAIT)
579 case TCP_ST_LAST_ACK:
580 if( Header->Flags & TCP_FLAG_ACK )
582 Connection->State = TCP_ST_FINISHED; // Connection completed
583 Log_Log("TCP", "LAST-ACK to CLOSED - Connection remote closed");
584 TCP_int_FreeTCB(Connection);
588 // --- Local close States
589 case TCP_ST_FIN_WAIT1:
590 if( Header->Flags & TCP_FLAG_FIN )
592 Connection->State = TCP_ST_CLOSING;
593 Log_Debug("TCP", "Conn %p closed, sent FIN and recieved FIN", Connection);
594 VFS_MarkError(&Connection->Node, 1);
596 TCP_INT_SendACK(Connection, "FINWAIT-1 FIN");
600 // TODO: Make sure that the packet is actually ACKing the FIN
601 if( Header->Flags & TCP_FLAG_ACK )
603 Connection->State = TCP_ST_FIN_WAIT2;
604 Log_Debug("TCP", "Conn %p closed, sent FIN ACKed", Connection);
605 VFS_MarkError(&Connection->Node, 1);
610 case TCP_ST_FIN_WAIT2:
611 if( Header->Flags & TCP_FLAG_FIN )
613 Connection->State = TCP_ST_TIME_WAIT;
614 Log_Debug("TCP", "Conn %p FINWAIT-2 -> TIME WAIT", Connection);
615 TCP_INT_SendACK(Connection, "FINWAIT-2 FIN");
620 // TODO: Make sure that the packet is actually ACKing the FIN
621 if( Header->Flags & TCP_FLAG_ACK )
623 Connection->State = TCP_ST_TIME_WAIT;
624 Log_Debug("TCP", "Conn %p CLOSING -> TIME WAIT", Connection);
625 VFS_MarkError(&Connection->Node, 1);
630 // --- Closed (or near closed) states) ---
631 case TCP_ST_TIME_WAIT:
632 Log_Log("TCP", "Packets on Time-Wait, ignored");
635 case TCP_ST_FINISHED:
636 Log_Log("TCP", "Packets when CLOSED, ignoring");
640 // Log_Warning("TCP", "Unhandled TCP state %i", Connection->State);
647 * \brief Appends a packet to the recieved list
648 * \param Connection Connection structure
649 * \param Data Packet contents
650 * \param Length Length of \a Data
652 int TCP_INT_AppendRecieved(tTCPConnection *Connection, const void *Data, size_t Length)
654 Mutex_Acquire( &Connection->lRecievedPackets );
656 if(Connection->RecievedBuffer->Length + Length > Connection->RecievedBuffer->Space )
658 VFS_MarkAvaliable(&Connection->Node, 1);
659 Log_Error("TCP", "Buffer filled, packet dropped (:%i) - %i + %i > %i",
660 Connection->LocalPort, Connection->RecievedBuffer->Length, Length,
661 Connection->RecievedBuffer->Space
663 Mutex_Release( &Connection->lRecievedPackets );
667 RingBuffer_Write( Connection->RecievedBuffer, Data, Length );
669 VFS_MarkAvaliable(&Connection->Node, 1);
671 Mutex_Release( &Connection->lRecievedPackets );
676 * \brief Updates the connections recieved list from the future list
677 * \param Connection Connection structure
679 * Updates the recieved packets list with packets from the future (out
680 * of order) packets list that are now able to be added in direct
683 void TCP_INT_UpdateRecievedFromFuture(tTCPConnection *Connection)
685 // Calculate length of contiguous bytes
686 const int length = Connection->HighestSequenceRcvd - Connection->NextSequenceRcv;
687 Uint32 index = Connection->NextSequenceRcv % TCP_WINDOW_SIZE;
688 size_t runlength = length;
689 LOG("length=%i, index=0x%x", length, index);
690 for( int i = 0; i < length; i ++ )
693 Uint8 bitfield_byte = Connection->FuturePacketValidBytes[index / 8];
694 if( (bitfield_byte & (1 << bit)) == 0 ) {
696 LOG("Hit missing, break");
700 if( bitfield_byte == 0xFF ) {
708 if(index > TCP_WINDOW_SIZE)
709 index -= TCP_WINDOW_SIZE;
712 index = Connection->NextSequenceRcv % TCP_WINDOW_SIZE;
713 Connection->NextSequenceRcv += runlength;
715 // Write data to to the ring buffer
716 if( TCP_WINDOW_SIZE - index > runlength )
719 RingBuffer_Write( Connection->RecievedBuffer, Connection->FuturePacketData + index, runlength );
723 int endLen = TCP_WINDOW_SIZE - index;
725 RingBuffer_Write( Connection->RecievedBuffer, Connection->FuturePacketData + index, endLen );
726 RingBuffer_Write( Connection->RecievedBuffer, Connection->FuturePacketData, endLen - runlength );
729 // Mark (now saved) bytes as invalid
731 while(index % 8 && runlength > 0)
733 Connection->FuturePacketData[index] = 0;
734 Connection->FuturePacketValidBytes[index/8] &= ~(1 << (index%8));
736 if(index > TCP_WINDOW_SIZE)
737 index -= TCP_WINDOW_SIZE;
740 while( runlength > 7 )
742 Connection->FuturePacketData[index] = 0;
743 Connection->FuturePacketValidBytes[index/8] = 0;
746 if(index > TCP_WINDOW_SIZE)
747 index -= TCP_WINDOW_SIZE;
749 while( runlength > 0)
751 Connection->FuturePacketData[index] = 0;
752 Connection->FuturePacketData[index/8] &= ~(1 << (index%8));
754 if(index > TCP_WINDOW_SIZE)
755 index -= TCP_WINDOW_SIZE;
760 void TCP_int_SendDelayedACK(void *ConnPtr)
762 TCP_INT_SendACK(ConnPtr, "DACK Timeout");
765 void TCP_INT_SendACK(tTCPConnection *Connection, const char *Reason)
769 hdr.DataOffset = (sizeof(tTCPHeader)/4) << 4;
770 hdr.DestPort = htons(Connection->RemotePort);
771 hdr.SourcePort = htons(Connection->LocalPort);
772 hdr.AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
773 hdr.SequenceNumber = htonl(Connection->NextSequenceSend);
774 hdr.WindowSize = htons(TCP_WINDOW_SIZE);
775 hdr.Flags = TCP_FLAG_ACK; // TODO: Determine if SYN is wanted too
776 hdr.Checksum = 0; // TODO: Checksum
777 hdr.UrgentPointer = 0;
778 Log_Debug("TCP", "Sending ACK for 0x%08x (%s)", Connection->NextSequenceRcv, Reason);
779 TCP_SendPacket( Connection, &hdr, 0, NULL );
780 //Connection->NextSequenceSend ++;
781 Connection->LastACKSequence = Connection->NextSequenceRcv;
785 * \fn Uint16 TCP_GetUnusedPort()
786 * \brief Gets an unused port and allocates it
788 Uint16 TCP_GetUnusedPort()
792 // Get Next outbound port
793 ret = giTCP_NextOutPort++;
794 while( gaTCP_PortBitmap[ret/32] & (1UL << (ret%32)) )
798 if(giTCP_NextOutPort == 0x10000) {
799 ret = giTCP_NextOutPort = TCP_MIN_DYNPORT;
803 // Mark the new port as used
804 gaTCP_PortBitmap[ret/32] |= 1 << (ret%32);
810 * \fn int TCP_AllocatePort(Uint16 Port)
811 * \brief Marks a port as used
813 int TCP_AllocatePort(Uint16 Port)
815 // Check if the port has already been allocated
816 if( gaTCP_PortBitmap[Port/32] & (1 << (Port%32)) )
820 gaTCP_PortBitmap[Port/32] |= 1 << (Port%32);
826 * \fn int TCP_DeallocatePort(Uint16 Port)
827 * \brief Marks a port as unused
829 int TCP_DeallocatePort(Uint16 Port)
831 // Check if the port has already been allocated
832 if( !(gaTCP_PortBitmap[Port/32] & (1 << (Port%32))) )
836 gaTCP_PortBitmap[Port/32] &= ~(1 << (Port%32));
841 tTCPConnection *TCP_int_CreateConnection(tInterface *Interface, enum eTCPConnectionState State)
843 tTCPConnection *conn = calloc( sizeof(tTCPConnection) + TCP_WINDOW_SIZE + TCP_WINDOW_SIZE/8, 1 );
846 conn->Interface = Interface;
847 conn->LocalPort = -1;
848 conn->RemotePort = -1;
850 conn->Node.ReferenceCount = 1;
851 conn->Node.ImplPtr = conn;
852 conn->Node.NumACLs = 1;
853 conn->Node.ACLs = &gVFS_ACL_EveryoneRW;
854 conn->Node.Type = &gTCP_ClientNodeType;
855 conn->Node.BufferFull = 1; // Cleared when connection opens
857 conn->RecievedBuffer = RingBuffer_Create( TCP_RECIEVE_BUFFER_SIZE );
859 conn->SentBuffer = RingBuffer_Create( TCP_SEND_BUFFER_SIZE );
860 Semaphore_Init(conn->SentBufferSpace, 0, TCP_SEND_BUFFER_SIZE, "TCP SentBuffer", conn->Name);
863 #if CACHE_FUTURE_PACKETS_IN_BYTES
864 // Future recieved data (ahead of the expected sequence number)
865 conn->FuturePacketData = (Uint8*)conn + sizeof(tTCPConnection);
866 conn->FuturePacketValidBytes = conn->FuturePacketData + TCP_WINDOW_SIZE;
869 conn->DeferredACKTimer = Time_AllocateTimer( TCP_int_SendDelayedACK, conn);
873 void TCP_int_FreeTCB(tTCPConnection *Connection)
875 ASSERTC(Connection->State, ==, TCP_ST_FINISHED);
876 ASSERTC(Connection->Node.ReferenceCount, ==, 0);
878 if( Connection->Server )
880 tTCPListener *srv = Connection->Server;
881 SHORTLOCK(&srv->lConnections);
883 Connection->Prev->Next = Connection->Next;
885 srv->Connections = Connection->Next;
887 Connection->Next->Prev = Connection->Prev;
889 ASSERT(srv->ConnectionsTail == Connection);
890 srv->ConnectionsTail = Connection->Prev;
892 SHORTREL(&srv->lConnections);
896 SHORTLOCK(&glTCP_OutbountCons);
898 Connection->Prev->Next = Connection->Next;
900 gTCP_OutbountCons = Connection->Next;
902 Connection->Next->Prev = Connection->Prev;
905 SHORTREL(&glTCP_OutbountCons);
908 RingBuffer_Free(Connection->RecievedBuffer);
909 Time_FreeTimer(Connection->DeferredACKTimer);
910 // TODO: Force VFS to close handles? (they should all be closed);
915 tVFS_Node *TCP_Server_Init(tInterface *Interface)
919 srv = calloc( 1, sizeof(tTCPListener) );
922 Log_Warning("TCP", "malloc failed for listener (%i) bytes", sizeof(tTCPListener));
926 srv->Interface = Interface;
929 srv->Connections = NULL;
930 srv->ConnectionsTail = NULL;
931 srv->NewConnections = NULL;
933 srv->Node.Flags = VFS_FFLAG_DIRECTORY;
935 srv->Node.ImplPtr = srv;
936 srv->Node.NumACLs = 1;
937 srv->Node.ACLs = &gVFS_ACL_EveryoneRW;
938 srv->Node.Type = &gTCP_ServerNodeType;
940 SHORTLOCK(&glTCP_Listeners);
941 srv->Next = gTCP_Listeners;
942 gTCP_Listeners = srv;
943 SHORTREL(&glTCP_Listeners);
949 * \brief Wait for a new connection and return the connection ID
950 * \note Blocks until a new connection is made
951 * \param Node Server node
952 * \param Pos Position (ignored)
954 int TCP_Server_ReadDir(tVFS_Node *Node, int Pos, char Dest[FILENAME_MAX])
956 tTCPListener *srv = Node->ImplPtr;
957 tTCPConnection *conn;
959 ENTER("pNode iPos", Node, Pos);
961 Log_Log("TCP", "Thread %i waiting for a connection", Threads_GetTID());
962 Semaphore_Wait( &srv->WaitingConnections, 1 );
964 SHORTLOCK(&srv->lConnections);
965 // Increment the new list (the current connection is still on the
967 conn = srv->NewConnections;
968 srv->NewConnections = conn->Next;
970 if( srv->NewConnections == NULL )
971 VFS_MarkAvaliable( Node, 0 );
973 SHORTREL( &srv->lConnections );
975 LOG("conn = %p", conn);
976 LOG("srv->Connections = %p", srv->Connections);
977 LOG("srv->NewConnections = %p", srv->NewConnections);
978 LOG("srv->ConnectionsTail = %p", srv->ConnectionsTail);
980 itoa(Dest, conn->Node.ImplInt, 16, 8, '0');
981 Log_Log("TCP", "Thread %i got connection '%s'", Threads_GetTID(), Dest);
987 * \brief Gets a client connection node
988 * \param Node Server node
989 * \param Name Hexadecimal ID of the node
991 tVFS_Node *TCP_Server_FindDir(tVFS_Node *Node, const char *Name, Uint Flags)
993 tTCPConnection *conn;
994 tTCPListener *srv = Node->ImplPtr;
998 ENTER("pNode sName", Node, Name);
1000 // Check for a non-empty name
1004 itoa(tmp, id, 16, 8, '0');
1005 if(strcmp(tmp, Name) != 0) {
1006 LOG("'%s' != '%s' (%08x)", Name, tmp, id);
1011 Log_Debug("TCP", "srv->Connections = %p", srv->Connections);
1012 Log_Debug("TCP", "srv->NewConnections = %p", srv->NewConnections);
1013 Log_Debug("TCP", "srv->ConnectionsTail = %p", srv->ConnectionsTail);
1016 SHORTLOCK( &srv->lConnections );
1017 for(conn = srv->Connections;
1021 LOG("conn->Node.ImplInt = %i", conn->Node.ImplInt);
1022 if(conn->Node.ImplInt == id) break;
1024 SHORTREL( &srv->lConnections );
1026 // If not found, ret NULL
1028 LOG("Connection %i not found", id);
1033 // Empty Name - Check for a new connection and if it's there, open it
1036 SHORTLOCK( &srv->lConnections );
1037 conn = srv->NewConnections;
1039 srv->NewConnections = conn->Next;
1040 VFS_MarkAvaliable( Node, srv->NewConnections != NULL );
1041 SHORTREL( &srv->lConnections );
1043 LOG("No new connections");
1050 LEAVE('p', &conn->Node);
1055 * \brief Handle IOCtl calls
1057 int TCP_Server_IOCtl(tVFS_Node *Node, int ID, void *Data)
1059 tTCPListener *srv = Node->ImplPtr;
1063 case 4: // Get/Set Port
1064 if(!Data) // Get Port
1067 if(srv->Port) // Wait, you can't CHANGE the port
1070 if(!CheckMem(Data, sizeof(Uint16))) // Sanity check
1073 // Permissions check
1074 if(Threads_GetUID() != 0
1075 && *(Uint16*)Data != 0
1076 && *(Uint16*)Data < 1024)
1079 // TODO: Check if a port is in use
1082 srv->Port = *(Uint16*)Data;
1083 if(srv->Port == 0) // Allocate a random port
1084 srv->Port = TCP_GetUnusedPort();
1085 else // Else, mark this as used
1086 TCP_AllocatePort(srv->Port);
1088 Log_Log("TCP", "Server %p listening on port %i", srv, srv->Port);
1095 void TCP_Server_Close(tVFS_Node *Node)
1097 free(Node->ImplPtr);
1102 * \brief Create a client node
1104 tVFS_Node *TCP_Client_Init(tInterface *Interface)
1106 tTCPConnection *conn = TCP_int_CreateConnection(Interface, TCP_ST_CLOSED);
1108 SHORTLOCK(&glTCP_OutbountCons);
1109 conn->Server = NULL;
1111 conn->Next = gTCP_OutbountCons;
1112 gTCP_OutbountCons->Prev = conn;
1113 gTCP_OutbountCons = conn;
1114 SHORTREL(&glTCP_OutbountCons);
1120 * \brief Wait for a packet and return it
1121 * \note If \a Length is smaller than the size of the packet, the rest
1122 * of the packet's data will be discarded.
1124 size_t TCP_Client_Read(tVFS_Node *Node, off_t Offset, size_t Length, void *Buffer, Uint Flags)
1126 tTCPConnection *conn = Node->ImplPtr;
1129 ENTER("pNode XOffset XLength pBuffer", Node, Offset, Length, Buffer);
1130 LOG("conn = %p {State:%i}", conn, conn->State);
1132 // If the connection has been closed (state > ST_OPEN) then clear
1133 // any stale data in the buffer (until it is empty (until it is empty))
1134 if( conn->State > TCP_ST_OPEN )
1136 Mutex_Acquire( &conn->lRecievedPackets );
1137 len = RingBuffer_Read( Buffer, conn->RecievedBuffer, Length );
1138 Mutex_Release( &conn->lRecievedPackets );
1141 VFS_MarkAvaliable(Node, 0);
1153 tTime *timeout = NULL;
1154 tTime timeout_zero = 0;
1155 if( Flags & VFS_IOFLAG_NOBLOCK )
1156 timeout = &timeout_zero;
1157 if( !VFS_SelectNode(Node, VFS_SELECT_READ|VFS_SELECT_ERROR, timeout, "TCP_Client_Read") ) {
1158 errno = EWOULDBLOCK;
1164 // Lock list and read as much as possible (up to `Length`)
1165 Mutex_Acquire( &conn->lRecievedPackets );
1166 len = RingBuffer_Read( Buffer, conn->RecievedBuffer, Length );
1168 if( len == 0 || conn->RecievedBuffer->Length == 0 ) {
1169 LOG("Marking as none avaliable (len = %i)", len);
1170 VFS_MarkAvaliable(Node, 0);
1173 // Release the lock (we don't need it any more)
1174 Mutex_Release( &conn->lRecievedPackets );
1181 * \brief Send a data packet on a connection
1183 void TCP_INT_SendDataPacket(tTCPConnection *Connection, size_t Length, const void *Data)
1185 char buf[sizeof(tTCPHeader)+Length];
1186 tTCPHeader *packet = (void*)buf;
1188 // - Stop Delayed ACK timer (as this data packet ACKs)
1189 Time_RemoveTimer(Connection->DeferredACKTimer);
1191 // TODO: Don't exceed window size
1193 packet->SourcePort = htons(Connection->LocalPort);
1194 packet->DestPort = htons(Connection->RemotePort);
1195 packet->DataOffset = (sizeof(tTCPHeader)/4)*16;
1196 packet->WindowSize = htons(TCP_WINDOW_SIZE);
1198 packet->AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
1199 packet->SequenceNumber = htonl(Connection->NextSequenceSend);
1200 packet->Flags = TCP_FLAG_PSH|TCP_FLAG_ACK; // Hey, ACK if you can!
1201 packet->UrgentPointer = 0;
1203 memcpy(packet->Options, Data, Length);
1205 Log_Debug("TCP", "Send sequence 0x%08x", Connection->NextSequenceSend);
1206 #if HEXDUMP_OUTGOING
1207 Debug_HexDump("TCP_INT_SendDataPacket: Data = ", Data, Length);
1210 TCP_SendPacket( Connection, packet, Length, Data );
1212 Connection->NextSequenceSend += Length;
1216 * \brief Send some bytes on a connection
1218 size_t TCP_Client_Write(tVFS_Node *Node, off_t Offset, size_t Length, const void *Buffer, Uint Flags)
1220 tTCPConnection *conn = Node->ImplPtr;
1221 size_t rem = Length;
1223 ENTER("pNode XOffset XLength pBuffer", Node, Offset, Length, Buffer);
1226 // Debug_HexDump("TCP_Client_Write: Buffer = ",
1230 // Don't allow a write to a closed connection
1231 if( conn->State > TCP_ST_OPEN ) {
1232 VFS_MarkError(Node, 1);
1240 tTime *timeout = NULL;
1241 tTime timeout_zero = 0;
1242 if( Flags & VFS_IOFLAG_NOBLOCK )
1243 timeout = &timeout_zero;
1244 if( !VFS_SelectNode(Node, VFS_SELECT_WRITE|VFS_SELECT_ERROR, timeout, "TCP_Client_Write") ) {
1245 errno = EWOULDBLOCK;
1253 int len = (rem < TCP_MAX_PACKET_SIZE) ? rem : TCP_MAX_PACKET_SIZE;
1256 // Wait for space in the buffer
1257 Semaphore_Signal( &Connection->SentBufferSpace, len );
1259 // Save data to buffer (and update the length read by the ammount written)
1260 len = RingBuffer_Write( &Connection->SentBuffer, Buffer, len);
1264 TCP_INT_SendDataPacket(conn, len, Buffer);
1275 * \brief Open a connection to another host using TCP
1276 * \param Conn Connection structure
1278 void TCP_StartConnection(tTCPConnection *Conn)
1280 tTCPHeader hdr = {0};
1282 Conn->State = TCP_ST_SYN_SENT;
1284 hdr.SourcePort = htons(Conn->LocalPort);
1285 hdr.DestPort = htons(Conn->RemotePort);
1286 Conn->NextSequenceSend = rand();
1287 hdr.SequenceNumber = htonl(Conn->NextSequenceSend);
1288 hdr.DataOffset = (sizeof(tTCPHeader)/4) << 4;
1289 hdr.Flags = TCP_FLAG_SYN;
1290 hdr.WindowSize = htons(TCP_WINDOW_SIZE); // Max
1291 hdr.Checksum = 0; // TODO
1293 TCP_SendPacket( Conn, &hdr, 0, NULL );
1295 Conn->NextSequenceSend ++;
1296 Conn->State = TCP_ST_SYN_SENT;
1302 * \brief Control a client socket
1304 int TCP_Client_IOCtl(tVFS_Node *Node, int ID, void *Data)
1306 tTCPConnection *conn = Node->ImplPtr;
1308 ENTER("pNode iID pData", Node, ID, Data);
1312 case 4: // Get/Set local port
1314 LEAVE_RET('i', conn->LocalPort);
1315 if(conn->State != TCP_ST_CLOSED)
1317 if(!CheckMem(Data, sizeof(Uint16)))
1320 if(Threads_GetUID() != 0 && *(Uint16*)Data < 1024)
1323 conn->LocalPort = *(Uint16*)Data;
1324 LEAVE_RET('i', conn->LocalPort);
1326 case 5: // Get/Set remote port
1327 if(!Data) LEAVE_RET('i', conn->RemotePort);
1328 if(conn->State != TCP_ST_CLOSED) LEAVE_RET('i', -1);
1329 if(!CheckMem(Data, sizeof(Uint16))) LEAVE_RET('i', -1);
1330 conn->RemotePort = *(Uint16*)Data;
1331 LEAVE_RET('i', conn->RemotePort);
1333 case 6: // Set Remote IP
1334 if( conn->State != TCP_ST_CLOSED )
1336 if( conn->Interface->Type == 4 )
1338 if(!CheckMem(Data, sizeof(tIPv4))) LEAVE_RET('i', -1);
1339 conn->RemoteIP.v4 = *(tIPv4*)Data;
1341 else if( conn->Interface->Type == 6 )
1343 if(!CheckMem(Data, sizeof(tIPv6))) LEAVE_RET('i', -1);
1344 conn->RemoteIP.v6 = *(tIPv6*)Data;
1349 if(conn->LocalPort == 0xFFFF)
1350 conn->LocalPort = TCP_GetUnusedPort();
1351 if(conn->RemotePort == -1)
1355 tTime timeout = conn->Interface->TimeoutDelay;
1357 TCP_StartConnection(conn);
1358 VFS_SelectNode(&conn->Node, VFS_SELECT_WRITE, &timeout, "TCP Connection");
1359 if( conn->State == TCP_ST_SYN_SENT )
1365 // Get recieve buffer length
1367 LEAVE_RET('i', conn->RecievedBuffer->Length);
1373 void TCP_Client_Close(tVFS_Node *Node)
1375 tTCPConnection *conn = Node->ImplPtr;
1378 ENTER("pNode", Node);
1380 ASSERT(Node->ReferenceCount != 0);
1382 if( Node->ReferenceCount > 1 ) {
1383 Node->ReferenceCount --;
1384 LOG("Dereference only");
1388 Node->ReferenceCount --;
1390 if( conn->State == TCP_ST_CLOSE_WAIT || conn->State == TCP_ST_OPEN )
1392 packet.SourcePort = htons(conn->LocalPort);
1393 packet.DestPort = htons(conn->RemotePort);
1394 packet.DataOffset = (sizeof(tTCPHeader)/4)*16;
1395 packet.WindowSize = TCP_WINDOW_SIZE;
1397 packet.AcknowlegementNumber = 0;
1398 packet.SequenceNumber = htonl(conn->NextSequenceSend);
1399 packet.Flags = TCP_FLAG_FIN;
1401 TCP_SendPacket( conn, &packet, 0, NULL );
1404 Time_RemoveTimer(conn->DeferredACKTimer);
1406 switch( conn->State )
1409 Log_Warning("TCP", "Closing connection that was never opened");
1410 TCP_int_FreeTCB(conn);
1412 case TCP_ST_CLOSE_WAIT:
1413 conn->State = TCP_ST_LAST_ACK;
1416 conn->State = TCP_ST_FIN_WAIT1;
1417 while( conn->State == TCP_ST_FIN_WAIT1 )
1419 // No free, freed after TIME_WAIT
1422 Log_Warning("TCP", "Unhandled connection state %i in TCP_Client_Close",
1431 * \brief Checks if a value is between two others (after taking into account wrapping)
1433 int WrapBetween(Uint32 Lower, Uint32 Value, Uint32 Higher, Uint32 MaxValue)
1435 if( MaxValue < 0xFFFFFFFF )
1437 Lower %= MaxValue + 1;
1438 Value %= MaxValue + 1;
1439 Higher %= MaxValue + 1;
1442 // Simple Case, no wrap ?
1443 // Lower Value Higher
1444 // | ... + ... + ... + ... |
1446 if( Lower < Higher ) {
1447 return Lower < Value && Value < Higher;
1449 // Higher has wrapped below lower
1452 // Higher Lower Value
1453 // | ... + ... + ... + ... |
1454 if( Value > Lower ) {
1459 // Value Higher Lower
1460 // | ... + ... + ... + ... |
1461 if( Value < Higher ) {
1467 Uint32 GetRelative(Uint32 Base, Uint32 Value)
1470 return Value - Base + 0xFFFFFFFF;
1472 return Value - Base;