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 * \fn void TCP_Initialise()
52 * \brief Initialise the TCP Layer
56 IPStack_AddFile(&gTCP_ServerFile);
57 IPStack_AddFile(&gTCP_ClientFile);
58 IPv4_RegisterCallback(IP4PROT_TCP, TCP_GetPacket);
62 * \brief Open a connection to another host using TCP
64 void TCP_StartConnection(tTCPConnection *Conn)
68 hdr.SourcePort = Conn->LocalPort;
69 hdr.DestPort = Conn->RemotePort;
70 Conn->NextSequenceSend = rand();
71 hdr.SequenceNumber = Conn->NextSequenceSend;
72 hdr.DataOffset = (sizeof(tTCPHeader)/4) << 4;
73 hdr.Flags = TCP_FLAG_SYN;
74 hdr.WindowSize = 0; // TODO
75 hdr.Checksum = 0; // TODO
76 hdr.UrgentPointer = 0;
78 TCP_SendPacket( Conn, sizeof(tTCPHeader), &hdr );
83 * \brief Sends a packet from the specified connection, calculating the checksums
84 * \param Conn Connection
85 * \param Length Length of data
86 * \param Data Packet data
88 void TCP_SendPacket( tTCPConnection *Conn, size_t Length, tTCPHeader *Data )
92 switch( Conn->Interface->Type )
94 case 4: // Append IPv4 Pseudo Header
95 buflen = 4 + 4 + 4 + ((Length+1)&~1);
96 buf = malloc( buflen );
97 buf[0] = Conn->Interface->IP4.Address.L;
98 buf[1] = Conn->RemoteIP.v4.L;
99 buf[2] = (htons(Length)<<16) | (6<<8) | 0;
101 memcpy( &buf[3], Data, Length );
102 Data->Checksum = IPv4_Checksum( buf, buflen );
104 IPv4_SendPacket(Conn->Interface, Conn->RemoteIP.v4, IP4PROT_TCP, 0, Length, Data);
110 * \fn void TCP_GetPacket(tInterface *Interface, void *Address, int Length, void *Buffer)
111 * \brief Handles a packet from the IP Layer
113 void TCP_GetPacket(tInterface *Interface, void *Address, int Length, void *Buffer)
115 tTCPHeader *hdr = Buffer;
117 tTCPConnection *conn;
119 Log("[TCP ] SourcePort = %i, DestPort = %i",
120 ntohs(hdr->SourcePort), ntohs(hdr->DestPort));
121 Log("[TCP ] SequenceNumber = 0x%x", ntohl(hdr->SequenceNumber));
122 Log("[TCP ] AcknowlegementNumber = 0x%x", ntohl(hdr->AcknowlegementNumber));
123 Log("[TCP ] DataOffset = %i", hdr->DataOffset >> 4);
124 Log("[TCP ] Flags = {");
125 Log("[TCP ] CWR = %B, ECE = %B",
126 !!(hdr->Flags & TCP_FLAG_CWR), !!(hdr->Flags & TCP_FLAG_ECE));
127 Log("[TCP ] URG = %B, ACK = %B",
128 !!(hdr->Flags & TCP_FLAG_URG), !!(hdr->Flags & TCP_FLAG_ACK));
129 Log("[TCP ] PSH = %B, RST = %B",
130 !!(hdr->Flags & TCP_FLAG_PSH), !!(hdr->Flags & TCP_FLAG_RST));
131 Log("[TCP ] SYN = %B, FIN = %B",
132 !!(hdr->Flags & TCP_FLAG_SYN), !!(hdr->Flags & TCP_FLAG_FIN));
134 Log("[TCP ] WindowSize = %i", htons(hdr->WindowSize));
135 Log("[TCP ] Checksum = 0x%x", htons(hdr->Checksum));
136 Log("[TCP ] UrgentPointer = 0x%x", htons(hdr->UrgentPointer));
138 if( Length > (hdr->DataOffset >> 4)*4 )
141 "[TCP ] Packet Data = ",
142 (Uint8*)hdr + (hdr->DataOffset >> 4)*4,
143 Length - (hdr->DataOffset >> 4)*4
149 for( srv = gTCP_Listeners; srv; srv = srv->Next )
151 // Check if the server is active
152 if(srv->Port == 0) continue;
153 // Check the interface
154 if(srv->Interface && srv->Interface != Interface) continue;
155 // Check the destination port
156 if(srv->Port != htons(hdr->DestPort)) continue;
158 Log("[TCP ] Matches server %p", srv);
159 // Is this in an established connection?
160 for( conn = srv->Connections; conn; conn = conn->Next )
162 Log("[TCP ] conn->Interface(%p) == Interface(%p)",
163 conn->Interface, Interface);
164 // Check that it is coming in on the same interface
165 if(conn->Interface != Interface) continue;
168 Log("[TCP ] conn->RemotePort(%i) == hdr->SourcePort(%i)",
169 conn->RemotePort, ntohs(hdr->SourcePort));
170 if(conn->RemotePort != ntohs(hdr->SourcePort)) continue;
173 if(conn->Interface->Type == 6 && !IP6_EQU(conn->RemoteIP.v6, *(tIPv6*)Address))
175 if(conn->Interface->Type == 4 && !IP4_EQU(conn->RemoteIP.v4, *(tIPv4*)Address))
178 Log("[TCP ] Matches connection %p", conn);
179 // We have a response!
180 TCP_INT_HandleConnectionPacket(conn, hdr, Length);
185 Log("[TCP ] Opening Connection");
186 // Open a new connection (well, check that it's a SYN)
187 if(hdr->Flags != TCP_FLAG_SYN) {
188 Log("[TCP ] Packet is not a SYN");
192 // TODO: Check for halfopen max
194 conn = calloc(1, sizeof(tTCPConnection));
195 conn->State = TCP_ST_HALFOPEN;
196 conn->LocalPort = srv->Port;
197 conn->RemotePort = ntohs(hdr->SourcePort);
198 conn->Interface = Interface;
200 switch(Interface->Type)
202 case 4: conn->RemoteIP.v4 = *(tIPv4*)Address; break;
203 case 6: conn->RemoteIP.v6 = *(tIPv6*)Address; break;
206 conn->NextSequenceRcv = ntohl( hdr->SequenceNumber ) + 1;
207 // + (Length-(hdr->DataOffset>>4)*4);
208 conn->NextSequenceSend = rand();
211 conn->Node.NumACLs = 1;
212 conn->Node.ACLs = &gVFS_ACL_EveryoneRW;
213 conn->Node.ImplInt = srv->NextID ++;
214 conn->Node.Read = TCP_Client_Read;
215 conn->Node.Write = TCP_Client_Write;
216 //conn->Node.Close = TCP_SrvConn_Close;
218 // Hmm... Theoretically, this lock will never have to wait,
219 // as the interface is locked to the watching thread, and this
220 // runs in the watching thread. But, it's a good idea to have
222 // Oh, wait, there is a case where a wildcard can be used
223 // (srv->Interface == NULL) so having the lock is a good idea
224 LOCK(&srv->lConnections);
225 if( !srv->Connections )
226 srv->Connections = conn;
228 srv->ConnectionsTail->Next = conn;
229 srv->ConnectionsTail = conn;
230 if(!srv->NewConnections)
231 srv->NewConnections = conn;
232 RELEASE(&srv->lConnections);
235 hdr->Flags |= TCP_FLAG_ACK;
236 hdr->AcknowlegementNumber = htonl(conn->NextSequenceRcv);
237 hdr->SequenceNumber = htonl(conn->NextSequenceSend);
238 hdr->DestPort = hdr->SourcePort;
239 hdr->SourcePort = htons(srv->Port);
240 hdr->DataOffset = (sizeof(tTCPHeader)/4) << 4;
241 TCP_SendPacket( conn, sizeof(tTCPHeader), hdr );
248 // Check Open Connections
250 for( conn = gTCP_OutbountCons; conn; conn = conn->Next )
252 // Check that it is coming in on the same interface
253 if(conn->Interface != Interface) continue;
256 if(conn->RemotePort != ntohs(hdr->SourcePort)) continue;
259 if(conn->Interface->Type == 6 && !IP6_EQU(conn->RemoteIP.v6, *(tIPv6*)Address))
261 if(conn->Interface->Type == 4 && !IP4_EQU(conn->RemoteIP.v4, *(tIPv4*)Address))
264 TCP_INT_HandleConnectionPacket(conn, hdr, Length);
269 Log("[TCP ] No Match");
273 * \brief Handles a packet sent to a specific connection
275 void TCP_INT_HandleConnectionPacket(tTCPConnection *Connection, tTCPHeader *Header, int Length)
277 tTCPStoredPacket *pkt;
280 Connection->State = TCP_ST_OPEN;
281 if(Header->Flags & TCP_FLAG_SYN) {
282 Connection->NextSequenceRcv = Header->SequenceNumber + 1;
285 // Get length of data
286 dataLen = Length - (Header->DataOffset>>4)*4;
287 Log("[TCP ] HandleConnectionPacket - dataLen = %i", dataLen);
289 if(Header->Flags & TCP_FLAG_ACK) {
290 // TODO: Process an ACKed Packet
291 Log("[TCP ] Conn %p, Packet 0x%x ACKed", Connection, Header->AcknowlegementNumber);
294 if(dataLen == 0) return ;
301 // Allocate and fill cached packet
302 pkt = malloc( dataLen + sizeof(tTCPStoredPacket) );
304 pkt->Sequence = ntohl(Header->SequenceNumber);
305 pkt->Length = dataLen;
306 memcpy(pkt->Data, (Uint8*)Header + (Header->DataOffset>>4)*4, dataLen);
308 // Is this packet the next expected packet?
309 if( pkt->Sequence != Connection->NextSequenceRcv )
311 tTCPStoredPacket *tmp, *prev;
313 Log("[TCP ] Out of sequence packet (0x%08x != 0x%08x)",
314 pkt->Sequence, Connection->NextSequenceRcv);
316 // No? Well, let's cache it and look at it later
317 LOCK( &Connection->lFuturePackets );
318 for(tmp = Connection->FuturePackets;
320 prev = tmp, tmp = tmp->Next)
322 if(tmp->Sequence > pkt->Sequence) break;
327 Connection->FuturePackets = pkt;
329 RELEASE( &Connection->lFuturePackets );
333 // Ooh, Goodie! Add it to the recieved list
334 TCP_INT_AppendRecieved(Connection, pkt);
335 Connection->NextSequenceRcv ++;
337 // TODO: This should be moved out of the watcher thread,
338 // so that a single lost packet on one connection doesn't cause
339 // all connections on the interface to lag.
340 TCP_INT_UpdateRecievedFromFuture(Connection);
343 // TODO: Check ACK code validity
344 Header->AcknowlegementNumber = ntohl(pkt->Sequence);
345 Header->SequenceNumber = ntohl(Connection->NextSequenceSend);
346 Header->Flags &= TCP_FLAG_SYN;
347 Header->Flags = TCP_FLAG_ACK;
348 TCP_SendPacket( Connection, sizeof(tTCPHeader), Header );
352 * \brief Appends a packet to the recieved list
354 void TCP_INT_AppendRecieved(tTCPConnection *Connection, tTCPStoredPacket *Pkt)
356 LOCK( &Connection->lRecievedPackets );
357 if(Connection->RecievedPackets)
359 Connection->RecievedPacketsTail->Next = Pkt;
360 Connection->RecievedPacketsTail = Pkt;
364 Connection->RecievedPackets = Pkt;
365 Connection->RecievedPacketsTail = Pkt;
367 RELEASE( &Connection->lRecievedPackets );
371 * \brief Updates the connections recieved list from the future list
373 void TCP_INT_UpdateRecievedFromFuture(tTCPConnection *Connection)
375 tTCPStoredPacket *pkt, *prev;
379 // Look for the next expected packet in the cache.
380 LOCK( &Connection->lFuturePackets );
381 for(pkt = Connection->FuturePackets;
382 pkt && pkt->Sequence < Connection->NextSequenceRcv;
383 prev = pkt, pkt = pkt->Next);
385 // If we can't find the expected next packet, stop looking
386 if(!pkt || pkt->Sequence > Connection->NextSequenceRcv) {
387 RELEASE( &Connection->lFuturePackets );
391 // Delete packet from future list
393 prev->Next = pkt->Next;
395 Connection->FuturePackets = pkt->Next;
398 RELEASE( &Connection->lFuturePackets );
400 // Looks like we found one
401 TCP_INT_AppendRecieved(Connection, pkt);
402 Connection->NextSequenceRcv ++;
407 * \fn Uint16 TCP_GetUnusedPort()
408 * \brief Gets an unused port and allocates it
410 Uint16 TCP_GetUnusedPort()
414 // Get Next outbound port
415 ret = giTCP_NextOutPort++;
416 while( gaTCP_PortBitmap[ret/32] & (1 << (ret%32)) )
420 if(giTCP_NextOutPort == 0x10000) {
421 ret = giTCP_NextOutPort = TCP_MIN_DYNPORT;
425 // Mark the new port as used
426 gaTCP_PortBitmap[ret/32] |= 1 << (ret%32);
432 * \fn int TCP_AllocatePort(Uint16 Port)
433 * \brief Marks a port as used
435 int TCP_AllocatePort(Uint16 Port)
437 // Check if the port has already been allocated
438 if( gaTCP_PortBitmap[Port/32] & (1 << (Port%32)) )
442 gaTCP_PortBitmap[Port/32] |= 1 << (Port%32);
448 * \fn int TCP_DeallocatePort(Uint16 Port)
449 * \brief Marks a port as unused
451 int TCP_DeallocatePort(Uint16 Port)
453 // Check if the port has already been allocated
454 if( !(gaTCP_PortBitmap[Port/32] & (1 << (Port%32))) )
458 gaTCP_PortBitmap[Port/32] &= ~(1 << (Port%32));
464 tVFS_Node *TCP_Server_Init(tInterface *Interface)
466 tTCPListener *srv = malloc( sizeof(tTCPListener) );
468 srv->Interface = Interface;
471 srv->Connections = NULL;
473 srv->Node.Flags = VFS_FFLAG_DIRECTORY;
475 srv->Node.ImplPtr = srv;
476 srv->Node.NumACLs = 1;
477 srv->Node.ACLs = &gVFS_ACL_EveryoneRW;
478 srv->Node.ReadDir = TCP_Server_ReadDir;
479 srv->Node.FindDir = TCP_Server_FindDir;
480 srv->Node.IOCtl = TCP_Server_IOCtl;
481 srv->Node.Close = TCP_Server_Close;
483 LOCK(&glTCP_Listeners);
484 srv->Next = gTCP_Listeners;
485 gTCP_Listeners = srv;
486 RELEASE(&glTCP_Listeners);
492 * \brief Wait for a new connection and return the connection ID
493 * \note Blocks until a new connection is made
494 * \param Node Server node
495 * \param Pos Position (ignored)
497 char *TCP_Server_ReadDir(tVFS_Node *Node, int Pos)
499 tTCPListener *srv = Node->ImplPtr;
500 tTCPConnection *conn;
503 Log("[TCP ] Thread %i waiting for a connection", Threads_GetTID());
506 LOCK( &srv->lConnections );
507 if( srv->NewConnections != NULL ) break;
508 RELEASE( &srv->lConnections );
514 // Increment the new list (the current connection is still on the
516 conn = srv->NewConnections;
517 srv->NewConnections = conn->Next;
519 RELEASE( &srv->lConnections );
522 itoa(ret, Node->ImplInt, 16, 8, '0');
523 Log("TCP_Server_ReadDir: RETURN '%s'", ret);
528 * \brief Gets a client connection node
529 * \param Node Server node
530 * \param Name Hexadecimal ID of the node
532 tVFS_Node *TCP_Server_FindDir(tVFS_Node *Node, char *Name)
534 tTCPConnection *conn;
535 tTCPListener *srv = Node->ImplPtr;
540 itoa(tmp, id, 16, 8, '0');
541 if(strcmp(tmp, Name) != 0) return NULL;
544 LOCK( &srv->lConnections );
545 for(conn = srv->Connections;
546 conn && conn->Node.ImplInt != id;
548 RELEASE( &srv->lConnections );
550 // If not found, ret NULL
551 if(!conn) return NULL;
558 * \brief Handle IOCtl calls
560 int TCP_Server_IOCtl(tVFS_Node *Node, int ID, void *Data)
562 tTCPListener *srv = Node->ImplPtr;
566 case 4: // Get/Set Port
567 if(!Data) // Get Port
570 if(srv->Port) // Wait, you can't CHANGE the port
573 if(!CheckMem(Data, sizeof(Uint16))) // Sanity check
577 if(Threads_GetUID() != 0
578 && *(Uint16*)Data != 0
579 && *(Uint16*)Data < 1024)
582 // TODO: Check if a port is in use
585 srv->Port = *(Uint16*)Data;
586 if(srv->Port == 0) // Allocate a random port
587 srv->Port = TCP_GetUnusedPort();
588 else // Else, mark this as used
589 TCP_AllocatePort(srv->Port);
591 Log("[TCP ] Server %p listening on port %i", srv, srv->Port);
598 void TCP_Server_Close(tVFS_Node *Node)
605 * \brief Create a client node
607 tVFS_Node *TCP_Client_Init(tInterface *Interface)
609 tTCPConnection *conn = malloc( sizeof(tTCPConnection) );
611 conn->State = TCP_ST_CLOSED;
612 conn->Interface = Interface;
614 conn->RemotePort = 0;
615 memset( &conn->RemoteIP, 0, sizeof(conn->RemoteIP) );
617 conn->Node.ImplPtr = conn;
618 conn->Node.NumACLs = 1;
619 conn->Node.ACLs = &gVFS_ACL_EveryoneRW;
620 conn->Node.Read = TCP_Client_Read;
621 conn->Node.Write = TCP_Client_Write;
622 conn->Node.IOCtl = TCP_Client_IOCtl;
623 conn->Node.Close = TCP_Client_Close;
625 LOCK(&glTCP_OutbountCons);
626 conn->Next = gTCP_OutbountCons;
627 gTCP_OutbountCons = conn;
628 RELEASE(&glTCP_OutbountCons);
634 * \brief Wait for a packet and return it
635 * \note If \a Length is smaller than the size of the packet, the rest
636 * of the packet's data will be discarded.
638 Uint64 TCP_Client_Read(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer)
640 tTCPConnection *conn = Node->ImplPtr;
641 tTCPStoredPacket *pkt;
643 Log("TCP_Client_Read: (Length=%i)", Length);
645 // Check if connection is open
646 if( conn->State != TCP_ST_OPEN ) return 0;
651 // Lock list and check if there is a packet
652 LOCK( &conn->lRecievedPackets );
653 if( conn->RecievedPackets == NULL ) {
654 // If not, release the lock, yield and try again
655 RELEASE( &conn->lRecievedPackets );
660 // Get packet pointer
661 pkt = conn->RecievedPackets;
662 conn->RecievedPackets = pkt->Next;
663 // Release the lock (we don't need it any more)
664 RELEASE( &conn->lRecievedPackets );
666 Log("TCP_Client_Read: pkt->Length = %i", pkt->Length);
669 if(Length > pkt->Length) Length = pkt->Length;
670 memcpy(Buffer, pkt->Data, Length);
672 // Free packet and return
678 Uint64 TCP_Client_Write(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer)
684 * \brief Control a client socket
686 int TCP_Client_IOCtl(tVFS_Node *Node, int ID, void *Data)
688 tTCPConnection *conn = Node->ImplPtr;
692 case 4: // Get/Set local port
694 return conn->LocalPort;
695 if(conn->State != TCP_ST_CLOSED)
697 if(!CheckMem(Data, sizeof(Uint16)))
700 if(Threads_GetUID() != 0 && *(Uint16*)Data < 1024)
703 conn->LocalPort = *(Uint16*)Data;
706 case 5: // Get/Set remote port
707 if(!Data) return conn->RemotePort;
708 if(conn->State != TCP_ST_CLOSED) return -1;
709 if(!CheckMem(Data, sizeof(Uint16))) return -1;
710 conn->RemotePort = *(Uint16*)Data;
713 case 6: // Set Remote IP
714 if( conn->State != TCP_ST_CLOSED )
716 if( conn->Interface->Type == 4 )
718 if(!CheckMem(Data, sizeof(tIPv4))) return -1;
719 conn->RemoteIP.v4 = *(tIPv4*)Data;
721 else if( conn->Interface->Type == 6 )
723 if(!CheckMem(Data, sizeof(tIPv6))) return -1;
724 conn->RemoteIP.v6 = *(tIPv6*)Data;
729 if(conn->LocalPort == -1)
730 conn->LocalPort = TCP_GetUnusedPort();
731 if(conn->RemotePort == -1)
734 TCP_StartConnection(conn);
741 void TCP_Client_Close(tVFS_Node *Node)