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 Log("[TCP ] Server %p, Port = 0x%04x", srv, srv->Port);
144 // Check if the server is active
145 if(srv->Port == 0) continue;
146 // Check the interface
147 Log("[TCP ] Interface = %p (== %p ?)", srv->Interface, Interface);
148 if(srv->Interface && srv->Interface != Interface) continue;
149 // Check the destination port
150 Log("[TCP ] hdr->DestPort = 0x%04x", ntohs(hdr->DestPort));
151 if(srv->Port != htons(hdr->DestPort)) continue;
153 Log("[TCP ] Matches");
154 // Is this in an established connection?
155 for( conn = srv->Connections; conn; conn = conn->Next )
157 // Check that it is coming in on the same interface
158 if(conn->Interface != Interface) continue;
161 if(conn->RemotePort != ntohs(hdr->SourcePort)) continue;
164 if(conn->Interface->Type == 6 && !IP6_EQU(conn->RemoteIP.v6, *(tIPv6*)Address))
166 if(conn->Interface->Type == 4 && !IP4_EQU(conn->RemoteIP.v4, *(tIPv4*)Address))
169 // We have a response!
170 TCP_INT_HandleConnectionPacket(conn, hdr, Length);
175 Log("[TCP ] Opening Connection");
176 // Open a new connection (well, check that it's a SYN)
177 if(hdr->Flags != TCP_FLAG_SYN) {
178 Log("[TCP ] Packet is not a SYN");
182 // TODO: Check for halfopen max
184 conn = calloc(1, sizeof(tTCPConnection));
185 conn->State = TCP_ST_HALFOPEN;
186 conn->LocalPort = srv->Port;
187 conn->RemotePort = ntohs(hdr->SourcePort);
188 conn->Interface = Interface;
190 switch(Interface->Type)
192 case 4: conn->RemoteIP.v4 = *(tIPv4*)Address; break;
193 case 6: conn->RemoteIP.v6 = *(tIPv6*)Address; break;
196 conn->NextSequenceRcv = ntohl( hdr->SequenceNumber );
197 conn->NextSequenceSend = rand();
200 conn->Node.NumACLs = 1;
201 conn->Node.ACLs = &gVFS_ACL_EveryoneRW;
202 conn->Node.ImplInt = srv->NextID ++;
203 conn->Node.Read = TCP_Client_Read;
204 conn->Node.Write = TCP_Client_Write;
205 //conn->Node.Close = TCP_SrvConn_Close;
207 // Hmm... Theoretically, this lock will never have to wait,
208 // as the interface is locked to the watching thread, and this
209 // runs in the watching thread. But, it's a good idea to have
211 LOCK(&srv->lConnections);
212 conn->Next = srv->Connections;
213 srv->Connections = conn;
214 RELEASE(&srv->lConnections);
217 Log("[TCP ] TODO: Sending SYN ACK");
218 hdr->Flags |= TCP_FLAG_ACK;
219 hdr->AcknowlegementNumber = hdr->SequenceNumber;
220 hdr->SequenceNumber = htonl(conn->NextSequenceSend);
221 hdr->DestPort = hdr->SourcePort;
222 hdr->SourcePort = htonl(srv->Port);
223 TCP_SendPacket( conn, sizeof(tTCPHeader), hdr );
230 // Check Open Connections
232 for( conn = gTCP_OutbountCons; conn; conn = conn->Next )
234 // Check that it is coming in on the same interface
235 if(conn->Interface != Interface) continue;
238 if(conn->RemotePort != ntohs(hdr->SourcePort)) continue;
241 if(conn->Interface->Type == 6 && !IP6_EQU(conn->RemoteIP.v6, *(tIPv6*)Address))
243 if(conn->Interface->Type == 4 && !IP4_EQU(conn->RemoteIP.v4, *(tIPv4*)Address))
246 TCP_INT_HandleConnectionPacket(conn, hdr, Length);
252 * \brief Handles a packet sent to a specific connection
254 void TCP_INT_HandleConnectionPacket(tTCPConnection *Connection, tTCPHeader *Header, int Length)
256 tTCPStoredPacket *pkt;
259 Connection->State = TCP_ST_OPEN;
260 if(Header->Flags & TCP_FLAG_SYN) {
261 Connection->NextSequenceRcv = Header->SequenceNumber + 1;
264 if(Header->Flags & TCP_FLAG_ACK) {
265 // TODO: Process an ACKed Packet
266 Log("[TCP ] Conn %p, Packet 0x%x ACKed", Connection, Header->AcknowlegementNumber);
270 // Allocate and fill cached packet
271 dataLen = Length - (Header->DataOffset&0xF)*4;
272 pkt = malloc( dataLen + sizeof(tTCPStoredPacket) );
274 pkt->Sequence = Header->SequenceNumber;
275 memcpy(pkt->Data, (Uint8*)Header + (Header->DataOffset&0xF)*4, dataLen);
277 // Is this packet the next expected packet?
278 if( Header->SequenceNumber != Connection->NextSequenceRcv )
280 tTCPStoredPacket *tmp, *prev;
281 // No? Well, let's cache it and look at it later
282 LOCK( &Connection->lFuturePackets );
283 for(tmp = Connection->FuturePackets;
285 prev = tmp, tmp = tmp->Next)
287 if(tmp->Sequence > pkt->Sequence) break;
292 Connection->FuturePackets = pkt;
294 RELEASE( &Connection->lFuturePackets );
298 // Ooh, Goodie! Add it to the recieved list
299 TCP_INT_AppendRecieved(Connection, pkt);
300 Connection->NextSequenceRcv ++;
302 // TODO: This should be moved out of the watcher thread,
303 // so that a single lost packet on one connection doesn't cause
304 // all connections on the interface to lag.
305 TCP_INT_UpdateRecievedFromFuture(Connection);
308 // TODO: Check ACK code validity
309 Header->AcknowlegementNumber = pkt->Sequence;
310 Header->SequenceNumber = Connection->NextSequenceSend;
311 Header->Flags |= TCP_FLAG_ACK;
312 TCP_SendPacket( Connection, sizeof(tTCPHeader), Header );
316 * \brief Appends a packet to the recieved list
318 void TCP_INT_AppendRecieved(tTCPConnection *Connection, tTCPStoredPacket *Pkt)
320 LOCK( &Connection->lRecievedPackets );
321 if(Connection->RecievedPackets)
323 Connection->RecievedPacketsTail->Next = Pkt;
324 Connection->RecievedPacketsTail = Pkt;
328 Connection->RecievedPackets = Pkt;
329 Connection->RecievedPacketsTail = Pkt;
331 RELEASE( &Connection->lRecievedPackets );
335 * \brief Updates the connections recieved list from the future list
337 void TCP_INT_UpdateRecievedFromFuture(tTCPConnection *Connection)
339 tTCPStoredPacket *pkt, *prev;
343 // Look for the next expected packet in the cache.
344 LOCK( &Connection->lFuturePackets );
345 for(pkt = Connection->FuturePackets;
346 pkt && pkt->Sequence < Connection->NextSequenceRcv;
347 prev = pkt, pkt = pkt->Next);
349 // If we can't find the expected next packet, stop looking
350 if(!pkt || pkt->Sequence > Connection->NextSequenceRcv) {
351 RELEASE( &Connection->lFuturePackets );
355 // Delete packet from future list
357 prev->Next = pkt->Next;
359 Connection->FuturePackets = pkt->Next;
362 RELEASE( &Connection->lFuturePackets );
364 // Looks like we found one
365 TCP_INT_AppendRecieved(Connection, pkt);
366 Connection->NextSequenceRcv ++;
371 * \fn Uint16 TCP_GetUnusedPort()
372 * \brief Gets an unused port and allocates it
374 Uint16 TCP_GetUnusedPort()
378 // Get Next outbound port
379 ret = giTCP_NextOutPort++;
380 while( gaTCP_PortBitmap[ret/32] & (1 << (ret%32)) )
384 if(giTCP_NextOutPort == 0x10000) {
385 ret = giTCP_NextOutPort = TCP_MIN_DYNPORT;
389 // Mark the new port as used
390 gaTCP_PortBitmap[ret/32] |= 1 << (ret%32);
396 * \fn int TCP_AllocatePort(Uint16 Port)
397 * \brief Marks a port as used
399 int TCP_AllocatePort(Uint16 Port)
401 // Check if the port has already been allocated
402 if( gaTCP_PortBitmap[Port/32] & (1 << (Port%32)) )
406 gaTCP_PortBitmap[Port/32] |= 1 << (Port%32);
412 * \fn int TCP_DeallocatePort(Uint16 Port)
413 * \brief Marks a port as unused
415 int TCP_DeallocatePort(Uint16 Port)
417 // Check if the port has already been allocated
418 if( !(gaTCP_PortBitmap[Port/32] & (1 << (Port%32))) )
422 gaTCP_PortBitmap[Port/32] &= ~(1 << (Port%32));
428 tVFS_Node *TCP_Server_Init(tInterface *Interface)
430 tTCPListener *srv = malloc( sizeof(tTCPListener) );
432 srv->Interface = Interface;
435 srv->Connections = NULL;
437 srv->Node.Flags = VFS_FFLAG_DIRECTORY;
439 srv->Node.ImplPtr = srv;
440 srv->Node.NumACLs = 1;
441 srv->Node.ACLs = &gVFS_ACL_EveryoneRW;
442 srv->Node.ReadDir = TCP_Server_ReadDir;
443 srv->Node.FindDir = TCP_Server_FindDir;
444 srv->Node.IOCtl = TCP_Server_IOCtl;
445 srv->Node.Close = TCP_Server_Close;
447 LOCK(&glTCP_Listeners);
448 srv->Next = gTCP_Listeners;
449 gTCP_Listeners = srv;
450 RELEASE(&glTCP_Listeners);
456 * \brief Wait for a new connection and return the connection ID
457 * \note Blocks until a new connection is made
458 * \param Node Server node
459 * \param Pos Position (ignored)
461 char *TCP_Server_ReadDir(tVFS_Node *Node, int Pos)
463 tTCPListener *srv = Node->ImplPtr;
464 tTCPConnection *conn;
467 while( srv->NewConnections == NULL ) Threads_Yield();
469 conn = srv->NewConnections;
470 srv->NewConnections = conn->Next;
473 itoa(ret, Node->ImplInt, 16, '0', 8);
478 * \brief Gets a client connection node
479 * \param Node Server node
480 * \param Name Hexadecimal ID of the node
482 tVFS_Node *TCP_Server_FindDir(tVFS_Node *Node, char *Name)
488 * \brief Handle IOCtl calls
490 int TCP_Server_IOCtl(tVFS_Node *Node, int ID, void *Data)
492 tTCPListener *srv = Node->ImplPtr;
496 case 4: // Get/Set Port
497 if(!Data) // Get Port
500 if(srv->Port) // Wait, you can't CHANGE the port
503 if(!CheckMem(Data, sizeof(Uint16))) // Sanity check
507 if(Threads_GetUID() != 0
508 && *(Uint16*)Data != 0
509 && *(Uint16*)Data < 1024)
512 // TODO: Check if a port is in use
515 srv->Port = *(Uint16*)Data;
516 if(srv->Port == 0) // Allocate a random port
517 srv->Port = TCP_GetUnusedPort();
518 else // Else, mark this as used
519 TCP_AllocatePort(srv->Port);
521 Log("[TCP ] Server %p listening on port %i", srv, srv->Port);
528 void TCP_Server_Close(tVFS_Node *Node)
535 * \brief Create a client node
537 tVFS_Node *TCP_Client_Init(tInterface *Interface)
539 tTCPConnection *conn = malloc( sizeof(tTCPConnection) );
541 conn->State = TCP_ST_CLOSED;
542 conn->Interface = Interface;
544 conn->RemotePort = 0;
545 memset( &conn->RemoteIP, 0, sizeof(conn->RemoteIP) );
547 conn->Node.ImplPtr = conn;
548 conn->Node.NumACLs = 1;
549 conn->Node.ACLs = &gVFS_ACL_EveryoneRW;
550 conn->Node.Read = TCP_Client_Read;
551 conn->Node.Write = TCP_Client_Write;
552 conn->Node.IOCtl = TCP_Client_IOCtl;
553 conn->Node.Close = TCP_Client_Close;
555 LOCK(&glTCP_OutbountCons);
556 conn->Next = gTCP_OutbountCons;
557 gTCP_OutbountCons = conn;
558 RELEASE(&glTCP_OutbountCons);
564 * \brief Wait for a packet and return it
565 * \note If \a Length is smaller than the size of the packet, the rest
566 * of the packet's data will be discarded.
568 Uint64 TCP_Client_Read(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer)
570 tTCPConnection *conn = Node->ImplPtr;
571 tTCPStoredPacket *pkt;
573 // Check if connection is open
574 if( conn->State != TCP_ST_OPEN ) return 0;
579 // Sleep until the packet is recieved
580 while( conn->RecievedPackets == NULL )
584 // Lock list and check if there is a packet
585 LOCK( &conn->lRecievedPackets );
586 if( conn->RecievedPackets == NULL ) {
587 // If not, release the lock and return to waiting
588 RELEASE( &conn->lRecievedPackets );
592 // Get packet pointer
593 pkt = conn->RecievedPackets;
594 conn->RecievedPackets = pkt->Next;
595 // Release the lock (we don't need it any more)
596 RELEASE( &conn->lRecievedPackets );
599 if(Length > pkt->Length) Length = pkt->Length;
600 memcpy(Buffer, pkt->Data, Length);
602 // Free packet and return
608 Uint64 TCP_Client_Write(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer)
614 * \brief Control a client socket
616 int TCP_Client_IOCtl(tVFS_Node *Node, int ID, void *Data)
618 tTCPConnection *conn = Node->ImplPtr;
622 case 4: // Get/Set local port
624 return conn->LocalPort;
625 if(conn->State != TCP_ST_CLOSED)
627 if(!CheckMem(Data, sizeof(Uint16)))
630 if(Threads_GetUID() != 0 && *(Uint16*)Data < 1024)
633 conn->LocalPort = *(Uint16*)Data;
636 case 5: // Get/Set remote port
637 if(!Data) return conn->RemotePort;
638 if(conn->State != TCP_ST_CLOSED) return -1;
639 if(!CheckMem(Data, sizeof(Uint16))) return -1;
640 conn->RemotePort = *(Uint16*)Data;
643 case 6: // Set Remote IP
644 if( conn->State != TCP_ST_CLOSED )
646 if( conn->Interface->Type == 4 )
648 if(!CheckMem(Data, sizeof(tIPv4))) return -1;
649 conn->RemoteIP.v4 = *(tIPv4*)Data;
651 else if( conn->Interface->Type == 6 )
653 if(!CheckMem(Data, sizeof(tIPv6))) return -1;
654 conn->RemoteIP.v6 = *(tIPv6*)Data;
659 if(conn->LocalPort == -1)
660 conn->LocalPort = TCP_GetUnusedPort();
661 if(conn->RemotePort == -1)
664 TCP_StartConnection(conn);
671 void TCP_Client_Close(tVFS_Node *Node)