9 #define TCP_MIN_DYNPORT 0xC000
10 #define TCP_MAX_HALFOPEN 1024 // Should be enough
13 void TCP_Initialise();
14 void TCP_StartConnection(tTCPConnection *Conn);
15 void TCP_SendPacket(tTCPConnection *Conn, size_t Length, tTCPHeader *Data);
16 void TCP_GetPacket(tInterface *Interface, void *Address, int Length, void *Buffer);
17 void TCP_INT_HandleConnectionPacket(tTCPConnection *Connection, tTCPHeader *Header, int Length);
18 void TCP_INT_AppendRecieved(tTCPConnection *Connection, tTCPStoredPacket *Ptk);
19 void TCP_INT_UpdateRecievedFromFuture(tTCPConnection *Connection);
20 Uint16 TCP_GetUnusedPort();
21 int TCP_AllocatePort(Uint16 Port);
22 int TCP_DeallocatePort(Uint16 Port);
24 tVFS_Node *TCP_Server_Init(tInterface *Interface);
25 char *TCP_Server_ReadDir(tVFS_Node *Node, int Pos);
26 tVFS_Node *TCP_Server_FindDir(tVFS_Node *Node, char *Name);
27 int TCP_Server_IOCtl(tVFS_Node *Node, int ID, void *Data);
28 void TCP_Server_Close(tVFS_Node *Node);
30 tVFS_Node *TCP_Client_Init(tInterface *Interface);
31 Uint64 TCP_Client_Read(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer);
32 Uint64 TCP_Client_Write(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer);
33 int TCP_Client_IOCtl(tVFS_Node *Node, int ID, void *Data);
34 void TCP_Client_Close(tVFS_Node *Node);
37 tSocketFile gTCP_ServerFile = {NULL, "tcps", TCP_Server_Init};
38 tSocketFile gTCP_ClientFile = {NULL, "tcpc", TCP_Client_Init};
41 int giTCP_NumHalfopen = 0;
42 tSpinlock glTCP_Listeners;
43 tTCPListener *gTCP_Listeners;
44 tSpinlock glTCP_OutbountCons;
45 tTCPConnection *gTCP_OutbountCons;
46 Uint32 gaTCP_PortBitmap[0x800];
47 int giTCP_NextOutPort = TCP_MIN_DYNPORT;
51 * \brief Initialise the TCP Layer
53 * Registers the client and server files and the GetPacket callback
57 IPStack_AddFile(&gTCP_ServerFile);
58 IPStack_AddFile(&gTCP_ClientFile);
59 IPv4_RegisterCallback(IP4PROT_TCP, TCP_GetPacket);
63 * \brief Open a connection to another host using TCP
64 * \param Conn Connection structure
66 void TCP_StartConnection(tTCPConnection *Conn)
70 hdr.SourcePort = Conn->LocalPort;
71 hdr.DestPort = Conn->RemotePort;
72 Conn->NextSequenceSend = rand();
73 hdr.SequenceNumber = Conn->NextSequenceSend;
74 hdr.DataOffset = (sizeof(tTCPHeader)/4) << 4;
75 hdr.Flags = TCP_FLAG_SYN;
76 hdr.WindowSize = 0; // TODO
77 hdr.Checksum = 0; // TODO
78 hdr.UrgentPointer = 0;
80 TCP_SendPacket( Conn, sizeof(tTCPHeader), &hdr );
85 * \brief Sends a packet from the specified connection, calculating the checksums
86 * \param Conn Connection
87 * \param Length Length of data
88 * \param Data Packet data (cast as a TCP Header)
90 void TCP_SendPacket( tTCPConnection *Conn, size_t Length, tTCPHeader *Data )
94 switch( Conn->Interface->Type )
96 case 4: // Append IPv4 Pseudo Header
97 buflen = 4 + 4 + 4 + ((Length+1)&~1);
98 buf = malloc( buflen );
99 buf[0] = Conn->Interface->IP4.Address.L;
100 buf[1] = Conn->RemoteIP.v4.L;
101 buf[2] = (htons(Length)<<16) | (6<<8) | 0;
103 memcpy( &buf[3], Data, Length );
104 Data->Checksum = IPv4_Checksum( buf, buflen );
106 IPv4_SendPacket(Conn->Interface, Conn->RemoteIP.v4, IP4PROT_TCP, 0, Length, Data);
112 * \brief Handles a packet from the IP Layer
113 * \param Interface Interface the packet arrived from
114 * \param Address Pointer to the addres structure
115 * \param Length Size of packet in bytes
116 * \param Buffer Packet data
118 void TCP_GetPacket(tInterface *Interface, void *Address, int Length, void *Buffer)
120 tTCPHeader *hdr = Buffer;
122 tTCPConnection *conn;
124 Log_Log("TCP", "SourcePort = %i, DestPort = %i",
125 ntohs(hdr->SourcePort), ntohs(hdr->DestPort));
126 Log_Log("TCP", "SequenceNumber = 0x%x", ntohl(hdr->SequenceNumber));
127 Log_Log("TCP", "AcknowlegementNumber = 0x%x", ntohl(hdr->AcknowlegementNumber));
128 Log_Log("TCP", "DataOffset = %i", hdr->DataOffset >> 4);
129 Log_Log("TCP", "Flags = {");
130 Log_Log("TCP", " CWR = %B, ECE = %B",
131 !!(hdr->Flags & TCP_FLAG_CWR), !!(hdr->Flags & TCP_FLAG_ECE));
132 Log_Log("TCP", " URG = %B, ACK = %B",
133 !!(hdr->Flags & TCP_FLAG_URG), !!(hdr->Flags & TCP_FLAG_ACK));
134 Log_Log("TCP", " PSH = %B, RST = %B",
135 !!(hdr->Flags & TCP_FLAG_PSH), !!(hdr->Flags & TCP_FLAG_RST));
136 Log_Log("TCP", " SYN = %B, FIN = %B",
137 !!(hdr->Flags & TCP_FLAG_SYN), !!(hdr->Flags & TCP_FLAG_FIN));
139 Log_Log("TCP", "WindowSize = %i", htons(hdr->WindowSize));
140 Log_Log("TCP", "Checksum = 0x%x", htons(hdr->Checksum));
141 Log_Log("TCP", "UrgentPointer = 0x%x", htons(hdr->UrgentPointer));
143 if( Length > (hdr->DataOffset >> 4)*4 )
146 "[TCP ] Packet Data = ",
147 (Uint8*)hdr + (hdr->DataOffset >> 4)*4,
148 Length - (hdr->DataOffset >> 4)*4
154 for( srv = gTCP_Listeners; srv; srv = srv->Next )
156 // Check if the server is active
157 if(srv->Port == 0) continue;
158 // Check the interface
159 if(srv->Interface && srv->Interface != Interface) continue;
160 // Check the destination port
161 if(srv->Port != htons(hdr->DestPort)) continue;
163 Log_Log("TCP", "Matches server %p", srv);
164 // Is this in an established connection?
165 for( conn = srv->Connections; conn; conn = conn->Next )
167 Log_Log("TCP", "conn->Interface(%p) == Interface(%p)",
168 conn->Interface, Interface);
169 // Check that it is coming in on the same interface
170 if(conn->Interface != Interface) continue;
173 Log_Log("TCP", "conn->RemotePort(%i) == hdr->SourcePort(%i)",
174 conn->RemotePort, ntohs(hdr->SourcePort));
175 if(conn->RemotePort != ntohs(hdr->SourcePort)) continue;
178 if(conn->Interface->Type == 6 && !IP6_EQU(conn->RemoteIP.v6, *(tIPv6*)Address))
180 if(conn->Interface->Type == 4 && !IP4_EQU(conn->RemoteIP.v4, *(tIPv4*)Address))
183 Log_Log("TCP", "Matches connection %p", conn);
184 // We have a response!
185 TCP_INT_HandleConnectionPacket(conn, hdr, Length);
190 Log_Log("TCP", "Opening Connection");
191 // Open a new connection (well, check that it's a SYN)
192 if(hdr->Flags != TCP_FLAG_SYN) {
193 Log_Log("TCP", "Packet is not a SYN");
197 // TODO: Check for halfopen max
199 conn = calloc(1, sizeof(tTCPConnection));
200 conn->State = TCP_ST_HALFOPEN;
201 conn->LocalPort = srv->Port;
202 conn->RemotePort = ntohs(hdr->SourcePort);
203 conn->Interface = Interface;
205 switch(Interface->Type)
207 case 4: conn->RemoteIP.v4 = *(tIPv4*)Address; break;
208 case 6: conn->RemoteIP.v6 = *(tIPv6*)Address; break;
211 conn->NextSequenceRcv = ntohl( hdr->SequenceNumber ) + 1;
212 conn->NextSequenceSend = rand();
215 conn->Node.NumACLs = 1;
216 conn->Node.ACLs = &gVFS_ACL_EveryoneRW;
217 conn->Node.ImplInt = srv->NextID ++;
218 conn->Node.Read = TCP_Client_Read;
219 conn->Node.Write = TCP_Client_Write;
220 //conn->Node.Close = TCP_SrvConn_Close;
222 // Hmm... Theoretically, this lock will never have to wait,
223 // as the interface is locked to the watching thread, and this
224 // runs in the watching thread. But, it's a good idea to have
226 // Oh, wait, there is a case where a wildcard can be used
227 // (srv->Interface == NULL) so having the lock is a good idea
228 LOCK(&srv->lConnections);
229 if( !srv->Connections )
230 srv->Connections = conn;
232 srv->ConnectionsTail->Next = conn;
233 srv->ConnectionsTail = conn;
234 if(!srv->NewConnections)
235 srv->NewConnections = conn;
236 RELEASE(&srv->lConnections);
239 hdr->Flags |= TCP_FLAG_ACK;
240 hdr->AcknowlegementNumber = htonl(conn->NextSequenceRcv);
241 hdr->SequenceNumber = htonl(conn->NextSequenceSend);
242 hdr->DestPort = hdr->SourcePort;
243 hdr->SourcePort = htons(srv->Port);
244 hdr->DataOffset = (sizeof(tTCPHeader)/4) << 4;
245 TCP_SendPacket( conn, sizeof(tTCPHeader), hdr );
252 // Check Open Connections
254 for( conn = gTCP_OutbountCons; conn; conn = conn->Next )
256 // Check that it is coming in on the same interface
257 if(conn->Interface != Interface) continue;
260 if(conn->RemotePort != ntohs(hdr->SourcePort)) continue;
263 if(conn->Interface->Type == 6 && !IP6_EQU(conn->RemoteIP.v6, *(tIPv6*)Address))
265 if(conn->Interface->Type == 4 && !IP4_EQU(conn->RemoteIP.v4, *(tIPv4*)Address))
268 TCP_INT_HandleConnectionPacket(conn, hdr, Length);
273 Log_Log("TCP", "No Match");
277 * \brief Handles a packet sent to a specific connection
278 * \param Connection TCP Connection pointer
279 * \param Header TCP Packet pointer
280 * \param Length Length of the packet
282 void TCP_INT_HandleConnectionPacket(tTCPConnection *Connection, tTCPHeader *Header, int Length)
284 tTCPStoredPacket *pkt;
287 Connection->State = TCP_ST_OPEN;
288 if(Header->Flags & TCP_FLAG_SYN) {
289 Connection->NextSequenceRcv = Header->SequenceNumber + 1;
292 // Get length of data
293 dataLen = Length - (Header->DataOffset>>4)*4;
294 Log_Log("TCP", "HandleConnectionPacket - dataLen = %i", dataLen);
296 if(Header->Flags & TCP_FLAG_ACK) {
297 // TODO: Process an ACKed Packet
298 Log_Log("TCP", "Conn %p, Packet 0x%x ACKed", Connection, Header->AcknowlegementNumber);
301 if(dataLen == 0) return ;
308 // Allocate and fill cached packet
309 pkt = malloc( dataLen + sizeof(tTCPStoredPacket) );
311 pkt->Sequence = ntohl(Header->SequenceNumber);
312 pkt->Length = dataLen;
313 memcpy(pkt->Data, (Uint8*)Header + (Header->DataOffset>>4)*4, dataLen);
315 // Is this packet the next expected packet?
316 if( pkt->Sequence != Connection->NextSequenceRcv )
318 tTCPStoredPacket *tmp, *prev = NULL;
320 Log_Log("TCP", "Out of sequence packet (0x%08x != 0x%08x)",
321 pkt->Sequence, Connection->NextSequenceRcv);
323 // No? Well, let's cache it and look at it later
324 LOCK( &Connection->lFuturePackets );
325 for(tmp = Connection->FuturePackets;
327 prev = tmp, tmp = tmp->Next)
329 if(tmp->Sequence > pkt->Sequence) break;
334 Connection->FuturePackets = pkt;
336 RELEASE( &Connection->lFuturePackets );
340 // Ooh, Goodie! Add it to the recieved list
341 TCP_INT_AppendRecieved(Connection, pkt);
343 Connection->NextSequenceRcv += dataLen;
345 Connection->NextSequenceRcv += 1;
347 // TODO: This should be moved out of the watcher thread,
348 // so that a single lost packet on one connection doesn't cause
349 // all connections on the interface to lag.
350 TCP_INT_UpdateRecievedFromFuture(Connection);
352 // TODO: Check ACK code validity
353 Header->AcknowlegementNumber = ntohl(pkt->Sequence) + dataLen;
354 Header->SequenceNumber = ntohl(Connection->NextSequenceSend);
355 Header->Flags &= TCP_FLAG_SYN;
356 Header->Flags = TCP_FLAG_ACK;
357 TCP_SendPacket( Connection, sizeof(tTCPHeader), Header );
362 * \brief Appends a packet to the recieved list
363 * \param Connection Connection structure
364 * \param Pkt Packet structure on heap
366 void TCP_INT_AppendRecieved(tTCPConnection *Connection, tTCPStoredPacket *Pkt)
368 LOCK( &Connection->lRecievedPackets );
369 if(Connection->RecievedPackets)
371 Connection->RecievedPacketsTail->Next = Pkt;
372 Connection->RecievedPacketsTail = Pkt;
376 Connection->RecievedPackets = Pkt;
377 Connection->RecievedPacketsTail = Pkt;
379 RELEASE( &Connection->lRecievedPackets );
383 * \brief Updates the connections recieved list from the future list
384 * \param Connection Connection structure
386 * Updates the recieved packets list with packets from the future (out
387 * of order) packets list that are now able to be added in direct
390 void TCP_INT_UpdateRecievedFromFuture(tTCPConnection *Connection)
392 tTCPStoredPacket *pkt, *prev;
396 // Look for the next expected packet in the cache.
397 LOCK( &Connection->lFuturePackets );
398 for(pkt = Connection->FuturePackets;
399 pkt && pkt->Sequence < Connection->NextSequenceRcv;
400 prev = pkt, pkt = pkt->Next);
402 // If we can't find the expected next packet, stop looking
403 if(!pkt || pkt->Sequence > Connection->NextSequenceRcv) {
404 RELEASE( &Connection->lFuturePackets );
408 // Delete packet from future list
410 prev->Next = pkt->Next;
412 Connection->FuturePackets = pkt->Next;
415 RELEASE( &Connection->lFuturePackets );
417 // Looks like we found one
418 TCP_INT_AppendRecieved(Connection, pkt);
419 Connection->NextSequenceRcv ++;
424 * \fn Uint16 TCP_GetUnusedPort()
425 * \brief Gets an unused port and allocates it
427 Uint16 TCP_GetUnusedPort()
431 // Get Next outbound port
432 ret = giTCP_NextOutPort++;
433 while( gaTCP_PortBitmap[ret/32] & (1 << (ret%32)) )
437 if(giTCP_NextOutPort == 0x10000) {
438 ret = giTCP_NextOutPort = TCP_MIN_DYNPORT;
442 // Mark the new port as used
443 gaTCP_PortBitmap[ret/32] |= 1 << (ret%32);
449 * \fn int TCP_AllocatePort(Uint16 Port)
450 * \brief Marks a port as used
452 int TCP_AllocatePort(Uint16 Port)
454 // Check if the port has already been allocated
455 if( gaTCP_PortBitmap[Port/32] & (1 << (Port%32)) )
459 gaTCP_PortBitmap[Port/32] |= 1 << (Port%32);
465 * \fn int TCP_DeallocatePort(Uint16 Port)
466 * \brief Marks a port as unused
468 int TCP_DeallocatePort(Uint16 Port)
470 // Check if the port has already been allocated
471 if( !(gaTCP_PortBitmap[Port/32] & (1 << (Port%32))) )
475 gaTCP_PortBitmap[Port/32] &= ~(1 << (Port%32));
481 tVFS_Node *TCP_Server_Init(tInterface *Interface)
485 srv = malloc( sizeof(tTCPListener) );
487 Log_Debug("TCP", "srv = %p", srv);
490 Log_Warning("TCP", "malloc failed for listener (%i) bytes", sizeof(tTCPListener));
494 srv->Interface = Interface;
497 srv->Connections = NULL;
499 srv->Node.Flags = VFS_FFLAG_DIRECTORY;
501 srv->Node.ImplPtr = srv;
502 srv->Node.NumACLs = 1;
503 srv->Node.ACLs = &gVFS_ACL_EveryoneRW;
504 srv->Node.ReadDir = TCP_Server_ReadDir;
505 srv->Node.FindDir = TCP_Server_FindDir;
506 srv->Node.IOCtl = TCP_Server_IOCtl;
507 srv->Node.Close = TCP_Server_Close;
509 LOCK(&glTCP_Listeners);
510 srv->Next = gTCP_Listeners;
511 gTCP_Listeners = srv;
512 RELEASE(&glTCP_Listeners);
518 * \brief Wait for a new connection and return the connection ID
519 * \note Blocks until a new connection is made
520 * \param Node Server node
521 * \param Pos Position (ignored)
523 char *TCP_Server_ReadDir(tVFS_Node *Node, int Pos)
525 tTCPListener *srv = Node->ImplPtr;
526 tTCPConnection *conn;
529 Log_Log("TCP", "Thread %i waiting for a connection", Threads_GetTID());
532 LOCK( &srv->lConnections );
533 if( srv->NewConnections != NULL ) break;
534 RELEASE( &srv->lConnections );
540 // Increment the new list (the current connection is still on the
542 conn = srv->NewConnections;
543 srv->NewConnections = conn->Next;
545 RELEASE( &srv->lConnections );
548 itoa(ret, Node->ImplInt, 16, 8, '0');
549 Log("TCP_Server_ReadDir: RETURN '%s'", ret);
554 * \brief Gets a client connection node
555 * \param Node Server node
556 * \param Name Hexadecimal ID of the node
558 tVFS_Node *TCP_Server_FindDir(tVFS_Node *Node, char *Name)
560 tTCPConnection *conn;
561 tTCPListener *srv = Node->ImplPtr;
566 itoa(tmp, id, 16, 8, '0');
567 if(strcmp(tmp, Name) != 0) return NULL;
570 LOCK( &srv->lConnections );
571 for(conn = srv->Connections;
572 conn && conn->Node.ImplInt != id;
574 RELEASE( &srv->lConnections );
576 // If not found, ret NULL
577 if(!conn) return NULL;
584 * \brief Handle IOCtl calls
586 int TCP_Server_IOCtl(tVFS_Node *Node, int ID, void *Data)
588 tTCPListener *srv = Node->ImplPtr;
592 case 4: // Get/Set Port
593 if(!Data) // Get Port
596 if(srv->Port) // Wait, you can't CHANGE the port
599 if(!CheckMem(Data, sizeof(Uint16))) // Sanity check
603 if(Threads_GetUID() != 0
604 && *(Uint16*)Data != 0
605 && *(Uint16*)Data < 1024)
608 // TODO: Check if a port is in use
611 srv->Port = *(Uint16*)Data;
612 if(srv->Port == 0) // Allocate a random port
613 srv->Port = TCP_GetUnusedPort();
614 else // Else, mark this as used
615 TCP_AllocatePort(srv->Port);
617 Log_Log("TCP", "Server %p listening on port %i", srv, srv->Port);
624 void TCP_Server_Close(tVFS_Node *Node)
631 * \brief Create a client node
633 tVFS_Node *TCP_Client_Init(tInterface *Interface)
635 tTCPConnection *conn = malloc( sizeof(tTCPConnection) );
637 conn->State = TCP_ST_CLOSED;
638 conn->Interface = Interface;
640 conn->RemotePort = 0;
641 memset( &conn->RemoteIP, 0, sizeof(conn->RemoteIP) );
643 conn->Node.ImplPtr = conn;
644 conn->Node.NumACLs = 1;
645 conn->Node.ACLs = &gVFS_ACL_EveryoneRW;
646 conn->Node.Read = TCP_Client_Read;
647 conn->Node.Write = TCP_Client_Write;
648 conn->Node.IOCtl = TCP_Client_IOCtl;
649 conn->Node.Close = TCP_Client_Close;
651 LOCK(&glTCP_OutbountCons);
652 conn->Next = gTCP_OutbountCons;
653 gTCP_OutbountCons = conn;
654 RELEASE(&glTCP_OutbountCons);
660 * \brief Wait for a packet and return it
661 * \note If \a Length is smaller than the size of the packet, the rest
662 * of the packet's data will be discarded.
664 Uint64 TCP_Client_Read(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer)
666 tTCPConnection *conn = Node->ImplPtr;
667 tTCPStoredPacket *pkt;
669 Log("TCP_Client_Read: (Length=%i)", Length);
671 // Check if connection is open
672 if( conn->State != TCP_ST_OPEN ) return 0;
677 // Lock list and check if there is a packet
678 LOCK( &conn->lRecievedPackets );
679 if( conn->RecievedPackets == NULL ) {
680 // If not, release the lock, yield and try again
681 RELEASE( &conn->lRecievedPackets );
686 // Get packet pointer
687 pkt = conn->RecievedPackets;
688 conn->RecievedPackets = pkt->Next;
689 // Release the lock (we don't need it any more)
690 RELEASE( &conn->lRecievedPackets );
692 Log("TCP_Client_Read: pkt->Length = %i", pkt->Length);
695 if(Length > pkt->Length) Length = pkt->Length;
696 memcpy(Buffer, pkt->Data, Length);
698 // Free packet and return
704 Uint64 TCP_Client_Write(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer)
710 * \brief Control a client socket
712 int TCP_Client_IOCtl(tVFS_Node *Node, int ID, void *Data)
714 tTCPConnection *conn = Node->ImplPtr;
718 case 4: // Get/Set local port
720 return conn->LocalPort;
721 if(conn->State != TCP_ST_CLOSED)
723 if(!CheckMem(Data, sizeof(Uint16)))
726 if(Threads_GetUID() != 0 && *(Uint16*)Data < 1024)
729 conn->LocalPort = *(Uint16*)Data;
732 case 5: // Get/Set remote port
733 if(!Data) return conn->RemotePort;
734 if(conn->State != TCP_ST_CLOSED) return -1;
735 if(!CheckMem(Data, sizeof(Uint16))) return -1;
736 conn->RemotePort = *(Uint16*)Data;
739 case 6: // Set Remote IP
740 if( conn->State != TCP_ST_CLOSED )
742 if( conn->Interface->Type == 4 )
744 if(!CheckMem(Data, sizeof(tIPv4))) return -1;
745 conn->RemoteIP.v4 = *(tIPv4*)Data;
747 else if( conn->Interface->Type == 6 )
749 if(!CheckMem(Data, sizeof(tIPv6))) return -1;
750 conn->RemoteIP.v6 = *(tIPv6*)Data;
755 if(conn->LocalPort == -1)
756 conn->LocalPort = TCP_GetUnusedPort();
757 if(conn->RemotePort == -1)
760 TCP_StartConnection(conn);
767 void TCP_Client_Close(tVFS_Node *Node)