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("[TCP ] SourcePort = %i, DestPort = %i",
125 ntohs(hdr->SourcePort), ntohs(hdr->DestPort));
126 Log("[TCP ] SequenceNumber = 0x%x", ntohl(hdr->SequenceNumber));
127 Log("[TCP ] AcknowlegementNumber = 0x%x", ntohl(hdr->AcknowlegementNumber));
128 Log("[TCP ] DataOffset = %i", hdr->DataOffset >> 4);
129 Log("[TCP ] Flags = {");
130 Log("[TCP ] CWR = %B, ECE = %B",
131 !!(hdr->Flags & TCP_FLAG_CWR), !!(hdr->Flags & TCP_FLAG_ECE));
132 Log("[TCP ] URG = %B, ACK = %B",
133 !!(hdr->Flags & TCP_FLAG_URG), !!(hdr->Flags & TCP_FLAG_ACK));
134 Log("[TCP ] PSH = %B, RST = %B",
135 !!(hdr->Flags & TCP_FLAG_PSH), !!(hdr->Flags & TCP_FLAG_RST));
136 Log("[TCP ] SYN = %B, FIN = %B",
137 !!(hdr->Flags & TCP_FLAG_SYN), !!(hdr->Flags & TCP_FLAG_FIN));
139 Log("[TCP ] WindowSize = %i", htons(hdr->WindowSize));
140 Log("[TCP ] Checksum = 0x%x", htons(hdr->Checksum));
141 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("[TCP ] Matches server %p", srv);
164 // Is this in an established connection?
165 for( conn = srv->Connections; conn; conn = conn->Next )
167 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("[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("[TCP ] Matches connection %p", conn);
184 // We have a response!
185 TCP_INT_HandleConnectionPacket(conn, hdr, Length);
190 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("[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("[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("[TCP ] HandleConnectionPacket - dataLen = %i", dataLen);
296 if(Header->Flags & TCP_FLAG_ACK) {
297 // TODO: Process an ACKed Packet
298 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("[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);
353 // TODO: Check ACK code validity
354 Header->AcknowlegementNumber = ntohl(pkt->Sequence) + dataLen;
355 Header->SequenceNumber = ntohl(Connection->NextSequenceSend);
356 Header->Flags &= TCP_FLAG_SYN;
357 Header->Flags = TCP_FLAG_ACK;
358 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)
483 tTCPListener *srv = malloc( sizeof(tTCPListener) );
485 Log_Debug("TCP", "srv = %p", srv);
488 Log_Warning("TCP", "malloc failed for listener (%i) bytes", sizeof(tTCPListener));
492 srv->Interface = Interface;
495 srv->Connections = NULL;
497 srv->Node.Flags = VFS_FFLAG_DIRECTORY;
499 srv->Node.ImplPtr = srv;
500 srv->Node.NumACLs = 1;
501 srv->Node.ACLs = &gVFS_ACL_EveryoneRW;
502 srv->Node.ReadDir = TCP_Server_ReadDir;
503 srv->Node.FindDir = TCP_Server_FindDir;
504 srv->Node.IOCtl = TCP_Server_IOCtl;
505 srv->Node.Close = TCP_Server_Close;
507 LOCK(&glTCP_Listeners);
508 srv->Next = gTCP_Listeners;
509 gTCP_Listeners = srv;
510 RELEASE(&glTCP_Listeners);
516 * \brief Wait for a new connection and return the connection ID
517 * \note Blocks until a new connection is made
518 * \param Node Server node
519 * \param Pos Position (ignored)
521 char *TCP_Server_ReadDir(tVFS_Node *Node, int Pos)
523 tTCPListener *srv = Node->ImplPtr;
524 tTCPConnection *conn;
527 Log("[TCP ] Thread %i waiting for a connection", Threads_GetTID());
530 LOCK( &srv->lConnections );
531 if( srv->NewConnections != NULL ) break;
532 RELEASE( &srv->lConnections );
538 // Increment the new list (the current connection is still on the
540 conn = srv->NewConnections;
541 srv->NewConnections = conn->Next;
543 RELEASE( &srv->lConnections );
546 itoa(ret, Node->ImplInt, 16, 8, '0');
547 Log("TCP_Server_ReadDir: RETURN '%s'", ret);
552 * \brief Gets a client connection node
553 * \param Node Server node
554 * \param Name Hexadecimal ID of the node
556 tVFS_Node *TCP_Server_FindDir(tVFS_Node *Node, char *Name)
558 tTCPConnection *conn;
559 tTCPListener *srv = Node->ImplPtr;
564 itoa(tmp, id, 16, 8, '0');
565 if(strcmp(tmp, Name) != 0) return NULL;
568 LOCK( &srv->lConnections );
569 for(conn = srv->Connections;
570 conn && conn->Node.ImplInt != id;
572 RELEASE( &srv->lConnections );
574 // If not found, ret NULL
575 if(!conn) return NULL;
582 * \brief Handle IOCtl calls
584 int TCP_Server_IOCtl(tVFS_Node *Node, int ID, void *Data)
586 tTCPListener *srv = Node->ImplPtr;
590 case 4: // Get/Set Port
591 if(!Data) // Get Port
594 if(srv->Port) // Wait, you can't CHANGE the port
597 if(!CheckMem(Data, sizeof(Uint16))) // Sanity check
601 if(Threads_GetUID() != 0
602 && *(Uint16*)Data != 0
603 && *(Uint16*)Data < 1024)
606 // TODO: Check if a port is in use
609 srv->Port = *(Uint16*)Data;
610 if(srv->Port == 0) // Allocate a random port
611 srv->Port = TCP_GetUnusedPort();
612 else // Else, mark this as used
613 TCP_AllocatePort(srv->Port);
615 Log("[TCP ] Server %p listening on port %i", srv, srv->Port);
622 void TCP_Server_Close(tVFS_Node *Node)
629 * \brief Create a client node
631 tVFS_Node *TCP_Client_Init(tInterface *Interface)
633 tTCPConnection *conn = malloc( sizeof(tTCPConnection) );
635 conn->State = TCP_ST_CLOSED;
636 conn->Interface = Interface;
638 conn->RemotePort = 0;
639 memset( &conn->RemoteIP, 0, sizeof(conn->RemoteIP) );
641 conn->Node.ImplPtr = conn;
642 conn->Node.NumACLs = 1;
643 conn->Node.ACLs = &gVFS_ACL_EveryoneRW;
644 conn->Node.Read = TCP_Client_Read;
645 conn->Node.Write = TCP_Client_Write;
646 conn->Node.IOCtl = TCP_Client_IOCtl;
647 conn->Node.Close = TCP_Client_Close;
649 LOCK(&glTCP_OutbountCons);
650 conn->Next = gTCP_OutbountCons;
651 gTCP_OutbountCons = conn;
652 RELEASE(&glTCP_OutbountCons);
658 * \brief Wait for a packet and return it
659 * \note If \a Length is smaller than the size of the packet, the rest
660 * of the packet's data will be discarded.
662 Uint64 TCP_Client_Read(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer)
664 tTCPConnection *conn = Node->ImplPtr;
665 tTCPStoredPacket *pkt;
667 Log("TCP_Client_Read: (Length=%i)", Length);
669 // Check if connection is open
670 if( conn->State != TCP_ST_OPEN ) return 0;
675 // Lock list and check if there is a packet
676 LOCK( &conn->lRecievedPackets );
677 if( conn->RecievedPackets == NULL ) {
678 // If not, release the lock, yield and try again
679 RELEASE( &conn->lRecievedPackets );
684 // Get packet pointer
685 pkt = conn->RecievedPackets;
686 conn->RecievedPackets = pkt->Next;
687 // Release the lock (we don't need it any more)
688 RELEASE( &conn->lRecievedPackets );
690 Log("TCP_Client_Read: pkt->Length = %i", pkt->Length);
693 if(Length > pkt->Length) Length = pkt->Length;
694 memcpy(Buffer, pkt->Data, Length);
696 // Free packet and return
702 Uint64 TCP_Client_Write(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer)
708 * \brief Control a client socket
710 int TCP_Client_IOCtl(tVFS_Node *Node, int ID, void *Data)
712 tTCPConnection *conn = Node->ImplPtr;
716 case 4: // Get/Set local port
718 return conn->LocalPort;
719 if(conn->State != TCP_ST_CLOSED)
721 if(!CheckMem(Data, sizeof(Uint16)))
724 if(Threads_GetUID() != 0 && *(Uint16*)Data < 1024)
727 conn->LocalPort = *(Uint16*)Data;
730 case 5: // Get/Set remote port
731 if(!Data) return conn->RemotePort;
732 if(conn->State != TCP_ST_CLOSED) return -1;
733 if(!CheckMem(Data, sizeof(Uint16))) return -1;
734 conn->RemotePort = *(Uint16*)Data;
737 case 6: // Set Remote IP
738 if( conn->State != TCP_ST_CLOSED )
740 if( conn->Interface->Type == 4 )
742 if(!CheckMem(Data, sizeof(tIPv4))) return -1;
743 conn->RemoteIP.v4 = *(tIPv4*)Data;
745 else if( conn->Interface->Type == 6 )
747 if(!CheckMem(Data, sizeof(tIPv6))) return -1;
748 conn->RemoteIP.v6 = *(tIPv6*)Data;
753 if(conn->LocalPort == -1)
754 conn->LocalPort = TCP_GetUnusedPort();
755 if(conn->RemotePort == -1)
758 TCP_StartConnection(conn);
765 void TCP_Client_Close(tVFS_Node *Node)