10 #define TCP_MIN_DYNPORT 0xC000
11 #define TCP_MAX_HALFOPEN 1024 // Should be enough
13 #define TCP_MAX_PACKET_SIZE 1024
14 #define TCP_WINDOW_SIZE 0x2000
15 #define TCP_RECIEVE_BUFFER_SIZE 0x4000
18 void TCP_Initialise();
19 void TCP_StartConnection(tTCPConnection *Conn);
20 void TCP_SendPacket(tTCPConnection *Conn, size_t Length, tTCPHeader *Data);
21 void TCP_GetPacket(tInterface *Interface, void *Address, int Length, void *Buffer);
22 void TCP_INT_HandleConnectionPacket(tTCPConnection *Connection, tTCPHeader *Header, int Length);
23 void TCP_INT_AppendRecieved(tTCPConnection *Connection, tTCPStoredPacket *Ptk);
24 void TCP_INT_UpdateRecievedFromFuture(tTCPConnection *Connection);
25 Uint16 TCP_GetUnusedPort();
26 int TCP_AllocatePort(Uint16 Port);
27 int TCP_DeallocatePort(Uint16 Port);
29 tVFS_Node *TCP_Server_Init(tInterface *Interface);
30 char *TCP_Server_ReadDir(tVFS_Node *Node, int Pos);
31 tVFS_Node *TCP_Server_FindDir(tVFS_Node *Node, char *Name);
32 int TCP_Server_IOCtl(tVFS_Node *Node, int ID, void *Data);
33 void TCP_Server_Close(tVFS_Node *Node);
35 tVFS_Node *TCP_Client_Init(tInterface *Interface);
36 Uint64 TCP_Client_Read(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer);
37 Uint64 TCP_Client_Write(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer);
38 int TCP_Client_IOCtl(tVFS_Node *Node, int ID, void *Data);
39 void TCP_Client_Close(tVFS_Node *Node);
42 tSocketFile gTCP_ServerFile = {NULL, "tcps", TCP_Server_Init};
43 tSocketFile gTCP_ClientFile = {NULL, "tcpc", TCP_Client_Init};
46 int giTCP_NumHalfopen = 0;
47 tSpinlock glTCP_Listeners;
48 tTCPListener *gTCP_Listeners;
49 tSpinlock glTCP_OutbountCons;
50 tTCPConnection *gTCP_OutbountCons;
51 Uint32 gaTCP_PortBitmap[0x800];
52 int giTCP_NextOutPort = TCP_MIN_DYNPORT;
56 * \brief Initialise the TCP Layer
58 * Registers the client and server files and the GetPacket callback
62 IPStack_AddFile(&gTCP_ServerFile);
63 IPStack_AddFile(&gTCP_ClientFile);
64 IPv4_RegisterCallback(IP4PROT_TCP, TCP_GetPacket);
68 * \brief Open a connection to another host using TCP
69 * \param Conn Connection structure
71 void TCP_StartConnection(tTCPConnection *Conn)
75 Conn->State = TCP_ST_SYN_SENT;
77 hdr.SourcePort = htons(Conn->LocalPort);
78 hdr.DestPort = htons(Conn->RemotePort);
79 Conn->NextSequenceSend = rand();
80 hdr.SequenceNumber = htonl(Conn->NextSequenceSend);
81 hdr.DataOffset = (sizeof(tTCPHeader)/4) << 4;
82 hdr.Flags = TCP_FLAG_SYN;
83 hdr.WindowSize = htons(TCP_WINDOW_SIZE); // Max
84 hdr.Checksum = 0; // TODO
85 hdr.UrgentPointer = 0;
87 TCP_SendPacket( Conn, sizeof(tTCPHeader), &hdr );
92 * \brief Sends a packet from the specified connection, calculating the checksums
93 * \param Conn Connection
94 * \param Length Length of data
95 * \param Data Packet data (cast as a TCP Header)
97 void TCP_SendPacket( tTCPConnection *Conn, size_t Length, tTCPHeader *Data )
101 switch( Conn->Interface->Type )
103 case 4: // Append IPv4 Pseudo Header
104 buflen = 4 + 4 + 4 + ((Length+1)&~1);
105 buf = malloc( buflen );
106 buf[0] = Conn->Interface->IP4.Address.L;
107 buf[1] = Conn->RemoteIP.v4.L;
108 buf[2] = (htons(Length)<<16) | (6<<8) | 0;
110 memcpy( &buf[3], Data, Length );
111 Data->Checksum = IPv4_Checksum( buf, buflen );
113 IPv4_SendPacket(Conn->Interface, Conn->RemoteIP.v4, IP4PROT_TCP, 0, Length, Data);
119 * \brief Handles a packet from the IP Layer
120 * \param Interface Interface the packet arrived from
121 * \param Address Pointer to the addres structure
122 * \param Length Size of packet in bytes
123 * \param Buffer Packet data
125 void TCP_GetPacket(tInterface *Interface, void *Address, int Length, void *Buffer)
127 tTCPHeader *hdr = Buffer;
129 tTCPConnection *conn;
131 Log_Log("TCP", "SourcePort = %i, DestPort = %i",
132 ntohs(hdr->SourcePort), ntohs(hdr->DestPort));
134 Log_Log("TCP", "SequenceNumber = 0x%x", ntohl(hdr->SequenceNumber));
135 Log_Log("TCP", "AcknowlegementNumber = 0x%x", ntohl(hdr->AcknowlegementNumber));
136 Log_Log("TCP", "DataOffset = %i", hdr->DataOffset >> 4);
137 Log_Log("TCP", "Flags = {");
138 Log_Log("TCP", " CWR = %B, ECE = %B",
139 !!(hdr->Flags & TCP_FLAG_CWR), !!(hdr->Flags & TCP_FLAG_ECE));
140 Log_Log("TCP", " URG = %B, ACK = %B",
141 !!(hdr->Flags & TCP_FLAG_URG), !!(hdr->Flags & TCP_FLAG_ACK));
142 Log_Log("TCP", " PSH = %B, RST = %B",
143 !!(hdr->Flags & TCP_FLAG_PSH), !!(hdr->Flags & TCP_FLAG_RST));
144 Log_Log("TCP", " SYN = %B, FIN = %B",
145 !!(hdr->Flags & TCP_FLAG_SYN), !!(hdr->Flags & TCP_FLAG_FIN));
147 Log_Log("TCP", "WindowSize = %i", htons(hdr->WindowSize));
148 Log_Log("TCP", "Checksum = 0x%x", htons(hdr->Checksum));
149 Log_Log("TCP", "UrgentPointer = 0x%x", htons(hdr->UrgentPointer));
152 if( Length > (hdr->DataOffset >> 4)*4 )
155 "[TCP ] Packet Data = ",
156 (Uint8*)hdr + (hdr->DataOffset >> 4)*4,
157 Length - (hdr->DataOffset >> 4)*4
163 for( srv = gTCP_Listeners; srv; srv = srv->Next )
165 // Check if the server is active
166 if(srv->Port == 0) continue;
167 // Check the interface
168 if(srv->Interface && srv->Interface != Interface) continue;
169 // Check the destination port
170 if(srv->Port != htons(hdr->DestPort)) continue;
172 Log_Log("TCP", "Matches server %p", srv);
173 // Is this in an established connection?
174 for( conn = srv->Connections; conn; conn = conn->Next )
176 Log_Log("TCP", "conn->Interface(%p) == Interface(%p)",
177 conn->Interface, Interface);
178 // Check that it is coming in on the same interface
179 if(conn->Interface != Interface) continue;
182 Log_Log("TCP", "conn->RemotePort(%i) == hdr->SourcePort(%i)",
183 conn->RemotePort, ntohs(hdr->SourcePort));
184 if(conn->RemotePort != ntohs(hdr->SourcePort)) continue;
187 if(conn->Interface->Type == 6 && !IP6_EQU(conn->RemoteIP.v6, *(tIPv6*)Address))
189 if(conn->Interface->Type == 4 && !IP4_EQU(conn->RemoteIP.v4, *(tIPv4*)Address))
192 Log_Log("TCP", "Matches connection %p", conn);
193 // We have a response!
194 TCP_INT_HandleConnectionPacket(conn, hdr, Length);
199 Log_Log("TCP", "Opening Connection");
200 // Open a new connection (well, check that it's a SYN)
201 if(hdr->Flags != TCP_FLAG_SYN) {
202 Log_Log("TCP", "Packet is not a SYN");
206 // TODO: Check for halfopen max
208 conn = calloc(1, sizeof(tTCPConnection));
209 conn->State = TCP_ST_HALFOPEN;
210 conn->LocalPort = srv->Port;
211 conn->RemotePort = ntohs(hdr->SourcePort);
212 conn->Interface = Interface;
214 switch(Interface->Type)
216 case 4: conn->RemoteIP.v4 = *(tIPv4*)Address; break;
217 case 6: conn->RemoteIP.v6 = *(tIPv6*)Address; break;
220 conn->RecievedBuffer = RingBuffer_Create( TCP_RECIEVE_BUFFER_SIZE );
222 conn->NextSequenceRcv = ntohl( hdr->SequenceNumber ) + 1;
223 conn->NextSequenceSend = rand();
226 conn->Node.NumACLs = 1;
227 conn->Node.ACLs = &gVFS_ACL_EveryoneRW;
228 conn->Node.ImplPtr = conn;
229 conn->Node.ImplInt = srv->NextID ++;
230 conn->Node.Read = TCP_Client_Read;
231 conn->Node.Write = TCP_Client_Write;
232 //conn->Node.Close = TCP_SrvConn_Close;
234 // Hmm... Theoretically, this lock will never have to wait,
235 // as the interface is locked to the watching thread, and this
236 // runs in the watching thread. But, it's a good idea to have
238 // Oh, wait, there is a case where a wildcard can be used
239 // (srv->Interface == NULL) so having the lock is a good idea
240 LOCK(&srv->lConnections);
241 if( !srv->Connections )
242 srv->Connections = conn;
244 srv->ConnectionsTail->Next = conn;
245 srv->ConnectionsTail = conn;
246 if(!srv->NewConnections)
247 srv->NewConnections = conn;
248 RELEASE(&srv->lConnections);
251 hdr->Flags |= TCP_FLAG_ACK;
252 hdr->AcknowlegementNumber = htonl(conn->NextSequenceRcv);
253 hdr->SequenceNumber = htonl(conn->NextSequenceSend);
254 hdr->DestPort = hdr->SourcePort;
255 hdr->SourcePort = htons(srv->Port);
256 hdr->DataOffset = (sizeof(tTCPHeader)/4) << 4;
257 TCP_SendPacket( conn, sizeof(tTCPHeader), hdr );
258 conn->NextSequenceSend ++;
264 // Check Open Connections
266 for( conn = gTCP_OutbountCons; conn; conn = conn->Next )
268 // Check that it is coming in on the same interface
269 if(conn->Interface != Interface) continue;
272 if(conn->RemotePort != ntohs(hdr->SourcePort)) continue;
275 if(conn->Interface->Type == 6 && !IP6_EQU(conn->RemoteIP.v6, *(tIPv6*)Address))
277 if(conn->Interface->Type == 4 && !IP4_EQU(conn->RemoteIP.v4, *(tIPv4*)Address))
280 TCP_INT_HandleConnectionPacket(conn, hdr, Length);
285 Log_Log("TCP", "No Match");
289 * \brief Handles a packet sent to a specific connection
290 * \param Connection TCP Connection pointer
291 * \param Header TCP Packet pointer
292 * \param Length Length of the packet
294 void TCP_INT_HandleConnectionPacket(tTCPConnection *Connection, tTCPHeader *Header, int Length)
296 tTCPStoredPacket *pkt;
299 if(Header->Flags & TCP_FLAG_SYN) {
300 Connection->NextSequenceRcv = ntohl(Header->SequenceNumber) + 1;
303 if( Connection->State == TCP_ST_SYN_SENT )
305 if( Header->Flags & (TCP_FLAG_SYN|TCP_FLAG_ACK) ) {
307 Header->DestPort = Header->SourcePort;
308 Header->SourcePort = htons(Connection->LocalPort);
309 Header->AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
310 Header->SequenceNumber = htonl(Connection->NextSequenceSend);
311 Header->WindowSize = htons(TCP_WINDOW_SIZE);
312 Header->Flags = TCP_FLAG_ACK;
313 Header->DataOffset = (sizeof(tTCPHeader)/4) << 4;
314 Log_Log("TCP", "ACKing SYN-ACK");
315 TCP_SendPacket( Connection, sizeof(tTCPHeader), Header );
317 Connection->State = TCP_ST_OPEN;
320 // Get length of data
321 dataLen = Length - (Header->DataOffset>>4)*4;
322 Log_Log("TCP", "HandleConnectionPacket - dataLen = %i", dataLen);
324 if(Header->Flags & TCP_FLAG_ACK) {
325 // TODO: Process an ACKed Packet
326 Log_Log("TCP", "Conn %p, Packet 0x%x ACKed", Connection, Header->AcknowlegementNumber);
329 // TODO: Check what to do here
330 if(Header->Flags & TCP_FLAG_FIN) {
331 if( Connection->State == TCP_ST_FIN_SENT ) {
335 Connection->State = TCP_ST_FINISHED;
336 Header->DestPort = Header->SourcePort;
337 Header->SourcePort = htons(Connection->LocalPort);
338 Header->AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
339 Header->SequenceNumber = htonl(Connection->NextSequenceSend);
340 Header->Flags = TCP_FLAG_ACK;
341 TCP_SendPacket( Connection, sizeof(tTCPHeader), Header );
347 Log_Log("TCP", "Empty Packet");
356 // Allocate and fill cached packet
357 pkt = malloc( dataLen + sizeof(tTCPStoredPacket) );
359 pkt->Sequence = ntohl(Header->SequenceNumber);
360 pkt->Length = dataLen;
361 memcpy(pkt->Data, (Uint8*)Header + (Header->DataOffset>>4)*4, dataLen);
363 // Is this packet the next expected packet?
364 // TODO: Fix this to check if the packet is in the window.
365 if( pkt->Sequence != Connection->NextSequenceRcv )
367 tTCPStoredPacket *tmp, *prev = NULL;
369 Log_Log("TCP", "Out of sequence packet (0x%08x != 0x%08x)",
370 pkt->Sequence, Connection->NextSequenceRcv);
372 // No? Well, let's cache it and look at it later
373 LOCK( &Connection->lFuturePackets );
374 for(tmp = Connection->FuturePackets;
376 prev = tmp, tmp = tmp->Next)
378 if(tmp->Sequence > pkt->Sequence) break;
383 Connection->FuturePackets = pkt;
385 RELEASE( &Connection->lFuturePackets );
389 // Ooh, Goodie! Add it to the recieved list
390 TCP_INT_AppendRecieved(Connection, pkt);
392 Log_Log("TCP", "0x%08x += %i", Connection->NextSequenceRcv, dataLen);
393 Connection->NextSequenceRcv += dataLen;
395 // TODO: This should be moved out of the watcher thread,
396 // so that a single lost packet on one connection doesn't cause
397 // all connections on the interface to lag.
398 TCP_INT_UpdateRecievedFromFuture(Connection);
401 Header->DestPort = Header->SourcePort;
402 Header->SourcePort = htons(Connection->LocalPort);
403 Header->AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
404 Header->SequenceNumber = htonl(Connection->NextSequenceSend);
405 Header->WindowSize = htons(TCP_WINDOW_SIZE);
406 Header->Flags &= TCP_FLAG_SYN; // Eliminate all flags save for SYN
407 Header->Flags |= TCP_FLAG_ACK; // Add ACK
408 Log_Log("TCP", "Sending ACK for 0x%08x", Connection->NextSequenceRcv);
409 TCP_SendPacket( Connection, sizeof(tTCPHeader), Header );
410 //Connection->NextSequenceSend ++;
415 * \brief Appends a packet to the recieved list
416 * \param Connection Connection structure
417 * \param Pkt Packet structure on heap
419 void TCP_INT_AppendRecieved(tTCPConnection *Connection, tTCPStoredPacket *Pkt)
421 LOCK( &Connection->lRecievedPackets );
422 if(Connection->RecievedBuffer->Length + Pkt->Length > Connection->RecievedBuffer->Space )
424 Log_Error("TCP", "Buffer filled, packet dropped (%s)",
425 // TCP_INT_DumpConnection(Connection)
431 RingBuffer_Write( Connection->RecievedBuffer, Pkt->Data, Pkt->Length );
433 RELEASE( &Connection->lRecievedPackets );
437 * \brief Updates the connections recieved list from the future list
438 * \param Connection Connection structure
440 * Updates the recieved packets list with packets from the future (out
441 * of order) packets list that are now able to be added in direct
444 void TCP_INT_UpdateRecievedFromFuture(tTCPConnection *Connection)
446 tTCPStoredPacket *pkt, *prev;
450 // Look for the next expected packet in the cache.
451 LOCK( &Connection->lFuturePackets );
452 for(pkt = Connection->FuturePackets;
453 pkt && pkt->Sequence < Connection->NextSequenceRcv;
454 prev = pkt, pkt = pkt->Next);
456 // If we can't find the expected next packet, stop looking
457 if(!pkt || pkt->Sequence > Connection->NextSequenceRcv) {
458 RELEASE( &Connection->lFuturePackets );
462 // Delete packet from future list
464 prev->Next = pkt->Next;
466 Connection->FuturePackets = pkt->Next;
469 RELEASE( &Connection->lFuturePackets );
471 // Looks like we found one
472 TCP_INT_AppendRecieved(Connection, pkt);
473 Connection->NextSequenceRcv += pkt->Length;
479 * \fn Uint16 TCP_GetUnusedPort()
480 * \brief Gets an unused port and allocates it
482 Uint16 TCP_GetUnusedPort()
486 // Get Next outbound port
487 ret = giTCP_NextOutPort++;
488 while( gaTCP_PortBitmap[ret/32] & (1 << (ret%32)) )
492 if(giTCP_NextOutPort == 0x10000) {
493 ret = giTCP_NextOutPort = TCP_MIN_DYNPORT;
497 // Mark the new port as used
498 gaTCP_PortBitmap[ret/32] |= 1 << (ret%32);
504 * \fn int TCP_AllocatePort(Uint16 Port)
505 * \brief Marks a port as used
507 int TCP_AllocatePort(Uint16 Port)
509 // Check if the port has already been allocated
510 if( gaTCP_PortBitmap[Port/32] & (1 << (Port%32)) )
514 gaTCP_PortBitmap[Port/32] |= 1 << (Port%32);
520 * \fn int TCP_DeallocatePort(Uint16 Port)
521 * \brief Marks a port as unused
523 int TCP_DeallocatePort(Uint16 Port)
525 // Check if the port has already been allocated
526 if( !(gaTCP_PortBitmap[Port/32] & (1 << (Port%32))) )
530 gaTCP_PortBitmap[Port/32] &= ~(1 << (Port%32));
536 tVFS_Node *TCP_Server_Init(tInterface *Interface)
540 srv = malloc( sizeof(tTCPListener) );
543 Log_Warning("TCP", "malloc failed for listener (%i) bytes", sizeof(tTCPListener));
547 srv->Interface = Interface;
550 srv->Connections = NULL;
551 srv->ConnectionsTail = NULL;
552 srv->NewConnections = NULL;
554 srv->Node.Flags = VFS_FFLAG_DIRECTORY;
556 srv->Node.ImplPtr = srv;
557 srv->Node.NumACLs = 1;
558 srv->Node.ACLs = &gVFS_ACL_EveryoneRW;
559 srv->Node.ReadDir = TCP_Server_ReadDir;
560 srv->Node.FindDir = TCP_Server_FindDir;
561 srv->Node.IOCtl = TCP_Server_IOCtl;
562 srv->Node.Close = TCP_Server_Close;
564 LOCK(&glTCP_Listeners);
565 srv->Next = gTCP_Listeners;
566 gTCP_Listeners = srv;
567 RELEASE(&glTCP_Listeners);
573 * \brief Wait for a new connection and return the connection ID
574 * \note Blocks until a new connection is made
575 * \param Node Server node
576 * \param Pos Position (ignored)
578 char *TCP_Server_ReadDir(tVFS_Node *Node, int Pos)
580 tTCPListener *srv = Node->ImplPtr;
581 tTCPConnection *conn;
584 ENTER("pNode iPos", Node, Pos);
586 Log_Log("TCP", "Thread %i waiting for a connection", Threads_GetTID());
589 LOCK( &srv->lConnections );
590 if( srv->NewConnections != NULL ) break;
591 RELEASE( &srv->lConnections );
597 // Increment the new list (the current connection is still on the
599 conn = srv->NewConnections;
600 srv->NewConnections = conn->Next;
602 LOG("conn = %p", conn);
603 LOG("srv->Connections = %p", srv->Connections);
604 LOG("srv->NewConnections = %p", srv->NewConnections);
605 LOG("srv->ConnectionsTail = %p", srv->ConnectionsTail);
607 RELEASE( &srv->lConnections );
610 itoa(ret, conn->Node.ImplInt, 16, 8, '0');
611 Log_Log("TCP", "Thread %i got '%s'", Threads_GetTID(), ret);
617 * \brief Gets a client connection node
618 * \param Node Server node
619 * \param Name Hexadecimal ID of the node
621 tVFS_Node *TCP_Server_FindDir(tVFS_Node *Node, char *Name)
623 tTCPConnection *conn;
624 tTCPListener *srv = Node->ImplPtr;
628 ENTER("pNode sName", Node, Name);
631 itoa(tmp, id, 16, 8, '0');
632 if(strcmp(tmp, Name) != 0) {
633 LOG("'%s' != '%s' (%08x)", Name, tmp, id);
638 Log_Debug("TCP", "srv->Connections = %p", srv->Connections);
639 Log_Debug("TCP", "srv->NewConnections = %p", srv->NewConnections);
640 Log_Debug("TCP", "srv->ConnectionsTail = %p", srv->ConnectionsTail);
643 LOCK( &srv->lConnections );
644 for(conn = srv->Connections;
648 LOG("conn->Node.ImplInt = %i", conn->Node.ImplInt);
649 if(conn->Node.ImplInt == id) break;
651 RELEASE( &srv->lConnections );
653 // If not found, ret NULL
655 LOG("Connection %i not found", id);
661 LEAVE('p', &conn->Node);
666 * \brief Handle IOCtl calls
668 int TCP_Server_IOCtl(tVFS_Node *Node, int ID, void *Data)
670 tTCPListener *srv = Node->ImplPtr;
674 case 4: // Get/Set Port
675 if(!Data) // Get Port
678 if(srv->Port) // Wait, you can't CHANGE the port
681 if(!CheckMem(Data, sizeof(Uint16))) // Sanity check
685 if(Threads_GetUID() != 0
686 && *(Uint16*)Data != 0
687 && *(Uint16*)Data < 1024)
690 // TODO: Check if a port is in use
693 srv->Port = *(Uint16*)Data;
694 if(srv->Port == 0) // Allocate a random port
695 srv->Port = TCP_GetUnusedPort();
696 else // Else, mark this as used
697 TCP_AllocatePort(srv->Port);
699 Log_Log("TCP", "Server %p listening on port %i", srv, srv->Port);
706 void TCP_Server_Close(tVFS_Node *Node)
713 * \brief Create a client node
715 tVFS_Node *TCP_Client_Init(tInterface *Interface)
717 tTCPConnection *conn = malloc( sizeof(tTCPConnection) );
719 conn->State = TCP_ST_CLOSED;
720 conn->Interface = Interface;
721 conn->LocalPort = -1;
722 conn->RemotePort = -1;
723 memset( &conn->RemoteIP, 0, sizeof(conn->RemoteIP) );
725 conn->Node.ImplPtr = conn;
726 conn->Node.NumACLs = 1;
727 conn->Node.ACLs = &gVFS_ACL_EveryoneRW;
728 conn->Node.Read = TCP_Client_Read;
729 conn->Node.Write = TCP_Client_Write;
730 conn->Node.IOCtl = TCP_Client_IOCtl;
731 conn->Node.Close = TCP_Client_Close;
733 LOCK(&glTCP_OutbountCons);
734 conn->Next = gTCP_OutbountCons;
735 gTCP_OutbountCons = conn;
736 RELEASE(&glTCP_OutbountCons);
742 * \brief Wait for a packet and return it
743 * \note If \a Length is smaller than the size of the packet, the rest
744 * of the packet's data will be discarded.
746 Uint64 TCP_Client_Read(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer)
748 tTCPConnection *conn = Node->ImplPtr;
749 char *destbuf = Buffer;
752 ENTER("pNode XOffset XLength pBuffer", Node, Offset, Length, Buffer);
754 // Check if connection is open
755 while( conn->State == TCP_ST_HALFOPEN ) Threads_Yield();
756 if( conn->State != TCP_ST_OPEN ) {
764 // Lock list and check if there is a packet
765 LOCK( &conn->lRecievedPackets );
766 if( conn->RecievedBuffer->Length == 0 ) {
767 // If not, release the lock, yield and try again
768 RELEASE( &conn->lRecievedPackets );
773 // Attempt to read all `Length` bytes
774 len = RingBuffer_Read( destbuf, conn->RecievedBuffer, Length );
776 // Release the lock (we don't need it any more)
777 RELEASE( &conn->lRecievedPackets );
785 * \brief Send a data packet on a connection
787 void TCP_INT_SendDataPacket(tTCPConnection *Connection, size_t Length, void *Data)
789 char buf[sizeof(tTCPHeader)+Length];
790 tTCPHeader *packet = (void*)buf;
792 packet->SourcePort = htons(Connection->LocalPort);
793 packet->DestPort = htons(Connection->RemotePort);
794 packet->DataOffset = (sizeof(tTCPHeader)/4)*16;
795 packet->WindowSize = TCP_WINDOW_SIZE;
797 //packet->AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
798 packet->AcknowlegementNumber = 0;
799 packet->SequenceNumber = htonl(Connection->NextSequenceSend);
800 packet->Flags = TCP_FLAG_PSH; // Hey, ACK if you can!
802 memcpy(packet->Options, Data, Length);
804 TCP_SendPacket( Connection, sizeof(tTCPHeader)+Length, packet );
806 Connection->NextSequenceSend += Length;
810 * \brief Send some bytes on a connection
812 Uint64 TCP_Client_Write(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer)
814 tTCPConnection *conn = Node->ImplPtr;
817 ENTER("pNode XOffset XLength pBuffer", Node, Offset, Length, Buffer);
819 // Check if connection is open
820 while( conn->State == TCP_ST_HALFOPEN ) Threads_Yield();
821 if( conn->State != TCP_ST_OPEN ) {
826 while( rem > TCP_MAX_PACKET_SIZE )
828 TCP_INT_SendDataPacket(conn, TCP_MAX_PACKET_SIZE, Buffer);
829 Buffer += TCP_MAX_PACKET_SIZE;
832 TCP_INT_SendDataPacket(conn, rem, Buffer);
839 * \brief Control a client socket
841 int TCP_Client_IOCtl(tVFS_Node *Node, int ID, void *Data)
843 tTCPConnection *conn = Node->ImplPtr;
847 case 4: // Get/Set local port
849 return conn->LocalPort;
850 if(conn->State != TCP_ST_CLOSED)
852 if(!CheckMem(Data, sizeof(Uint16)))
855 if(Threads_GetUID() != 0 && *(Uint16*)Data < 1024)
858 conn->LocalPort = *(Uint16*)Data;
861 case 5: // Get/Set remote port
862 if(!Data) return conn->RemotePort;
863 if(conn->State != TCP_ST_CLOSED) return -1;
864 if(!CheckMem(Data, sizeof(Uint16))) return -1;
865 conn->RemotePort = *(Uint16*)Data;
868 case 6: // Set Remote IP
869 if( conn->State != TCP_ST_CLOSED )
871 if( conn->Interface->Type == 4 )
873 if(!CheckMem(Data, sizeof(tIPv4))) return -1;
874 conn->RemoteIP.v4 = *(tIPv4*)Data;
876 else if( conn->Interface->Type == 6 )
878 if(!CheckMem(Data, sizeof(tIPv6))) return -1;
879 conn->RemoteIP.v6 = *(tIPv6*)Data;
884 if(conn->LocalPort == -1)
885 conn->LocalPort = TCP_GetUnusedPort();
886 if(conn->RemotePort == -1)
889 TCP_StartConnection(conn);
896 void TCP_Client_Close(tVFS_Node *Node)