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, const 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 tShortSpinlock glTCP_Listeners;
48 tTCPListener *gTCP_Listeners;
49 tShortSpinlock 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] = ((tIPv4*)Conn->Interface->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 = htons( 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", "TCP_GetPacket: SourcePort = %i, DestPort = %i",
108 ntohs(hdr->SourcePort), ntohs(hdr->DestPort));
110 Log_Log("TCP", "TCP_GetPacket: SequenceNumber = 0x%x", ntohl(hdr->SequenceNumber));
111 Log_Log("TCP", "TCP_GetPacket: AcknowlegementNumber = 0x%x", ntohl(hdr->AcknowlegementNumber));
112 Log_Log("TCP", "TCP_GetPacket: DataOffset = %i", hdr->DataOffset >> 4);
113 Log_Log("TCP", "TCP_GetPacket: Flags = {");
114 Log_Log("TCP", "TCP_GetPacket: CWR = %B, ECE = %B",
115 !!(hdr->Flags & TCP_FLAG_CWR), !!(hdr->Flags & TCP_FLAG_ECE));
116 Log_Log("TCP", "TCP_GetPacket: URG = %B, ACK = %B",
117 !!(hdr->Flags & TCP_FLAG_URG), !!(hdr->Flags & TCP_FLAG_ACK));
118 Log_Log("TCP", "TCP_GetPacket: PSH = %B, RST = %B",
119 !!(hdr->Flags & TCP_FLAG_PSH), !!(hdr->Flags & TCP_FLAG_RST));
120 Log_Log("TCP", "TCP_GetPacket: SYN = %B, FIN = %B",
121 !!(hdr->Flags & TCP_FLAG_SYN), !!(hdr->Flags & TCP_FLAG_FIN));
122 Log_Log("TCP", "TCP_GetPacket: }");
123 Log_Log("TCP", "TCP_GetPacket: WindowSize = %i", htons(hdr->WindowSize));
124 Log_Log("TCP", "TCP_GetPacket: Checksum = 0x%x", htons(hdr->Checksum));
125 Log_Log("TCP", "TCP_GetPacket: UrgentPointer = 0x%x", htons(hdr->UrgentPointer));
127 Log_Log("TCP", "TCP_GetPacket: Flags = %s%s%s%s%s%s",
128 (hdr->Flags & TCP_FLAG_CWR) ? "CWR " : "",
129 (hdr->Flags & TCP_FLAG_ECE) ? "ECE " : "",
130 (hdr->Flags & TCP_FLAG_URG) ? "URG " : "",
131 (hdr->Flags & TCP_FLAG_ACK) ? "ACK " : "",
132 (hdr->Flags & TCP_FLAG_PSH) ? "PSH " : "",
133 (hdr->Flags & TCP_FLAG_RST) ? "RST " : "",
134 (hdr->Flags & TCP_FLAG_SYN) ? "SYN " : "",
135 (hdr->Flags & TCP_FLAG_FIN) ? "FIN " : ""
138 if( Length > (hdr->DataOffset >> 4)*4 )
141 "[TCP ] Packet Data = ",
142 (Uint8*)hdr + (hdr->DataOffset >> 4)*4,
143 Length - (hdr->DataOffset >> 4)*4
149 for( srv = gTCP_Listeners; srv; srv = srv->Next )
151 // Check if the server is active
152 if(srv->Port == 0) continue;
153 // Check the interface
154 if(srv->Interface && srv->Interface != Interface) continue;
155 // Check the destination port
156 if(srv->Port != htons(hdr->DestPort)) continue;
158 Log_Log("TCP", "TCP_GetPacket: Matches server %p", srv);
159 // Is this in an established connection?
160 for( conn = srv->Connections; conn; conn = conn->Next )
162 Log_Log("TCP", "TCP_GetPacket: conn->Interface(%p) == Interface(%p)",
163 conn->Interface, Interface);
164 // Check that it is coming in on the same interface
165 if(conn->Interface != Interface) continue;
168 Log_Log("TCP", "TCP_GetPacket: conn->RemotePort(%i) == hdr->SourcePort(%i)",
169 conn->RemotePort, ntohs(hdr->SourcePort));
170 if(conn->RemotePort != ntohs(hdr->SourcePort)) continue;
173 if(conn->Interface->Type == 6 && !IP6_EQU(conn->RemoteIP.v6, *(tIPv6*)Address))
175 if(conn->Interface->Type == 4 && !IP4_EQU(conn->RemoteIP.v4, *(tIPv4*)Address))
178 Log_Log("TCP", "TCP_GetPacket: Matches connection %p", conn);
179 // We have a response!
180 TCP_INT_HandleConnectionPacket(conn, hdr, Length);
185 Log_Log("TCP", "TCP_GetPacket: Opening Connection");
186 // Open a new connection (well, check that it's a SYN)
187 if(hdr->Flags != TCP_FLAG_SYN) {
188 Log_Log("TCP", "TCP_GetPacket: Packet is not a SYN");
192 // TODO: Check for halfopen max
194 conn = calloc(1, sizeof(tTCPConnection));
195 conn->State = TCP_ST_HALFOPEN;
196 conn->LocalPort = srv->Port;
197 conn->RemotePort = ntohs(hdr->SourcePort);
198 conn->Interface = Interface;
200 switch(Interface->Type)
202 case 4: conn->RemoteIP.v4 = *(tIPv4*)Address; break;
203 case 6: conn->RemoteIP.v6 = *(tIPv6*)Address; break;
206 conn->RecievedBuffer = RingBuffer_Create( TCP_RECIEVE_BUFFER_SIZE );
208 conn->NextSequenceRcv = ntohl( hdr->SequenceNumber ) + 1;
209 conn->NextSequenceSend = rand();
212 conn->Node.NumACLs = 1;
213 conn->Node.ACLs = &gVFS_ACL_EveryoneRW;
214 conn->Node.ImplPtr = conn;
215 conn->Node.ImplInt = srv->NextID ++;
216 conn->Node.Read = TCP_Client_Read;
217 conn->Node.Write = TCP_Client_Write;
218 //conn->Node.Close = TCP_SrvConn_Close;
220 // Hmm... Theoretically, this lock will never have to wait,
221 // as the interface is locked to the watching thread, and this
222 // runs in the watching thread. But, it's a good idea to have
224 // Oh, wait, there is a case where a wildcard can be used
225 // (srv->Interface == NULL) so having the lock is a good idea
226 SHORTLOCK(&srv->lConnections);
227 if( !srv->Connections )
228 srv->Connections = conn;
230 srv->ConnectionsTail->Next = conn;
231 srv->ConnectionsTail = conn;
232 if(!srv->NewConnections)
233 srv->NewConnections = conn;
234 SHORTREL(&srv->lConnections);
237 hdr->Flags |= TCP_FLAG_ACK;
238 hdr->AcknowlegementNumber = htonl(conn->NextSequenceRcv);
239 hdr->SequenceNumber = htonl(conn->NextSequenceSend);
240 hdr->DestPort = hdr->SourcePort;
241 hdr->SourcePort = htons(srv->Port);
242 hdr->DataOffset = (sizeof(tTCPHeader)/4) << 4;
243 TCP_SendPacket( conn, sizeof(tTCPHeader), hdr );
244 conn->NextSequenceSend ++;
250 // Check Open Connections
252 for( conn = gTCP_OutbountCons; conn; conn = conn->Next )
254 // Check that it is coming in on the same interface
255 if(conn->Interface != Interface) continue;
258 if(conn->RemotePort != ntohs(hdr->SourcePort)) continue;
261 if(conn->Interface->Type == 6 && !IP6_EQU(conn->RemoteIP.v6, *(tIPv6*)Address))
263 if(conn->Interface->Type == 4 && !IP4_EQU(conn->RemoteIP.v4, *(tIPv4*)Address))
266 TCP_INT_HandleConnectionPacket(conn, hdr, Length);
271 Log_Log("TCP", "TCP_GetPacket: No Match");
275 * \brief Handles a packet sent to a specific connection
276 * \param Connection TCP Connection pointer
277 * \param Header TCP Packet pointer
278 * \param Length Length of the packet
280 void TCP_INT_HandleConnectionPacket(tTCPConnection *Connection, tTCPHeader *Header, int Length)
282 tTCPStoredPacket *pkt;
285 // Syncronise sequence values
286 if(Header->Flags & TCP_FLAG_SYN) {
287 Connection->NextSequenceRcv = ntohl(Header->SequenceNumber) + 1;
290 // Handle a server replying to our initial SYN
291 if( Connection->State == TCP_ST_SYN_SENT )
293 if( (Header->Flags & (TCP_FLAG_SYN|TCP_FLAG_ACK)) == (TCP_FLAG_SYN|TCP_FLAG_ACK) )
295 Header->DestPort = Header->SourcePort;
296 Header->SourcePort = htons(Connection->LocalPort);
297 Header->AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
298 Header->SequenceNumber = htonl(Connection->NextSequenceSend);
299 Header->WindowSize = htons(TCP_WINDOW_SIZE);
300 Header->Flags = TCP_FLAG_ACK;
301 Header->DataOffset = (sizeof(tTCPHeader)/4) << 4;
302 Log_Log("TCP", "ACKing SYN-ACK");
303 TCP_SendPacket( Connection, sizeof(tTCPHeader), Header );
304 Connection->State = TCP_ST_OPEN;
308 // Handle a client confirming the connection
309 if( Connection->State == TCP_ST_HALFOPEN && (Header->Flags & TCP_FLAG_ACK) )
311 Connection->State = TCP_ST_OPEN;
312 Log_Log("TCP", "Connection fully opened");
315 // Get length of data
316 dataLen = Length - (Header->DataOffset>>4)*4;
317 Log_Log("TCP", "HandleConnectionPacket - dataLen = %i", dataLen);
319 if(Header->Flags & TCP_FLAG_ACK) {
320 // TODO: Process an ACKed Packet
321 Log_Log("TCP", "Conn %p, Packet 0x%x ACKed", Connection, Header->AcknowlegementNumber);
324 // TODO: Check what to do here
325 if(Header->Flags & TCP_FLAG_FIN) {
326 if( Connection->State == TCP_ST_FIN_SENT ) {
327 Connection->State = TCP_ST_FINISHED;
331 Connection->State = TCP_ST_FINISHED;
332 Header->DestPort = Header->SourcePort;
333 Header->SourcePort = htons(Connection->LocalPort);
334 Header->AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
335 Header->SequenceNumber = htonl(Connection->NextSequenceSend);
336 Header->Flags = TCP_FLAG_ACK;
337 TCP_SendPacket( Connection, sizeof(tTCPHeader), Header );
342 // Check for an empty packet
344 Log_Log("TCP", "Empty Packet");
353 // Allocate and fill cached packet
354 pkt = malloc( dataLen + sizeof(tTCPStoredPacket) );
356 pkt->Sequence = ntohl(Header->SequenceNumber);
357 pkt->Length = dataLen;
358 memcpy(pkt->Data, (Uint8*)Header + (Header->DataOffset>>4)*4, dataLen);
360 // Is this packet the next expected packet?
361 // TODO: Fix this to check if the packet is in the window.
362 if( pkt->Sequence != Connection->NextSequenceRcv )
364 tTCPStoredPacket *tmp, *prev = NULL;
366 Log_Log("TCP", "Out of sequence packet (0x%08x != 0x%08x)",
367 pkt->Sequence, Connection->NextSequenceRcv);
369 // No? Well, let's cache it and look at it later
370 SHORTLOCK( &Connection->lFuturePackets );
371 for(tmp = Connection->FuturePackets;
373 prev = tmp, tmp = tmp->Next)
375 if(tmp->Sequence > pkt->Sequence) break;
380 Connection->FuturePackets = pkt;
382 SHORTREL( &Connection->lFuturePackets );
386 // Ooh, Goodie! Add it to the recieved list
387 TCP_INT_AppendRecieved(Connection, pkt);
389 Log_Log("TCP", "0x%08x += %i", Connection->NextSequenceRcv, dataLen);
390 Connection->NextSequenceRcv += dataLen;
392 // TODO: This should be moved out of the watcher thread,
393 // so that a single lost packet on one connection doesn't cause
394 // all connections on the interface to lag.
395 TCP_INT_UpdateRecievedFromFuture(Connection);
398 Header->DestPort = Header->SourcePort;
399 Header->SourcePort = htons(Connection->LocalPort);
400 Header->AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
401 Header->SequenceNumber = htonl(Connection->NextSequenceSend);
402 Header->WindowSize = htons(TCP_WINDOW_SIZE);
403 Header->Flags &= TCP_FLAG_SYN; // Eliminate all flags save for SYN
404 Header->Flags |= TCP_FLAG_ACK; // Add ACK
405 Log_Log("TCP", "Sending ACK for 0x%08x", Connection->NextSequenceRcv);
406 TCP_SendPacket( Connection, sizeof(tTCPHeader), Header );
407 //Connection->NextSequenceSend ++;
412 * \brief Appends a packet to the recieved list
413 * \param Connection Connection structure
414 * \param Pkt Packet structure on heap
416 void TCP_INT_AppendRecieved(tTCPConnection *Connection, tTCPStoredPacket *Pkt)
418 Mutex_Acquire( &Connection->lRecievedPackets );
419 if(Connection->RecievedBuffer->Length + Pkt->Length > Connection->RecievedBuffer->Space )
421 Log_Error("TCP", "Buffer filled, packet dropped (%s)",
422 // TCP_INT_DumpConnection(Connection)
428 RingBuffer_Write( Connection->RecievedBuffer, Pkt->Data, Pkt->Length );
431 VFS_MarkAvaliable(&Connection->Node, 1);
434 Mutex_Release( &Connection->lRecievedPackets );
438 * \brief Updates the connections recieved list from the future list
439 * \param Connection Connection structure
441 * Updates the recieved packets list with packets from the future (out
442 * of order) packets list that are now able to be added in direct
445 void TCP_INT_UpdateRecievedFromFuture(tTCPConnection *Connection)
447 tTCPStoredPacket *pkt, *prev;
451 // Look for the next expected packet in the cache.
452 SHORTLOCK( &Connection->lFuturePackets );
453 for(pkt = Connection->FuturePackets;
454 pkt && pkt->Sequence < Connection->NextSequenceRcv;
455 prev = pkt, pkt = pkt->Next);
457 // If we can't find the expected next packet, stop looking
458 if(!pkt || pkt->Sequence > Connection->NextSequenceRcv) {
459 SHORTREL( &Connection->lFuturePackets );
463 // Delete packet from future list
465 prev->Next = pkt->Next;
467 Connection->FuturePackets = pkt->Next;
470 SHORTREL( &Connection->lFuturePackets );
472 // Looks like we found one
473 TCP_INT_AppendRecieved(Connection, pkt);
474 Connection->NextSequenceRcv += pkt->Length;
480 * \fn Uint16 TCP_GetUnusedPort()
481 * \brief Gets an unused port and allocates it
483 Uint16 TCP_GetUnusedPort()
487 // Get Next outbound port
488 ret = giTCP_NextOutPort++;
489 while( gaTCP_PortBitmap[ret/32] & (1 << (ret%32)) )
493 if(giTCP_NextOutPort == 0x10000) {
494 ret = giTCP_NextOutPort = TCP_MIN_DYNPORT;
498 // Mark the new port as used
499 gaTCP_PortBitmap[ret/32] |= 1 << (ret%32);
505 * \fn int TCP_AllocatePort(Uint16 Port)
506 * \brief Marks a port as used
508 int TCP_AllocatePort(Uint16 Port)
510 // Check if the port has already been allocated
511 if( gaTCP_PortBitmap[Port/32] & (1 << (Port%32)) )
515 gaTCP_PortBitmap[Port/32] |= 1 << (Port%32);
521 * \fn int TCP_DeallocatePort(Uint16 Port)
522 * \brief Marks a port as unused
524 int TCP_DeallocatePort(Uint16 Port)
526 // Check if the port has already been allocated
527 if( !(gaTCP_PortBitmap[Port/32] & (1 << (Port%32))) )
531 gaTCP_PortBitmap[Port/32] &= ~(1 << (Port%32));
537 tVFS_Node *TCP_Server_Init(tInterface *Interface)
541 srv = malloc( sizeof(tTCPListener) );
544 Log_Warning("TCP", "malloc failed for listener (%i) bytes", sizeof(tTCPListener));
548 srv->Interface = Interface;
551 srv->Connections = NULL;
552 srv->ConnectionsTail = NULL;
553 srv->NewConnections = NULL;
555 srv->Node.Flags = VFS_FFLAG_DIRECTORY;
557 srv->Node.ImplPtr = srv;
558 srv->Node.NumACLs = 1;
559 srv->Node.ACLs = &gVFS_ACL_EveryoneRW;
560 srv->Node.ReadDir = TCP_Server_ReadDir;
561 srv->Node.FindDir = TCP_Server_FindDir;
562 srv->Node.IOCtl = TCP_Server_IOCtl;
563 srv->Node.Close = TCP_Server_Close;
565 SHORTLOCK(&glTCP_Listeners);
566 srv->Next = gTCP_Listeners;
567 gTCP_Listeners = srv;
568 SHORTREL(&glTCP_Listeners);
574 * \brief Wait for a new connection and return the connection ID
575 * \note Blocks until a new connection is made
576 * \param Node Server node
577 * \param Pos Position (ignored)
579 char *TCP_Server_ReadDir(tVFS_Node *Node, int Pos)
581 tTCPListener *srv = Node->ImplPtr;
582 tTCPConnection *conn;
585 ENTER("pNode iPos", Node, Pos);
587 Log_Log("TCP", "Thread %i waiting for a connection", Threads_GetTID());
590 SHORTLOCK( &srv->lConnections );
591 if( srv->NewConnections != NULL ) break;
592 SHORTREL( &srv->lConnections );
593 Threads_Yield(); // TODO: Sleep until poked
598 // Increment the new list (the current connection is still on the
600 conn = srv->NewConnections;
601 srv->NewConnections = conn->Next;
603 SHORTREL( &srv->lConnections );
605 LOG("conn = %p", conn);
606 LOG("srv->Connections = %p", srv->Connections);
607 LOG("srv->NewConnections = %p", srv->NewConnections);
608 LOG("srv->ConnectionsTail = %p", srv->ConnectionsTail);
611 itoa(ret, conn->Node.ImplInt, 16, 8, '0');
612 Log_Log("TCP", "Thread %i got '%s'", Threads_GetTID(), ret);
618 * \brief Gets a client connection node
619 * \param Node Server node
620 * \param Name Hexadecimal ID of the node
622 tVFS_Node *TCP_Server_FindDir(tVFS_Node *Node, const char *Name)
624 tTCPConnection *conn;
625 tTCPListener *srv = Node->ImplPtr;
629 ENTER("pNode sName", Node, Name);
632 itoa(tmp, id, 16, 8, '0');
633 if(strcmp(tmp, Name) != 0) {
634 LOG("'%s' != '%s' (%08x)", Name, tmp, id);
639 Log_Debug("TCP", "srv->Connections = %p", srv->Connections);
640 Log_Debug("TCP", "srv->NewConnections = %p", srv->NewConnections);
641 Log_Debug("TCP", "srv->ConnectionsTail = %p", srv->ConnectionsTail);
644 SHORTLOCK( &srv->lConnections );
645 for(conn = srv->Connections;
649 LOG("conn->Node.ImplInt = %i", conn->Node.ImplInt);
650 if(conn->Node.ImplInt == id) break;
652 SHORTREL( &srv->lConnections );
654 // If not found, ret NULL
656 LOG("Connection %i not found", id);
662 LEAVE('p', &conn->Node);
667 * \brief Handle IOCtl calls
669 int TCP_Server_IOCtl(tVFS_Node *Node, int ID, void *Data)
671 tTCPListener *srv = Node->ImplPtr;
675 case 4: // Get/Set Port
676 if(!Data) // Get Port
679 if(srv->Port) // Wait, you can't CHANGE the port
682 if(!CheckMem(Data, sizeof(Uint16))) // Sanity check
686 if(Threads_GetUID() != 0
687 && *(Uint16*)Data != 0
688 && *(Uint16*)Data < 1024)
691 // TODO: Check if a port is in use
694 srv->Port = *(Uint16*)Data;
695 if(srv->Port == 0) // Allocate a random port
696 srv->Port = TCP_GetUnusedPort();
697 else // Else, mark this as used
698 TCP_AllocatePort(srv->Port);
700 Log_Log("TCP", "Server %p listening on port %i", srv, srv->Port);
707 void TCP_Server_Close(tVFS_Node *Node)
714 * \brief Create a client node
716 tVFS_Node *TCP_Client_Init(tInterface *Interface)
718 tTCPConnection *conn = malloc( sizeof(tTCPConnection) );
720 conn->State = TCP_ST_CLOSED;
721 conn->Interface = Interface;
722 conn->LocalPort = -1;
723 conn->RemotePort = -1;
724 memset( &conn->RemoteIP, 0, sizeof(conn->RemoteIP) );
726 conn->Node.ImplPtr = conn;
727 conn->Node.NumACLs = 1;
728 conn->Node.ACLs = &gVFS_ACL_EveryoneRW;
729 conn->Node.Read = TCP_Client_Read;
730 conn->Node.Write = TCP_Client_Write;
731 conn->Node.IOCtl = TCP_Client_IOCtl;
732 conn->Node.Close = TCP_Client_Close;
734 conn->RecievedBuffer = RingBuffer_Create( TCP_RECIEVE_BUFFER_SIZE );
736 SHORTLOCK(&glTCP_OutbountCons);
737 conn->Next = gTCP_OutbountCons;
738 gTCP_OutbountCons = conn;
739 SHORTREL(&glTCP_OutbountCons);
745 * \brief Wait for a packet and return it
746 * \note If \a Length is smaller than the size of the packet, the rest
747 * of the packet's data will be discarded.
749 Uint64 TCP_Client_Read(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer)
751 tTCPConnection *conn = Node->ImplPtr;
752 char *destbuf = Buffer;
755 ENTER("pNode XOffset XLength pBuffer", Node, Offset, Length, Buffer);
756 LOG("conn = %p", conn);
757 LOG("conn->State = %i", conn->State);
759 // Check if connection is open
760 while( conn->State == TCP_ST_HALFOPEN || conn->State == TCP_ST_SYN_SENT )
762 if( conn->State != TCP_ST_OPEN ) {
772 VFS_SelectNode(Node, VFS_SELECT_READ, NULL);
773 // Lock list and read
774 Mutex_Acquire( &conn->lRecievedPackets );
776 // Lock list and check if there is a packet
777 Mutex_Acquire( &conn->lRecievedPackets );
778 if( conn->RecievedBuffer->Length == 0 ) {
779 // If not, release the lock, yield and try again
780 Mutex_Release( &conn->lRecievedPackets );
781 Threads_Yield(); // TODO: Less expensive wait
786 // Attempt to read all `Length` bytes
787 len = RingBuffer_Read( destbuf, conn->RecievedBuffer, Length );
790 if( conn->RecievedBuffer->Length == 0 )
791 VFS_MarkAvaliable(Node, 0);
794 // Release the lock (we don't need it any more)
795 Mutex_Release( &conn->lRecievedPackets );
803 * \brief Send a data packet on a connection
805 void TCP_INT_SendDataPacket(tTCPConnection *Connection, size_t Length, void *Data)
807 char buf[sizeof(tTCPHeader)+Length];
808 tTCPHeader *packet = (void*)buf;
810 packet->SourcePort = htons(Connection->LocalPort);
811 packet->DestPort = htons(Connection->RemotePort);
812 packet->DataOffset = (sizeof(tTCPHeader)/4)*16;
813 packet->WindowSize = TCP_WINDOW_SIZE;
815 packet->AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
816 packet->SequenceNumber = htonl(Connection->NextSequenceSend);
817 packet->Flags = TCP_FLAG_PSH|TCP_FLAG_ACK; // Hey, ACK if you can!
819 memcpy(packet->Options, Data, Length);
821 TCP_SendPacket( Connection, sizeof(tTCPHeader)+Length, packet );
823 Connection->NextSequenceSend += Length;
827 * \brief Send some bytes on a connection
829 Uint64 TCP_Client_Write(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer)
831 tTCPConnection *conn = Node->ImplPtr;
834 ENTER("pNode XOffset XLength pBuffer", Node, Offset, Length, Buffer);
836 // Check if connection is open
837 while( conn->State == TCP_ST_HALFOPEN || conn->State == TCP_ST_SYN_SENT )
839 if( conn->State != TCP_ST_OPEN ) {
844 while( rem > TCP_MAX_PACKET_SIZE )
846 TCP_INT_SendDataPacket(conn, TCP_MAX_PACKET_SIZE, Buffer);
847 Buffer += TCP_MAX_PACKET_SIZE;
850 TCP_INT_SendDataPacket(conn, rem, Buffer);
857 * \brief Open a connection to another host using TCP
858 * \param Conn Connection structure
860 void TCP_StartConnection(tTCPConnection *Conn)
862 tTCPHeader hdr = {0};
864 Conn->State = TCP_ST_SYN_SENT;
866 hdr.SourcePort = htons(Conn->LocalPort);
867 hdr.DestPort = htons(Conn->RemotePort);
868 Conn->NextSequenceSend = rand();
869 hdr.SequenceNumber = htonl(Conn->NextSequenceSend);
870 hdr.DataOffset = (sizeof(tTCPHeader)/4) << 4;
871 hdr.Flags = TCP_FLAG_SYN;
872 hdr.WindowSize = htons(TCP_WINDOW_SIZE); // Max
873 hdr.Checksum = 0; // TODO
875 TCP_SendPacket( Conn, sizeof(tTCPHeader), &hdr );
877 Conn->NextSequenceSend ++;
878 Conn->State = TCP_ST_SYN_SENT;
883 * \brief Control a client socket
885 int TCP_Client_IOCtl(tVFS_Node *Node, int ID, void *Data)
887 tTCPConnection *conn = Node->ImplPtr;
889 ENTER("pNode iID pData", Node, ID, Data);
893 case 4: // Get/Set local port
895 LEAVE_RET('i', conn->LocalPort);
896 if(conn->State != TCP_ST_CLOSED)
898 if(!CheckMem(Data, sizeof(Uint16)))
901 if(Threads_GetUID() != 0 && *(Uint16*)Data < 1024)
904 conn->LocalPort = *(Uint16*)Data;
905 LEAVE_RET('i', conn->LocalPort);
907 case 5: // Get/Set remote port
908 if(!Data) LEAVE_RET('i', conn->RemotePort);
909 if(conn->State != TCP_ST_CLOSED) LEAVE_RET('i', -1);
910 if(!CheckMem(Data, sizeof(Uint16))) LEAVE_RET('i', -1);
911 conn->RemotePort = *(Uint16*)Data;
912 LEAVE_RET('i', conn->RemotePort);
914 case 6: // Set Remote IP
915 if( conn->State != TCP_ST_CLOSED )
917 if( conn->Interface->Type == 4 )
919 if(!CheckMem(Data, sizeof(tIPv4))) LEAVE_RET('i', -1);
920 conn->RemoteIP.v4 = *(tIPv4*)Data;
922 else if( conn->Interface->Type == 6 )
924 if(!CheckMem(Data, sizeof(tIPv6))) LEAVE_RET('i', -1);
925 conn->RemoteIP.v6 = *(tIPv6*)Data;
930 if(conn->LocalPort == 0xFFFF)
931 conn->LocalPort = TCP_GetUnusedPort();
932 if(conn->RemotePort == -1)
935 TCP_StartConnection(conn);
938 // Get recieve buffer length
940 LEAVE_RET('i', conn->RecievedBuffer->Length);
946 void TCP_Client_Close(tVFS_Node *Node)
948 tTCPConnection *conn = Node->ImplPtr;
951 ENTER("pNode", Node);
953 packet.SourcePort = htons(conn->LocalPort);
954 packet.DestPort = htons(conn->RemotePort);
955 packet.DataOffset = (sizeof(tTCPHeader)/4)*16;
956 packet.WindowSize = TCP_WINDOW_SIZE;
958 packet.AcknowlegementNumber = 0;
959 packet.SequenceNumber = htonl(conn->NextSequenceSend);
960 packet.Flags = TCP_FLAG_FIN;
962 conn->State = TCP_ST_FIN_SENT;
964 TCP_SendPacket( conn, sizeof(tTCPHeader), &packet );
966 while( conn->State == TCP_ST_FIN_SENT ) Threads_Yield();