12 #define TCP_MIN_DYNPORT 0xC000
13 #define TCP_MAX_HALFOPEN 1024 // Should be enough
15 #define TCP_MAX_PACKET_SIZE 1024
16 #define TCP_WINDOW_SIZE 0x2000
17 #define TCP_RECIEVE_BUFFER_SIZE 0x4000
20 void TCP_Initialise();
21 void TCP_StartConnection(tTCPConnection *Conn);
22 void TCP_SendPacket(tTCPConnection *Conn, size_t Length, tTCPHeader *Data);
23 void TCP_GetPacket(tInterface *Interface, void *Address, int Length, void *Buffer);
24 void TCP_INT_HandleConnectionPacket(tTCPConnection *Connection, tTCPHeader *Header, int Length);
25 void TCP_INT_AppendRecieved(tTCPConnection *Connection, tTCPStoredPacket *Ptk);
26 void TCP_INT_UpdateRecievedFromFuture(tTCPConnection *Connection);
27 Uint16 TCP_GetUnusedPort();
28 int TCP_AllocatePort(Uint16 Port);
29 int TCP_DeallocatePort(Uint16 Port);
31 tVFS_Node *TCP_Server_Init(tInterface *Interface);
32 char *TCP_Server_ReadDir(tVFS_Node *Node, int Pos);
33 tVFS_Node *TCP_Server_FindDir(tVFS_Node *Node, const char *Name);
34 int TCP_Server_IOCtl(tVFS_Node *Node, int ID, void *Data);
35 void TCP_Server_Close(tVFS_Node *Node);
37 tVFS_Node *TCP_Client_Init(tInterface *Interface);
38 Uint64 TCP_Client_Read(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer);
39 Uint64 TCP_Client_Write(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer);
40 int TCP_Client_IOCtl(tVFS_Node *Node, int ID, void *Data);
41 void TCP_Client_Close(tVFS_Node *Node);
44 tSocketFile gTCP_ServerFile = {NULL, "tcps", TCP_Server_Init};
45 tSocketFile gTCP_ClientFile = {NULL, "tcpc", TCP_Client_Init};
48 int giTCP_NumHalfopen = 0;
49 tShortSpinlock glTCP_Listeners;
50 tTCPListener *gTCP_Listeners;
51 tShortSpinlock glTCP_OutbountCons;
52 tTCPConnection *gTCP_OutbountCons;
53 Uint32 gaTCP_PortBitmap[0x800];
54 int giTCP_NextOutPort = TCP_MIN_DYNPORT;
58 * \brief Initialise the TCP Layer
60 * Registers the client and server files and the GetPacket callback
64 IPStack_AddFile(&gTCP_ServerFile);
65 IPStack_AddFile(&gTCP_ClientFile);
66 IPv4_RegisterCallback(IP4PROT_TCP, TCP_GetPacket);
70 * \brief Sends a packet from the specified connection, calculating the checksums
71 * \param Conn Connection
72 * \param Length Length of data
73 * \param Data Packet data (cast as a TCP Header)
75 void TCP_SendPacket( tTCPConnection *Conn, size_t Length, tTCPHeader *Data )
79 switch( Conn->Interface->Type )
81 case 4: // Append IPv4 Pseudo Header
82 buflen = 4 + 4 + 4 + ((Length+1)&~1);
83 buf = malloc( buflen );
84 buf[0] = ((tIPv4*)Conn->Interface->Address)->L;
85 buf[1] = Conn->RemoteIP.v4.L;
86 buf[2] = (htons(Length)<<16) | (6<<8) | 0;
88 memcpy( &buf[3], Data, Length );
89 Data->Checksum = htons( IPv4_Checksum( buf, buflen ) );
91 IPv4_SendPacket(Conn->Interface, Conn->RemoteIP.v4, IP4PROT_TCP, 0, Length, Data);
97 * \brief Handles a packet from the IP Layer
98 * \param Interface Interface the packet arrived from
99 * \param Address Pointer to the addres structure
100 * \param Length Size of packet in bytes
101 * \param Buffer Packet data
103 void TCP_GetPacket(tInterface *Interface, void *Address, int Length, void *Buffer)
105 tTCPHeader *hdr = Buffer;
107 tTCPConnection *conn;
109 Log_Log("TCP", "TCP_GetPacket: SourcePort = %i, DestPort = %i",
110 ntohs(hdr->SourcePort), ntohs(hdr->DestPort));
112 Log_Log("TCP", "TCP_GetPacket: SequenceNumber = 0x%x", ntohl(hdr->SequenceNumber));
113 Log_Log("TCP", "TCP_GetPacket: AcknowlegementNumber = 0x%x", ntohl(hdr->AcknowlegementNumber));
114 Log_Log("TCP", "TCP_GetPacket: DataOffset = %i", hdr->DataOffset >> 4);
115 Log_Log("TCP", "TCP_GetPacket: Flags = {");
116 Log_Log("TCP", "TCP_GetPacket: CWR = %B, ECE = %B",
117 !!(hdr->Flags & TCP_FLAG_CWR), !!(hdr->Flags & TCP_FLAG_ECE));
118 Log_Log("TCP", "TCP_GetPacket: URG = %B, ACK = %B",
119 !!(hdr->Flags & TCP_FLAG_URG), !!(hdr->Flags & TCP_FLAG_ACK));
120 Log_Log("TCP", "TCP_GetPacket: PSH = %B, RST = %B",
121 !!(hdr->Flags & TCP_FLAG_PSH), !!(hdr->Flags & TCP_FLAG_RST));
122 Log_Log("TCP", "TCP_GetPacket: SYN = %B, FIN = %B",
123 !!(hdr->Flags & TCP_FLAG_SYN), !!(hdr->Flags & TCP_FLAG_FIN));
124 Log_Log("TCP", "TCP_GetPacket: }");
125 Log_Log("TCP", "TCP_GetPacket: WindowSize = %i", htons(hdr->WindowSize));
126 Log_Log("TCP", "TCP_GetPacket: Checksum = 0x%x", htons(hdr->Checksum));
127 Log_Log("TCP", "TCP_GetPacket: UrgentPointer = 0x%x", htons(hdr->UrgentPointer));
129 Log_Log("TCP", "TCP_GetPacket: Flags = %s%s%s%s%s%s",
130 (hdr->Flags & TCP_FLAG_CWR) ? "CWR " : "",
131 (hdr->Flags & TCP_FLAG_ECE) ? "ECE " : "",
132 (hdr->Flags & TCP_FLAG_URG) ? "URG " : "",
133 (hdr->Flags & TCP_FLAG_ACK) ? "ACK " : "",
134 (hdr->Flags & TCP_FLAG_PSH) ? "PSH " : "",
135 (hdr->Flags & TCP_FLAG_RST) ? "RST " : "",
136 (hdr->Flags & TCP_FLAG_SYN) ? "SYN " : "",
137 (hdr->Flags & TCP_FLAG_FIN) ? "FIN " : ""
140 if( Length > (hdr->DataOffset >> 4)*4 )
143 "[TCP ] Packet Data = ",
144 (Uint8*)hdr + (hdr->DataOffset >> 4)*4,
145 Length - (hdr->DataOffset >> 4)*4
151 for( srv = gTCP_Listeners; srv; srv = srv->Next )
153 // Check if the server is active
154 if(srv->Port == 0) continue;
155 // Check the interface
156 if(srv->Interface && srv->Interface != Interface) continue;
157 // Check the destination port
158 if(srv->Port != htons(hdr->DestPort)) continue;
160 Log_Log("TCP", "TCP_GetPacket: Matches server %p", srv);
161 // Is this in an established connection?
162 for( conn = srv->Connections; conn; conn = conn->Next )
164 Log_Log("TCP", "TCP_GetPacket: conn->Interface(%p) == Interface(%p)",
165 conn->Interface, Interface);
166 // Check that it is coming in on the same interface
167 if(conn->Interface != Interface) continue;
170 Log_Log("TCP", "TCP_GetPacket: conn->RemotePort(%i) == hdr->SourcePort(%i)",
171 conn->RemotePort, ntohs(hdr->SourcePort));
172 if(conn->RemotePort != ntohs(hdr->SourcePort)) continue;
175 if(conn->Interface->Type == 6 && !IP6_EQU(conn->RemoteIP.v6, *(tIPv6*)Address))
177 if(conn->Interface->Type == 4 && !IP4_EQU(conn->RemoteIP.v4, *(tIPv4*)Address))
180 Log_Log("TCP", "TCP_GetPacket: Matches connection %p", conn);
181 // We have a response!
182 TCP_INT_HandleConnectionPacket(conn, hdr, Length);
187 Log_Log("TCP", "TCP_GetPacket: Opening Connection");
188 // Open a new connection (well, check that it's a SYN)
189 if(hdr->Flags != TCP_FLAG_SYN) {
190 Log_Log("TCP", "TCP_GetPacket: Packet is not a SYN");
194 // TODO: Check for halfopen max
196 conn = calloc(1, sizeof(tTCPConnection));
197 conn->State = TCP_ST_HALFOPEN;
198 conn->LocalPort = srv->Port;
199 conn->RemotePort = ntohs(hdr->SourcePort);
200 conn->Interface = Interface;
202 switch(Interface->Type)
204 case 4: conn->RemoteIP.v4 = *(tIPv4*)Address; break;
205 case 6: conn->RemoteIP.v6 = *(tIPv6*)Address; break;
208 conn->RecievedBuffer = RingBuffer_Create( TCP_RECIEVE_BUFFER_SIZE );
210 conn->NextSequenceRcv = ntohl( hdr->SequenceNumber ) + 1;
211 conn->NextSequenceSend = rand();
214 conn->Node.NumACLs = 1;
215 conn->Node.ACLs = &gVFS_ACL_EveryoneRW;
216 conn->Node.ImplPtr = conn;
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 SHORTLOCK(&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 SHORTREL(&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 );
246 conn->NextSequenceSend ++;
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", "TCP_GetPacket: 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 // Syncronise sequence values
288 if(Header->Flags & TCP_FLAG_SYN) {
289 Connection->NextSequenceRcv = ntohl(Header->SequenceNumber) + 1;
292 // Handle a server replying to our initial SYN
293 if( Connection->State == TCP_ST_SYN_SENT )
295 if( (Header->Flags & (TCP_FLAG_SYN|TCP_FLAG_ACK)) == (TCP_FLAG_SYN|TCP_FLAG_ACK) )
297 Header->DestPort = Header->SourcePort;
298 Header->SourcePort = htons(Connection->LocalPort);
299 Header->AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
300 Header->SequenceNumber = htonl(Connection->NextSequenceSend);
301 Header->WindowSize = htons(TCP_WINDOW_SIZE);
302 Header->Flags = TCP_FLAG_ACK;
303 Header->DataOffset = (sizeof(tTCPHeader)/4) << 4;
304 Log_Log("TCP", "ACKing SYN-ACK");
305 TCP_SendPacket( Connection, sizeof(tTCPHeader), Header );
306 Connection->State = TCP_ST_OPEN;
310 // Handle a client confirming the connection
311 if( Connection->State == TCP_ST_HALFOPEN && (Header->Flags & TCP_FLAG_ACK) )
313 Connection->State = TCP_ST_OPEN;
314 Log_Log("TCP", "Connection fully opened");
317 // Get length of data
318 dataLen = Length - (Header->DataOffset>>4)*4;
319 Log_Log("TCP", "HandleConnectionPacket - dataLen = %i", dataLen);
321 if(Header->Flags & TCP_FLAG_ACK) {
322 // TODO: Process an ACKed Packet
323 Log_Log("TCP", "Conn %p, Packet 0x%x ACKed", Connection, Header->AcknowlegementNumber);
326 // TODO: Make sure that the packet is actually ACKing the FIN
327 if( Connection->State == TCP_ST_FIN_SENT ) {
328 Connection->State = TCP_ST_FINISHED;
333 // TODO: Check what to do here
334 if(Header->Flags & TCP_FLAG_FIN) {
335 if( Connection->State == TCP_ST_FIN_SENT ) {
336 Connection->State = TCP_ST_FINISHED;
340 Connection->State = TCP_ST_FINISHED;
341 Header->DestPort = Header->SourcePort;
342 Header->SourcePort = htons(Connection->LocalPort);
343 Header->AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
344 Header->SequenceNumber = htonl(Connection->NextSequenceSend);
345 Header->Flags = TCP_FLAG_ACK;
346 TCP_SendPacket( Connection, sizeof(tTCPHeader), Header );
351 // Check for an empty packet
353 Log_Log("TCP", "Empty Packet");
362 // Allocate and fill cached packet
363 pkt = malloc( dataLen + sizeof(tTCPStoredPacket) );
365 pkt->Sequence = ntohl(Header->SequenceNumber);
366 pkt->Length = dataLen;
367 memcpy(pkt->Data, (Uint8*)Header + (Header->DataOffset>>4)*4, dataLen);
369 // Is this packet the next expected packet?
370 // TODO: Fix this to check if the packet is in the window.
371 if( pkt->Sequence != Connection->NextSequenceRcv )
373 tTCPStoredPacket *tmp, *prev = NULL;
375 Log_Log("TCP", "Out of sequence packet (0x%08x != 0x%08x)",
376 pkt->Sequence, Connection->NextSequenceRcv);
378 // No? Well, let's cache it and look at it later
379 SHORTLOCK( &Connection->lFuturePackets );
380 for(tmp = Connection->FuturePackets;
382 prev = tmp, tmp = tmp->Next)
384 if(tmp->Sequence > pkt->Sequence) break;
389 Connection->FuturePackets = pkt;
391 SHORTREL( &Connection->lFuturePackets );
395 // Ooh, Goodie! Add it to the recieved list
396 TCP_INT_AppendRecieved(Connection, pkt);
398 Log_Log("TCP", "0x%08x += %i", Connection->NextSequenceRcv, dataLen);
399 Connection->NextSequenceRcv += dataLen;
401 // TODO: This should be moved out of the watcher thread,
402 // so that a single lost packet on one connection doesn't cause
403 // all connections on the interface to lag.
404 TCP_INT_UpdateRecievedFromFuture(Connection);
407 Header->DestPort = Header->SourcePort;
408 Header->SourcePort = htons(Connection->LocalPort);
409 Header->AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
410 Header->SequenceNumber = htonl(Connection->NextSequenceSend);
411 Header->WindowSize = htons(TCP_WINDOW_SIZE);
412 Header->Flags &= TCP_FLAG_SYN; // Eliminate all flags save for SYN
413 Header->Flags |= TCP_FLAG_ACK; // Add ACK
414 Log_Log("TCP", "Sending ACK for 0x%08x", Connection->NextSequenceRcv);
415 TCP_SendPacket( Connection, sizeof(tTCPHeader), Header );
416 //Connection->NextSequenceSend ++;
421 * \brief Appends a packet to the recieved list
422 * \param Connection Connection structure
423 * \param Pkt Packet structure on heap
425 void TCP_INT_AppendRecieved(tTCPConnection *Connection, tTCPStoredPacket *Pkt)
427 Mutex_Acquire( &Connection->lRecievedPackets );
428 if(Connection->RecievedBuffer->Length + Pkt->Length > Connection->RecievedBuffer->Space )
430 Log_Error("TCP", "Buffer filled, packet dropped (%s)",
431 // TCP_INT_DumpConnection(Connection)
437 RingBuffer_Write( Connection->RecievedBuffer, Pkt->Data, Pkt->Length );
440 VFS_MarkAvaliable(&Connection->Node, 1);
443 Mutex_Release( &Connection->lRecievedPackets );
447 * \brief Updates the connections recieved list from the future list
448 * \param Connection Connection structure
450 * Updates the recieved packets list with packets from the future (out
451 * of order) packets list that are now able to be added in direct
454 void TCP_INT_UpdateRecievedFromFuture(tTCPConnection *Connection)
456 tTCPStoredPacket *pkt, *prev;
460 // Look for the next expected packet in the cache.
461 SHORTLOCK( &Connection->lFuturePackets );
462 for(pkt = Connection->FuturePackets;
463 pkt && pkt->Sequence < Connection->NextSequenceRcv;
464 prev = pkt, pkt = pkt->Next);
466 // If we can't find the expected next packet, stop looking
467 if(!pkt || pkt->Sequence > Connection->NextSequenceRcv) {
468 SHORTREL( &Connection->lFuturePackets );
472 // Delete packet from future list
474 prev->Next = pkt->Next;
476 Connection->FuturePackets = pkt->Next;
479 SHORTREL( &Connection->lFuturePackets );
481 // Looks like we found one
482 TCP_INT_AppendRecieved(Connection, pkt);
483 Connection->NextSequenceRcv += pkt->Length;
489 * \fn Uint16 TCP_GetUnusedPort()
490 * \brief Gets an unused port and allocates it
492 Uint16 TCP_GetUnusedPort()
496 // Get Next outbound port
497 ret = giTCP_NextOutPort++;
498 while( gaTCP_PortBitmap[ret/32] & (1 << (ret%32)) )
502 if(giTCP_NextOutPort == 0x10000) {
503 ret = giTCP_NextOutPort = TCP_MIN_DYNPORT;
507 // Mark the new port as used
508 gaTCP_PortBitmap[ret/32] |= 1 << (ret%32);
514 * \fn int TCP_AllocatePort(Uint16 Port)
515 * \brief Marks a port as used
517 int TCP_AllocatePort(Uint16 Port)
519 // Check if the port has already been allocated
520 if( gaTCP_PortBitmap[Port/32] & (1 << (Port%32)) )
524 gaTCP_PortBitmap[Port/32] |= 1 << (Port%32);
530 * \fn int TCP_DeallocatePort(Uint16 Port)
531 * \brief Marks a port as unused
533 int TCP_DeallocatePort(Uint16 Port)
535 // Check if the port has already been allocated
536 if( !(gaTCP_PortBitmap[Port/32] & (1 << (Port%32))) )
540 gaTCP_PortBitmap[Port/32] &= ~(1 << (Port%32));
546 tVFS_Node *TCP_Server_Init(tInterface *Interface)
550 srv = malloc( sizeof(tTCPListener) );
553 Log_Warning("TCP", "malloc failed for listener (%i) bytes", sizeof(tTCPListener));
557 srv->Interface = Interface;
560 srv->Connections = NULL;
561 srv->ConnectionsTail = NULL;
562 srv->NewConnections = NULL;
564 srv->Node.Flags = VFS_FFLAG_DIRECTORY;
566 srv->Node.ImplPtr = srv;
567 srv->Node.NumACLs = 1;
568 srv->Node.ACLs = &gVFS_ACL_EveryoneRW;
569 srv->Node.ReadDir = TCP_Server_ReadDir;
570 srv->Node.FindDir = TCP_Server_FindDir;
571 srv->Node.IOCtl = TCP_Server_IOCtl;
572 srv->Node.Close = TCP_Server_Close;
574 SHORTLOCK(&glTCP_Listeners);
575 srv->Next = gTCP_Listeners;
576 gTCP_Listeners = srv;
577 SHORTREL(&glTCP_Listeners);
583 * \brief Wait for a new connection and return the connection ID
584 * \note Blocks until a new connection is made
585 * \param Node Server node
586 * \param Pos Position (ignored)
588 char *TCP_Server_ReadDir(tVFS_Node *Node, int Pos)
590 tTCPListener *srv = Node->ImplPtr;
591 tTCPConnection *conn;
594 ENTER("pNode iPos", Node, Pos);
596 Log_Log("TCP", "Thread %i waiting for a connection", Threads_GetTID());
599 SHORTLOCK( &srv->lConnections );
600 if( srv->NewConnections != NULL ) break;
601 SHORTREL( &srv->lConnections );
602 Threads_Yield(); // TODO: Sleep until poked
607 // Increment the new list (the current connection is still on the
609 conn = srv->NewConnections;
610 srv->NewConnections = conn->Next;
612 SHORTREL( &srv->lConnections );
614 LOG("conn = %p", conn);
615 LOG("srv->Connections = %p", srv->Connections);
616 LOG("srv->NewConnections = %p", srv->NewConnections);
617 LOG("srv->ConnectionsTail = %p", srv->ConnectionsTail);
620 itoa(ret, conn->Node.ImplInt, 16, 8, '0');
621 Log_Log("TCP", "Thread %i got '%s'", Threads_GetTID(), ret);
627 * \brief Gets a client connection node
628 * \param Node Server node
629 * \param Name Hexadecimal ID of the node
631 tVFS_Node *TCP_Server_FindDir(tVFS_Node *Node, const char *Name)
633 tTCPConnection *conn;
634 tTCPListener *srv = Node->ImplPtr;
638 ENTER("pNode sName", Node, Name);
641 itoa(tmp, id, 16, 8, '0');
642 if(strcmp(tmp, Name) != 0) {
643 LOG("'%s' != '%s' (%08x)", Name, tmp, id);
648 Log_Debug("TCP", "srv->Connections = %p", srv->Connections);
649 Log_Debug("TCP", "srv->NewConnections = %p", srv->NewConnections);
650 Log_Debug("TCP", "srv->ConnectionsTail = %p", srv->ConnectionsTail);
653 SHORTLOCK( &srv->lConnections );
654 for(conn = srv->Connections;
658 LOG("conn->Node.ImplInt = %i", conn->Node.ImplInt);
659 if(conn->Node.ImplInt == id) break;
661 SHORTREL( &srv->lConnections );
663 // If not found, ret NULL
665 LOG("Connection %i not found", id);
671 LEAVE('p', &conn->Node);
676 * \brief Handle IOCtl calls
678 int TCP_Server_IOCtl(tVFS_Node *Node, int ID, void *Data)
680 tTCPListener *srv = Node->ImplPtr;
684 case 4: // Get/Set Port
685 if(!Data) // Get Port
688 if(srv->Port) // Wait, you can't CHANGE the port
691 if(!CheckMem(Data, sizeof(Uint16))) // Sanity check
695 if(Threads_GetUID() != 0
696 && *(Uint16*)Data != 0
697 && *(Uint16*)Data < 1024)
700 // TODO: Check if a port is in use
703 srv->Port = *(Uint16*)Data;
704 if(srv->Port == 0) // Allocate a random port
705 srv->Port = TCP_GetUnusedPort();
706 else // Else, mark this as used
707 TCP_AllocatePort(srv->Port);
709 Log_Log("TCP", "Server %p listening on port %i", srv, srv->Port);
716 void TCP_Server_Close(tVFS_Node *Node)
723 * \brief Create a client node
725 tVFS_Node *TCP_Client_Init(tInterface *Interface)
727 tTCPConnection *conn = malloc( sizeof(tTCPConnection) );
729 conn->State = TCP_ST_CLOSED;
730 conn->Interface = Interface;
731 conn->LocalPort = -1;
732 conn->RemotePort = -1;
733 memset( &conn->RemoteIP, 0, sizeof(conn->RemoteIP) );
735 conn->Node.ImplPtr = conn;
736 conn->Node.NumACLs = 1;
737 conn->Node.ACLs = &gVFS_ACL_EveryoneRW;
738 conn->Node.Read = TCP_Client_Read;
739 conn->Node.Write = TCP_Client_Write;
740 conn->Node.IOCtl = TCP_Client_IOCtl;
741 conn->Node.Close = TCP_Client_Close;
743 conn->RecievedBuffer = RingBuffer_Create( TCP_RECIEVE_BUFFER_SIZE );
745 SHORTLOCK(&glTCP_OutbountCons);
746 conn->Next = gTCP_OutbountCons;
747 gTCP_OutbountCons = conn;
748 SHORTREL(&glTCP_OutbountCons);
754 * \brief Wait for a packet and return it
755 * \note If \a Length is smaller than the size of the packet, the rest
756 * of the packet's data will be discarded.
758 Uint64 TCP_Client_Read(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer)
760 tTCPConnection *conn = Node->ImplPtr;
761 char *destbuf = Buffer;
764 ENTER("pNode XOffset XLength pBuffer", Node, Offset, Length, Buffer);
765 LOG("conn = %p", conn);
766 LOG("conn->State = %i", conn->State);
768 // Check if connection is open
769 while( conn->State == TCP_ST_HALFOPEN || conn->State == TCP_ST_SYN_SENT )
771 if( conn->State != TCP_ST_OPEN ) {
780 VFS_SelectNode(Node, VFS_SELECT_READ, NULL);
781 // Lock list and read
782 Mutex_Acquire( &conn->lRecievedPackets );
784 // Attempt to read all `Length` bytes
785 len = RingBuffer_Read( destbuf, conn->RecievedBuffer, Length );
787 if( len == 0 || conn->RecievedBuffer->Length == 0 ) {
788 LOG("Marking as none avaliable (len = %i)\n", len);
789 VFS_MarkAvaliable(Node, 0);
792 // Release the lock (we don't need it any more)
793 Mutex_Release( &conn->lRecievedPackets );
801 * \brief Send a data packet on a connection
803 void TCP_INT_SendDataPacket(tTCPConnection *Connection, size_t Length, void *Data)
805 char buf[sizeof(tTCPHeader)+Length];
806 tTCPHeader *packet = (void*)buf;
808 packet->SourcePort = htons(Connection->LocalPort);
809 packet->DestPort = htons(Connection->RemotePort);
810 packet->DataOffset = (sizeof(tTCPHeader)/4)*16;
811 packet->WindowSize = TCP_WINDOW_SIZE;
813 packet->AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
814 packet->SequenceNumber = htonl(Connection->NextSequenceSend);
815 packet->Flags = TCP_FLAG_PSH|TCP_FLAG_ACK; // Hey, ACK if you can!
817 memcpy(packet->Options, Data, Length);
819 TCP_SendPacket( Connection, sizeof(tTCPHeader)+Length, packet );
821 Connection->NextSequenceSend += Length;
825 * \brief Send some bytes on a connection
827 Uint64 TCP_Client_Write(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer)
829 tTCPConnection *conn = Node->ImplPtr;
832 ENTER("pNode XOffset XLength pBuffer", Node, Offset, Length, Buffer);
834 // Check if connection is open
835 while( conn->State == TCP_ST_HALFOPEN || conn->State == TCP_ST_SYN_SENT )
837 if( conn->State != TCP_ST_OPEN ) {
842 while( rem > TCP_MAX_PACKET_SIZE )
844 TCP_INT_SendDataPacket(conn, TCP_MAX_PACKET_SIZE, Buffer);
845 Buffer += TCP_MAX_PACKET_SIZE;
848 TCP_INT_SendDataPacket(conn, rem, Buffer);
855 * \brief Open a connection to another host using TCP
856 * \param Conn Connection structure
858 void TCP_StartConnection(tTCPConnection *Conn)
860 tTCPHeader hdr = {0};
862 Conn->State = TCP_ST_SYN_SENT;
864 hdr.SourcePort = htons(Conn->LocalPort);
865 hdr.DestPort = htons(Conn->RemotePort);
866 Conn->NextSequenceSend = rand();
867 hdr.SequenceNumber = htonl(Conn->NextSequenceSend);
868 hdr.DataOffset = (sizeof(tTCPHeader)/4) << 4;
869 hdr.Flags = TCP_FLAG_SYN;
870 hdr.WindowSize = htons(TCP_WINDOW_SIZE); // Max
871 hdr.Checksum = 0; // TODO
873 TCP_SendPacket( Conn, sizeof(tTCPHeader), &hdr );
875 Conn->NextSequenceSend ++;
876 Conn->State = TCP_ST_SYN_SENT;
881 * \brief Control a client socket
883 int TCP_Client_IOCtl(tVFS_Node *Node, int ID, void *Data)
885 tTCPConnection *conn = Node->ImplPtr;
887 ENTER("pNode iID pData", Node, ID, Data);
891 case 4: // Get/Set local port
893 LEAVE_RET('i', conn->LocalPort);
894 if(conn->State != TCP_ST_CLOSED)
896 if(!CheckMem(Data, sizeof(Uint16)))
899 if(Threads_GetUID() != 0 && *(Uint16*)Data < 1024)
902 conn->LocalPort = *(Uint16*)Data;
903 LEAVE_RET('i', conn->LocalPort);
905 case 5: // Get/Set remote port
906 if(!Data) LEAVE_RET('i', conn->RemotePort);
907 if(conn->State != TCP_ST_CLOSED) LEAVE_RET('i', -1);
908 if(!CheckMem(Data, sizeof(Uint16))) LEAVE_RET('i', -1);
909 conn->RemotePort = *(Uint16*)Data;
910 LEAVE_RET('i', conn->RemotePort);
912 case 6: // Set Remote IP
913 if( conn->State != TCP_ST_CLOSED )
915 if( conn->Interface->Type == 4 )
917 if(!CheckMem(Data, sizeof(tIPv4))) LEAVE_RET('i', -1);
918 conn->RemoteIP.v4 = *(tIPv4*)Data;
920 else if( conn->Interface->Type == 6 )
922 if(!CheckMem(Data, sizeof(tIPv6))) LEAVE_RET('i', -1);
923 conn->RemoteIP.v6 = *(tIPv6*)Data;
928 if(conn->LocalPort == 0xFFFF)
929 conn->LocalPort = TCP_GetUnusedPort();
930 if(conn->RemotePort == -1)
933 TCP_StartConnection(conn);
936 // Get recieve buffer length
938 LEAVE_RET('i', conn->RecievedBuffer->Length);
944 void TCP_Client_Close(tVFS_Node *Node)
946 tTCPConnection *conn = Node->ImplPtr;
949 ENTER("pNode", Node);
951 packet.SourcePort = htons(conn->LocalPort);
952 packet.DestPort = htons(conn->RemotePort);
953 packet.DataOffset = (sizeof(tTCPHeader)/4)*16;
954 packet.WindowSize = TCP_WINDOW_SIZE;
956 packet.AcknowlegementNumber = 0;
957 packet.SequenceNumber = htonl(conn->NextSequenceSend);
958 packet.Flags = TCP_FLAG_FIN;
960 conn->State = TCP_ST_FIN_SENT;
962 TCP_SendPacket( conn, sizeof(tTCPHeader), &packet );
964 while( conn->State == TCP_ST_FIN_SENT ) Threads_Yield();