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)+3)/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, buflen, buf);
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 ] sizeof(tTCPHeader) = %i", sizeof(tTCPHeader));
120 Log("[TCP ] SourcePort = %i", ntohs(hdr->SourcePort));
121 Log("[TCP ] DestPort = %i", ntohs(hdr->DestPort));
122 Log("[TCP ] SequenceNumber = 0x%x", ntohl(hdr->SequenceNumber));
123 Log("[TCP ] AcknowlegementNumber = 0x%x", ntohl(hdr->AcknowlegementNumber));
124 Log("[TCP ] DataOffset = %i", hdr->DataOffset >> 4);
125 Log("[TCP ] Flags = {");
126 Log("[TCP ] CWR = %B", !!(hdr->Flags & TCP_FLAG_CWR));
127 Log("[TCP ] ECE = %B", !!(hdr->Flags & TCP_FLAG_ECE));
128 Log("[TCP ] URG = %B", !!(hdr->Flags & TCP_FLAG_URG));
129 Log("[TCP ] ACK = %B", !!(hdr->Flags & TCP_FLAG_ACK));
130 Log("[TCP ] PSH = %B", !!(hdr->Flags & TCP_FLAG_PSH));
131 Log("[TCP ] RST = %B", !!(hdr->Flags & TCP_FLAG_RST));
132 Log("[TCP ] SYN = %B", !!(hdr->Flags & TCP_FLAG_SYN));
133 Log("[TCP ] FIN = %B", !!(hdr->Flags & TCP_FLAG_FIN));
135 Log("[TCP ] WindowSize = %i", htons(hdr->WindowSize));
136 Log("[TCP ] Checksum = 0x%x", htons(hdr->Checksum));
137 Log("[TCP ] UrgentPointer = 0x%x", htons(hdr->UrgentPointer));
141 for( srv = gTCP_Listeners; srv; srv = srv->Next )
143 // Check if the server is active
144 if(srv->Port == 0) continue;
145 // Check the interface
146 if(srv->Interface && srv->Interface != Interface) continue;
147 // Check the destination port
148 if(srv->Port != hdr->DestPort) continue;
150 // Is this in an established connection?
151 for( conn = srv->Connections; conn; conn = conn->Next )
153 // Check that it is coming in on the same interface
154 if(conn->Interface != Interface) continue;
157 if(conn->RemotePort != hdr->SourcePort) continue;
160 if(conn->Interface->Type == 6 && !IP6_EQU(conn->RemoteIP.v6, *(tIPv6*)Address))
162 if(conn->Interface->Type == 4 && !IP4_EQU(conn->RemoteIP.v4, *(tIPv4*)Address))
165 // We have a response!
166 TCP_INT_HandleConnectionPacket(conn, hdr, Length);
171 // Open a new connection (well, check that it's a SYN)
172 if(hdr->Flags != TCP_FLAG_SYN) {
173 Log("[TCP ] Packet is not a SYN");
177 // TODO: Check for halfopen max
179 conn = calloc(1, sizeof(tTCPConnection));
180 conn->State = TCP_ST_HALFOPEN;
181 conn->LocalPort = srv->Port;
182 conn->RemotePort = hdr->SourcePort;
183 conn->Interface = Interface;
185 switch(Interface->Type)
187 case 4: conn->RemoteIP.v4 = *(tIPv4*)Address; break;
188 case 6: conn->RemoteIP.v6 = *(tIPv6*)Address; break;
191 conn->NextSequenceRcv = ntohl( hdr->SequenceNumber );
192 conn->NextSequenceSend = rand();
195 conn->Node.NumACLs = 1;
196 conn->Node.ACLs = &gVFS_ACL_EveryoneRW;
197 conn->Node.ImplInt = srv->NextID ++;
198 conn->Node.Read = TCP_Client_Read;
199 conn->Node.Write = TCP_Client_Write;
200 //conn->Node.Close = TCP_SrvConn_Close;
202 // Hmm... Theoretically, this lock will never have to wait,
203 // as the interface is locked to the watching thread, and this
204 // runs in the watching thread. But, it's a good idea to have
206 LOCK(&srv->lConnections);
207 conn->Next = srv->Connections;
208 srv->Connections = conn;
209 RELEASE(&srv->lConnections);
212 Log("[TCP ] TODO: Sending SYN ACK");
213 hdr->Flags |= TCP_FLAG_ACK;
214 hdr->AcknowlegementNumber = hdr->SequenceNumber;
215 hdr->SequenceNumber = conn->NextSequenceSend;
216 hdr->DestPort = hdr->SourcePort;
217 hdr->SourcePort = srv->Port;
218 TCP_SendPacket( conn, sizeof(tTCPHeader), hdr );
225 // Check Open Connections
227 for( conn = gTCP_OutbountCons; conn; conn = conn->Next )
229 // Check that it is coming in on the same interface
230 if(conn->Interface != Interface) continue;
233 if(conn->RemotePort != hdr->SourcePort) continue;
236 if(conn->Interface->Type == 6 && !IP6_EQU(conn->RemoteIP.v6, *(tIPv6*)Address))
238 if(conn->Interface->Type == 4 && !IP4_EQU(conn->RemoteIP.v4, *(tIPv4*)Address))
241 TCP_INT_HandleConnectionPacket(conn, hdr, Length);
247 * \brief Handles a packet sent to a specific connection
249 void TCP_INT_HandleConnectionPacket(tTCPConnection *Connection, tTCPHeader *Header, int Length)
251 tTCPStoredPacket *pkt;
254 Connection->State = TCP_ST_OPEN;
255 if(Header->Flags & TCP_FLAG_SYN) {
256 Connection->NextSequenceRcv = Header->SequenceNumber + 1;
259 if(Header->Flags & TCP_FLAG_ACK) {
260 // TODO: Process an ACKed Packet
261 Log("[TCP ] Conn %p, Packet 0x%x ACKed", Connection, Header->AcknowlegementNumber);
265 // Allocate and fill cached packet
266 dataLen = Length - (Header->DataOffset&0xF)*4;
267 pkt = malloc( dataLen + sizeof(tTCPStoredPacket) );
269 pkt->Sequence = Header->SequenceNumber;
270 memcpy(pkt->Data, (Uint8*)Header + (Header->DataOffset&0xF)*4, dataLen);
272 // Is this packet the next expected packet?
273 if( Header->SequenceNumber != Connection->NextSequenceRcv )
275 tTCPStoredPacket *tmp, *prev;
276 // No? Well, let's cache it and look at it later
277 LOCK( &Connection->lFuturePackets );
278 for(tmp = Connection->FuturePackets;
280 prev = tmp, tmp = tmp->Next)
282 if(tmp->Sequence > pkt->Sequence) break;
287 Connection->FuturePackets = pkt;
289 RELEASE( &Connection->lFuturePackets );
293 // Ooh, Goodie! Add it to the recieved list
294 TCP_INT_AppendRecieved(Connection, pkt);
295 Connection->NextSequenceRcv ++;
297 // TODO: This should be moved out of the watcher thread,
298 // so that a single lost packet on one connection doesn't cause
299 // all connections on the interface to lag.
300 TCP_INT_UpdateRecievedFromFuture(Connection);
303 // TODO: Check ACK code validity
304 Header->AcknowlegementNumber = pkt->Sequence;
305 Header->SequenceNumber = Connection->NextSequenceSend;
306 Header->Flags |= TCP_FLAG_ACK;
307 TCP_SendPacket( Connection, sizeof(tTCPHeader), Header );
311 * \brief Appends a packet to the recieved list
313 void TCP_INT_AppendRecieved(tTCPConnection *Connection, tTCPStoredPacket *Pkt)
315 LOCK( &Connection->lRecievedPackets );
316 if(Connection->RecievedPackets)
318 Connection->RecievedPacketsTail->Next = Pkt;
319 Connection->RecievedPacketsTail = Pkt;
323 Connection->RecievedPackets = Pkt;
324 Connection->RecievedPacketsTail = Pkt;
326 RELEASE( &Connection->lRecievedPackets );
330 * \brief Updates the connections recieved list from the future list
332 void TCP_INT_UpdateRecievedFromFuture(tTCPConnection *Connection)
334 tTCPStoredPacket *pkt, *prev;
338 // Look for the next expected packet in the cache.
339 LOCK( &Connection->lFuturePackets );
340 for(pkt = Connection->FuturePackets;
341 pkt && pkt->Sequence < Connection->NextSequenceRcv;
342 prev = pkt, pkt = pkt->Next);
344 // If we can't find the expected next packet, stop looking
345 if(!pkt || pkt->Sequence > Connection->NextSequenceRcv) {
346 RELEASE( &Connection->lFuturePackets );
350 // Delete packet from future list
352 prev->Next = pkt->Next;
354 Connection->FuturePackets = pkt->Next;
357 RELEASE( &Connection->lFuturePackets );
359 // Looks like we found one
360 TCP_INT_AppendRecieved(Connection, pkt);
361 Connection->NextSequenceRcv ++;
366 * \fn Uint16 TCP_GetUnusedPort()
367 * \brief Gets an unused port and allocates it
369 Uint16 TCP_GetUnusedPort()
373 // Get Next outbound port
374 ret = giTCP_NextOutPort++;
375 while( gaTCP_PortBitmap[ret/32] & (1 << (ret%32)) )
379 if(giTCP_NextOutPort == 0x10000) {
380 ret = giTCP_NextOutPort = TCP_MIN_DYNPORT;
384 // Mark the new port as used
385 gaTCP_PortBitmap[ret/32] |= 1 << (ret%32);
391 * \fn int TCP_AllocatePort(Uint16 Port)
392 * \brief Marks a port as used
394 int TCP_AllocatePort(Uint16 Port)
396 // Check if the port has already been allocated
397 if( gaTCP_PortBitmap[Port/32] & (1 << (Port%32)) )
401 gaTCP_PortBitmap[Port/32] |= 1 << (Port%32);
407 * \fn int TCP_DeallocatePort(Uint16 Port)
408 * \brief Marks a port as unused
410 int TCP_DeallocatePort(Uint16 Port)
412 // Check if the port has already been allocated
413 if( !(gaTCP_PortBitmap[Port/32] & (1 << (Port%32))) )
417 gaTCP_PortBitmap[Port/32] &= ~(1 << (Port%32));
423 tVFS_Node *TCP_Server_Init(tInterface *Interface)
425 tTCPListener *srv = malloc( sizeof(tTCPListener) );
427 srv->Interface = Interface;
430 srv->Connections = NULL;
432 srv->Node.ImplPtr = srv;
433 srv->Node.NumACLs = 1;
434 srv->Node.ACLs = &gVFS_ACL_EveryoneRW;
435 srv->Node.ReadDir = TCP_Server_ReadDir;
436 srv->Node.FindDir = TCP_Server_FindDir;
437 srv->Node.IOCtl = TCP_Server_IOCtl;
438 srv->Node.Close = TCP_Server_Close;
440 LOCK(&glTCP_Listeners);
441 srv->Next = gTCP_Listeners;
442 gTCP_Listeners = srv;
443 RELEASE(&glTCP_Listeners);
449 * \brief Wait for a new connection and return the connection ID
450 * \note Blocks until a new connection is made
451 * \param Node Server node
452 * \param Pos Position (ignored)
454 char *TCP_Server_ReadDir(tVFS_Node *Node, int Pos)
456 tTCPListener *srv = Node->ImplPtr;
457 tTCPConnection *conn;
460 while( srv->NewConnections == NULL ) Threads_Yield();
462 conn = srv->NewConnections;
463 srv->NewConnections = conn->Next;
466 itoa(ret, Node->ImplInt, 16, '0', 8);
471 * \brief Gets a client connection node
472 * \param Node Server node
473 * \param Name Hexadecimal ID of the node
475 tVFS_Node *TCP_Server_FindDir(tVFS_Node *Node, char *Name)
480 int TCP_Server_IOCtl(tVFS_Node *Node, int ID, void *Data)
482 tTCPListener *srv = Node->ImplPtr;
486 case 4: // Get/Set Port
487 if(!Data) // Get Port
490 if(srv->Port) // Wait, you can't CHANGE the port
493 if(!CheckMem(Data, sizeof(Uint16))) // Sanity check
497 if(Threads_GetUID() != 0
498 && *(Uint16*)Data != 0
499 && *(Uint16*)Data < 1024)
502 // TODO: Check if a port is in use
505 srv->Port = *(Uint16*)Data;
506 if(srv->Port == 0) // Allocate a random port
507 srv->Port = TCP_GetUnusedPort();
508 else // Else, mark this as used
509 TCP_AllocatePort(srv->Port);
515 void TCP_Server_Close(tVFS_Node *Node)
522 * \brief Create a client node
524 tVFS_Node *TCP_Client_Init(tInterface *Interface)
526 tTCPConnection *conn = malloc( sizeof(tTCPConnection) );
528 conn->State = TCP_ST_CLOSED;
529 conn->Interface = Interface;
531 conn->RemotePort = 0;
532 memset( &conn->RemoteIP, 0, sizeof(conn->RemoteIP) );
534 conn->Node.ImplPtr = conn;
535 conn->Node.NumACLs = 1;
536 conn->Node.ACLs = &gVFS_ACL_EveryoneRW;
537 conn->Node.Read = TCP_Client_Read;
538 conn->Node.Write = TCP_Client_Write;
539 conn->Node.IOCtl = TCP_Client_IOCtl;
540 conn->Node.Close = TCP_Client_Close;
542 LOCK(&glTCP_OutbountCons);
543 conn->Next = gTCP_OutbountCons;
544 gTCP_OutbountCons = conn;
545 RELEASE(&glTCP_OutbountCons);
551 * \brief Wait for a packet and return it
552 * \note If \a Length is smaller than the size of the packet, the rest
553 * of the packet's data will be discarded.
555 Uint64 TCP_Client_Read(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer)
557 tTCPConnection *conn = Node->ImplPtr;
558 tTCPStoredPacket *pkt;
560 // Check if connection is open
561 if( conn->State != TCP_ST_OPEN ) return 0;
566 // Sleep until the packet is recieved
567 while( conn->RecievedPackets == NULL )
571 // Lock list and check if there is a packet
572 LOCK( &conn->lRecievedPackets );
573 if( conn->RecievedPackets == NULL ) {
574 // If not, release the lock and return to waiting
575 RELEASE( &conn->lRecievedPackets );
579 // Get packet pointer
580 pkt = conn->RecievedPackets;
581 conn->RecievedPackets = pkt->Next;
582 // Release the lock (we don't need it any more)
583 RELEASE( &conn->lRecievedPackets );
586 if(Length > pkt->Length) Length = pkt->Length;
587 memcpy(Buffer, pkt->Data, Length);
589 // Free packet and return
595 Uint64 TCP_Client_Write(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer)
601 * \brief Control a client socket
603 int TCP_Client_IOCtl(tVFS_Node *Node, int ID, void *Data)
605 tTCPConnection *conn = Node->ImplPtr;
609 case 4: // Get/Set local port
611 return conn->LocalPort;
612 if(conn->State != TCP_ST_CLOSED)
614 if(!CheckMem(Data, sizeof(Uint16)))
617 if(Threads_GetUID() != 0 && *(Uint16*)Data < 1024)
620 conn->LocalPort = *(Uint16*)Data;
623 case 5: // Get/Set remote port
624 if(!Data) return conn->RemotePort;
625 if(conn->State != TCP_ST_CLOSED) return -1;
626 if(!CheckMem(Data, sizeof(Uint16))) return -1;
627 conn->RemotePort = *(Uint16*)Data;
630 case 6: // Set Remote IP
631 if( conn->State != TCP_ST_CLOSED )
633 if( conn->Interface->Type == 4 )
635 if(!CheckMem(Data, sizeof(tIPv4))) return -1;
636 conn->RemoteIP.v4 = *(tIPv4*)Data;
638 else if( conn->Interface->Type == 6 )
640 if(!CheckMem(Data, sizeof(tIPv6))) return -1;
641 conn->RemoteIP.v6 = *(tIPv6*)Data;
646 if(conn->LocalPort == -1)
647 conn->LocalPort = TCP_GetUnusedPort();
648 if(conn->RemotePort == -1)
651 TCP_StartConnection(conn);
658 void TCP_Client_Close(tVFS_Node *Node)