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 Sends a packet from the specified connection, calculating the checksums
69 * \param Conn Connection
70 * \param Length Length of data
71 * \param Data Packet data (cast as a TCP Header)
73 void TCP_SendPacket( tTCPConnection *Conn, size_t Length, tTCPHeader *Data )
77 switch( Conn->Interface->Type )
79 case 4: // Append IPv4 Pseudo Header
80 buflen = 4 + 4 + 4 + ((Length+1)&~1);
81 buf = malloc( buflen );
82 buf[0] = Conn->Interface->IP4.Address.L;
83 buf[1] = Conn->RemoteIP.v4.L;
84 buf[2] = (htons(Length)<<16) | (6<<8) | 0;
86 memcpy( &buf[3], Data, Length );
87 Data->Checksum = IPv4_Checksum( buf, buflen );
89 IPv4_SendPacket(Conn->Interface, Conn->RemoteIP.v4, IP4PROT_TCP, 0, Length, Data);
95 * \brief Handles a packet from the IP Layer
96 * \param Interface Interface the packet arrived from
97 * \param Address Pointer to the addres structure
98 * \param Length Size of packet in bytes
99 * \param Buffer Packet data
101 void TCP_GetPacket(tInterface *Interface, void *Address, int Length, void *Buffer)
103 tTCPHeader *hdr = Buffer;
105 tTCPConnection *conn;
107 Log_Log("TCP", "SourcePort = %i, DestPort = %i",
108 ntohs(hdr->SourcePort), ntohs(hdr->DestPort));
110 Log_Log("TCP", "SequenceNumber = 0x%x", ntohl(hdr->SequenceNumber));
111 Log_Log("TCP", "AcknowlegementNumber = 0x%x", ntohl(hdr->AcknowlegementNumber));
112 Log_Log("TCP", "DataOffset = %i", hdr->DataOffset >> 4);
113 Log_Log("TCP", "Flags = {");
114 Log_Log("TCP", " CWR = %B, ECE = %B",
115 !!(hdr->Flags & TCP_FLAG_CWR), !!(hdr->Flags & TCP_FLAG_ECE));
116 Log_Log("TCP", " URG = %B, ACK = %B",
117 !!(hdr->Flags & TCP_FLAG_URG), !!(hdr->Flags & TCP_FLAG_ACK));
118 Log_Log("TCP", " PSH = %B, RST = %B",
119 !!(hdr->Flags & TCP_FLAG_PSH), !!(hdr->Flags & TCP_FLAG_RST));
120 Log_Log("TCP", " SYN = %B, FIN = %B",
121 !!(hdr->Flags & TCP_FLAG_SYN), !!(hdr->Flags & TCP_FLAG_FIN));
123 Log_Log("TCP", "WindowSize = %i", htons(hdr->WindowSize));
124 Log_Log("TCP", "Checksum = 0x%x", htons(hdr->Checksum));
125 Log_Log("TCP", "UrgentPointer = 0x%x", htons(hdr->UrgentPointer));
128 if( Length > (hdr->DataOffset >> 4)*4 )
131 "[TCP ] Packet Data = ",
132 (Uint8*)hdr + (hdr->DataOffset >> 4)*4,
133 Length - (hdr->DataOffset >> 4)*4
139 for( srv = gTCP_Listeners; srv; srv = srv->Next )
141 // Check if the server is active
142 if(srv->Port == 0) continue;
143 // Check the interface
144 if(srv->Interface && srv->Interface != Interface) continue;
145 // Check the destination port
146 if(srv->Port != htons(hdr->DestPort)) continue;
148 Log_Log("TCP", "Matches server %p", srv);
149 // Is this in an established connection?
150 for( conn = srv->Connections; conn; conn = conn->Next )
152 Log_Log("TCP", "conn->Interface(%p) == Interface(%p)",
153 conn->Interface, Interface);
154 // Check that it is coming in on the same interface
155 if(conn->Interface != Interface) continue;
158 Log_Log("TCP", "conn->RemotePort(%i) == hdr->SourcePort(%i)",
159 conn->RemotePort, ntohs(hdr->SourcePort));
160 if(conn->RemotePort != ntohs(hdr->SourcePort)) continue;
163 if(conn->Interface->Type == 6 && !IP6_EQU(conn->RemoteIP.v6, *(tIPv6*)Address))
165 if(conn->Interface->Type == 4 && !IP4_EQU(conn->RemoteIP.v4, *(tIPv4*)Address))
168 Log_Log("TCP", "Matches connection %p", conn);
169 // We have a response!
170 TCP_INT_HandleConnectionPacket(conn, hdr, Length);
175 Log_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_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->RecievedBuffer = RingBuffer_Create( TCP_RECIEVE_BUFFER_SIZE );
198 conn->NextSequenceRcv = ntohl( hdr->SequenceNumber ) + 1;
199 conn->NextSequenceSend = rand();
202 conn->Node.NumACLs = 1;
203 conn->Node.ACLs = &gVFS_ACL_EveryoneRW;
204 conn->Node.ImplPtr = conn;
205 conn->Node.ImplInt = srv->NextID ++;
206 conn->Node.Read = TCP_Client_Read;
207 conn->Node.Write = TCP_Client_Write;
208 //conn->Node.Close = TCP_SrvConn_Close;
210 // Hmm... Theoretically, this lock will never have to wait,
211 // as the interface is locked to the watching thread, and this
212 // runs in the watching thread. But, it's a good idea to have
214 // Oh, wait, there is a case where a wildcard can be used
215 // (srv->Interface == NULL) so having the lock is a good idea
216 LOCK(&srv->lConnections);
217 if( !srv->Connections )
218 srv->Connections = conn;
220 srv->ConnectionsTail->Next = conn;
221 srv->ConnectionsTail = conn;
222 if(!srv->NewConnections)
223 srv->NewConnections = conn;
224 RELEASE(&srv->lConnections);
227 hdr->Flags |= TCP_FLAG_ACK;
228 hdr->AcknowlegementNumber = htonl(conn->NextSequenceRcv);
229 hdr->SequenceNumber = htonl(conn->NextSequenceSend);
230 hdr->DestPort = hdr->SourcePort;
231 hdr->SourcePort = htons(srv->Port);
232 hdr->DataOffset = (sizeof(tTCPHeader)/4) << 4;
233 TCP_SendPacket( conn, sizeof(tTCPHeader), hdr );
234 conn->NextSequenceSend ++;
240 // Check Open Connections
242 for( conn = gTCP_OutbountCons; conn; conn = conn->Next )
244 // Check that it is coming in on the same interface
245 if(conn->Interface != Interface) continue;
248 if(conn->RemotePort != ntohs(hdr->SourcePort)) continue;
251 if(conn->Interface->Type == 6 && !IP6_EQU(conn->RemoteIP.v6, *(tIPv6*)Address))
253 if(conn->Interface->Type == 4 && !IP4_EQU(conn->RemoteIP.v4, *(tIPv4*)Address))
256 TCP_INT_HandleConnectionPacket(conn, hdr, Length);
261 Log_Log("TCP", "No Match");
265 * \brief Handles a packet sent to a specific connection
266 * \param Connection TCP Connection pointer
267 * \param Header TCP Packet pointer
268 * \param Length Length of the packet
270 void TCP_INT_HandleConnectionPacket(tTCPConnection *Connection, tTCPHeader *Header, int Length)
272 tTCPStoredPacket *pkt;
275 if(Header->Flags & TCP_FLAG_SYN) {
276 Connection->NextSequenceRcv = ntohl(Header->SequenceNumber) + 1;
279 if( Connection->State == TCP_ST_SYN_SENT )
281 if( (Header->Flags & (TCP_FLAG_SYN|TCP_FLAG_ACK)) == (TCP_FLAG_SYN|TCP_FLAG_ACK) ) {
283 Header->DestPort = Header->SourcePort;
284 Header->SourcePort = htons(Connection->LocalPort);
285 Header->AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
286 Header->SequenceNumber = htonl(Connection->NextSequenceSend);
287 Header->WindowSize = htons(TCP_WINDOW_SIZE);
288 Header->Flags = TCP_FLAG_ACK;
289 Header->DataOffset = (sizeof(tTCPHeader)/4) << 4;
290 Log_Log("TCP", "ACKing SYN-ACK");
291 TCP_SendPacket( Connection, sizeof(tTCPHeader), Header );
292 Connection->State = TCP_ST_OPEN;
296 // Get length of data
297 dataLen = Length - (Header->DataOffset>>4)*4;
298 Log_Log("TCP", "HandleConnectionPacket - dataLen = %i", dataLen);
300 if(Header->Flags & TCP_FLAG_ACK) {
301 // TODO: Process an ACKed Packet
302 Log_Log("TCP", "Conn %p, Packet 0x%x ACKed", Connection, Header->AcknowlegementNumber);
305 // TODO: Check what to do here
306 if(Header->Flags & TCP_FLAG_FIN) {
307 if( Connection->State == TCP_ST_FIN_SENT ) {
308 Connection->State = TCP_ST_FINISHED;
312 Connection->State = TCP_ST_FINISHED;
313 Header->DestPort = Header->SourcePort;
314 Header->SourcePort = htons(Connection->LocalPort);
315 Header->AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
316 Header->SequenceNumber = htonl(Connection->NextSequenceSend);
317 Header->Flags = TCP_FLAG_ACK;
318 TCP_SendPacket( Connection, sizeof(tTCPHeader), Header );
324 Log_Log("TCP", "Empty Packet");
333 // Allocate and fill cached packet
334 pkt = malloc( dataLen + sizeof(tTCPStoredPacket) );
336 pkt->Sequence = ntohl(Header->SequenceNumber);
337 pkt->Length = dataLen;
338 memcpy(pkt->Data, (Uint8*)Header + (Header->DataOffset>>4)*4, dataLen);
340 // Is this packet the next expected packet?
341 // TODO: Fix this to check if the packet is in the window.
342 if( pkt->Sequence != Connection->NextSequenceRcv )
344 tTCPStoredPacket *tmp, *prev = NULL;
346 Log_Log("TCP", "Out of sequence packet (0x%08x != 0x%08x)",
347 pkt->Sequence, Connection->NextSequenceRcv);
349 // No? Well, let's cache it and look at it later
350 LOCK( &Connection->lFuturePackets );
351 for(tmp = Connection->FuturePackets;
353 prev = tmp, tmp = tmp->Next)
355 if(tmp->Sequence > pkt->Sequence) break;
360 Connection->FuturePackets = pkt;
362 RELEASE( &Connection->lFuturePackets );
366 // Ooh, Goodie! Add it to the recieved list
367 TCP_INT_AppendRecieved(Connection, pkt);
369 Log_Log("TCP", "0x%08x += %i", Connection->NextSequenceRcv, dataLen);
370 Connection->NextSequenceRcv += dataLen;
372 // TODO: This should be moved out of the watcher thread,
373 // so that a single lost packet on one connection doesn't cause
374 // all connections on the interface to lag.
375 TCP_INT_UpdateRecievedFromFuture(Connection);
378 Header->DestPort = Header->SourcePort;
379 Header->SourcePort = htons(Connection->LocalPort);
380 Header->AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
381 Header->SequenceNumber = htonl(Connection->NextSequenceSend);
382 Header->WindowSize = htons(TCP_WINDOW_SIZE);
383 Header->Flags &= TCP_FLAG_SYN; // Eliminate all flags save for SYN
384 Header->Flags |= TCP_FLAG_ACK; // Add ACK
385 Log_Log("TCP", "Sending ACK for 0x%08x", Connection->NextSequenceRcv);
386 TCP_SendPacket( Connection, sizeof(tTCPHeader), Header );
387 //Connection->NextSequenceSend ++;
392 * \brief Appends a packet to the recieved list
393 * \param Connection Connection structure
394 * \param Pkt Packet structure on heap
396 void TCP_INT_AppendRecieved(tTCPConnection *Connection, tTCPStoredPacket *Pkt)
398 LOCK( &Connection->lRecievedPackets );
399 if(Connection->RecievedBuffer->Length + Pkt->Length > Connection->RecievedBuffer->Space )
401 Log_Error("TCP", "Buffer filled, packet dropped (%s)",
402 // TCP_INT_DumpConnection(Connection)
408 RingBuffer_Write( Connection->RecievedBuffer, Pkt->Data, Pkt->Length );
410 RELEASE( &Connection->lRecievedPackets );
414 * \brief Updates the connections recieved list from the future list
415 * \param Connection Connection structure
417 * Updates the recieved packets list with packets from the future (out
418 * of order) packets list that are now able to be added in direct
421 void TCP_INT_UpdateRecievedFromFuture(tTCPConnection *Connection)
423 tTCPStoredPacket *pkt, *prev;
427 // Look for the next expected packet in the cache.
428 LOCK( &Connection->lFuturePackets );
429 for(pkt = Connection->FuturePackets;
430 pkt && pkt->Sequence < Connection->NextSequenceRcv;
431 prev = pkt, pkt = pkt->Next);
433 // If we can't find the expected next packet, stop looking
434 if(!pkt || pkt->Sequence > Connection->NextSequenceRcv) {
435 RELEASE( &Connection->lFuturePackets );
439 // Delete packet from future list
441 prev->Next = pkt->Next;
443 Connection->FuturePackets = pkt->Next;
446 RELEASE( &Connection->lFuturePackets );
448 // Looks like we found one
449 TCP_INT_AppendRecieved(Connection, pkt);
450 Connection->NextSequenceRcv += pkt->Length;
456 * \fn Uint16 TCP_GetUnusedPort()
457 * \brief Gets an unused port and allocates it
459 Uint16 TCP_GetUnusedPort()
463 // Get Next outbound port
464 ret = giTCP_NextOutPort++;
465 while( gaTCP_PortBitmap[ret/32] & (1 << (ret%32)) )
469 if(giTCP_NextOutPort == 0x10000) {
470 ret = giTCP_NextOutPort = TCP_MIN_DYNPORT;
474 // Mark the new port as used
475 gaTCP_PortBitmap[ret/32] |= 1 << (ret%32);
481 * \fn int TCP_AllocatePort(Uint16 Port)
482 * \brief Marks a port as used
484 int TCP_AllocatePort(Uint16 Port)
486 // Check if the port has already been allocated
487 if( gaTCP_PortBitmap[Port/32] & (1 << (Port%32)) )
491 gaTCP_PortBitmap[Port/32] |= 1 << (Port%32);
497 * \fn int TCP_DeallocatePort(Uint16 Port)
498 * \brief Marks a port as unused
500 int TCP_DeallocatePort(Uint16 Port)
502 // Check if the port has already been allocated
503 if( !(gaTCP_PortBitmap[Port/32] & (1 << (Port%32))) )
507 gaTCP_PortBitmap[Port/32] &= ~(1 << (Port%32));
513 tVFS_Node *TCP_Server_Init(tInterface *Interface)
517 srv = malloc( sizeof(tTCPListener) );
520 Log_Warning("TCP", "malloc failed for listener (%i) bytes", sizeof(tTCPListener));
524 srv->Interface = Interface;
527 srv->Connections = NULL;
528 srv->ConnectionsTail = NULL;
529 srv->NewConnections = NULL;
531 srv->Node.Flags = VFS_FFLAG_DIRECTORY;
533 srv->Node.ImplPtr = srv;
534 srv->Node.NumACLs = 1;
535 srv->Node.ACLs = &gVFS_ACL_EveryoneRW;
536 srv->Node.ReadDir = TCP_Server_ReadDir;
537 srv->Node.FindDir = TCP_Server_FindDir;
538 srv->Node.IOCtl = TCP_Server_IOCtl;
539 srv->Node.Close = TCP_Server_Close;
541 LOCK(&glTCP_Listeners);
542 srv->Next = gTCP_Listeners;
543 gTCP_Listeners = srv;
544 RELEASE(&glTCP_Listeners);
550 * \brief Wait for a new connection and return the connection ID
551 * \note Blocks until a new connection is made
552 * \param Node Server node
553 * \param Pos Position (ignored)
555 char *TCP_Server_ReadDir(tVFS_Node *Node, int Pos)
557 tTCPListener *srv = Node->ImplPtr;
558 tTCPConnection *conn;
561 ENTER("pNode iPos", Node, Pos);
563 Log_Log("TCP", "Thread %i waiting for a connection", Threads_GetTID());
566 LOCK( &srv->lConnections );
567 if( srv->NewConnections != NULL ) break;
568 RELEASE( &srv->lConnections );
574 // Increment the new list (the current connection is still on the
576 conn = srv->NewConnections;
577 srv->NewConnections = conn->Next;
579 LOG("conn = %p", conn);
580 LOG("srv->Connections = %p", srv->Connections);
581 LOG("srv->NewConnections = %p", srv->NewConnections);
582 LOG("srv->ConnectionsTail = %p", srv->ConnectionsTail);
584 RELEASE( &srv->lConnections );
587 itoa(ret, conn->Node.ImplInt, 16, 8, '0');
588 Log_Log("TCP", "Thread %i got '%s'", Threads_GetTID(), ret);
594 * \brief Gets a client connection node
595 * \param Node Server node
596 * \param Name Hexadecimal ID of the node
598 tVFS_Node *TCP_Server_FindDir(tVFS_Node *Node, char *Name)
600 tTCPConnection *conn;
601 tTCPListener *srv = Node->ImplPtr;
605 ENTER("pNode sName", Node, Name);
608 itoa(tmp, id, 16, 8, '0');
609 if(strcmp(tmp, Name) != 0) {
610 LOG("'%s' != '%s' (%08x)", Name, tmp, id);
615 Log_Debug("TCP", "srv->Connections = %p", srv->Connections);
616 Log_Debug("TCP", "srv->NewConnections = %p", srv->NewConnections);
617 Log_Debug("TCP", "srv->ConnectionsTail = %p", srv->ConnectionsTail);
620 LOCK( &srv->lConnections );
621 for(conn = srv->Connections;
625 LOG("conn->Node.ImplInt = %i", conn->Node.ImplInt);
626 if(conn->Node.ImplInt == id) break;
628 RELEASE( &srv->lConnections );
630 // If not found, ret NULL
632 LOG("Connection %i not found", id);
638 LEAVE('p', &conn->Node);
643 * \brief Handle IOCtl calls
645 int TCP_Server_IOCtl(tVFS_Node *Node, int ID, void *Data)
647 tTCPListener *srv = Node->ImplPtr;
651 case 4: // Get/Set Port
652 if(!Data) // Get Port
655 if(srv->Port) // Wait, you can't CHANGE the port
658 if(!CheckMem(Data, sizeof(Uint16))) // Sanity check
662 if(Threads_GetUID() != 0
663 && *(Uint16*)Data != 0
664 && *(Uint16*)Data < 1024)
667 // TODO: Check if a port is in use
670 srv->Port = *(Uint16*)Data;
671 if(srv->Port == 0) // Allocate a random port
672 srv->Port = TCP_GetUnusedPort();
673 else // Else, mark this as used
674 TCP_AllocatePort(srv->Port);
676 Log_Log("TCP", "Server %p listening on port %i", srv, srv->Port);
683 void TCP_Server_Close(tVFS_Node *Node)
690 * \brief Create a client node
692 tVFS_Node *TCP_Client_Init(tInterface *Interface)
694 tTCPConnection *conn = malloc( sizeof(tTCPConnection) );
696 conn->State = TCP_ST_CLOSED;
697 conn->Interface = Interface;
698 conn->LocalPort = -1;
699 conn->RemotePort = -1;
700 memset( &conn->RemoteIP, 0, sizeof(conn->RemoteIP) );
702 conn->Node.ImplPtr = conn;
703 conn->Node.NumACLs = 1;
704 conn->Node.ACLs = &gVFS_ACL_EveryoneRW;
705 conn->Node.Read = TCP_Client_Read;
706 conn->Node.Write = TCP_Client_Write;
707 conn->Node.IOCtl = TCP_Client_IOCtl;
708 conn->Node.Close = TCP_Client_Close;
710 conn->RecievedBuffer = RingBuffer_Create( TCP_RECIEVE_BUFFER_SIZE );
712 LOCK(&glTCP_OutbountCons);
713 conn->Next = gTCP_OutbountCons;
714 gTCP_OutbountCons = conn;
715 RELEASE(&glTCP_OutbountCons);
721 * \brief Wait for a packet and return it
722 * \note If \a Length is smaller than the size of the packet, the rest
723 * of the packet's data will be discarded.
725 Uint64 TCP_Client_Read(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer)
727 tTCPConnection *conn = Node->ImplPtr;
728 char *destbuf = Buffer;
731 ENTER("pNode XOffset XLength pBuffer", Node, Offset, Length, Buffer);
732 LOG("conn = %p", conn);
733 LOG("conn->State = %i", conn->State);
735 // Check if connection is open
736 while( conn->State == TCP_ST_HALFOPEN || conn->State == TCP_ST_SYN_SENT )
738 if( conn->State != TCP_ST_OPEN ) {
746 // Lock list and check if there is a packet
747 LOCK( &conn->lRecievedPackets );
748 if( conn->RecievedBuffer->Length == 0 ) {
749 // If not, release the lock, yield and try again
750 RELEASE( &conn->lRecievedPackets );
755 // Attempt to read all `Length` bytes
756 len = RingBuffer_Read( destbuf, conn->RecievedBuffer, Length );
758 // Release the lock (we don't need it any more)
759 RELEASE( &conn->lRecievedPackets );
767 * \brief Send a data packet on a connection
769 void TCP_INT_SendDataPacket(tTCPConnection *Connection, size_t Length, void *Data)
771 char buf[sizeof(tTCPHeader)+Length];
772 tTCPHeader *packet = (void*)buf;
774 packet->SourcePort = htons(Connection->LocalPort);
775 packet->DestPort = htons(Connection->RemotePort);
776 packet->DataOffset = (sizeof(tTCPHeader)/4)*16;
777 packet->WindowSize = TCP_WINDOW_SIZE;
779 packet->AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
780 packet->SequenceNumber = htonl(Connection->NextSequenceSend);
781 packet->Flags = TCP_FLAG_PSH|TCP_FLAG_ACK; // Hey, ACK if you can!
783 memcpy(packet->Options, Data, Length);
785 TCP_SendPacket( Connection, sizeof(tTCPHeader)+Length, packet );
787 Connection->NextSequenceSend += Length;
791 * \brief Send some bytes on a connection
793 Uint64 TCP_Client_Write(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer)
795 tTCPConnection *conn = Node->ImplPtr;
798 ENTER("pNode XOffset XLength pBuffer", Node, Offset, Length, Buffer);
800 // Check if connection is open
801 while( conn->State == TCP_ST_HALFOPEN || conn->State == TCP_ST_SYN_SENT )
803 if( conn->State != TCP_ST_OPEN ) {
808 while( rem > TCP_MAX_PACKET_SIZE )
810 TCP_INT_SendDataPacket(conn, TCP_MAX_PACKET_SIZE, Buffer);
811 Buffer += TCP_MAX_PACKET_SIZE;
814 TCP_INT_SendDataPacket(conn, rem, Buffer);
821 * \brief Open a connection to another host using TCP
822 * \param Conn Connection structure
824 void TCP_StartConnection(tTCPConnection *Conn)
828 Conn->State = TCP_ST_SYN_SENT;
830 hdr.SourcePort = htons(Conn->LocalPort);
831 hdr.DestPort = htons(Conn->RemotePort);
832 Conn->NextSequenceSend = rand();
833 hdr.SequenceNumber = htonl(Conn->NextSequenceSend);
834 hdr.DataOffset = (sizeof(tTCPHeader)/4) << 4;
835 hdr.Flags = TCP_FLAG_SYN;
836 hdr.WindowSize = htons(TCP_WINDOW_SIZE); // Max
837 hdr.Checksum = 0; // TODO
838 hdr.UrgentPointer = 0;
840 TCP_SendPacket( Conn, sizeof(tTCPHeader), &hdr );
842 Conn->NextSequenceSend ++;
843 Conn->State = TCP_ST_SYN_SENT;
848 * \brief Control a client socket
850 int TCP_Client_IOCtl(tVFS_Node *Node, int ID, void *Data)
852 tTCPConnection *conn = Node->ImplPtr;
856 case 4: // Get/Set local port
858 return conn->LocalPort;
859 if(conn->State != TCP_ST_CLOSED)
861 if(!CheckMem(Data, sizeof(Uint16)))
864 if(Threads_GetUID() != 0 && *(Uint16*)Data < 1024)
867 conn->LocalPort = *(Uint16*)Data;
870 case 5: // Get/Set remote port
871 if(!Data) return conn->RemotePort;
872 if(conn->State != TCP_ST_CLOSED) return -1;
873 if(!CheckMem(Data, sizeof(Uint16))) return -1;
874 conn->RemotePort = *(Uint16*)Data;
877 case 6: // Set Remote IP
878 if( conn->State != TCP_ST_CLOSED )
880 if( conn->Interface->Type == 4 )
882 if(!CheckMem(Data, sizeof(tIPv4))) return -1;
883 conn->RemoteIP.v4 = *(tIPv4*)Data;
885 else if( conn->Interface->Type == 6 )
887 if(!CheckMem(Data, sizeof(tIPv6))) return -1;
888 conn->RemoteIP.v6 = *(tIPv6*)Data;
893 if(conn->LocalPort == 0xFFFF)
894 conn->LocalPort = TCP_GetUnusedPort();
895 if(conn->RemotePort == -1)
898 TCP_StartConnection(conn);
905 void TCP_Client_Close(tVFS_Node *Node)
907 tTCPConnection *conn = Node->ImplPtr;
910 packet.SourcePort = htons(conn->LocalPort);
911 packet.DestPort = htons(conn->RemotePort);
912 packet.DataOffset = (sizeof(tTCPHeader)/4)*16;
913 packet.WindowSize = TCP_WINDOW_SIZE;
915 packet.AcknowlegementNumber = 0;
916 packet.SequenceNumber = htonl(conn->NextSequenceSend);
917 packet.Flags = TCP_FLAG_FIN;
919 conn->State = TCP_ST_FIN_SENT;
921 TCP_SendPacket( conn, sizeof(tTCPHeader), &packet );
923 while( conn->State == TCP_ST_FIN_SENT ) Threads_Yield();