12 #define HEXDUMP_INCOMING 0
13 #define HEXDUMP_OUTGOING 0
14 #define CACHE_FUTURE_PACKETS_IN_BYTES 1 // Use a ring buffer to cache out of order packets
16 #define TCP_MIN_DYNPORT 0xC000
17 #define TCP_MAX_HALFOPEN 1024 // Should be enough
19 #define TCP_MAX_PACKET_SIZE 1024
20 #define TCP_WINDOW_SIZE 0x2000
21 #define TCP_RECIEVE_BUFFER_SIZE 0x4000
24 void TCP_Initialise(void);
25 void TCP_StartConnection(tTCPConnection *Conn);
26 void TCP_SendPacket(tTCPConnection *Conn, tTCPHeader *Header, size_t DataLen, const void *Data);
27 void TCP_GetPacket(tInterface *Interface, void *Address, int Length, void *Buffer);
28 void TCP_INT_HandleConnectionPacket(tTCPConnection *Connection, tTCPHeader *Header, int Length);
29 int TCP_INT_AppendRecieved(tTCPConnection *Connection, const void *Data, size_t Length);
30 void TCP_INT_UpdateRecievedFromFuture(tTCPConnection *Connection);
31 Uint16 TCP_GetUnusedPort();
32 int TCP_AllocatePort(Uint16 Port);
33 int TCP_DeallocatePort(Uint16 Port);
35 tVFS_Node *TCP_Server_Init(tInterface *Interface);
36 char *TCP_Server_ReadDir(tVFS_Node *Node, int Pos);
37 tVFS_Node *TCP_Server_FindDir(tVFS_Node *Node, const char *Name);
38 int TCP_Server_IOCtl(tVFS_Node *Node, int ID, void *Data);
39 void TCP_Server_Close(tVFS_Node *Node);
41 tVFS_Node *TCP_Client_Init(tInterface *Interface);
42 size_t TCP_Client_Read(tVFS_Node *Node, off_t Offset, size_t Length, void *Buffer);
43 size_t TCP_Client_Write(tVFS_Node *Node, off_t Offset, size_t Length, const void *Buffer);
44 int TCP_Client_IOCtl(tVFS_Node *Node, int ID, void *Data);
45 void TCP_Client_Close(tVFS_Node *Node);
47 int WrapBetween(Uint32 Lower, Uint32 Value, Uint32 Higher, Uint32 MaxValue);
50 tSocketFile gTCP_ServerFile = {NULL, "tcps", TCP_Server_Init};
51 tSocketFile gTCP_ClientFile = {NULL, "tcpc", TCP_Client_Init};
52 tVFS_NodeType gTCP_ServerNodeType = {
53 .TypeName = "TCP Server",
54 .ReadDir = TCP_Server_ReadDir,
55 .FindDir = TCP_Server_FindDir,
56 .IOCtl = TCP_Server_IOCtl,
57 .Close = TCP_Server_Close
59 tVFS_NodeType gTCP_ClientNodeType = {
60 .TypeName = "TCP Client/Connection",
61 .Read = TCP_Client_Read,
62 .Write = TCP_Client_Write,
63 .IOCtl = TCP_Client_IOCtl,
64 .Close = TCP_Client_Close
68 int giTCP_NumHalfopen = 0;
69 tShortSpinlock glTCP_Listeners;
70 tTCPListener *gTCP_Listeners;
71 tShortSpinlock glTCP_OutbountCons;
72 tTCPConnection *gTCP_OutbountCons;
73 Uint32 gaTCP_PortBitmap[0x800];
74 int giTCP_NextOutPort = TCP_MIN_DYNPORT;
78 * \brief Initialise the TCP Layer
80 * Registers the client and server files and the GetPacket callback
82 void TCP_Initialise(void)
84 giTCP_NextOutPort += rand()%32;
85 IPStack_AddFile(&gTCP_ServerFile);
86 IPStack_AddFile(&gTCP_ClientFile);
87 IPv4_RegisterCallback(IP4PROT_TCP, TCP_GetPacket);
88 IPv6_RegisterCallback(IP4PROT_TCP, TCP_GetPacket);
92 * \brief Sends a packet from the specified connection, calculating the checksums
93 * \param Conn Connection
94 * \param Length Length of data
95 * \param Data Packet data (cast as a TCP Header)
97 void TCP_SendPacket( tTCPConnection *Conn, tTCPHeader *Header, size_t Length, const void *Data )
99 tIPStackBuffer *buffer;
101 int packlen = sizeof(*Header) + Length;
103 buffer = IPStack_Buffer_CreateBuffer(2 + IPV4_BUFFERS);
105 IPStack_Buffer_AppendSubBuffer(buffer, Length, 0, Data, NULL, NULL);
106 IPStack_Buffer_AppendSubBuffer(buffer, sizeof(*Header), 0, Header, NULL, NULL);
108 Log_Debug("TCP", "Sending %i+%i to %s:%i", sizeof(*Header), Length,
109 IPStack_PrintAddress(Conn->Interface->Type, &Conn->RemoteIP),
113 Header->Checksum = 0;
114 checksum[1] = htons( ~IPv4_Checksum(Header, sizeof(tTCPHeader)) );
115 checksum[2] = htons( ~IPv4_Checksum(Data, Length) );
117 // TODO: Fragment packet
119 switch( Conn->Interface->Type )
122 // Get IPv4 pseudo-header checksum
125 buf[0] = ((tIPv4*)Conn->Interface->Address)->L;
126 buf[1] = Conn->RemoteIP.v4.L;
127 buf[2] = (htons(packlen)<<16) | (6<<8) | 0;
128 checksum[0] = htons( ~IPv4_Checksum(buf, sizeof(buf)) ); // Partial checksum
130 // - Combine checksums
131 Header->Checksum = htons( IPv4_Checksum(checksum, sizeof(checksum)) );
132 IPv4_SendPacket(Conn->Interface, Conn->RemoteIP.v4, IP4PROT_TCP, 0, buffer);
136 // Append IPv6 Pseudo Header
139 memcpy(buf, Conn->Interface->Address, 16);
140 memcpy(&buf[4], &Conn->RemoteIP, 16);
141 buf[8] = htonl(packlen);
143 checksum[0] = htons( ~IPv4_Checksum(buf, sizeof(buf)) ); // Partial checksum
145 Header->Checksum = htons( IPv4_Checksum(checksum, sizeof(checksum)) ); // Combine the two
146 IPv6_SendPacket(Conn->Interface, Conn->RemoteIP.v6, IP4PROT_TCP, Length, Data);
152 * \brief Handles a packet from the IP Layer
153 * \param Interface Interface the packet arrived from
154 * \param Address Pointer to the addres structure
155 * \param Length Size of packet in bytes
156 * \param Buffer Packet data
158 void TCP_GetPacket(tInterface *Interface, void *Address, int Length, void *Buffer)
160 tTCPHeader *hdr = Buffer;
162 tTCPConnection *conn;
164 Log_Log("TCP", "TCP_GetPacket: <Local>:%i from [%s]:%i, Flags= %s%s%s%s%s%s%s%s",
165 ntohs(hdr->DestPort),
166 IPStack_PrintAddress(Interface->Type, Address),
167 ntohs(hdr->SourcePort),
168 (hdr->Flags & TCP_FLAG_CWR) ? "CWR " : "",
169 (hdr->Flags & TCP_FLAG_ECE) ? "ECE " : "",
170 (hdr->Flags & TCP_FLAG_URG) ? "URG " : "",
171 (hdr->Flags & TCP_FLAG_ACK) ? "ACK " : "",
172 (hdr->Flags & TCP_FLAG_PSH) ? "PSH " : "",
173 (hdr->Flags & TCP_FLAG_RST) ? "RST " : "",
174 (hdr->Flags & TCP_FLAG_SYN) ? "SYN " : "",
175 (hdr->Flags & TCP_FLAG_FIN) ? "FIN " : ""
178 if( Length > (hdr->DataOffset >> 4)*4 )
180 Log_Log("TCP", "TCP_GetPacket: SequenceNumber = 0x%x", ntohl(hdr->SequenceNumber));
183 "TCP_GetPacket: Packet Data = ",
184 (Uint8*)hdr + (hdr->DataOffset >> 4)*4,
185 Length - (hdr->DataOffset >> 4)*4
191 for( srv = gTCP_Listeners; srv; srv = srv->Next )
193 // Check if the server is active
194 if(srv->Port == 0) continue;
195 // Check the interface
196 if(srv->Interface && srv->Interface != Interface) continue;
197 // Check the destination port
198 if(srv->Port != htons(hdr->DestPort)) continue;
200 Log_Log("TCP", "TCP_GetPacket: Matches server %p", srv);
201 // Is this in an established connection?
202 for( conn = srv->Connections; conn; conn = conn->Next )
204 // Check that it is coming in on the same interface
205 if(conn->Interface != Interface) continue;
208 Log_Log("TCP", "TCP_GetPacket: conn->RemotePort(%i) == hdr->SourcePort(%i)",
209 conn->RemotePort, ntohs(hdr->SourcePort));
210 if(conn->RemotePort != ntohs(hdr->SourcePort)) continue;
213 Log_Debug("TCP", "TCP_GetPacket: conn->RemoteIP(%s)",
214 IPStack_PrintAddress(conn->Interface->Type, &conn->RemoteIP));
215 Log_Debug("TCP", " == Address(%s)",
216 IPStack_PrintAddress(conn->Interface->Type, Address));
217 if( IPStack_CompareAddress(conn->Interface->Type, &conn->RemoteIP, Address, -1) == 0 )
220 Log_Log("TCP", "TCP_GetPacket: Matches connection %p", conn);
221 // We have a response!
222 TCP_INT_HandleConnectionPacket(conn, hdr, Length);
227 Log_Log("TCP", "TCP_GetPacket: Opening Connection");
228 // Open a new connection (well, check that it's a SYN)
229 if(hdr->Flags != TCP_FLAG_SYN) {
230 Log_Log("TCP", "TCP_GetPacket: Packet is not a SYN");
234 // TODO: Check for halfopen max
236 conn = calloc(1, sizeof(tTCPConnection));
237 conn->State = TCP_ST_SYN_RCVD;
238 conn->LocalPort = srv->Port;
239 conn->RemotePort = ntohs(hdr->SourcePort);
240 conn->Interface = Interface;
242 switch(Interface->Type)
244 case 4: conn->RemoteIP.v4 = *(tIPv4*)Address; break;
245 case 6: conn->RemoteIP.v6 = *(tIPv6*)Address; break;
248 conn->RecievedBuffer = RingBuffer_Create( TCP_RECIEVE_BUFFER_SIZE );
250 conn->NextSequenceRcv = ntohl( hdr->SequenceNumber ) + 1;
251 conn->NextSequenceSend = rand();
254 conn->Node.NumACLs = 1;
255 conn->Node.ACLs = &gVFS_ACL_EveryoneRW;
256 conn->Node.ImplPtr = conn;
257 conn->Node.ImplInt = srv->NextID ++;
258 conn->Node.Type = &gTCP_ClientNodeType; // TODO: Special type for the server end?
260 // Hmm... Theoretically, this lock will never have to wait,
261 // as the interface is locked to the watching thread, and this
262 // runs in the watching thread. But, it's a good idea to have
264 // Oh, wait, there is a case where a wildcard can be used
265 // (srv->Interface == NULL) so having the lock is a good idea
266 SHORTLOCK(&srv->lConnections);
267 if( !srv->Connections )
268 srv->Connections = conn;
270 srv->ConnectionsTail->Next = conn;
271 srv->ConnectionsTail = conn;
272 if(!srv->NewConnections)
273 srv->NewConnections = conn;
274 VFS_MarkAvaliable( &srv->Node, 1 );
275 SHORTREL(&srv->lConnections);
278 hdr->Flags |= TCP_FLAG_ACK;
279 hdr->AcknowlegementNumber = htonl(conn->NextSequenceRcv);
280 hdr->SequenceNumber = htonl(conn->NextSequenceSend);
281 hdr->DestPort = hdr->SourcePort;
282 hdr->SourcePort = htons(srv->Port);
283 hdr->DataOffset = (sizeof(tTCPHeader)/4) << 4;
284 TCP_SendPacket( conn, hdr, 0, NULL );
285 conn->NextSequenceSend ++;
289 // Check Open Connections
291 for( conn = gTCP_OutbountCons; conn; conn = conn->Next )
293 // Check that it is coming in on the same interface
294 if(conn->Interface != Interface) continue;
297 if(conn->RemotePort != ntohs(hdr->SourcePort)) continue;
300 if(conn->Interface->Type == 6 && !IP6_EQU(conn->RemoteIP.v6, *(tIPv6*)Address))
302 if(conn->Interface->Type == 4 && !IP4_EQU(conn->RemoteIP.v4, *(tIPv4*)Address))
305 TCP_INT_HandleConnectionPacket(conn, hdr, Length);
310 Log_Log("TCP", "TCP_GetPacket: No Match");
314 * \brief Handles a packet sent to a specific connection
315 * \param Connection TCP Connection pointer
316 * \param Header TCP Packet pointer
317 * \param Length Length of the packet
319 void TCP_INT_HandleConnectionPacket(tTCPConnection *Connection, tTCPHeader *Header, int Length)
324 // Silently drop once finished
325 // TODO: Check if this needs to be here
326 if( Connection->State == TCP_ST_FINISHED ) {
327 Log_Log("TCP", "Packet ignored - connection finnished");
331 // Syncronise sequence values
332 if(Header->Flags & TCP_FLAG_SYN) {
333 // TODO: What if the packet also has data?
334 Connection->NextSequenceRcv = ntohl(Header->SequenceNumber);
337 // Ackowledge a sent packet
338 if(Header->Flags & TCP_FLAG_ACK) {
339 // TODO: Process an ACKed Packet
340 Log_Log("TCP", "Conn %p, Sent packet 0x%x ACKed", Connection, Header->AcknowlegementNumber);
343 // Get length of data
344 dataLen = Length - (Header->DataOffset>>4)*4;
345 Log_Log("TCP", "HandleConnectionPacket - dataLen = %i", dataLen);
350 switch( Connection->State )
352 // Pre-init connection?
354 Log_Log("TCP", "Packets to a closed connection?!");
357 // --- Init States ---
358 // SYN sent, expecting SYN-ACK Connection Opening
359 case TCP_ST_SYN_SENT:
360 if( Header->Flags & TCP_FLAG_SYN )
362 Connection->NextSequenceRcv ++;
363 Header->DestPort = Header->SourcePort;
364 Header->SourcePort = htons(Connection->LocalPort);
365 Header->AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
366 Header->SequenceNumber = htonl(Connection->NextSequenceSend);
367 Header->WindowSize = htons(TCP_WINDOW_SIZE);
368 Header->Flags = TCP_FLAG_ACK;
369 Header->DataOffset = (sizeof(tTCPHeader)/4) << 4;
370 TCP_SendPacket( Connection, Header, 0, NULL );
372 if( Header->Flags & TCP_FLAG_ACK )
374 Log_Log("TCP", "ACKing SYN-ACK");
375 Connection->State = TCP_ST_OPEN;
379 Log_Log("TCP", "ACKing SYN");
380 Connection->State = TCP_ST_SYN_RCVD;
385 // SYN-ACK sent, expecting ACK
386 case TCP_ST_SYN_RCVD:
387 if( Header->Flags & TCP_FLAG_ACK )
389 // TODO: Handle max half-open limit
390 Connection->State = TCP_ST_OPEN;
391 Log_Log("TCP", "Connection fully opened");
395 // --- Established State ---
397 // - Handle State changes
399 if( Header->Flags & TCP_FLAG_FIN ) {
400 Log_Log("TCP", "Conn %p closed, recieved FIN", Connection);
401 VFS_MarkError(&Connection->Node, 1);
402 Connection->State = TCP_ST_CLOSE_WAIT;
403 // Header->Flags &= ~TCP_FLAG_FIN;
404 // CLOSE WAIT requires the client to close (or does it?)
410 // Check for an empty packet
412 if( Header->Flags == TCP_FLAG_ACK )
414 Log_Log("TCP", "ACK only packet");
417 Connection->NextSequenceRcv ++; // TODO: Is this right? (empty packet counts as one byte)
418 Log_Log("TCP", "Empty Packet, inc and ACK the current sequence number");
419 Header->DestPort = Header->SourcePort;
420 Header->SourcePort = htons(Connection->LocalPort);
421 Header->AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
422 Header->SequenceNumber = htonl(Connection->NextSequenceSend);
423 Header->Flags |= TCP_FLAG_ACK;
424 TCP_SendPacket( Connection, Header, 0, NULL );
433 sequence_num = ntohl(Header->SequenceNumber);
435 Log_Log("TCP", "0x%08x <= 0x%08x < 0x%08x",
436 Connection->NextSequenceRcv,
437 ntohl(Header->SequenceNumber),
438 Connection->NextSequenceRcv + TCP_WINDOW_SIZE
441 // Is this packet the next expected packet?
442 if( sequence_num == Connection->NextSequenceRcv )
445 // Ooh, Goodie! Add it to the recieved list
446 rv = TCP_INT_AppendRecieved(Connection,
447 (Uint8*)Header + (Header->DataOffset>>4)*4,
453 Log_Log("TCP", "0x%08x += %i", Connection->NextSequenceRcv, dataLen);
454 Connection->NextSequenceRcv += dataLen;
456 // TODO: This should be moved out of the watcher thread,
457 // so that a single lost packet on one connection doesn't cause
458 // all connections on the interface to lag.
459 // - Meh, no real issue, as the cache shouldn't be that large
460 TCP_INT_UpdateRecievedFromFuture(Connection);
463 Header->DestPort = Header->SourcePort;
464 Header->SourcePort = htons(Connection->LocalPort);
465 Header->AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
466 Header->SequenceNumber = htonl(Connection->NextSequenceSend);
467 Header->WindowSize = htons(TCP_WINDOW_SIZE);
468 Header->Flags &= TCP_FLAG_SYN; // Eliminate all flags save for SYN
469 Header->Flags |= TCP_FLAG_ACK; // Add ACK
470 Log_Log("TCP", "Sending ACK for 0x%08x", Connection->NextSequenceRcv);
471 TCP_SendPacket( Connection, Header, 0, NULL );
472 //Connection->NextSequenceSend ++;
474 // Check if the packet is in window
475 else if( WrapBetween(Connection->NextSequenceRcv, sequence_num,
476 Connection->NextSequenceRcv+TCP_WINDOW_SIZE, 0xFFFFFFFF) )
478 Uint8 *dataptr = (Uint8*)Header + (Header->DataOffset>>4)*4;
479 #if CACHE_FUTURE_PACKETS_IN_BYTES
483 index = sequence_num % TCP_WINDOW_SIZE;
484 for( i = 0; i < dataLen; i ++ )
486 Connection->FuturePacketValidBytes[index/8] |= 1 << (index%8);
487 Connection->FuturePacketData[index] = dataptr[i];
488 // Do a wrap increment
490 if(index == TCP_WINDOW_SIZE) index = 0;
493 tTCPStoredPacket *pkt, *tmp, *prev = NULL;
495 // Allocate and fill cached packet
496 pkt = malloc( sizeof(tTCPStoredPacket) + dataLen );
498 pkt->Sequence = ntohl(Header->SequenceNumber);
499 pkt->Length = dataLen;
500 memcpy(pkt->Data, dataptr, dataLen);
502 Log_Log("TCP", "We missed a packet, caching",
503 pkt->Sequence, Connection->NextSequenceRcv);
505 // No? Well, let's cache it and look at it later
506 SHORTLOCK( &Connection->lFuturePackets );
507 for(tmp = Connection->FuturePackets;
509 prev = tmp, tmp = tmp->Next)
511 if(tmp->Sequence >= pkt->Sequence) break;
514 // Add if before first, or sequences don't match
515 if( !tmp || tmp->Sequence != pkt->Sequence )
520 Connection->FuturePackets = pkt;
524 else if(pkt->Length > tmp->Length)
528 pkt->Next = tmp->Next;
533 free(pkt); // TODO: Find some way to remove this
535 SHORTREL( &Connection->lFuturePackets );
538 // Badly out of sequence packet
541 Log_Log("TCP", "Fully out of sequence packet (0x%08x not between 0x%08x and 0x%08x), dropped",
542 sequence_num, Connection->NextSequenceRcv, Connection->NextSequenceRcv+TCP_WINDOW_SIZE);
543 // TODO: Spec says we should send an empty ACK with the current state
547 // --- Remote close states
548 case TCP_ST_CLOSE_WAIT:
550 // Ignore everything, CLOSE_WAIT is terminated by the client
551 Log_Debug("TCP", "CLOSE WAIT - Ignoring packets");
555 // LAST-ACK - Waiting for the ACK of FIN (from CLOSE WAIT)
556 case TCP_ST_LAST_ACK:
557 if( Header->Flags & TCP_FLAG_ACK )
559 Connection->State = TCP_ST_FINISHED; // Connection completed
560 Log_Log("TCP", "LAST-ACK to CLOSED - Connection remote closed");
561 // TODO: Destrory the TCB
565 // --- Local close States
566 case TCP_ST_FIN_WAIT1:
567 if( Header->Flags & TCP_FLAG_FIN )
569 Connection->State = TCP_ST_CLOSING;
570 Log_Debug("TCP", "Conn %p closed, sent FIN and recieved FIN", Connection);
571 VFS_MarkError(&Connection->Node, 1);
574 Header->DestPort = Header->SourcePort;
575 Header->SourcePort = htons(Connection->LocalPort);
576 Header->AcknowlegementNumber = Header->SequenceNumber;
577 Header->SequenceNumber = htonl(Connection->NextSequenceSend);
578 Header->WindowSize = htons(TCP_WINDOW_SIZE);
579 Header->Flags = TCP_FLAG_ACK;
580 TCP_SendPacket( Connection, Header, 0, NULL );
584 // TODO: Make sure that the packet is actually ACKing the FIN
585 if( Header->Flags & TCP_FLAG_ACK )
587 Connection->State = TCP_ST_FIN_WAIT2;
588 Log_Debug("TCP", "Conn %p closed, sent FIN ACKed", Connection);
589 VFS_MarkError(&Connection->Node, 1);
594 case TCP_ST_FIN_WAIT2:
595 if( Header->Flags & TCP_FLAG_FIN )
597 Connection->State = TCP_ST_TIME_WAIT;
598 Log_Debug("TCP", "FIN sent and recieved, ACKing and going into TIME WAIT %p FINWAIT-2 -> TIME WAIT", Connection);
600 Header->DestPort = Header->SourcePort;
601 Header->SourcePort = htons(Connection->LocalPort);
602 Header->AcknowlegementNumber = Header->SequenceNumber;
603 Header->SequenceNumber = htonl(Connection->NextSequenceSend);
604 Header->WindowSize = htons(TCP_WINDOW_SIZE);
605 Header->Flags = TCP_FLAG_ACK;
606 TCP_SendPacket( Connection, Header, 0, NULL );
611 // TODO: Make sure that the packet is actually ACKing the FIN
612 if( Header->Flags & TCP_FLAG_ACK )
614 Connection->State = TCP_ST_TIME_WAIT;
615 Log_Debug("TCP", "Conn %p CLOSING -> TIME WAIT", Connection);
616 VFS_MarkError(&Connection->Node, 1);
621 // --- Closed (or near closed) states) ---
622 case TCP_ST_TIME_WAIT:
623 Log_Log("TCP", "Packets on Time-Wait, ignored");
626 case TCP_ST_FINISHED:
627 Log_Log("TCP", "Packets when CLOSED, ignoring");
631 // Log_Warning("TCP", "Unhandled TCP state %i", Connection->State);
638 * \brief Appends a packet to the recieved list
639 * \param Connection Connection structure
640 * \param Data Packet contents
641 * \param Length Length of \a Data
643 int TCP_INT_AppendRecieved(tTCPConnection *Connection, const void *Data, size_t Length)
645 Mutex_Acquire( &Connection->lRecievedPackets );
647 if(Connection->RecievedBuffer->Length + Length > Connection->RecievedBuffer->Space )
649 VFS_MarkAvaliable(&Connection->Node, 1);
650 Log_Error("TCP", "Buffer filled, packet dropped (:%i) - %i + %i > %i",
651 Connection->LocalPort, Connection->RecievedBuffer->Length, Length,
652 Connection->RecievedBuffer->Space
654 Mutex_Release( &Connection->lRecievedPackets );
658 RingBuffer_Write( Connection->RecievedBuffer, Data, Length );
660 VFS_MarkAvaliable(&Connection->Node, 1);
662 Mutex_Release( &Connection->lRecievedPackets );
667 * \brief Updates the connections recieved list from the future list
668 * \param Connection Connection structure
670 * Updates the recieved packets list with packets from the future (out
671 * of order) packets list that are now able to be added in direct
674 void TCP_INT_UpdateRecievedFromFuture(tTCPConnection *Connection)
676 #if CACHE_FUTURE_PACKETS_IN_BYTES
680 // Calculate length of contiguous bytes
681 length = Connection->HighestSequenceRcvd - Connection->NextSequenceRcv;
682 index = Connection->NextSequenceRcv % TCP_WINDOW_SIZE;
683 for( i = 0; i < length; i ++ )
685 if( Connection->FuturePacketValidBytes[i / 8] == 0xFF ) {
689 else if( !(Connection->FuturePacketValidBytes[i / 8] & (1 << (i%8))) )
693 if(index > TCP_WINDOW_SIZE)
694 index -= TCP_WINDOW_SIZE;
698 index = Connection->NextSequenceRcv % TCP_WINDOW_SIZE;
700 // Write data to to the ring buffer
701 if( TCP_WINDOW_SIZE - index > length )
704 RingBuffer_Write( Connection->RecievedBuffer, Connection->FuturePacketData + index, length );
708 int endLen = TCP_WINDOW_SIZE - index;
710 RingBuffer_Write( Connection->RecievedBuffer, Connection->FuturePacketData + index, endLen );
711 RingBuffer_Write( Connection->RecievedBuffer, Connection->FuturePacketData, endLen - length );
714 // Mark (now saved) bytes as invalid
716 while(index % 8 && length)
718 Connection->FuturePacketData[index] = 0;
719 Connection->FuturePacketData[index/8] &= ~(1 << (index%8));
721 if(index > TCP_WINDOW_SIZE)
722 index -= TCP_WINDOW_SIZE;
727 Connection->FuturePacketData[index] = 0;
728 Connection->FuturePacketValidBytes[index/8] = 0;
731 if(index > TCP_WINDOW_SIZE)
732 index -= TCP_WINDOW_SIZE;
736 Connection->FuturePacketData[index] = 0;
737 Connection->FuturePacketData[index/8] &= ~(1 << (index%8));
739 if(index > TCP_WINDOW_SIZE)
740 index -= TCP_WINDOW_SIZE;
745 tTCPStoredPacket *pkt;
748 SHORTLOCK( &Connection->lFuturePackets );
750 // Clear out duplicates from cache
751 // - If a packet has just been recieved, and it is expected, then
752 // (since NextSequenceRcv = rcvd->Sequence + rcvd->Length) all
753 // packets in cache that are smaller than the next expected
755 pkt = Connection->FuturePackets;
756 while(pkt && pkt->Sequence < Connection->NextSequenceRcv)
758 tTCPStoredPacket *next = pkt->Next;
763 // If there's no packets left in cache, stop looking
764 if(!pkt || pkt->Sequence > Connection->NextSequenceRcv) {
765 SHORTREL( &Connection->lFuturePackets );
769 // Delete packet from future list
770 Connection->FuturePackets = pkt->Next;
773 SHORTREL( &Connection->lFuturePackets );
775 // Looks like we found one
776 TCP_INT_AppendRecieved(Connection, pkt);
777 Connection->NextSequenceRcv += pkt->Length;
784 * \fn Uint16 TCP_GetUnusedPort()
785 * \brief Gets an unused port and allocates it
787 Uint16 TCP_GetUnusedPort()
791 // Get Next outbound port
792 ret = giTCP_NextOutPort++;
793 while( gaTCP_PortBitmap[ret/32] & (1UL << (ret%32)) )
797 if(giTCP_NextOutPort == 0x10000) {
798 ret = giTCP_NextOutPort = TCP_MIN_DYNPORT;
802 // Mark the new port as used
803 gaTCP_PortBitmap[ret/32] |= 1 << (ret%32);
809 * \fn int TCP_AllocatePort(Uint16 Port)
810 * \brief Marks a port as used
812 int TCP_AllocatePort(Uint16 Port)
814 // Check if the port has already been allocated
815 if( gaTCP_PortBitmap[Port/32] & (1 << (Port%32)) )
819 gaTCP_PortBitmap[Port/32] |= 1 << (Port%32);
825 * \fn int TCP_DeallocatePort(Uint16 Port)
826 * \brief Marks a port as unused
828 int TCP_DeallocatePort(Uint16 Port)
830 // Check if the port has already been allocated
831 if( !(gaTCP_PortBitmap[Port/32] & (1 << (Port%32))) )
835 gaTCP_PortBitmap[Port/32] &= ~(1 << (Port%32));
841 tVFS_Node *TCP_Server_Init(tInterface *Interface)
845 srv = calloc( 1, sizeof(tTCPListener) );
848 Log_Warning("TCP", "malloc failed for listener (%i) bytes", sizeof(tTCPListener));
852 srv->Interface = Interface;
855 srv->Connections = NULL;
856 srv->ConnectionsTail = NULL;
857 srv->NewConnections = NULL;
859 srv->Node.Flags = VFS_FFLAG_DIRECTORY;
861 srv->Node.ImplPtr = srv;
862 srv->Node.NumACLs = 1;
863 srv->Node.ACLs = &gVFS_ACL_EveryoneRW;
864 srv->Node.Type = &gTCP_ServerNodeType;
866 SHORTLOCK(&glTCP_Listeners);
867 srv->Next = gTCP_Listeners;
868 gTCP_Listeners = srv;
869 SHORTREL(&glTCP_Listeners);
875 * \brief Wait for a new connection and return the connection ID
876 * \note Blocks until a new connection is made
877 * \param Node Server node
878 * \param Pos Position (ignored)
880 char *TCP_Server_ReadDir(tVFS_Node *Node, int Pos)
882 tTCPListener *srv = Node->ImplPtr;
883 tTCPConnection *conn;
886 ENTER("pNode iPos", Node, Pos);
888 Log_Log("TCP", "Thread %i waiting for a connection", Threads_GetTID());
891 SHORTLOCK( &srv->lConnections );
892 if( srv->NewConnections != NULL ) break;
893 SHORTREL( &srv->lConnections );
894 Threads_Yield(); // TODO: Sleep until poked
898 // Increment the new list (the current connection is still on the
900 conn = srv->NewConnections;
901 srv->NewConnections = conn->Next;
903 if( srv->NewConnections == NULL )
904 VFS_MarkAvaliable( Node, 0 );
906 SHORTREL( &srv->lConnections );
908 LOG("conn = %p", conn);
909 LOG("srv->Connections = %p", srv->Connections);
910 LOG("srv->NewConnections = %p", srv->NewConnections);
911 LOG("srv->ConnectionsTail = %p", srv->ConnectionsTail);
914 itoa(ret, conn->Node.ImplInt, 16, 8, '0');
915 Log_Log("TCP", "Thread %i got '%s'", Threads_GetTID(), ret);
921 * \brief Gets a client connection node
922 * \param Node Server node
923 * \param Name Hexadecimal ID of the node
925 tVFS_Node *TCP_Server_FindDir(tVFS_Node *Node, const char *Name)
927 tTCPConnection *conn;
928 tTCPListener *srv = Node->ImplPtr;
932 ENTER("pNode sName", Node, Name);
934 // Check for a non-empty name
938 itoa(tmp, id, 16, 8, '0');
939 if(strcmp(tmp, Name) != 0) {
940 LOG("'%s' != '%s' (%08x)", Name, tmp, id);
945 Log_Debug("TCP", "srv->Connections = %p", srv->Connections);
946 Log_Debug("TCP", "srv->NewConnections = %p", srv->NewConnections);
947 Log_Debug("TCP", "srv->ConnectionsTail = %p", srv->ConnectionsTail);
950 SHORTLOCK( &srv->lConnections );
951 for(conn = srv->Connections;
955 LOG("conn->Node.ImplInt = %i", conn->Node.ImplInt);
956 if(conn->Node.ImplInt == id) break;
958 SHORTREL( &srv->lConnections );
960 // If not found, ret NULL
962 LOG("Connection %i not found", id);
967 // Empty Name - Check for a new connection and if it's there, open it
970 SHORTLOCK( &srv->lConnections );
971 conn = srv->NewConnections;
973 srv->NewConnections = conn->Next;
974 VFS_MarkAvaliable( Node, srv->NewConnections != NULL );
975 SHORTREL( &srv->lConnections );
977 LOG("No new connections");
984 LEAVE('p', &conn->Node);
989 * \brief Handle IOCtl calls
991 int TCP_Server_IOCtl(tVFS_Node *Node, int ID, void *Data)
993 tTCPListener *srv = Node->ImplPtr;
997 case 4: // Get/Set Port
998 if(!Data) // Get Port
1001 if(srv->Port) // Wait, you can't CHANGE the port
1004 if(!CheckMem(Data, sizeof(Uint16))) // Sanity check
1007 // Permissions check
1008 if(Threads_GetUID() != 0
1009 && *(Uint16*)Data != 0
1010 && *(Uint16*)Data < 1024)
1013 // TODO: Check if a port is in use
1016 srv->Port = *(Uint16*)Data;
1017 if(srv->Port == 0) // Allocate a random port
1018 srv->Port = TCP_GetUnusedPort();
1019 else // Else, mark this as used
1020 TCP_AllocatePort(srv->Port);
1022 Log_Log("TCP", "Server %p listening on port %i", srv, srv->Port);
1029 void TCP_Server_Close(tVFS_Node *Node)
1031 free(Node->ImplPtr);
1036 * \brief Create a client node
1038 tVFS_Node *TCP_Client_Init(tInterface *Interface)
1040 tTCPConnection *conn = calloc( sizeof(tTCPConnection) + TCP_WINDOW_SIZE + TCP_WINDOW_SIZE/8, 1 );
1042 conn->State = TCP_ST_CLOSED;
1043 conn->Interface = Interface;
1044 conn->LocalPort = -1;
1045 conn->RemotePort = -1;
1047 conn->Node.ImplPtr = conn;
1048 conn->Node.NumACLs = 1;
1049 conn->Node.ACLs = &gVFS_ACL_EveryoneRW;
1050 conn->Node.Type = &gTCP_ClientNodeType;
1052 conn->RecievedBuffer = RingBuffer_Create( TCP_RECIEVE_BUFFER_SIZE );
1054 conn->SentBuffer = RingBuffer_Create( TCP_SEND_BUFFER_SIZE );
1055 Semaphore_Init(conn->SentBufferSpace, 0, TCP_SEND_BUFFER_SIZE, "TCP SentBuffer", conn->Name);
1058 #if CACHE_FUTURE_PACKETS_IN_BYTES
1059 // Future recieved data (ahead of the expected sequence number)
1060 conn->FuturePacketData = (Uint8*)conn + sizeof(tTCPConnection);
1061 conn->FuturePacketValidBytes = conn->FuturePacketData + TCP_WINDOW_SIZE;
1064 SHORTLOCK(&glTCP_OutbountCons);
1065 conn->Next = gTCP_OutbountCons;
1066 gTCP_OutbountCons = conn;
1067 SHORTREL(&glTCP_OutbountCons);
1073 * \brief Wait for a packet and return it
1074 * \note If \a Length is smaller than the size of the packet, the rest
1075 * of the packet's data will be discarded.
1077 size_t TCP_Client_Read(tVFS_Node *Node, off_t Offset, size_t Length, void *Buffer)
1079 tTCPConnection *conn = Node->ImplPtr;
1082 ENTER("pNode XOffset XLength pBuffer", Node, Offset, Length, Buffer);
1083 LOG("conn = %p {State:%i}", conn, conn->State);
1085 // Check if connection is estabilishing
1086 // - TODO: Sleep instead (maybe using VFS_SelectNode to wait for the
1087 // data to be availiable
1088 while( conn->State == TCP_ST_SYN_RCVD || conn->State == TCP_ST_SYN_SENT )
1091 // If the conneciton is not open, then clean out the recieved buffer
1092 if( conn->State != TCP_ST_OPEN )
1094 Mutex_Acquire( &conn->lRecievedPackets );
1095 len = RingBuffer_Read( Buffer, conn->RecievedBuffer, Length );
1096 Mutex_Release( &conn->lRecievedPackets );
1099 VFS_MarkAvaliable(Node, 0);
1109 VFS_SelectNode(Node, VFS_SELECT_READ|VFS_SELECT_ERROR, NULL, "TCP_Client_Read");
1111 // Lock list and read as much as possible (up to `Length`)
1112 Mutex_Acquire( &conn->lRecievedPackets );
1113 len = RingBuffer_Read( Buffer, conn->RecievedBuffer, Length );
1115 if( len == 0 || conn->RecievedBuffer->Length == 0 ) {
1116 LOG("Marking as none avaliable (len = %i)", len);
1117 VFS_MarkAvaliable(Node, 0);
1120 // Release the lock (we don't need it any more)
1121 Mutex_Release( &conn->lRecievedPackets );
1128 * \brief Send a data packet on a connection
1130 void TCP_INT_SendDataPacket(tTCPConnection *Connection, size_t Length, const void *Data)
1132 char buf[sizeof(tTCPHeader)+Length];
1133 tTCPHeader *packet = (void*)buf;
1135 packet->SourcePort = htons(Connection->LocalPort);
1136 packet->DestPort = htons(Connection->RemotePort);
1137 packet->DataOffset = (sizeof(tTCPHeader)/4)*16;
1138 packet->WindowSize = htons(TCP_WINDOW_SIZE);
1140 packet->AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
1141 packet->SequenceNumber = htonl(Connection->NextSequenceSend);
1142 packet->Flags = TCP_FLAG_PSH|TCP_FLAG_ACK; // Hey, ACK if you can!
1144 memcpy(packet->Options, Data, Length);
1146 Log_Debug("TCP", "Send sequence 0x%08x", Connection->NextSequenceSend);
1147 #if HEXDUMP_OUTGOING
1148 Debug_HexDump("TCP_INT_SendDataPacket: Data = ", Data, Length);
1151 TCP_SendPacket( Connection, packet, Length, Data );
1153 Connection->NextSequenceSend += Length;
1157 * \brief Send some bytes on a connection
1159 size_t TCP_Client_Write(tVFS_Node *Node, off_t Offset, size_t Length, const void *Buffer)
1161 tTCPConnection *conn = Node->ImplPtr;
1162 size_t rem = Length;
1164 ENTER("pNode XOffset XLength pBuffer", Node, Offset, Length, Buffer);
1167 // Debug_HexDump("TCP_Client_Write: Buffer = ",
1171 // Check if connection is open
1172 while( conn->State == TCP_ST_SYN_RCVD || conn->State == TCP_ST_SYN_SENT )
1175 if( conn->State != TCP_ST_OPEN ) {
1176 VFS_MarkError(Node, 1);
1183 int len = (rem < TCP_MAX_PACKET_SIZE) ? rem : TCP_MAX_PACKET_SIZE;
1186 // Wait for space in the buffer
1187 Semaphore_Signal( &Connection->SentBufferSpace, len );
1189 // Save data to buffer (and update the length read by the ammount written)
1190 len = RingBuffer_Write( &Connection->SentBuffer, Buffer, len);
1194 TCP_INT_SendDataPacket(conn, len, Buffer);
1205 * \brief Open a connection to another host using TCP
1206 * \param Conn Connection structure
1208 void TCP_StartConnection(tTCPConnection *Conn)
1210 tTCPHeader hdr = {0};
1212 Conn->State = TCP_ST_SYN_SENT;
1214 hdr.SourcePort = htons(Conn->LocalPort);
1215 hdr.DestPort = htons(Conn->RemotePort);
1216 Conn->NextSequenceSend = rand();
1217 hdr.SequenceNumber = htonl(Conn->NextSequenceSend);
1218 hdr.DataOffset = (sizeof(tTCPHeader)/4) << 4;
1219 hdr.Flags = TCP_FLAG_SYN;
1220 hdr.WindowSize = htons(TCP_WINDOW_SIZE); // Max
1221 hdr.Checksum = 0; // TODO
1223 TCP_SendPacket( Conn, &hdr, 0, NULL );
1225 Conn->NextSequenceSend ++;
1226 Conn->State = TCP_ST_SYN_SENT;
1232 * \brief Control a client socket
1234 int TCP_Client_IOCtl(tVFS_Node *Node, int ID, void *Data)
1236 tTCPConnection *conn = Node->ImplPtr;
1238 ENTER("pNode iID pData", Node, ID, Data);
1242 case 4: // Get/Set local port
1244 LEAVE_RET('i', conn->LocalPort);
1245 if(conn->State != TCP_ST_CLOSED)
1247 if(!CheckMem(Data, sizeof(Uint16)))
1250 if(Threads_GetUID() != 0 && *(Uint16*)Data < 1024)
1253 conn->LocalPort = *(Uint16*)Data;
1254 LEAVE_RET('i', conn->LocalPort);
1256 case 5: // Get/Set remote port
1257 if(!Data) LEAVE_RET('i', conn->RemotePort);
1258 if(conn->State != TCP_ST_CLOSED) LEAVE_RET('i', -1);
1259 if(!CheckMem(Data, sizeof(Uint16))) LEAVE_RET('i', -1);
1260 conn->RemotePort = *(Uint16*)Data;
1261 LEAVE_RET('i', conn->RemotePort);
1263 case 6: // Set Remote IP
1264 if( conn->State != TCP_ST_CLOSED )
1266 if( conn->Interface->Type == 4 )
1268 if(!CheckMem(Data, sizeof(tIPv4))) LEAVE_RET('i', -1);
1269 conn->RemoteIP.v4 = *(tIPv4*)Data;
1271 else if( conn->Interface->Type == 6 )
1273 if(!CheckMem(Data, sizeof(tIPv6))) LEAVE_RET('i', -1);
1274 conn->RemoteIP.v6 = *(tIPv6*)Data;
1279 if(conn->LocalPort == 0xFFFF)
1280 conn->LocalPort = TCP_GetUnusedPort();
1281 if(conn->RemotePort == -1)
1285 tTime timeout_end = now() + conn->Interface->TimeoutDelay;
1287 TCP_StartConnection(conn);
1288 // TODO: Wait for connection to open
1289 while( conn->State == TCP_ST_SYN_SENT && timeout_end > now() ) {
1292 if( conn->State == TCP_ST_SYN_SENT )
1298 // Get recieve buffer length
1300 LEAVE_RET('i', conn->RecievedBuffer->Length);
1306 void TCP_Client_Close(tVFS_Node *Node)
1308 tTCPConnection *conn = Node->ImplPtr;
1311 ENTER("pNode", Node);
1313 if( conn->State == TCP_ST_CLOSE_WAIT || conn->State == TCP_ST_OPEN )
1315 packet.SourcePort = htons(conn->LocalPort);
1316 packet.DestPort = htons(conn->RemotePort);
1317 packet.DataOffset = (sizeof(tTCPHeader)/4)*16;
1318 packet.WindowSize = TCP_WINDOW_SIZE;
1320 packet.AcknowlegementNumber = 0;
1321 packet.SequenceNumber = htonl(conn->NextSequenceSend);
1322 packet.Flags = TCP_FLAG_FIN;
1324 TCP_SendPacket( conn, &packet, 0, NULL );
1327 switch( conn->State )
1329 case TCP_ST_CLOSE_WAIT:
1330 conn->State = TCP_ST_LAST_ACK;
1333 conn->State = TCP_ST_FIN_WAIT1;
1334 while( conn->State == TCP_ST_FIN_WAIT1 ) Threads_Yield();
1337 Log_Warning("TCP", "Unhandled connection state in TCP_Client_Close");
1347 * \brief Checks if a value is between two others (after taking into account wrapping)
1349 int WrapBetween(Uint32 Lower, Uint32 Value, Uint32 Higher, Uint32 MaxValue)
1351 if( MaxValue < 0xFFFFFFFF )
1353 Lower %= MaxValue + 1;
1354 Value %= MaxValue + 1;
1355 Higher %= MaxValue + 1;
1358 // Simple Case, no wrap ?
1359 // Lower Value Higher
1360 // | ... + ... + ... + ... |
1362 if( Lower < Higher ) {
1363 return Lower < Value && Value < Higher;
1365 // Higher has wrapped below lower
1368 // Higher Lower Value
1369 // | ... + ... + ... + ... |
1370 if( Value > Lower ) {
1375 // Value Higher Lower
1376 // | ... + ... + ... + ... |
1377 if( Value < Higher ) {